rigless 0.2.0

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The direct memory access controller of RM0090 rev 22 chapter 10, written against the `dma2`
//! layout.
//!
//! One layout serves both controllers. What differs between them is the part's, not the layout's:
//! which peripheral request reaches which stream on which channel, tables 43 and 44, and whether
//! the peripheral port reaches the bus matrix at all, which the note under figure 34 gives DMA2
//! alone.
//!
//! A stream is a byte pipe with a FIFO in the middle. It loads from the source port and stores to
//! the destination port, one access at a time, as one AHB master is. Everything a transfer does
//! happens at the instant of the access or the request that caused it, because a settle is the part
//! reaching its next steady state rather than time passing.
//!
//! **The counter follows the peripheral port.** Section 10.3.10 gives it the peripheral bus's
//! width. Section 10.3.13 ends a transfer when it "has reached zero in the memory-to-peripheral
//! mode", where the peripheral is the destination, and section 10.3.15's `0xFFFF - DMA_SxNDTR`
//! counts what the peripheral moved. The manual doesn't agree with itself about the instant.
//! Section 10.3.2 makes the decrement the third of three operations, after the store, which for a
//! stream whose two ports are decoupled by the FIFO is a different moment from the peripheral's own
//! access. And section 10.3.12 has the counter after a flush "indicate how many data items are
//! currently available in the destination memory", which only holds if it hadn't already come down
//! for what the FIFO was holding. Both of those read the counter against the memory port. This
//! model takes the peripheral port, which is the reading the other three sections carry, and makes
//! the flush the exception by freezing the counter there.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | Channel selection | A request reaches the stream whose `CHSEL` names the channel it arrives on, and the part says which requests reach which channels | 10.3.3, tables 43 and 44 | `a_request_reaches_only_the_stream_whose_channel_selects_it` |
//! | Serving a peripheral | A stream takes a word off an interface, or gives one to it, while the request stands, and the access it makes is what clears the flag behind the request | 10.3.2, 28.3.9 | `a_serial_interface_drives_a_stream_each_way_and_the_peers_answers_come_back` |
//! | Either port on a peripheral | Both ports reach the bus matrix, so a stream moves words between two peripherals with no memory in between | 10.3.1, 10.3.6 | `a_stream_carries_words_from_one_peripheral_to_another` |
//! | `DIR` | Peripheral-to-memory, memory-to-peripheral, and memory-to-memory, with the source and destination of table 45 | 10.3.6 | `each_direction_moves_its_block_between_the_right_two_ports` |
//! | Memory to memory | Runs as soon as the stream is enabled, with no request, and only on a controller whose peripheral port reaches the bus matrix | 10.3.6, figure 34 note | `memory_to_memory_copies_a_block_with_no_request`, `the_first_controller_cannot_reach_memory_from_its_peripheral_port` |
//! | Direct mode | There's no FIFO to fill: a memory-to-peripheral stream preloads one item and a peripheral-to-memory one drains each straight through, `MSIZE` follows `PSIZE`, and the burst fields are forced to single | 10.3.12, 10.5.5 | `enabling_a_stream_applies_every_rule_the_configuration_forces`, `the_counter_counts_the_peripheral_ports_items_and_not_the_memory_ports` |
//! | FIFO mode | Bytes gather to the threshold before the destination is written, the tail of a transfer drains whatever is left, and a memory-to-peripheral stream reloads the FIFO whole once its level falls to the threshold | 10.3.6, 10.3.12 | `the_fifo_holds_bytes_until_the_threshold_and_then_drains`, `a_memory_to_peripheral_stream_reloads_the_fifo_at_its_threshold` |
//! | Packing | Source and destination widths differ and the bytes repack little-endian, table 47 | 10.3.10 | `bytes_repack_between_two_widths_in_the_order_the_table_gives` |
//! | `FS` | The FIFO level as the encodings of section 10.5.10 give it | 10.5.10 | `the_fifo_holds_bytes_until_the_threshold_and_then_drains` |
//! | `PINC`, `MINC`, `PINCOS` | Each port's pointer steps by its own width, or by four where `PINCOS` fixes it, or stands still | 10.3.7, 10.5.5 | `a_fixed_pointer_writes_one_address_and_an_incrementing_one_walks`, `the_peripheral_step_is_four_where_pincos_survives_the_enable` |
//! | `NDTR` | Counts peripheral-port items, decrements as they move, is read-only while the stream is enabled, holds what's left after a suspension, is reloaded with what was last programmed at every enable, and serves nothing at zero | 10.3.2, 10.3.14, 10.5.6 | `the_counter_follows_the_peripheral_port_and_survives_a_suspension`, `the_counter_counts_the_peripheral_ports_items_and_not_the_memory_ports`, `a_stream_enabled_again_runs_the_block_it_was_programmed_with`, `a_stream_enabled_with_no_count_serves_nothing_and_stays_enabled` |
//! | Circular | The counter and the pointers start again and the requests go on being served | 10.3.8 | `circular_mode_starts_the_block_again` |
//! | Double buffer | `CT` names the pointer in use and swaps at each end of transaction. The current one is write-protected, and writing it is a transfer error | 10.3.9 | `double_buffer_swaps_its_target_at_each_end`, `writing_the_target_in_use_is_a_transfer_error` |
//! | `HTIF`, `TCIF` | Half and whole of the block as the destination port takes it | 10.3.17 | `the_half_and_complete_flags_stand_at_the_halves_of_the_block` |
//! | `TEIF`, `FEIF` | An access the bus refuses, a write to the target in use, and a FIFO threshold the memory burst doesn't divide, each of which clears `EN` and ends the block where it stands | 10.3.18, table 49 | `a_stream_pointed_at_an_instance_the_part_refuses_ends_in_a_transfer_error`, `a_threshold_the_burst_does_not_divide_is_a_fifo_error`, `a_stream_stopped_while_an_access_was_in_flight_does_not_take_the_answer` |
//! | `LIFCR`, `HIFCR` | A written one clears its flag in `LISR` or `HISR` | 10.5.3, 10.5.4 | `a_written_one_clears_its_own_flag_and_no_other` |
//! | Interrupts | Each stream raises its own line while an enabled flag stands | 10.4, table 51 | `each_enable_raises_the_streams_own_line` |
//! | Suspension | Clearing `EN` ends the transfer, sets `TCIF`, and drains what the FIFO still holds toward memory | 10.3.12, 10.3.14 | `clearing_the_enable_flushes_what_the_fifo_holds` |
//! | `PFCTRL`, the peripheral as flow controller | The counter is forced to `0xFFFF` at the enable. The stream ends, `TCIF` set and `EN` cleared, when the peripheral signals its last data and what the FIFO holds has reached memory, and `0xFFFF - NDTR` is what moved. Section 10.3.15 names one peripheral that can signal it, the card interface, and the part says which of its lines is the signal | 10.3.13, 10.3.15, 10.5.5 | `a_stream_the_peripheral_controls_ends_when_it_signals_the_last_data`, `a_write_the_peripheral_controls_ends_the_same_way`, `a_stream_the_dma_controls_outlives_the_card_interfaces_last_data` |
//! | Register protection | The configuration, counter, and pointer registers take no write while `EN` stands | 10.5.5, 10.5.6 | `the_configuration_registers_take_no_write_while_the_stream_runs` |
//! | Enable procedure | `DBM` forces `CIRC`, memory-to-memory forces `PFCTRL` clear and the FIFO on, and the counter and pointers are taken at the enable | 10.3.17, 10.5.5, 10.5.10 | `enabling_a_stream_applies_every_rule_the_configuration_forces` |
//! | ES0206 rev 24 | No item of Table 3 names the DMA controller. 2.6.1 is the DAC's own request, and the part has no DAC model | not applicable | |
//!
//! **What the model leaves out, and why.**
//!
//! | Behavior | Source | Reason |
//! |---|---|---|
//! | The arbiter, and `PL` as anything but a stored field | 10.3.4 | Priority decides which of two streams reaches the bus matrix first in a cycle neither of them has. Every stream here is served in stream order, which is the arbiter's own tie-break, and nothing a firmware can read distinguishes the two |
//! | `DMEIF`, the direct mode error | 10.3.18 | It's set "because the memory bus was not granted" while a second request arrives. The memory bus here is always granted within the access that asked for it, so the condition can't arise. The bit and its enable are stored and never set |
//! | `FEIF` from an underrun or an overrun | 10.3.18 | The same: both are the FIFO caught out by a bus that didn't grant in time. The threshold error of table 49, which is a configuration and not a race, is modeled |
//! | A burst as an indivisible run of AHB beats, and `PBURST` as a count of them per request | 10.3.11 | Each beat is its own access, so nothing observes the lock. And a request here is the level section 10.3.2 gives it, so what decides how many beats one request is worth is the peripheral's own flag rather than a count. `MBURST` is read, because the threshold rule of table 49 is a configuration error and not a race |
//! | Clock gating and the reset registers | 6.3.5 to 6.3.9 | The part gates the instance through the bus, which is `memory_map.rs`. Being held at reset is a third behavior and isn't this |
//!
//! **Where this model departs from the vendor's file.** Section 10.5.3 types every bit of `LIFCR`
//! and `HIFCR` write-only and ST's file types both registers read-write, so a written one stays in
//! the register where the part would drop it. The model clears them itself. ST also gives `SxFCR`
//! no write rule for `FS`, which section 10.5.10 types read-only, and the register file enforces
//! that from the table, so the model writes the level through [`RegisterFile::set`].

use std::collections::VecDeque;

use crate::device::{Device, DeviceContext, Level, RegisterFile, RequestChange};
use crate::snapshot::store;
use crate::soc::{Layout, Width};

use crate::soc::stm32f427::generated::dma2::{Register, hisr, lisr, s0cr, s0fcr, s0ndtr};

/// Streams per controller, RM0090 rev 22 section 10.2.
pub const STREAMS: usize = 8;

/// Channels each stream chooses between, section 10.3.3.
pub const CHANNELS: usize = 8;

/// The FIFO of section 10.3.12: four words, whatever the widths either side of it.
const FIFO_BYTES: usize = 16;

/// The registers of one stream follow the four status registers, six to a stream, in this order.
/// `the_streams_registers_run_in_blocks_of_six` holds the generated table to it.
const FIRST_STREAM_ROW: usize = 4;
const ROWS_PER_STREAM: usize = 6;

/// Which of a stream's six registers, by its place in the block.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Row {
    Control = 0,
    Count = 1,
    Peripheral = 2,
    Memory0 = 3,
    Memory1 = 4,
    Fifo = 5,
}

/// Every stream row of the layout, so a write can be told from one to a status register.
const ROWS: [Row; ROWS_PER_STREAM] = [
    Row::Control,
    Row::Count,
    Row::Peripheral,
    Row::Memory0,
    Row::Memory1,
    Row::Fifo,
];

/// The register `row` of `stream`.
fn register(stream: usize, row: Row) -> Register {
    let index = FIRST_STREAM_ROW + stream * ROWS_PER_STREAM + row as usize;
    Register::from_index(index).expect("a controller carries eight streams of six registers")
}

/// Each stream's five flags, RM0090 rev 22 sections 10.5.1 and 10.5.2, in the order of [`Flag`].
///
/// Streams 0 to 3 report in `LISR` and 4 to 7 in `HISR`. The clearing registers carry the same bits
/// at the same places, which `every_flag_has_its_clearing_bit_at_the_same_position` asserts rather
/// than assumes.
const FLAGS: [[&crate::soc::FieldSpec; 5]; STREAMS] = [
    [
        lisr::FEIF0,
        lisr::DMEIF0,
        lisr::TEIF0,
        lisr::HTIF0,
        lisr::TCIF0,
    ],
    [
        lisr::FEIF1,
        lisr::DMEIF1,
        lisr::TEIF1,
        lisr::HTIF1,
        lisr::TCIF1,
    ],
    [
        lisr::FEIF2,
        lisr::DMEIF2,
        lisr::TEIF2,
        lisr::HTIF2,
        lisr::TCIF2,
    ],
    [
        lisr::FEIF3,
        lisr::DMEIF3,
        lisr::TEIF3,
        lisr::HTIF3,
        lisr::TCIF3,
    ],
    [
        hisr::FEIF4,
        hisr::DMEIF4,
        hisr::TEIF4,
        hisr::HTIF4,
        hisr::TCIF4,
    ],
    [
        hisr::FEIF5,
        hisr::DMEIF5,
        hisr::TEIF5,
        hisr::HTIF5,
        hisr::TCIF5,
    ],
    [
        hisr::FEIF6,
        hisr::DMEIF6,
        hisr::TEIF6,
        hisr::HTIF6,
        hisr::TCIF6,
    ],
    [
        hisr::FEIF7,
        hisr::DMEIF7,
        hisr::TEIF7,
        hisr::HTIF7,
        hisr::TCIF7,
    ],
];

/// One of a stream's five event flags, RM0090 rev 22 table 51.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Flag {
    Fifo = 0,
    Direct = 1,
    Transfer = 2,
    Half = 3,
    Complete = 4,
}

/// One row of the part's request mapping: a peripheral's request output, and where it arrives.
///
/// RM0090 rev 22 tables 43 and 44 are this, read the other way round: a cell of the table names a
/// peripheral request, and the row and column name the channel and the stream it reaches. A part
/// declares one of these for every request one of its modeled instances drives.
#[derive(Debug, Clone, Copy)]
pub struct Wire {
    /// The instance driving it, as the vendor names it.
    pub instance: &'static str,
    /// Which of that instance's request outputs, in the instance's own numbering.
    pub request: usize,
    /// The channel it arrives on, below [`CHANNELS`], which a stream's `CHSEL` chooses,
    /// section 10.3.3.
    pub channel: usize,
    /// The streams it reaches.
    pub streams: &'static [usize],
}

/// The direction of a transfer, RM0090 rev 22 table 45.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Direction {
    PeripheralToMemory,
    MemoryToPeripheral,
    MemoryToMemory,
}

impl Direction {
    /// The encoding of `DIR`, section 10.5.5 bits 7:6. `11` is reserved and moves nothing.
    fn of(encoding: u64) -> Option<Self> {
        match encoding {
            0 => Some(Self::PeripheralToMemory),
            1 => Some(Self::MemoryToPeripheral),
            2 => Some(Self::MemoryToMemory),
            _ => None,
        }
    }

    /// Whether the peripheral port is the source. Table 45 gives it to every direction but one.
    fn peripheral_is_the_source(self) -> bool {
        self != Self::MemoryToPeripheral
    }
}

/// Which port an access in flight belongs to, so an answer reaches the half of the pipe that asked.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Port {
    Source = 0,
    Destination = 1,
}

/// One stream's configuration, read from its registers at the moment it's needed.
#[derive(Clone, Copy, Debug)]
struct Shape {
    direction: Direction,
    peripheral_width: Width,
    memory_width: Width,
    direct: bool,
    /// The FIFO level a drain waits for, in bytes, section 10.5.10 bits 1:0.
    threshold: u64,
    circular: bool,
    double_buffer: bool,
    /// How far each port's pointer steps after a beat, or nothing where it stands still.
    peripheral_step: Option<u64>,
    memory_step: Option<u64>,
    /// Beats of the memory burst, for the threshold rule of table 49.
    memory_beats: u64,
    /// The channel this stream's `CHSEL` selects, section 10.3.3.
    channel: usize,
}

impl Shape {
    fn source_width(self) -> Width {
        if self.direction.peripheral_is_the_source() {
            self.peripheral_width
        } else {
            self.memory_width
        }
    }

    fn destination_width(self) -> Width {
        if self.direction.peripheral_is_the_source() {
            self.memory_width
        } else {
            self.peripheral_width
        }
    }

    /// Whether the destination port is the one a request gates. Table 45 puts the peripheral there
    /// in exactly one direction, and memory-to-memory has no request at all.
    fn request_gates_the_destination(self) -> bool {
        self.direction == Direction::MemoryToPeripheral
    }
}

/// The data size encodings of `PSIZE` and `MSIZE`, section 10.5.5 bits 14:11. `11` is reserved.
fn data_width(encoding: u64) -> Width {
    match encoding {
        0 => Width::W8,
        1 => Width::W16,
        _ => Width::W32,
    }
}

/// The burst encodings of `PBURST` and `MBURST` as a count of beats, section 10.5.5 bits 24:21.
fn burst_beats(encoding: u64) -> u64 {
    match encoding {
        0 => 1,
        other => 4 << (other - 1),
    }
}

/// The FIFO threshold encodings as a level in bytes, section 10.5.10 bits 1:0.
fn threshold_bytes(encoding: u64) -> u64 {
    (encoding + 1) * 4
}

/// How a stream ends before its block does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Finish {
    Running,
    /// The peripheral has signaled its last data, section 10.3.15. The stream ends once its
    /// request is released and the access in flight has been answered.
    Signaled,
    /// The FIFO is draining toward memory, section 10.3.12, after which the stream stops.
    Flushing,
}

/// One stream of a controller.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Stream {
    /// Where the next beat lands on each port. The registers keep the bases, section 10.3.7.
    peripheral_at: u64,
    memory_at: u64,
    /// Bytes loaded and not yet stored, oldest first: the FIFO of section 10.3.12.
    fifo: VecDeque<u8>,
    /// Bytes still to take from the source, and still to give to the destination.
    to_load: u64,
    to_store: u64,
    /// Bytes the destination port has taken, for the half-transfer flag of section 10.3.17.
    stored: u64,
    /// The whole block in bytes, which circular mode starts again from.
    total: u64,
    /// The last count the firmware programmed, in peripheral-port items, that an enable starts
    /// from.
    programmed: u64,
    /// The access on the bus, if any. One at a time, as one AHB master is.
    outstanding: Option<Port>,
    /// The level on each of this stream's eight request inputs, figure 35.
    inputs: [bool; CHANNELS],
    /// Whether the half-transfer flag has been raised for the block in flight.
    halved: bool,
    /// How the stream is ending, if it is.
    finish: Finish,
    /// Whether the memory port is reloading the FIFO. Section 10.3.6 has a memory-to-peripheral
    /// stream fill it entirely once its level has fallen to the threshold, rather than topping it
    /// up after every beat that leaves.
    refilling: bool,
    /// What the protected registers held before the access being served, so a refused write goes
    /// back.
    guarded: [u64; ROWS_PER_STREAM],
    interrupt: Level,
}

impl Default for Stream {
    fn default() -> Self {
        Self {
            peripheral_at: 0,
            memory_at: 0,
            fifo: VecDeque::with_capacity(FIFO_BYTES),
            to_load: 0,
            to_store: 0,
            stored: 0,
            total: 0,
            programmed: 0,
            outstanding: None,
            inputs: [false; CHANNELS],
            halved: false,
            finish: Finish::Running,
            refilling: false,
            guarded: [0; ROWS_PER_STREAM],
            interrupt: Level::Low,
        }
    }
}

/// One direct memory access controller of an STM32F42xxx, RM0090 rev 22 chapter 10.
#[derive(Debug)]
pub struct Dma {
    streams: [Stream; STREAMS],
    wiring: &'static [Wire],
    /// The lines that carry a peripheral's last-data signal, section 10.3.15, in the shape of a
    /// request.
    last_data: &'static [Wire],
    reaches_memory_from_the_peripheral_port: bool,
}

store!(Dma {
    values: [streams],
    parts: [],
    built: [wiring, last_data, reaches_memory_from_the_peripheral_port],
});

impl Dma {
    /// A controller whose streams carry `wiring`, the part's reading of tables 43 and 44, and whose
    /// streams under `PFCTRL` end on `last_data`, the lines section 10.3.15 has a peripheral signal
    /// on.
    ///
    /// `reaches_memory_from_the_peripheral_port` is the note under figure 34. One of the two
    /// controllers has its peripheral port on the bus matrix, so it can move memory to memory, and
    /// the other can't. A controller that can't takes a transfer error rather than moving a byte.
    #[must_use]
    pub fn new(
        wiring: &'static [Wire],
        last_data: &'static [Wire],
        reaches_memory_from_the_peripheral_port: bool,
    ) -> Self {
        Self {
            streams: std::array::from_fn(|_| Stream::default()),
            wiring,
            last_data,
            reaches_memory_from_the_peripheral_port,
        }
    }

    /// How many bytes each of a stream's ports has left to move, for a test watching a transfer.
    #[must_use]
    pub fn remaining(&self, stream: usize) -> (u64, u64) {
        (self.streams[stream].to_load, self.streams[stream].to_store)
    }
}

/// The value of a stream's register.
fn held(registers: &RegisterFile, stream: usize, row: Row) -> u64 {
    registers.get(register(stream, row))
}

/// Applies `change` to a stream's register, the way hardware writes a bit of its own.
fn modify(registers: &mut RegisterFile, stream: usize, row: Row, change: impl FnOnce(u64) -> u64) {
    let target = register(stream, row);
    let value = registers.get(target);
    registers.set(target, change(value));
}

impl Dma {
    /// What a stream is configured to do, read from its registers.
    fn shape(registers: &RegisterFile, stream: usize) -> Option<Shape> {
        let control = held(registers, stream, Row::Control);
        let fifo = held(registers, stream, Row::Fifo);
        let direction = Direction::of(s0cr::DIR.get(control))?;
        let direct = !s0fcr::DMDIS.is_set(fifo);
        let peripheral_width = data_width(s0cr::PSIZE.get(control));
        let memory_width = data_width(s0cr::MSIZE.get(control));
        // Section 10.5.5 bit 15: PINCOS fixes the peripheral step at four whatever `PSIZE` says.
        // What forces it low is applied where the stream starts, so what stands here is what the
        // stream does.
        let peripheral_step = s0cr::PINC.is_set(control).then(|| {
            if s0cr::PINCOS.is_set(control) {
                4
            } else {
                u64::from(peripheral_width.bytes())
            }
        });
        Some(Shape {
            direction,
            peripheral_width,
            memory_width,
            direct,
            threshold: threshold_bytes(s0fcr::FTH.get(fifo)),
            circular: s0cr::CIRC.is_set(control),
            double_buffer: s0cr::DBM.is_set(control),
            peripheral_step,
            memory_step: s0cr::MINC
                .is_set(control)
                .then(|| u64::from(memory_width.bytes())),
            memory_beats: burst_beats(s0cr::MBURST.get(control)),
            channel: usize::try_from(s0cr::CHSEL.get(control)).expect("three bits"),
        })
    }

    fn enabled(registers: &RegisterFile, stream: usize) -> bool {
        s0cr::EN.is_set(held(registers, stream, Row::Control))
    }
}

/// The status register a stream reports in: the low four in `LISR`, the high four in `HISR`,
/// sections 10.5.1 and 10.5.2.
fn status_of(stream: usize) -> Register {
    if stream < STREAMS / 2 {
        Register::Lisr
    } else {
        Register::Hisr
    }
}

/// Raises or lowers a flag of `stream`.
fn set_flag(registers: &mut RegisterFile, stream: usize, flag: Flag, raised: bool) {
    let status = status_of(stream);
    let value = registers.get(status);
    let field = FLAGS[stream][flag as usize];
    registers.set(status, field.set(value, u64::from(raised)));
}

/// Whether a flag of `stream` stands.
fn flag_stands(registers: &RegisterFile, stream: usize, flag: Flag) -> bool {
    FLAGS[stream][flag as usize].is_set(registers.get(status_of(stream)))
}

/// Clears `EN`, as hardware does at the end of a transfer and on a fault, section 10.5.5 bit 0.
fn disable(registers: &mut RegisterFile, stream: usize) {
    modify(registers, stream, Row::Control, |control| {
        s0cr::EN.set(control, 0)
    });
}

impl Dma {
    /// Starts a stream, RM0090 rev 22 section 10.3.17 step 10.
    ///
    /// The configuration forces what it forces here rather than at each beat, which is what the
    /// register descriptions say: "as soon as bit EN = '1'". What the enable finds wrong ends it
    /// before it moves a byte, with the flag section 10.3.18 gives that fault.
    fn start(
        &mut self,
        stream: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let control = held(registers, stream, Row::Control);
        // Section 10.5.5 bit 8: DBM forces circular, and a peripheral flow controller forbids it.
        let mut forced = control;
        if s0cr::DBM.is_set(control) {
            forced = s0cr::CIRC.set(forced, 1);
        }
        if s0cr::PFCTRL.is_set(control) {
            forced = s0cr::CIRC.set(forced, 0);
        }
        let memory_to_memory =
            Direction::of(s0cr::DIR.get(control)) == Some(Direction::MemoryToMemory);
        if memory_to_memory {
            // Section 10.5.5 bit 5 and section 10.5.10 bit 2: memory to memory is the DMA's own
            // flow and can't use the direct mode, and hardware says so rather than the firmware.
            forced = s0cr::PFCTRL.set(forced, 0);
            modify(registers, stream, Row::Fifo, |fifo| {
                s0fcr::DMDIS.set(fifo, 1)
            });
        }
        // Sections 10.5.5 bits 24:21 and 14:13: direct mode forces the memory width to the
        // peripheral's and both burst fields to single. Bit 15 forces the peripheral increment
        // offset low "if the direct mode is selected or if PBURST are different from 00", so it
        // survives only a FIFO stream with no peripheral burst. They're written back, so a firmware
        // reading its own configuration sees what the stream does, not what it asked for.
        let direct = !s0fcr::DMDIS.is_set(held(registers, stream, Row::Fifo));
        if direct {
            forced = s0cr::MSIZE.set(forced, s0cr::PSIZE.get(forced));
            forced = s0cr::MBURST.set(forced, 0);
            forced = s0cr::PBURST.set(forced, 0);
        }
        if direct || s0cr::PBURST.get(forced) != 0 {
            forced = s0cr::PINCOS.set(forced, 0);
        }
        registers.set(register(stream, Row::Control), forced);

        let Some(shape) = Self::shape(registers, stream) else {
            // DIR = 11 is reserved. The stream is enabled and moves nothing.
            return;
        };
        if memory_to_memory && !self.reaches_memory_from_the_peripheral_port {
            // The note under figure 34: this controller's peripheral port isn't on the bus matrix,
            // so the source access is a bus error, which section 10.3.18 gives to TEIF.
            self.fail(stream, Flag::Transfer, registers, context);
            return;
        }
        // Table 49: the threshold has to hold a whole number of memory bursts, or the stream is
        // stopped with a FIFO error before it starts.
        if !shape.direct
            && shape.threshold % (shape.memory_beats * u64::from(shape.memory_width.bytes())) != 0
        {
            self.fail(stream, Flag::Fifo, registers, context);
            return;
        }

        // Section 10.5.6: "If the value of this register is zero, no transaction can be served even
        // if the stream is enabled", so a stream enabled with nothing programmed sits there, which
        // is what the block of zero bytes below comes to.
        //
        // Section 10.5.6: the counter is "reloaded automatically with the previously programmed
        // value ... when the stream is enabled again by setting EN bit to '1'", so a firmware that
        // runs the same block twice doesn't need to write it twice.
        let programmed = self.streams[stream].programmed;
        modify(registers, stream, Row::Count, |count| {
            s0ndtr::NDT.set(count, programmed)
        });
        // Section 10.3.15: with the peripheral as flow controller the counter is forced to its
        // maximum, whatever was written.
        if s0cr::PFCTRL.is_set(forced) {
            modify(registers, stream, Row::Count, |count| {
                s0ndtr::NDT.set(count, s0ndtr::NDT.mask() >> s0ndtr::NDT.bit)
            });
        }
        let items = s0ndtr::NDT.get(held(registers, stream, Row::Count));
        let total = items * u64::from(shape.peripheral_width.bytes());
        let stream_state = &mut self.streams[stream];
        stream_state.fifo.clear();
        stream_state.total = total;
        stream_state.to_load = total;
        stream_state.to_store = total;
        stream_state.stored = 0;
        stream_state.halved = false;
        stream_state.finish = Finish::Running;
        // Section 10.3.6: "the stream immediately initiates transfers from the source to entirely
        // fill the FIFO."
        stream_state.refilling = true;
        stream_state.outstanding = None;
        self.take_pointers(stream, registers, shape);
        self.report_fifo(stream, registers);
        self.pump(stream, registers, context);
    }

    /// Takes the pointers the registers hold, which is what a transaction starts from.
    /// Section 10.3.9 chooses between the two memory pointers by `CT`.
    fn take_pointers(&mut self, stream: usize, registers: &RegisterFile, shape: Shape) {
        let control = held(registers, stream, Row::Control);
        let second = shape.double_buffer && s0cr::CT.is_set(control);
        let memory = if second { Row::Memory1 } else { Row::Memory0 };
        let stream_state = &mut self.streams[stream];
        stream_state.peripheral_at = held(registers, stream, Row::Peripheral);
        stream_state.memory_at = held(registers, stream, memory);
    }

    /// Stops a stream on a fault: the flag stands and hardware clears `EN`.
    ///
    /// Section 10.3.18 clears the enable for the two faults that reach here, the bus error and the
    /// threshold. It leaves it standing for an overrun or an underrun, which this model doesn't
    /// raise.
    fn fail(
        &mut self,
        stream: usize,
        flag: Flag,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        set_flag(registers, stream, flag, true);
        disable(registers, stream);
        self.streams[stream].outstanding = None;
        self.streams[stream].to_load = 0;
        self.streams[stream].to_store = 0;
        self.streams[stream].fifo.clear();
        self.report_fifo(stream, registers);
        self.refresh_interrupt(stream, registers, context);
    }

    /// The firmware cleared `EN`, section 10.3.14.
    ///
    /// What's already in the FIFO still goes to memory, section 10.3.12's flush, and the transfer
    /// complete flag stands either way to say the transfer ended.
    fn suspend(
        &mut self,
        stream: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let shape = Self::shape(registers, stream);
        let flushes = shape.is_some_and(|shape| {
            shape.direction != Direction::MemoryToPeripheral
                && !self.streams[stream].fifo.is_empty()
        });
        self.streams[stream].to_load = 0;
        if flushes {
            self.streams[stream].finish = Finish::Flushing;
            self.pump(stream, registers, context);
            return;
        }
        self.streams[stream].to_store = 0;
        self.stop(stream, registers);
        self.refresh_interrupt(stream, registers, context);
    }

    /// The stream has finished: section 10.3.13's flag stands, what the FIFO still holds is
    /// dropped, and hardware clears the enable.
    fn stop(&mut self, stream: usize, registers: &mut RegisterFile) {
        set_flag(registers, stream, Flag::Complete, true);
        self.streams[stream].finish = Finish::Running;
        self.streams[stream].fifo.clear();
        self.report_fifo(stream, registers);
        disable(registers, stream);
    }
}

/// The tag a stream puts on the access it asks the runtime to make, so the answer comes back to the
/// port that asked for it.
fn token(stream: usize, port: Port) -> u64 {
    let stream = u64::try_from(stream).expect("eight streams");
    stream * 2 + port as u64
}

fn from_token(token: u64) -> (usize, Port) {
    let stream = usize::try_from(token / 2).expect("eight streams");
    let port = if token.is_multiple_of(2) {
        Port::Source
    } else {
        Port::Destination
    };
    (stream, port)
}

impl Dma {
    /// Issues the next access of a stream, if it has one to make.
    ///
    /// One at a time: a stream is one AHB master, so the runtime answers the access it has before
    /// the next is asked for, and every answer comes back here to ask for the one after it.
    fn pump(
        &mut self,
        stream: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let Some(shape) = Self::shape(registers, stream) else {
            return;
        };
        if self.streams[stream].outstanding.is_some() {
            return;
        }
        if self.streams[stream].finish != Finish::Flushing && !Self::enabled(registers, stream) {
            return;
        }
        let Some(port) = self.next_port(stream, shape) else {
            // Section 10.3.12: "When this flush is completed, the transfer complete status bit
            // (TCIFx) ... is set." A flush is over when the FIFO no longer holds a whole
            // destination item, which is where the block itself may still have items left.
            if self.streams[stream].finish == Finish::Flushing {
                self.stop(stream, registers);
                self.refresh_interrupt(stream, registers, context);
            }
            return;
        };
        match port {
            Port::Source => {
                let address = if shape.direction.peripheral_is_the_source() {
                    self.streams[stream].peripheral_at
                } else {
                    self.streams[stream].memory_at
                };
                context.read_from(address, shape.source_width(), token(stream, port));
            }
            Port::Destination => {
                let width = shape.destination_width();
                let address = if shape.direction.peripheral_is_the_source() {
                    self.streams[stream].memory_at
                } else {
                    self.streams[stream].peripheral_at
                };
                let value = self.take(stream, width);
                self.report_fifo(stream, registers);
                context.write_to(address, width, value, token(stream, port));
            }
        }
        self.streams[stream].outstanding = Some(port);
    }

    /// Which port goes next, or neither.
    ///
    /// The destination goes whenever it can, so the FIFO drains at the threshold section 10.3.12
    /// sets rather than filling past it, and the source fills otherwise.
    fn next_port(&self, stream: usize, shape: Shape) -> Option<Port> {
        let state = &self.streams[stream];
        let source_bytes = u64::from(shape.source_width().bytes());
        let destination_bytes = u64::from(shape.destination_width().bytes());
        let level = u64::try_from(state.fifo.len()).expect("sixteen bytes");
        let room = u64::try_from(FIFO_BYTES).expect("sixteen bytes") - level;
        // A request is a level, and the stream serves it for as long as it stands. Section 10.3.2
        // has the peripheral release it when the controller reaches it, which is the access this is
        // about to make.
        let requested = state.inputs[shape.channel];

        // In flight in the destination's direction: the threshold in FIFO mode, and whatever is
        // left once the source has finished, which is section 10.3.12's tail.
        let drained = shape.direct
            || state.finish == Finish::Flushing
            || level >= shape.threshold
            || state.to_load == 0;
        let store_allowed = if shape.request_gates_the_destination() {
            requested
        } else {
            drained
        };
        if state.to_store > 0 && level >= destination_bytes && store_allowed {
            return Some(Port::Destination);
        }
        // Section 10.3.12: in direct mode there's no FIFO to fill. A memory-to-peripheral stream
        // "preloads only one data from the memory to the internal FIFO", and a peripheral-to-memory
        // one drains each item straight through, so neither ever holds more than one item.
        let load_allowed = match shape.direction {
            Direction::PeripheralToMemory => requested,
            Direction::MemoryToPeripheral => shape.direct || state.refilling,
            Direction::MemoryToMemory => true,
        } && (!shape.direct || level < destination_bytes);
        if state.finish != Finish::Flushing
            && state.to_load >= source_bytes
            && room >= source_bytes
            && load_allowed
        {
            return Some(Port::Source);
        }
        None
    }

    /// Puts `width` bytes of `value` into the FIFO, low byte first. The controller is little-endian
    /// both ways, section 10.3.10.
    fn give(&mut self, stream: usize, width: Width, value: u64) {
        for offset in 0..width.bytes() {
            let byte = u8::try_from((value >> (offset * 8)) & 0xFF).expect("one byte");
            self.streams[stream].fifo.push_back(byte);
        }
    }

    /// Takes `width` bytes out of the FIFO, oldest first as the low byte.
    fn take(&mut self, stream: usize, width: Width) -> u64 {
        (0..width.bytes())
            .map(|offset| {
                let byte = self.streams[stream].fifo.pop_front().unwrap_or(0);
                u64::from(byte) << (offset * 8)
            })
            .sum()
    }

    /// Writes the FIFO level into `FS`, section 10.5.10 bits 5:3.
    fn report_fifo(&mut self, stream: usize, registers: &mut RegisterFile) {
        let level = self.streams[stream].fifo.len();
        let encoding = match level {
            0 => 4,
            FIFO_BYTES => 5,
            partial => u64::try_from(partial / (FIFO_BYTES / 4)).expect("three quarters"),
        };
        modify(registers, stream, Row::Fifo, |fifo| {
            s0fcr::FS.set(fifo, encoding)
        });
    }

    /// Writes what the peripheral port has left into `NDTR`. The paragraph at the top says why.
    ///
    /// It stands still through a flush, because section 10.3.12 has it name the memory the good
    /// data reached rather than what the peripheral still owes.
    fn set_count(&mut self, stream: usize, registers: &mut RegisterFile, shape: Shape) {
        if self.streams[stream].finish == Finish::Flushing {
            return;
        }
        let state = &self.streams[stream];
        let remaining = if shape.direction.peripheral_is_the_source() {
            state.to_load
        } else {
            state.to_store
        };
        let items = remaining / u64::from(shape.peripheral_width.bytes());
        modify(registers, stream, Row::Count, |count| {
            s0ndtr::NDT.set(count, items)
        });
    }

    /// One access a stream asked for has landed.
    fn answered(
        &mut self,
        token: u64,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let (stream, port) = from_token(token);
        let Some(shape) = Self::shape(registers, stream) else {
            return;
        };
        // A stream stopped by a fault while its access was in flight isn't waiting for this one.
        // Section 10.3.18 clears the enable there, and the block is over.
        if self.streams[stream].outstanding != Some(port) {
            return;
        }
        self.streams[stream].outstanding = None;
        let peripheral_is_the_source = shape.direction.peripheral_is_the_source();
        match port {
            Port::Source => {
                let width = shape.source_width();
                self.give(stream, width, value);
                // A suspension zeroes what's left to load while an access may still be in flight,
                // and section 10.3.14 lets that one finish. It takes nothing further off the block.
                let taken = u64::from(width.bytes()).min(self.streams[stream].to_load);
                self.streams[stream].to_load -= taken;
                self.step(stream, peripheral_is_the_source, shape);
                let state = &mut self.streams[stream];
                if state.fifo.len() == FIFO_BYTES || state.to_load == 0 {
                    state.refilling = false;
                }
            }
            Port::Destination => {
                let width = shape.destination_width();
                // Section 10.3.10 and table 48: a count that isn't a whole number of destination
                // items is a configuration the manual forbids, and the last store of one would take
                // more than the block has left. It saturates rather than wrapping.
                let moved = u64::from(width.bytes());
                self.streams[stream].to_store -= moved.min(self.streams[stream].to_store);
                self.streams[stream].stored += moved;
                self.step(stream, !peripheral_is_the_source, shape);
                let state = &mut self.streams[stream];
                if u64::try_from(state.fifo.len()).expect("sixteen bytes") <= shape.threshold {
                    state.refilling = true;
                }
                if !state.halved && state.stored * 2 >= state.total {
                    self.streams[stream].halved = true;
                    set_flag(registers, stream, Flag::Half, true);
                }
            }
        }
        self.report_fifo(stream, registers);
        self.set_count(stream, registers, shape);
        if self.streams[stream].to_store == 0 {
            self.complete(stream, shape, registers);
        }
        self.refresh_interrupt(stream, registers, context);
        self.pump(stream, registers, context);
    }

    /// Steps the pointer of the port that just moved a beat, section 10.3.7.
    fn step(&mut self, stream: usize, peripheral: bool, shape: Shape) {
        let state = &mut self.streams[stream];
        if peripheral {
            if let Some(step) = shape.peripheral_step {
                state.peripheral_at = state.peripheral_at.wrapping_add(step);
            }
        } else if let Some(step) = shape.memory_step {
            state.memory_at = state.memory_at.wrapping_add(step);
        }
    }

    /// Section 10.3.15: a stream whose flow controller is the peripheral ends "when the peripheral
    /// requests the last transfer ... and when this transfer is complete", which is the signal seen
    /// and the request released. Section 10.3.13 has "the remaining data ... transferred from the
    /// FIFO into the memory" first. That's the flush a cleared `EN` runs, ended the same way.
    fn end_if_signaled(
        &mut self,
        stream: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let Some(shape) = Self::shape(registers, stream) else {
            return;
        };
        let state = &self.streams[stream];
        let control = held(registers, stream, Row::Control);
        if state.finish != Finish::Signaled
            || state.inputs[shape.channel]
            || state.outstanding.is_some()
            || !Self::enabled(registers, stream)
            || !s0cr::PFCTRL.is_set(control)
        {
            return;
        }
        self.streams[stream].finish = Finish::Flushing;
        self.pump(stream, registers, context);
    }

    /// The destination has taken the last byte of the block, section 10.3.13.
    fn complete(&mut self, stream: usize, shape: Shape, registers: &mut RegisterFile) {
        // Section 10.3.6: memory to memory has no circular mode, so it ends like every other block.
        let again = shape.circular
            && shape.direction != Direction::MemoryToMemory
            && self.streams[stream].finish != Finish::Flushing;
        if !again {
            self.stop(stream, registers);
            return;
        }
        set_flag(registers, stream, Flag::Complete, true);
        if shape.double_buffer {
            // Section 10.3.9: "at each end of transaction, the memory pointers are swapped".
            modify(registers, stream, Row::Control, |control| {
                s0cr::CT.set(control, u64::from(!s0cr::CT.is_set(control)))
            });
        }
        let state = &mut self.streams[stream];
        state.to_load = state.total;
        state.to_store = state.total;
        state.stored = 0;
        state.halved = false;
        self.set_count(stream, registers, shape);
        self.take_pointers(stream, registers, shape);
    }

    /// Raises a stream's own line while an enabled flag stands, RM0090 rev 22 table 51.
    fn refresh_interrupt(
        &mut self,
        stream: usize,
        registers: &RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let control = held(registers, stream, Row::Control);
        let fifo = held(registers, stream, Row::Fifo);
        let enabled = [
            (Flag::Fifo, s0fcr::FEIE.is_set(fifo)),
            (Flag::Direct, s0cr::DMEIE.is_set(control)),
            (Flag::Transfer, s0cr::TEIE.is_set(control)),
            (Flag::Half, s0cr::HTIE.is_set(control)),
            (Flag::Complete, s0cr::TCIE.is_set(control)),
        ];
        let wanted = Level::from(
            enabled
                .into_iter()
                .any(|(flag, on)| on && flag_stands(registers, stream, flag)),
        );
        if wanted == self.streams[stream].interrupt {
            return;
        }
        self.streams[stream].interrupt = wanted;
        context.interrupt(stream, wanted);
    }
}

/// The stream and register a layout row belongs to, or nothing for the four status registers.
fn stream_row(register: Register) -> Option<(usize, Row)> {
    let index = register.index().checked_sub(FIRST_STREAM_ROW)?;
    Some((index / ROWS_PER_STREAM, ROWS[index % ROWS_PER_STREAM]))
}

impl Dma {
    /// Takes what a stream's registers hold, so the next write can be told from what stood before.
    ///
    /// Besides the firmware, only this model writes a stream's registers, and every path that does
    /// one or the other ends here for the stream it touched, so the copy is current wherever it's
    /// read. Nothing is protected until a write has set `EN`, and that write ends here too.
    fn remember(&mut self, stream: usize, registers: &RegisterFile) {
        for row in ROWS {
            self.streams[stream].guarded[row as usize] = held(registers, stream, row);
        }
    }

    /// A written one clears its flag, RM0090 rev 22 sections 10.5.3 and 10.5.4.
    fn clear_flags(
        &mut self,
        clear: Register,
        written: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let (status, streams) = if clear == Register::Lifcr {
            (Register::Lisr, 0..STREAMS / 2)
        } else {
            (Register::Hisr, STREAMS / 2..STREAMS)
        };
        let standing = registers.get(status);
        registers.set(status, standing & !written);
        // Section 10.5.3 types every bit write-only and ST's file types the register read-write, so
        // what was written would otherwise stay where the part keeps nothing.
        registers.set(clear, 0);
        for stream in streams {
            self.refresh_interrupt(stream, registers, context);
        }
    }

    /// A write to one of a stream's six registers.
    fn write_stream(
        &mut self,
        stream: usize,
        row: Row,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let kept = self.streams[stream].guarded[row as usize];
        let running = s0cr::EN.is_set(self.streams[stream].guarded[Row::Control as usize]);
        let target = register(stream, row);
        match row {
            // Section 10.5.5 bit 0: "It is forbidden to write these registers when the EN bit is
            // read as 1." Most fields say so a second time themselves. `CIRC` doesn't, and is
            // protected here on that blanket sentence rather than on one of its own.
            Row::Control if running => {
                let open = s0cr::EN.mask()
                    | s0cr::DMEIE.mask()
                    | s0cr::TEIE.mask()
                    | s0cr::HTIE.mask()
                    | s0cr::TCIE.mask();
                registers.restore(target, !open, kept);
            }
            // Section 10.5.10 protects the threshold and the direct mode, not the interrupt enable.
            Row::Fifo if running => {
                registers.restore(target, !s0fcr::FEIE.mask(), kept);
            }
            Row::Memory0 | Row::Memory1 if running => {
                let control = held(registers, stream, Row::Control);
                let second_is_current = s0cr::CT.is_set(control);
                let current = (row == Row::Memory1) == second_is_current;
                if !s0cr::DBM.is_set(control) || current {
                    registers.set(target, kept);
                }
                // Section 10.3.9: writing the pointer in use is section 10.3.18's transfer error.
                if s0cr::DBM.is_set(control) && current {
                    self.fail(stream, Flag::Transfer, registers, context);
                }
                return;
            }
            _ if running => {
                registers.set(target, kept);
                return;
            }
            // Section 10.5.6: what a stream is enabled with, now and every time after.
            Row::Count => {
                self.streams[stream].programmed =
                    s0ndtr::NDT.get(held(registers, stream, Row::Count));
            }
            _ => {}
        }
        if row != Row::Control {
            return;
        }
        let now = Self::enabled(registers, stream);
        match (running, now) {
            (false, true) => self.start(stream, registers, context),
            (true, false) => self.suspend(stream, registers, context),
            _ => self.refresh_interrupt(stream, registers, context),
        }
    }
}

impl Device for Dma {
    type Register = Register;

    fn write(
        &mut self,
        register: Register,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        match register {
            Register::Lifcr | Register::Hifcr => {
                self.clear_flags(register, value, registers, context);
            }
            other => {
                if let Some((stream, row)) = stream_row(other) {
                    self.write_stream(stream, row, registers, context);
                    self.remember(stream, registers);
                }
            }
        }
    }

    /// A request one of the part's peripherals drives reaches the stream whose `CHSEL` selects the
    /// channel it arrives on, RM0090 rev 22 section 10.3.3.
    ///
    /// Every input keeps its level whether or not a stream is listening, so a stream enabled while
    /// a request already stands starts at once, which is what a level means.
    fn on_request(
        &mut self,
        change: RequestChange,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let high = change.level == Level::High;
        for wire in self
            .wiring
            .iter()
            .filter(|wire| wire.instance == change.instance && wire.request == change.request)
        {
            for &stream in wire.streams {
                self.streams[stream].inputs[wire.channel] = high;
                if high {
                    self.pump(stream, registers, context);
                } else {
                    self.end_if_signaled(stream, registers, context);
                }
                self.remember(stream, registers);
            }
        }
        if !high {
            return;
        }
        for wire in self
            .last_data
            .iter()
            .filter(|wire| wire.instance == change.instance && wire.request == change.request)
        {
            for &stream in wire.streams {
                if Self::shape(registers, stream).is_some_and(|shape| shape.channel == wire.channel)
                    && self.streams[stream].finish == Finish::Running
                {
                    self.streams[stream].finish = Finish::Signaled;
                }
                self.end_if_signaled(stream, registers, context);
                self.remember(stream, registers);
            }
        }
    }

    fn on_access(
        &mut self,
        token: u64,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        self.answered(token, value, registers, context);
        let stream = from_token(token).0;
        self.end_if_signaled(stream, registers, context);
        self.remember(stream, registers);
    }

    /// An access the bus wouldn't make is the bus error of RM0090 rev 22 section 10.3.18. The
    /// transfer error stands and hardware clears the enable, so the block ends where it is rather
    /// than leaving the stream waiting on an answer that's never coming.
    fn on_refused(
        &mut self,
        token: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let (stream, port) = from_token(token);
        if self.streams[stream].outstanding == Some(port) {
            self.fail(stream, Flag::Transfer, registers, context);
        }
        self.remember(stream, registers);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::soc::FieldSpec;
    use crate::soc::stm32f427::generated::dma2::REGISTERS;

    /// The layout is regular, which is what lets [`register`] find a row by arithmetic instead of a
    /// table of forty-eight names. RM0090 rev 22 section 10.5.5 gives the shape in as many words,
    /// "Address offset: 0x10 + 0x18 x stream number", and sections 10.5.6 to 10.5.10 put the other
    /// five a word apart after it. This is the generated table held to that.
    #[test]
    fn the_streams_registers_run_in_blocks_of_six() {
        const SUFFIXES: [&str; ROWS_PER_STREAM] = ["CR", "NDTR", "PAR", "M0AR", "M1AR", "FCR"];

        assert_eq!(
            REGISTERS.len(),
            FIRST_STREAM_ROW + STREAMS * ROWS_PER_STREAM,
            "four status registers and six to a stream"
        );
        for number in 0..STREAMS {
            for (index, row) in ROWS.into_iter().enumerate() {
                let spec = register(number, row).spec();
                assert_eq!(spec.name, format!("S{number}{}", SUFFIXES[index]));
                assert_eq!(
                    u64::from(spec.offset),
                    0x10 + 0x18 * number as u64 + 4 * index as u64
                );
            }
        }
    }

    /// Each stream's five flags sit where RM0090 rev 22 sections 10.5.1 and 10.5.2 put them: the
    /// low four streams in `LISR` and the high four in `HISR`, four groups to a register beginning
    /// at bits 0, 6, 16 and 22, and the same five flags at the same places inside each group.
    ///
    /// [`FLAGS`] is written out by hand against the generated table, and the shape above is read
    /// from the page. Two witnesses, so a row of that table pointing at the wrong stream's flag is
    /// caught here rather than by a transfer setting somebody else's bit.
    #[test]
    fn every_streams_flags_sit_where_the_manual_groups_them() {
        const GROUPS: [u8; 4] = [0, 6, 16, 22];
        const WITHIN: [(&str, u8); 5] = [
            ("FEIF", 0),
            ("DMEIF", 2),
            ("TEIF", 3),
            ("HTIF", 4),
            ("TCIF", 5),
        ];

        for number in 0..STREAMS {
            let status = status_of(number);
            assert_eq!(
                status,
                if number < 4 {
                    Register::Lisr
                } else {
                    Register::Hisr
                }
            );
            for (index, (name, within)) in WITHIN.into_iter().enumerate() {
                let field = FLAGS[number][index];
                assert_eq!(field.name, format!("{name}{number}"));
                assert_eq!(field.bit, GROUPS[number % 4] + within);
                assert_eq!(field.width, 1);
                assert!(
                    status
                        .spec()
                        .fields
                        .iter()
                        .any(|spec| spec.name == field.name),
                    "{} is not a field of {}",
                    field.name,
                    status.spec().name
                );
            }
        }
    }

    /// Every flag's clearing bit is at the flag's own position, RM0090 rev 22 sections 10.5.3 and
    /// 10.5.4, which is what lets a write to `LIFCR` be applied to `LISR` as a mask.
    #[test]
    fn every_flag_has_its_clearing_bit_at_the_same_position() {
        for (number, flags) in FLAGS.into_iter().enumerate() {
            let clearing: &[FieldSpec] = if number < 4 {
                Register::Lifcr.spec().fields
            } else {
                Register::Hifcr.spec().fields
            };
            for field in flags {
                let named = format!("C{}", field.name);
                let clear = clearing
                    .iter()
                    .find(|spec| spec.name == named)
                    .unwrap_or_else(|| panic!("{named} clears {}", field.name));
                assert_eq!(
                    clear.bit, field.bit,
                    "{named} is not where {} is",
                    field.name
                );
            }
        }
    }

    /// The encodings of the two fields the model reads as numbers rather than as flags,
    /// RM0090 rev 22 sections 10.5.5 bits 24:21 and 10.5.10 bits 1:0.
    #[test]
    fn the_burst_and_threshold_encodings_are_the_ones_the_manual_lists() {
        assert_eq!([0, 1, 2, 3].map(burst_beats), [1, 4, 8, 16]);
        assert_eq!([0, 1, 2, 3].map(threshold_bytes), [4, 8, 12, 16]);
        assert_eq!(
            [0, 1, 2].map(data_width),
            [Width::W8, Width::W16, Width::W32]
        );
    }

    /// Table 49 is one rule: a memory burst has to divide the threshold. Every "forbidden" cell of
    /// that table fails it and every cell that names a number of bursts passes, which is what says
    /// the rule and the table are the same statement.
    #[test]
    fn the_threshold_rule_is_table_forty_nine() {
        // (memory width in bytes, threshold in bytes, burst beats, what the table says)
        const TABLE: [(u64, u64, u64, bool); 12] = [
            (1, 4, 4, true),
            (1, 4, 8, false),
            (1, 8, 8, true),
            (1, 12, 8, false),
            (1, 16, 16, true),
            (2, 4, 4, false),
            (2, 8, 4, true),
            (2, 12, 4, false),
            (2, 16, 8, true),
            (4, 4, 4, false),
            (4, 12, 4, false),
            (4, 16, 4, true),
        ];

        for (width, threshold, beats, allowed) in TABLE {
            assert_eq!(
                threshold % (beats * width) == 0,
                allowed,
                "{beats} beats of {width} bytes against a threshold of {threshold}"
            );
        }
    }
}