rigless 0.2.2

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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The direct memory access controllers of RM0433 rev 9 chapter 15, written against the `dma1` layout.
//!
//! One layout serves both controllers, `DMA1` and `DMA2`, and they differ only in which of DMAMUX1's
//! sixteen channels their eight streams listen to: section 17.3.2 connects DMAMUX1 channels 0 to 7 to the
//! streams of `DMA1` and channels 8 to 15 to those of `DMA2`. A stream has no channel select of its own on
//! this part, so the `CHSEL` field of the STM32F4 stream control register is gone, and a stream hears one
//! request line and no other. Every citation is RM0433 rev 9 unless it names another document.
//!
//! 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.
//!
//! **What reaches what.** Table 3 gives the memory port and the peripheral port of each controller the
//! same slaves, every one of them except ITCM and DTCM. Both ports reach the memories, which is what
//! section 15.3.3 asks for memory-to-memory transfers, so a stream of either controller copies one memory
//! to another, unlike the STM32F4, where the first controller's peripheral port is not on the bus matrix.
//! Section 2.1.6 words it differently: it gives the memory bus the memories alone, where Table 3 also
//! gives it the peripherals. The model follows Table 3. A stream that addresses a tightly coupled memory
//! is refused by the bus matrix, and the manual's only word for a refused access is the bus error that
//! section 15.3.20 gives `TEIF`. The model ends the stream in that flag, and does not make the access
//! that would have landed in memory the controller cannot reach.
//!
//! **What the controller tells the multiplexer.** Section 15.3.4 has the controller send an acknowledge
//! to the peripheral as soon as it accesses it. The multiplexer counts served requests, section 17.4.4, so
//! the stream drives its request output `n` high and low again at the instant it makes the peripheral
//! access that serves a request. Output `n` is the acknowledge of stream `n`.
//!
//! **The counter follows the peripheral port.** Section 15.3.7 gives it the peripheral bus's width.
//! Section 15.3.15 ends a transfer when it "has reached zero in the memory-to-peripheral mode", where the
//! peripheral is the destination, and section 15.3.17's `0xFFFF - DMA_SxNDTR` counts what the peripheral
//! moved. The manual doesn't agree with itself about the instant. Section 15.3.4 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 15.3.14 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.
//!
//! **What the model handles and what falls to the register file.** Every register of the chapter has an
//! arm in [`Device::write`] and the model overrides no read, so the register file answers every read from
//! the values the model keeps in it. `DMA_LISR` and `DMA_HISR` are read-only and the file drops a write to
//! either. `DMA_LIFCR` and `DMA_HIFCR` take their write in the model, which applies it to the status
//! register and clears itself. The model owns the flags, the `FS` level, the counter, the enable and the
//! forced configuration bits, and it restores the write-protected registers while a stream runs.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | Request mapping | A stream hears DMAMUX1's output of its own index: `DMA1` streams 0 to 7 channels 0 to 7 and `DMA2` streams 0 to 7 channels 8 to 15. No other instance's request reaches it | 15.1, 15.3.5, 17.3.2 | `a_request_reaches_only_the_stream_of_its_multiplexer_channel` |
//! | Serving a peripheral | A stream takes a word off a peripheral, or gives one to it, while the request stands, and the access it makes is what clears the flag behind the request. The stream acknowledges each served request to the multiplexer | 15.3.4, 15.3.8 | `a_peripheral_to_memory_stream_is_driven_by_a_fake_peripherals_request_through_the_multiplexer`, `a_peripheral_drives_a_stream_each_way_and_the_words_come_back`, `every_served_request_is_acknowledged_to_the_multiplexer` |
//! | Either port on a peripheral | Both ports reach the bus matrix, so a stream moves words between two peripherals with no memory in between | 15.3.3, 15.3.8, Table 3 | `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 110 | 15.3.8, 15.5.5 | `each_direction_moves_its_block_between_the_right_two_ports` |
//! | Memory to memory | Runs as soon as the stream is enabled, with no request, on either controller | 15.3.3, 15.3.8, Table 3 | `memory_to_memory_copies_a_block_with_no_request_on_either_controller` |
//! | The boot loader's copy | A byte-wide memory-to-memory copy of 128 bytes from flash to SRAM, `CR` written whole and then `EN` set by a read-modify-write, and a spin on `EN` clearing | 15.3.8, 15.5.5 | `a_stream_copies_flash_to_ram_the_way_the_boot_loader_does` |
//! | Memory the controller cannot reach | A transfer whose access lies in ITCM or DTCM ends in `TEIF` with `EN` cleared, and nothing lands. The same transfer to any other memory runs | 2.1.6, Table 3, 15.3.20 | `a_transfer_into_the_tightly_coupled_memories_ends_in_a_transfer_error`, `a_transfer_from_the_tightly_coupled_memories_ends_in_a_transfer_error`, `every_other_memory_is_reachable` |
//! | 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 | 15.3.14, 15.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 | 15.3.8, 15.3.14 | `the_fifo_holds_bytes_until_the_threshold_and_then_drains`, `a_half_threshold_drains_eight_bytes_at_a_time`, `a_memory_to_peripheral_stream_reloads_the_fifo_at_its_threshold` |
//! | Packing | Source and destination widths differ and the bytes repack little-endian, Table 112 | 15.3.12 | `bytes_repack_between_two_widths_in_the_order_the_table_gives` |
//! | `FS` | The FIFO level as the encodings of section 15.5.10 give it | 15.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 | 15.3.9, 15.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 | 15.3.4, 15.3.16, 15.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 | 15.3.10 | `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 | 15.3.11 | `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 | 15.3.19 | `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 | 15.3.20, Table 114 | `a_stream_pointed_at_an_address_nothing_answers_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` | 15.5.3, 15.5.4 | `a_written_one_clears_its_own_flag_and_no_other` |
//! | Interrupts | Each stream raises its own line while an enabled flag stands: `DMA1` streams 0 to 6 on lines 11 to 17 and stream 7 on line 47, `DMA2` streams 0 to 4 on 56 to 60 and 5 to 7 on 68 to 70 | 15.4, Table 116, Table 147 | `each_enable_raises_the_streams_own_line`, `each_flag_raises_the_line_only_under_its_own_enable` |
//! | Suspension | Clearing `EN` ends the transfer, sets `TCIF`, and drains what the FIFO still holds toward memory | 15.3.14, 15.3.16 | `clearing_the_enable_flushes_what_the_fifo_holds`, `a_flush_writes_a_partial_last_item_at_the_memory_width` |
//! | `PFCTRL`, the peripheral as flow controller | The counter is forced to `0xFFFF` at the enable and circular mode is forced off. The stream ends when the counter reaches zero or `EN` is cleared, and `0xFFFF - NDTR` is what moved. Section 15.3.17 has the peripheral signal its last data and no instance of this part does, so that end is left out below | 15.3.17, 15.5.5 | `the_peripheral_as_flow_controller_forces_the_counter_and_forbids_circular` |
//! | Register protection | The configuration, counter and pointer registers take no write while `EN` stands. Bit 20 is held with them | 15.5.5, 15.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 | 15.3.19, 15.5.5, 15.5.10 | `enabling_a_stream_applies_every_rule_the_configuration_forces` |
//! | `TRBUFF` | Stored with the rest of `SxCR` and protected while the stream runs. It selects "bufferable transfers", which the model's accesses don't distinguish | 15.5.5 | `the_configuration_registers_take_no_write_while_the_stream_runs` |
//! | Reset | A system reset leaves every stream idle with an empty FIFO | 15.5.5 | `a_reset_leaves_every_stream_idle` |
//! | Determinism and the snapshot | Two runs of one script are one run, and the state serializes mid-transfer | none | `two_runs_of_one_script_are_the_same_run`, `the_model_state_round_trips_through_a_snapshot` |
//! | ES0392 rev 15 2.20.4 | Applicable to revision V, table 3 marking it `A`. A USART request served while a concurrent transfer occurs "may not be served and the DMA stream may stay locked". The workaround is `TRBUFF`. See the table below | ES0392 rev 15 | none |
//! | ES0392 rev 15 2.2.28 | Applicable to revision V, marked `A`. HASH input data may be corrupted when a HASH transfer shares a controller with another stream. The part has no HASH | ES0392 rev 15 | none |
//!
//! **What the model leaves out, and why.**
//!
//! | Behavior | Source | Reason |
//! |---|---|---|
//! | The arbiter, and `PL` as anything but a stored field | 15.3.6 | 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 | 15.3.20 | 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 | 15.3.20 | The same: both are the FIFO caught out by a bus that didn't grant in time. The threshold error of Table 114, 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 | 15.3.13 | Each beat is its own access, so nothing observes the lock. And a request here is the level section 15.3.4 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 114 is a configuration error and not a race |
//! | The peripheral signaling its last data | 15.3.17 | Table 109 lists no input for it and no instance of this part is named as able to signal it, so there is nothing to wire. A stream under `PFCTRL` runs until its counter reaches zero, or `EN` is cleared |
//! | The AHB error of a burst across a 1 Kbyte boundary | 15.3.13 | The section says the error "is not reported by the DMA registers", and each beat is its own access here |
//! | What the stream does when the bus matrix refuses a peripheral that is not clocked | 15.3.20 | The part gates an instance through the bus and the refusal comes back as the bus error of the same section, which is modeled |
//! | ES0392 rev 15 2.20.4: a stream locked by a USART request served during a concurrent transfer | ES0392 rev 15 | Applicable to revision V. The errata says only that the requested transfer "may not be served", gives no condition for a concurrent transfer and no instant, and the model would have to invent both. The workaround, setting `TRBUFF` on the stream that serves the serial port, is stored and held like the rest of `SxCR`. ArduPilot's driver sets it |
//! | ES0392 rev 15 2.2.28: HASH input data corrupted when DMA is used | ES0392 rev 15 | Applicable to revision V. The part has no HASH, so there is no HASH stream to corrupt. The workaround is also `TRBUFF` on the HASH stream |
//! | Clock gating and the reset registers | 8.7 | 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 15.5.3 types every bit of `DMA_LIFCR` and
//! `DMA_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 `DMA_SxFCR` no write
//! rule for `FS`, which section 15.5.10 types read-only, and the register file enforces that from the
//! table, so the model writes the level through [`RegisterFile::set`]. The file leaves out bit 20 of
//! `DMA_SxCR`, `TRBUFF`, which section 15.5.5 gives. The register file stores a bit no field covers, so
//! it lands and reads back, and the model protects it with the rest of the register.
//!
//! **Determinism.** The model reads no clock and draws nothing. `two_runs_of_one_script_are_the_same_run`
//! drives two benches through the same script and compares every register, the memory, the interrupts
//! and the whole state of each model.

use std::collections::VecDeque;

use crate::device::{Device, DeviceContext, Level, RegisterFile, RequestChange};
use crate::snapshot::store;
use crate::soc::stm32h743::generated::DMAMUX1;
use crate::soc::stm32h743::generated::dma1::{Register, hisr, lisr, s0cr, s0fcr, s0ndtr};
use crate::soc::{Layout, Width};

/// Streams per controller, section 15.2.
pub(crate) const STREAMS: usize = 8;

/// The first of DMAMUX1's channels that `DMA1`'s streams hear, section 17.3.2. Stream `n` hears channel
/// `n`.
pub const DMA1_FIRST_CHANNEL: usize = 0;

/// The first of DMAMUX1's channels that `DMA2`'s streams hear, section 17.3.2. Stream `n` hears channel
/// `8 + n`.
pub const DMA2_FIRST_CHANNEL: usize = 8;

/// A span of the address space, for the memory a controller cannot reach.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Span {
    /// The first address.
    pub(crate) base: u64,
    /// How many bytes it covers.
    pub(crate) bytes: u64,
}

impl Span {
    /// Whether an access of `bytes` at `address` touches the span.
    #[must_use]
    pub(crate) const fn overlaps(self, address: u64, bytes: u64) -> bool {
        address < self.base + self.bytes && address + bytes > self.base
    }

    /// Whether an access of `bytes` at `address` lies wholly inside the span.
    #[must_use]
    pub(crate) const fn holds(self, address: u64, bytes: u64) -> bool {
        address >= self.base && address + bytes <= self.base + self.bytes
    }
}

/// ITCM, 64 Kbytes at address zero, section 2.4.
pub(crate) const ITCM: Span = Span {
    base: 0x0000_0000,
    bytes: 64 << 10,
};

/// DTCM, 128 Kbytes at `0x2000_0000`, section 2.4.
pub(crate) const DTCM: Span = Span {
    base: 0x2000_0000,
    bytes: 128 << 10,
};

/// The memory neither port of either controller reaches, section 2.1.6: "all internal memories except
/// ITCM and DTCM", and Table 3 gives both masters of both controllers no path to either.
pub(crate) const UNREACHABLE: [Span; 2] = [ITCM, DTCM];

const FIFO_BYTES: usize = 16;

const FIRST_STREAM_ROW: usize = 4;
const ROWS_PER_STREAM: usize = 6;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Row {
    Control = 0,
    Count = 1,
    Peripheral = 2,
    Memory0 = 3,
    Memory1 = 4,
    Fifo = 5,
}

const ROWS: [Row; ROWS_PER_STREAM] = [
    Row::Control,
    Row::Count,
    Row::Peripheral,
    Row::Memory0,
    Row::Memory1,
    Row::Fifo,
];

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")
}

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,
    ],
];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Flag {
    Fifo = 0,
    Direct = 1,
    Transfer = 2,
    Half = 3,
    Complete = 4,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Direction {
    PeripheralToMemory,
    MemoryToPeripheral,
    MemoryToMemory,
}

impl Direction {
    fn of(encoding: u64) -> Option<Self> {
        match encoding {
            0 => Some(Self::PeripheralToMemory),
            1 => Some(Self::MemoryToPeripheral),
            2 => Some(Self::MemoryToMemory),
            _ => None,
        }
    }

    fn peripheral_is_the_source(self) -> bool {
        self != Self::MemoryToPeripheral
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Port {
    Source = 0,
    Destination = 1,
}

#[derive(Clone, Copy, Debug)]
struct Shape {
    direction: Direction,
    peripheral_width: Width,
    memory_width: Width,
    direct: bool,
    threshold: u64,
    circular: bool,
    double_buffer: bool,
    peripheral_step: Option<u64>,
    memory_step: Option<u64>,
    memory_beats: u64,
}

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
        }
    }

    fn request_gates_the_destination(self) -> bool {
        self.direction == Direction::MemoryToPeripheral
    }

    fn serves_a_request_on(self, port: Port) -> bool {
        matches!(
            (self.direction, port),
            (Direction::PeripheralToMemory, Port::Source)
                | (Direction::MemoryToPeripheral, Port::Destination)
        )
    }
}

fn data_width(encoding: u64) -> Width {
    match encoding {
        0 => Width::W8,
        1 => Width::W16,
        _ => Width::W32,
    }
}

fn burst_beats(encoding: u64) -> u64 {
    match encoding {
        0 => 1,
        other => 4 << (other - 1),
    }
}

fn threshold_bytes(encoding: u64) -> u64 {
    (encoding + 1) * 4
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Finish {
    Running,
    Flushing,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Phase {
    Neither,
    Refilling,
    Draining,
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Stream {
    peripheral_at: u64,
    memory_at: u64,
    fifo: VecDeque<u8>,
    to_load: u64,
    to_store: u64,
    stored: u64,
    total: u64,
    programmed: u64,
    outstanding: Option<Port>,
    requested: bool,
    halved: bool,
    finish: Finish,
    phase: Phase,
    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,
            requested: false,
            halved: false,
            finish: Finish::Running,
            phase: Phase::Neither,
            guarded: [0; ROWS_PER_STREAM],
            interrupt: Level::Low,
        }
    }
}

/// One direct memory access controller of an STM32H743, RM0433 rev 9 chapter 15.
#[derive(Debug)]
pub struct Dma {
    streams: [Stream; STREAMS],
    first_channel: usize,
}

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

impl Dma {
    /// A controller whose stream `n` hears DMAMUX1's channel `first_channel + n`: [`DMA1_FIRST_CHANNEL`]
    /// for `DMA1` and [`DMA2_FIRST_CHANNEL`] for `DMA2`, section 17.3.2.
    ///
    /// The part names the multiplexer a reader of requests, and the controller as a reader too, so the
    /// stream hears the level the channel drives. It names the controller as a reader for the
    /// multiplexer as well, which counts the acknowledges the stream drives on its own request outputs,
    /// output `n` for stream `n`.
    #[must_use]
    pub fn new(first_channel: usize) -> Self {
        Self {
            streams: std::array::from_fn(|_| Stream::default()),
            first_channel,
        }
    }
}

fn held(registers: &RegisterFile, stream: usize, row: Row) -> u64 {
    registers.get(register(stream, row))
}

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 {
    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));
        // 15.5.5 bit 15: PINCOS fixes the step at four, and `start` has already forced it low where it must.
        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)),
        })
    }

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

fn status_of(stream: usize) -> Register {
    if stream < STREAMS / 2 {
        Register::Lisr
    } else {
        Register::Hisr
    }
}

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)));
}

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

fn disable(registers: &mut RegisterFile, stream: usize) {
    modify(registers, stream, Row::Control, |control| {
        s0cr::EN.set(control, 0)
    });
}

fn reaches(address: u64, width: Width) -> bool {
    let bytes = u64::from(width.bytes());
    !UNREACHABLE.iter().any(|span| span.overlaps(address, bytes))
}

impl Dma {
    fn start(
        &mut self,
        stream: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let control = held(registers, stream, Row::Control);
        // Section 15.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);
        }
        if Direction::of(s0cr::DIR.get(control)) == Some(Direction::MemoryToMemory) {
            // 15.5.5 bit 5 and 15.5.10 bit 2: memory to memory forces the DMA flow and the FIFO.
            forced = s0cr::PFCTRL.set(forced, 0);
            modify(registers, stream, Row::Fifo, |fifo| {
                s0fcr::DMDIS.set(fifo, 1)
            });
        }
        // 15.5.5: direct mode forces MSIZE, both bursts and PINCOS, written back so a firmware reads what runs.
        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;
        };
        // Table 114: a threshold that isn't a whole number of memory bursts is a FIFO error at the enable.
        if !shape.direct
            && shape.threshold % (shape.memory_beats * u64::from(shape.memory_width.bytes())) != 0
        {
            self.fail(stream, Flag::Fifo, registers, context);
            return;
        }

        // 15.5.6: the counter reloads with the programmed value at each enable, and zero serves nothing.
        let programmed = self.streams[stream].programmed;
        modify(registers, stream, Row::Count, |count| {
            s0ndtr::NDT.set(count, programmed)
        });
        // 15.3.17: the peripheral as flow controller forces the counter to its maximum.
        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;
        // 15.3.8: the stream at once fills the FIFO entirely.
        stream_state.phase = Phase::Refilling;
        stream_state.outstanding = None;
        self.take_pointers(stream, registers, shape);
        self.report_fifo(stream, registers);
        self.pump(stream, registers, context);
    }

    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);
    }

    fn fail(
        &mut self,
        stream: usize,
        flag: Flag,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        set_flag(registers, stream, flag, true);
        disable(registers, stream);
        let state = &mut self.streams[stream];
        state.outstanding = None;
        state.to_load = 0;
        state.to_store = 0;
        state.fifo.clear();
        state.finish = Finish::Running;
        self.report_fifo(stream, registers);
        self.refresh_interrupt(stream, registers, context);
    }

    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);
    }

    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);
    }
}

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)
}

fn acknowledge(context: &mut DeviceContext<'_>, stream: usize) {
    context.request(stream, Level::High);
    context.request(stream, Level::Low);
}

impl Dma {
    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 {
            // 15.3.14: a flush ends with TCIF once the FIFO is empty.
            if self.streams[stream].finish == Finish::Flushing {
                self.stop(stream, registers);
                self.refresh_interrupt(stream, registers, context);
            }
            return;
        };
        let (width, address) = match port {
            Port::Source if shape.direction.peripheral_is_the_source() => {
                (shape.source_width(), self.streams[stream].peripheral_at)
            }
            Port::Source => (shape.source_width(), self.streams[stream].memory_at),
            Port::Destination if shape.direction.peripheral_is_the_source() => {
                (shape.destination_width(), self.streams[stream].memory_at)
            }
            Port::Destination => (
                shape.destination_width(),
                self.streams[stream].peripheral_at,
            ),
        };
        if !reaches(address, width) {
            self.fail(stream, Flag::Transfer, registers, context);
            return;
        }
        if shape.serves_a_request_on(port) {
            acknowledge(context, stream);
        }
        match port {
            Port::Source => context.read_from(address, width, token(stream, port)),
            Port::Destination => {
                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);
    }

    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 served while it stands, and the peripheral releases it at the access (15.3.4).
        let requested = state.requested;

        // The destination drains at the threshold, or whatever is left once the source is done (15.3.14).
        let drained = shape.direct
            || state.finish == Finish::Flushing
            || state.phase == Phase::Draining
            || level >= shape.threshold
            || state.to_load == 0;
        let store_allowed = if shape.request_gates_the_destination() {
            requested
        } else {
            drained
        };
        let partial_tail = state.finish == Finish::Flushing && level > 0;
        if state.to_store > 0 && (level >= destination_bytes || partial_tail) && store_allowed {
            return Some(Port::Destination);
        }
        // 15.3.14: direct mode holds one item, preloaded for memory to peripheral.
        let load_allowed = match shape.direction {
            Direction::PeripheralToMemory => requested,
            Direction::MemoryToPeripheral => shape.direct || state.phase == Phase::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
    }

    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);
        }
    }

    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()
    }

    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)
        });
    }

    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)
        });
    }

    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 a fault stopped isn't waiting for this answer.
        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);
                // 15.3.16: a suspension lets the access in flight finish and takes nothing more 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];
                let level = u64::try_from(state.fifo.len()).expect("sixteen bytes");
                if shape.direction == Direction::MemoryToPeripheral {
                    if state.fifo.len() == FIFO_BYTES || state.to_load == 0 {
                        state.phase = Phase::Neither;
                    }
                } else if level >= shape.threshold {
                    state.phase = Phase::Draining;
                }
            }
            Port::Destination => {
                let width = shape.destination_width();
                // Table 113 forbids a count that isn't whole destination items, so the count saturates.
                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];
                let level = u64::try_from(state.fifo.len()).expect("sixteen bytes");
                if shape.direction == Direction::MemoryToPeripheral {
                    if level <= shape.threshold {
                        state.phase = Phase::Refilling;
                    }
                } else if level < moved {
                    state.phase = Phase::Neither;
                }
                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);
    }

    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);
        }
    }

    fn complete(&mut self, stream: usize, shape: Shape, registers: &mut RegisterFile) {
        // Section 15.3.8: 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 15.3.11: "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);
    }

    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);
    }
}

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 {
    fn remember(&mut self, stream: usize, registers: &RegisterFile) {
        for row in ROWS {
            self.streams[stream].guarded[row as usize] = held(registers, stream, row);
        }
    }

    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);
        // 15.5.3 types the clear register write-only, so it reads zero.
        registers.set(clear, 0);
        for stream in streams {
            self.refresh_interrupt(stream, registers, context);
        }
    }

    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 {
            // 15.5.5 bit 0 forbids writing these while EN reads 1, and `CIRC` is held on that sentence.
            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 15.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 15.3.11: writing the pointer in use is section 15.3.20'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 15.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);
                    self.refresh_interrupt(stream, registers, context);
                }
            }
        }
    }

    /// The level DMAMUX1 drives on the channel a stream listens to is the stream's request, RM0433
    /// rev 9 sections 15.1 and 17.3.2. Every other instance's request is somebody else's.
    ///
    /// The level is kept whether or not the stream is enabled, 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<'_>,
    ) {
        if change.instance != DMAMUX1.name {
            return;
        }
        let Some(stream) = change
            .request
            .checked_sub(self.first_channel)
            .filter(|stream| *stream < STREAMS)
        else {
            return;
        };
        let high = change.level == Level::High;
        self.streams[stream].requested = high;
        if high {
            self.pump(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);
        self.remember(from_token(token).0, registers);
    }

    /// An access the bus wouldn't make is the bus error of RM0433 rev 9 section 15.3.20. 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);
    }

    /// A system reset leaves every stream idle with an empty FIFO and no request standing.
    fn reset(&mut self) {
        self.streams = std::array::from_fn(|_| Stream::default());
    }
}

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

    /// The layout is regular, which is what lets [`register`] find a row by arithmetic instead of a
    /// table of forty-eight names. RM0433 rev 9 section 15.5.5 gives the shape in as many words,
    /// "Address offset: 0x010 + 0x18 * x", and sections 15.5.6 to 15.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 RM0433 rev 9 sections 15.5.1 and 15.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, RM0433 rev 9 sections 15.5.3 and
    /// 15.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 fields the model reads as numbers rather than as flags, RM0433 rev 9
    /// sections 15.5.5 bits 24:21 and 15.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 114 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_one_hundred_fourteen() {
        // (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}"
            );
        }
    }

    /// The controllers hear the multiplexer's sixteen channels in two halves, section 17.3.2, and the
    /// spans the controllers cannot reach are the two tightly coupled memories at the addresses the
    /// part's map gives them.
    #[test]
    fn the_wiring_constants_are_the_manuals() {
        for (span, name) in [(ITCM, "itcm"), (DTCM, "dtcm")] {
            let region = crate::soc::stm32h743::MEMORY
                .iter()
                .find(|region| region.name == name)
                .unwrap_or_else(|| panic!("the map has {name}"));
            assert_eq!(
                (span.base, span.bytes),
                (region.base, region.size),
                "{name}"
            );
        }
        assert!(ITCM.overlaps(0xFFFF, 1));
        assert!(!ITCM.overlaps(0x1_0000, 4), "the first byte past the end");
        assert!(ITCM.overlaps(0xFFFE, 4), "an access that straddles the end");
        assert!(
            DTCM.overlaps(0x1FFF_FFFE, 4),
            "and one that straddles the start"
        );
    }

    #[derive(Debug, Default)]
    struct Ram(std::collections::BTreeMap<u64, u8>);

    impl crate::emulator::Memory for Ram {
        fn read(&mut self, address: u64, width: Width) -> Result<u64, crate::emulator::Error> {
            Ok((0..u64::from(width.bytes()))
                .map(|offset| {
                    u64::from(self.0.get(&(address + offset)).copied().unwrap_or(0)) << (offset * 8)
                })
                .sum())
        }

        fn write(
            &mut self,
            address: u64,
            width: Width,
            value: u64,
        ) -> Result<(), crate::emulator::Error> {
            for offset in 0..u64::from(width.bytes()) {
                let byte = u8::try_from((value >> (offset * 8)) & 0xFF).expect("one byte");
                self.0.insert(address + offset, byte);
            }
            Ok(())
        }
    }

    /// The model's state serializes mid-block, with a byte in the FIFO and the counters part way down.
    #[test]
    fn the_model_state_round_trips_through_a_snapshot() {
        use crate::device::RequestChange;
        use crate::mcu::{Operate, Single};
        use crate::snapshot;
        use crate::time::VirtualNanos;

        const AT: VirtualNanos = VirtualNanos(0);
        let mut soc = Single::new(
            crate::soc::stm32h743::builder(),
            "DMA1",
            Dma::new(DMA1_FIRST_CHANNEL),
        )
        .expect("the bus builds");
        let mut memory = Ram::default();
        let base = crate::soc::stm32h743::generated::DMA1.base;
        let address = |register: Register| base + u64::from(register.spec().offset);
        let write = |soc: &mut Single<Dma>, register: Register, value: u64| {
            soc.write(AT, address(register), Width::W32, value)
                .expect("the controller answers");
        };
        write(
            &mut soc,
            Register::S2fcr,
            s0fcr::DMDIS.set(s0fcr::FTH.set(0, 3), 1),
        );
        write(&mut soc, Register::S2par, 0x3000_0000);
        write(&mut soc, Register::S2m0ar, 0x3000_1000);
        write(&mut soc, Register::S2ndtr, 16);
        write(
            &mut soc,
            Register::S2cr,
            s0cr::MINC.set(s0cr::EN.set(0, 1), 1),
        );
        for level in [Level::High, Level::Low] {
            soc.drive(AT, |model, registers, context| {
                let change = RequestChange {
                    instance: "DMAMUX1",
                    request: 2,
                    level,
                };
                model.on_request(change, registers, context);
            });
        }
        soc.settle(&mut memory).expect("the memory answers");
        assert_eq!(
            soc.model.streams[2].fifo.len(),
            1,
            "one byte is in the FIFO"
        );

        let saved = snapshot::stored(&soc.model).expect("the model serializes");
        let mut restored = Dma::new(DMA1_FIRST_CHANNEL);
        snapshot::load(&mut restored, snapshot::keep(saved)).expect("and deserializes");
        assert_eq!(format!("{restored:?}"), format!("{:?}", soc.model));
    }
}