rigless 0.3.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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The embedded flash memory interface of RM0433 rev 9 chapter 4, written against the `flash` layout.
//!
//! The chapter serves the STM32H742, H743 and H753, which have two banks of 1 Mbyte, and the H750 with
//! one sector. This is the first. Each bank has a key, control, status and clear register of its own,
//! a write buffer and a queue, and the registers neither bank owns, `FLASH_ACR`, the option registers
//! and the CRC result, are one register each at two addresses, section 4.3.13 and its Table 20.
//! Bank 1's registers govern the lower megabyte of the array and bank 2's the upper, always, which a
//! row of the left-out table below qualifies for `SWAP_BANK`. Every citation is RM0433 rev 9 unless it
//! names another document.
//!
//! The firmware cannot write the array. Its stores reach this model through the part's
//! `programmed_by("Flash")` region, [`Device::write_region`], and the model changes the array only by
//! asking the runtime to program it, [`DeviceContext::program`], in pieces of 8 bytes.
//!
//! **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. The register file answers all reads from
//! the values the model keeps in it. The registers whose write the file already settles once the part
//! has corrected them, `FLASH_SR1`, `FLASH_SR2`, the current option registers, `FLASH_CRCDATAR` and the
//! two `FLASH_ECC_FAxR`, have an arm that does nothing. Everything else is the model's: the key
//! sequences, the freezing of a locked register, the write buffer, the queues, the timing, the flags
//! and the interrupt, and the option bytes.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | Reset state | `CR1` and `CR2` locked with `PSIZE` x64, `ACR` at 7 wait states and `WRHIGHFREQ` 3, `OPTCR` locked, the option registers at Table 21's factory bytes, every other register zero but `CRCCR1`/`CRCCR2` at `0x001C_0000` | 4.9.1, 4.9.4, 4.9.7, 4.9.19, 4.9.25, 4.9.34, 4.9.38, Table 21, Table 28 | `reset_values_match_the_manual`, `the_factory_option_bytes_are_table_21s_by_field`, `the_models_seed_of_every_register_is_what_the_bus_resets_it_to` |
//! | Registers at two addresses | `ACR`, `OPTKEYR`, `OPTCR`, `OPTSR_CUR`, `OPTSR_PRG`, `OPTCCR`, `BOOT_CURR`, `BOOT_PRGR` and `CRCDATAR` are one register under the offset and the offset plus `0x100`, so a write to either shows at both | 4.3.13, Table 20 | `a_common_register_answers_alike_at_both_addresses`, `a_fresh_model_given_the_committed_bytes_reads_what_the_old_one_did` |
//! | Two banks | Each bank's registers, buffer, queue and sectors are its own, and the two run at once | 4.3.4, 4.3.11, Table 15 | `the_two_banks_program_in_parallel_with_registers_of_their_own`, `a_bank_that_is_busy_longer_finishes_after_the_other`, `bank_two_lays_its_registers_out_as_bank_one_does`, `a_bank_two_sector_erases_like_bank_one` |
//! | `ACR` `LATENCY`, `WRHIGHFREQ` | Stored, the reserved bits above them reading zero. No check against Table 17, which needs the clock and the supply, and the hardware makes none either | 4.9.1, 4.3.8 | `latency_and_wrhighfreq_are_stored` |
//! | `WRHIGHFREQ` or `PSIZE` changed under an operation | Told: "Modifying ... while programming/erasing the flash memory might corrupt the flash memory content." The write has landed and there is nothing to refuse | 4.3.9 | `changing_wrhighfreq_under_an_operation_is_told`, `changing_psize_under_an_operation_is_told` |
//! | `KEYR1`, `KEYR2` unlock | `KEY1` then `KEY2` clears `LOCK1` or `LOCK2`. The key registers are write-only and read zero | 4.5.1, 4.9.2, 4.9.24 | `the_unlock_sequence_clears_lock_of_its_own_bank_alone`, `the_key_and_clear_registers_read_zero` |
//! | A wrong sequence | A wrong second key, a first word that is not `KEY1`, a third key, or the sequence performed twice locks the register until the next system reset, and the model tells the session once, on the write that did it, since it cannot give the bus error | 4.5.1, 4.9.4, 4.9.25 | `a_wrong_second_key_locks_the_register_until_reset`, `a_wrong_first_key_locks_the_register_until_reset`, `unlocking_twice_or_a_third_key_locks_the_register_until_reset` |
//! | A write between the keys | A write to another register of the bank, before `KEY2`, locks the control register until reset. Another bank's registers and the common ones are not that bank's | 4.5.1 | `a_write_to_another_register_of_the_bank_between_the_keys_locks_it` |
//! | `LOCK1`, `LOCK2` | Type `rs`: written one sets it, written zero does nothing, and only the unlock sequence clears it. Setting it changes no other bit | 4.9.4, 4.9.25 | `lock_is_written_one_only_and_a_new_unlock_follows` |
//! | `CR1`, `CR2` frozen while locked | Every field but `LOCK` takes a write only while `LOCK` is clear: the enables, `PG`, `SER`, `BER`, `PSIZE`, `FW`, `START`, `SNB`, `CRC_EN` | 4.5.1, 4.9.4, 4.9.25, Table 22 | `the_control_register_is_frozen_while_locked` |
//! | `OPTKEYR` unlock | `OPTKEY1` then `OPTKEY2` clears `OPTLOCK`, at either address. A wrong sequence, a third key, or any other register written between the keys locks it until reset, and the session is told | 4.5.1, 4.9.3, 4.9.7 | `the_option_unlock_sequence_clears_optlock`, `a_wrong_option_key_locks_the_option_registers_until_reset`, `a_third_option_key_or_a_stray_write_between_the_keys_locks_the_option_registers` |
//! | `CR` `PG` and the write buffer | With `PG` set, stores into the bank fill its 256-bit buffer for one 32-byte word, in stores of 8, 16, 32 or 64 bits. A store that runs across two words is two stores | 4.3.9, 4.3.3 | `wbne_stands_while_the_buffer_is_partial`, `stores_of_every_width_fill_the_word`, `a_store_across_two_words_finishes_one_and_starts_the_next` |
//! | `SR` `WBNE` | Stands while the buffer is partial, and clears when it fills, when `FW` forces it, when an error drops it, or when `PG` clears | 4.9.5, 4.6.2, 4.3.9 | `wbne_stands_while_the_buffer_is_partial`, `clearing_pg_drops_a_partial_word`, `fw_forces_a_partial_word_with_ones_in_the_rest` |
//! | `CR` `FW` | Forces the buffer out with the bytes not written set to ones, and clears itself. No effect on an empty buffer, nor where nothing in it is cleared | 4.3.9, 4.9.4 | `fw_forces_a_partial_word_with_ones_in_the_rest`, `fw_has_no_effect_on_an_empty_buffer_or_one_with_nothing_cleared` |
//! | `CR` `PG` cleared | Disables the buffer and drops what it holds that was not sent to the queue | 4.9.4, 4.6.2 | `clearing_pg_drops_a_partial_word` |
//! | A program | A full word is queued, `QW` and `BSY` stand for the datasheet's time by `PSIZE`, then the word lands and `EOP` is set. The time is the typical programming time of x8, x16, x32 and x64 | 4.3.9, 4.9.5, Table 18, DS12110 rev 11 table 140 | `a_word_programs_after_its_time_by_psize`, `words_queued_behind_one_another_program_in_turn` |
//! | Programming only clears bits | The word lands as what the cells held and the new data both ask for, so a word programmed over holds the bits of both. The model reads the word at the end of the time to know the first. The inconsistent ECC the hardware leaves is a later read's, which the model never sees | 4.3.9, 4.3.12 | `programming_a_word_that_is_not_virgin_only_clears_bits` |
//! | A program the runtime refuses | An operation error, `OPERR`, with no `EOP`, and the bank is free again | 4.7.6 | `a_program_the_runtime_refuses_is_an_operation_error`, `an_erase_the_runtime_refuses_is_an_operation_error` |
//! | `PGSERR` | A store with `PG` clear is rejected with no bus error and flagged, the buffer is flushed. A standing `PGSERR` blocks any new program. A standing `INCERR` makes the next store a `PGSERR` | 4.3.9, 4.7.3 | `a_store_without_pg_is_rejected_with_pgserr_and_no_bus_error`, `a_standing_pgserr_blocks_stores_until_cleared`, `a_store_to_another_word_is_incerr_and_a_standing_incerr_makes_the_next_pgserr` |
//! | `INCERR` | A store to another word before the buffer is full is flagged. The partial word and the store that caused it are lost, which is the model's own reading: 4.7.5 does not say what the buffer holds afterward, and its recovery steps end "Restart the write operations where they have been interrupted", which has a driver send the word again from its start | 4.7.5 | `a_store_to_another_word_is_incerr_and_a_standing_incerr_makes_the_next_pgserr` |
//! | `STRBERR` | A byte written twice is flagged, the new byte replaces the old and the word goes on filling | 4.7.4 | `a_byte_written_twice_is_strobe_error_and_the_new_byte_replaces_the_old` |
//! | `WRPERR` on a program | Checked "just before the effective write operation", so as the queue reaches the word. A sector write-protected, in a valid PCROP area or in a valid secure-only area cancels it and nothing changes. The flag blocks nothing | 4.3.9, 4.5.2, 4.7.2 | `programming_a_write_protected_sector_is_canceled_with_wrperr` |
//! | The queue | A bank runs one operation at a time, in order. A word can be prepared while an erase runs | 4.3.9, 4.3.10, 4.9.4 | `a_program_waits_in_the_queue_behind_an_erase`, `erases_queued_in_a_bank_run_one_after_the_other` |
//! | `CR` `SER`, `SNB`, `START` | A sector erase of the 128 Kbyte sector `SNB` names, `QW` and `BSY` standing for the datasheet's typical sector erase time by `PSIZE`, then the sector reads all ones and `EOP` is set. `START` clears when the erase is acknowledged, which the model takes as the write that set it | 4.3.10, 4.9.4, DS12110 rev 11 table 140 | `a_sector_erase_takes_the_datasheets_time_by_psize` |
//! | `CR` `BER` | A bank erase of all eight sectors, which beats `SER` when both are set. It takes the datasheet's mass erase time by `PSIZE`: the datasheet gives none for one bank, and a mass erase is two bank erases at once | 4.3.10, 4.9.4, DS12110 rev 11 table 140 | `a_bank_erase_takes_the_mass_erase_time_by_psize`, `ber_beats_ser` |
//! | `START` with neither `SER` nor `BER` | Acknowledged and nothing starts, the manual saying nothing of it | 4.9.4 | `start_with_neither_sector_nor_bank_asked_starts_nothing` |
//! | `WRPERR` on an erase | A sector erase of a sector write-protected, or touched by a valid PCROP or secure-only area, is canceled with `WRPERR`, and so is a bank erase with any such sector, nothing being erased. A PCROP area whose start equals its end covers the bank, and one whose end is below its start covers nothing. A secure-only area counts only with `SECURITY` set. **The manual conflicts on the bank erase.** Section 4.3.10's standard bank erase and mass erase sequences erase "all bank sectors except for those containing secure-only and protected data", which reads as skipping the protected sectors. Section 4.5.2 says "a bank erase cannot be performed if one sector is write-protected", the `BER` note in 4.9.4 says "Write protection error is triggered when a bank erase is required and some sectors are protected", and sections 4.5.4 and 4.5.5 say "No mass erase can be performed if a single valid PCROP area is defined" and the same of a secure-only area. The model follows the three that say the erase cannot be performed, and raises `WRPERR` for it, since the register page gives the flag. It takes 4.3.10's phrase as naming what the sequence is for | 4.3.10, 4.5.2, 4.5.4, 4.5.5, 4.7.2, 4.9.4, 4.9.11, 4.9.13 | `an_erase_of_a_write_protected_sector_is_canceled_with_wrperr`, `a_pcrop_area_protects_every_sector_it_touches`, `an_area_whose_start_equals_its_end_covers_the_bank`, `a_secure_only_area_protects_its_sectors_only_with_security_set` |
//! | `OPTCR` `MER` | Sets `BER` and `START` of the banks whose control register is unlocked, a bank erase on each at once. That is the model's reading: 4.9.7 says `MER` "automatically sets BER1, BER2, START1 and START2" and that `FLASH_CR1` and `FLASH_CR2` "must be unlocked", and says nothing of a locked one, so a locked bank keeps its bits and does not erase. `OPTCR` must be unlocked. `MER` reads zero. A mass erase being two bank erases, a bank with a protected sector or a valid PCROP or secure-only area refuses its own with `WRPERR` and the other goes on. That is the model's reading of 4.5.4 and 4.5.5, "No mass erase can be performed" with such an area, since each bank has its own flag to raise | 4.3.10, 4.5.4, 4.5.5, 4.9.7 | `mer_erases_both_banks`, `mer_needs_the_option_register_and_each_banks_control_register_unlocked`, `a_mass_erase_with_one_bank_protected_erases_only_the_other`, `a_mass_erase_with_a_pcrop_area_in_one_bank_erases_only_the_other` |
//! | Erase with protection removal | A bank erase whose programming registers ask for no PCROP or secure-only area, with `DMEP` and `DMES` set where the area exists, and every sector writable, and which changes no other option byte, erases the protected sectors too and then makes those protection words current. Otherwise it is a simple bank erase and `WRPERR` refuses it. The same for a mass erase over both banks. The automatic change takes no time of its own | 4.3.10, 4.4.3 | `a_bank_erase_with_protection_removal_erases_protected_sectors_and_lifts_the_protection`, `a_bank_erase_that_changes_another_option_byte_is_a_simple_erase`, `a_mass_erase_with_protection_removal_erases_both_banks_and_lifts_the_protection` |
//! | `SR` flags | Every bit is `r`, so a write leaves the register as it was. `BSY`, `QW`, `WBNE` and `CRC_BUSY` are hardware's, `BSY` and `QW` standing from the queue and the running operation | 4.9.5, 4.9.26 | `the_status_registers_ignore_writes`, `wbne_stands_while_the_buffer_is_partial` |
//! | `CCR` | A written one clears its flag, and the register reads zero | 4.9.6, 4.9.27 | `ccr_clears_the_flag_of_each_bit_written_and_reads_zero` |
//! | `EOP` | Set when a program, an erase or an option change completes, whether or not `EOPIE` is set, and not for one that was canceled. Section 4.8's "End-of-program event", on page 200, names all three: "an interrupt at the end of an erase operation, a program operation or an option byte change on bank 1/2. The EOP1/2 bit in the `FLASH_SR1/2` register is also set when one of these events occurs." The `EOP1` page and Table 27 say "programming operation" alone, and the model follows 4.8 | 4.8, 4.9.5, Table 27 | `eop_is_set_either_way_and_the_interrupt_follows_eopie`, `a_word_programs_after_its_time_by_psize`, `a_sector_erase_takes_the_datasheets_time_by_psize`, `optstart_commits_the_programming_registers_when_its_time_is_up` |
//! | The flash interrupt | One interrupt, position zero of the instance's table, which is line 4. It stands while any flag of either bank stands with its enable set, and `OPTCHANGEERR` with `OPTCHANGEERRIE`, and lowers when the flag clears or the enable does | 4.8, Table 27, Table 147 | `the_flash_interrupt_follows_each_flag_and_its_enable`, `the_interrupt_stays_up_while_either_bank_has_a_flag`, `every_flag_sits_where_the_manual_puts_it` |
//! | `OPTSR_PRG` and the other programming registers | Written only while `OPTLOCK` is clear, and only in the bits the manual defines, the reserved ones keeping their value | 4.4.3, 4.5.1, Table 22 | `the_option_registers_are_frozen_while_optlock_stands` |
//! | `OPTCR` frozen while locked | `OPTCHANGEERRIE`, `MER` and `OPTSTART` take a write only while `OPTLOCK` is clear. `OPTLOCK` is `rs` and `SWAP_BANK` is `r` | 4.9.7 | `the_option_registers_are_frozen_while_optlock_stands`, `the_option_unlock_sequence_clears_optlock`, `the_corrected_fields_are_what_the_part_declares` |
//! | `OPTCR` `OPTSTART` | Programs the option bytes: `OPTSTART` clears at once, `OPT_BUSY` stands for the time, and then the current registers hold the programming ones. The operation is bank 1's, so `BSY1` and `QW1` stand for it and `EOP1` marks its end. Nothing happens where no programming register differs from its current one | 4.4.3, 4.9.7, 4.9.8, 4.9.5 | `optstart_commits_the_programming_registers_when_its_time_is_up`, `optstart_with_nothing_to_program_does_nothing` |
//! | The current option registers | Read-only, and read-only whatever the model's state | 4.9.8, 4.9.11, 4.9.13, 4.9.15, 4.9.17 | `the_current_option_registers_and_the_results_ignore_writes` |
//! | `BOOT_PRGR` | Written like the other programming registers, though the vendor's file makes it read-only. `BOOT_ADD0` and `BOOT_ADD1` are stored and committed | 4.9.17, 4.9.18 | `boot_prgr_takes_a_write_though_the_vendors_file_makes_it_read_only` |
//! | Writes during an option change | "All write accesses to flash registers are blocked until the option byte change completes." The model cannot stall the core, so it holds each write and applies them in order when the change ends | 4.9.7, 4.9.8 | `writes_made_during_an_option_change_land_when_it_ends`, `held_writes_replay_against_the_state_the_one_before_them_left` |
//! | `OPTCHANGEERR`, `OPTCCR` | A change that 4.4.3 refuses sets `OPTCHANGEERR`, nothing is programmed, the current registers keep the area, and the programming registers keep what was written. At level 2 it is anything but the bank swap. The area rules are these: removing or reducing a valid PCROP or secure-only area, or clearing `DMEP` or `DMES`, needs a level 1 to level 0 regression in the same change, and removing or reducing an area needs its erase enable set in the current or the programming register, or `OPTCHANGEERR`. Clearing `SECURITY` with an area standing needs a regression and every standing area's erase enable set. The manual says "removed or reduced" of a PCROP area and "removed" of a secure-only area, and the model takes both alike. `CLR_OPTCHANGEERR` clears the flag at either address | 4.4.3, 4.7.11, 4.9.10, 4.5.3 | `at_level_2_a_change_is_an_option_change_error_but_the_bank_swap`, `an_option_change_that_breaks_the_area_rules_is_an_option_change_error`, `a_level_regression_may_remove_an_area_with_its_erase_enable_set` |
//! | `SWAP_BANK` | Loaded from `SWAP_BANK_OPT` at a system reset, and read-only. A commit changes the option and not the bit | 4.3.13, 4.9.7, 4.9.8 | `swap_bank_is_loaded_from_the_option_bytes_at_reset` |
//! | Option bytes across a reset | The option registers read what the last completed commit left, `OPTLOCK` is set again, and a reset during a commit leaves the old bytes. [`Flash::keep_options`] is the part's call after a reset | 4.3.14, 4.4.3 | `the_option_registers_survive_a_system_reset`, `a_reset_during_a_commit_keeps_the_bytes_the_last_commit_left`, `a_reset_drops_what_was_pending` |
//! | `CRCCR`, `CRCSADD`, `CRCEADD`, `CRCDATAR` | `CRCCR` takes a write only while `CRC_EN` is set, its start and clear bits read zero, `CLEAN_CRC` clears the result, and clearing `CRC_EN` clears the configuration and the result. The addresses are stored. The computation is left out, below, and `START_CRC` is told | 4.3.12, 4.9.4, 4.9.19 to 4.9.22, 4.9.34 to 4.9.36 | `the_crc_configuration_takes_writes_only_while_crc_en_is_set`, `clean_crc_and_clearing_crc_en_clear_the_result_and_the_configuration`, `the_crc_addresses_are_stored_in_their_defined_bits` |
//! | Events and the snapshot | An event the model does not expect is ignored. The model's state serializes. An address outside the user flash is a gap | 4.3.4 | `a_stale_event_is_ignored`, `the_model_state_round_trips_through_a_snapshot`, `an_address_outside_the_user_flash_is_a_gap` |
//! | A driver's whole sequences | The unlock, erase, write, lock and option flows of ArduPilot's STM32H7 flash code, on the bus, in `tests/stm32h743_flash.rs` | 4.3.9, 4.3.10, 4.4.3, 4.5.1 | `a_driver_erases_a_sector_of_bank_two_writes_a_word_and_locks_again`, `a_driver_skips_a_word_that_matches_and_refuses_one_that_is_not_erased`, `a_driver_write_protects_the_flash_with_the_option_bytes_and_removes_it` |
//!
//! **What the model leaves out, and why.**
//!
//! | Behavior | Source | Reason |
//! |---|---|---|
//! | `ACR` `LATENCY` and `WRHIGHFREQ` held against the clock and the supply | 4.3.8, Table 17 | The table is the AXI clock against the core voltage range. This part has no clock controller or power controller model yet, so neither is available to the flash interface the way `HCLK` and the rail are on the STM32F427. It waits for the clock tree |
//! | `SNECCERR`, `DBECCERR`, `RDPERR`, `RDSERR` and `FLASH_ECC_FAxR` | 4.3.12, 4.7.7 to 4.7.9, 4.9.23, 4.9.37 | The array's reads go straight to the emulator's memory and never reach the model, so nothing sets these flags or the failing address. The flags read zero. `CCR` clears them and their enables raise the interrupt, which is all a firmware can do with them here, and the address stays zero. A double error's bus error and a protected read returning zero are the memory's |
//! | The CRC computation | 4.3.12 | The manual gives the polynomial `0x4C11DB7` and the burst sizes and says nothing of the start value, the bit order or the final inversion. `CRC_BUSY`, `CRCEND` and `CRCRDERR` are never raised, and `START_CRC` is told rather than ignored |
//! | A bus stall on `START`, `FW` and `OPTSTART`, on a full queue and on a read of a busy bank | 4.3.3, 4.3.9, 4.9.4, 4.9.7 | The model acknowledges at the write and cannot stall the core. A write while an option change runs is held and applied instead. The queues are two deep in the hardware and unbounded here |
//! | A bus error on a wrong key, a double ECC error, a protected read or a fetch from a secure-only area | 4.5.1, 4.7.7 to 4.7.9, 4.7.12 | The write has landed when a model is called, so there is nothing to refuse. The wrong key is told to the session. The others belong to the memory |
//! | A key register written in less than 32 bits | 4.5.1 | The model is handed the register's whole value, with no width. It cannot tell a byte write of a key from a word |
//! | The boot address | 4.4.7, 4.9.17 | `BOOT_ADD0` and `BOOT_ADD1` are stored and committed like the other option bytes. The address the core boots from comes from the machine, which names the region the BOOT pin selects. The model feeds the core nothing |
//! | Readout protection beyond the commit rules | 4.5.3, Tables 23 to 25 | The model reads the level from `RDP` for the rule at level 2. It does not detect an intrusion, a debugger, a boot from RAM or from system flash, so level 1 denies nothing. A regression from level 1 to 0 programs `RDP` and erases nothing: not the user flash, the backup SRAM or the RTC backup registers. The errata item below is why that matters |
//! | `SWAP_BANK` set: the array's halves and the option bytes' view | 4.3.13, Tables 19 and 20 | After a reset with `SWAP_BANK` set, Table 19 puts bank 2 at the lower megabyte of the array, and Table 20 has each numbered register, `FLASH_CR1` and `FLASH_PRAR_CUR1` among them, target the other bank. The model swaps neither the array's halves nor the option bytes' view. Bank 1's registers always govern the lower megabyte, and the first set of option bytes is bank 1's. Swapping the array needs the emulator to remap a region of its memory, which nothing a model asks of the runtime does, and the machine decides what boots. The bit and the option are modeled |
//! | The rest of the limits on option bytes | 4.4.3 | Beyond level 2 and the area rules above, the manual says a regression to level 0 "can" give `OPTCHANGEERR` "if some of the recommendations provided in this chapter have not been followed", and names none more |
//! | Secure access mode | 4.5.5 | "Executing from a valid secure-only area" cannot be told by a model, so all code counts as not secure. `SECURITY` sets which areas bind, and `ST_RAM_SIZE` and the secure boot do nothing |
//! | PCROP's instruction-fetch exception | 4.5.4 | Only a fetch may read a PCROP area, which is a property of the master and the access kind a model is not shown |
//! | `CR2` `SPSS2` | 4.9.25 | Selects the non-user sectors only ST's own code erases. It is stored, and an erase acts on the user sector `SNB2` names |
//! | The option bytes' effects elsewhere: `BOR_LEV`, `IWDG1_SW`, `IWDG_FZ_STOP`, `IWDG_FZ_SDBY`, `NRST_STOP_D1`, `NRST_STBY_D1`, `IO_HSLV`, `ST_RAM_SIZE` | 4.4.5, 4.4.6 | They are stored, committed and kept across a reset. What they do belongs to the power controller, the watchdog and the I/O ports |
//! | Option byte loading on wake-up from Standby and at power-on | 4.4.2 | A system reset loads them here through [`Flash::keep_options`]. Power domains are not modeled |
//! | The interface's busy state toward the clock controller | 4.6.2, Table 26 | `BSY`, `QW` and `WBNE` are in the status registers. The line that stops the domain entering Stop or Standby needs a clock controller to read it |
//! | Read-while-write timing across banks, the read and erase queues' depth, and a write executing before a simultaneous erase | 4.3.3, 4.3.7, 4.3.10, 4.3.11 | The first needs the array's reads, and the second and third need two requests at one instant, which a sequence of bus accesses never gives |
//! | `OPTSTART` while `CRC_BUSY` stands | 4.9.7 | `CRC_BUSY` is never set |
//! | A programming time that depends on `WRHIGHFREQ` | 4.3.9 | The datasheet gives the time by parallelism alone |
//! | A time for the option change, and for the automatic change that ends a protection removal | 4.4.3, 4.3.10 | DS12110 rev 11 gives none. The model's own figure for the first has no source, and the second takes none |
//! | ES0392 rev 15 2.2.5, 2.2.6, 2.2.7, 2.2.8, 2.2.9, 2.2.18 | ES0392 rev 15 | Not applicable to this part's revision V, the code `0x2003`: table 3 marks each present on revisions Y and W alone. They are an option byte load with the user wait states, a BusFault address that is not valid on a double ECC error, a failing address that may not update, PCROP areas that may unprotect on a regression, a bank swap that may make the interface unpredictable, and a CRC that may be wrong at the last address of sector 7. No test reproduces what this revision does not do |
//! | ES0392 rev 15 2.2.17: the device may stall when two level regressions follow without an access to the backup SRAM | ES0392 rev 15 | Applicable to revision V, which table 3 marks `A`. Its trigger is a regression from level 1 to 0, which the model does not perform, and an access to the backup SRAM, which the model is not shown. The workaround is a dummy access to the backup SRAM before the regression |
//!
//! **Where this model departs from the vendor's file.** The retyped fields and registers and the
//! factory option bytes are set out in the table on `flash_corrections` in `memory_map.rs`, and
//! [`LOCK1`], [`LOCK2`], [`OPTLOCK`], [`SWAP_BANK`], [`READ_ONLY`] and [`OptionBytes::FACTORY`] are what
//! it applies. What no correction there reaches is a register's direction. The file's `FLASH_KEYR1`,
//! `FLASH_OPTKEYR` and `FLASH_CCRx` are read-write where the pages type them write-only, and the model
//! clears each after a write so it reads zero. The file types `FLASH_KEYR2` and `FLASH_BOOT_PRGR`
//! read-only, where the pages type the first write-only and the second read-write, so the register file
//! drops a write to either, and the model takes the write it is shown. The file has `CRCRDERR1` in bank
//! 1's status and clear registers where sections 4.9.5 and 4.9.6 show bits 31 to 28 reserved. Section
//! 4.7.10 and Table 27 name the flag and its enable, and the file's bit is kept. It names bank 1's enable
//! of the single ECC error `SNECCERR1` where bank 2's is `SNECCERRIE2`, and bank 2's clear bits for
//! `RDSERR` and `DBECCERR` `CLR_RDSERR1` and `CLR_DBECCERR1`, which the bank tables here spell as the
//! file does.
//!
//! **Determinism.** `two_runs_of_one_script_are_the_same_run` drives two fresh instances through a
//! committed option byte, a bricked key, words programmed in bank 2 and a sector erased, and checks the
//! session's tells, the interrupt line, every register, the array and the model's whole state agree
//! between the two.

use std::collections::VecDeque;

use crate::device::{Device, DeviceContext, Level, RegisterFile};
use crate::soc::stm32h743::generated::flash::{
    Register, acr, ccr1, ccr2, cr1, cr2, crccr1, optccr, optcr, optsr_cur, optsr_prg, prar_cur1,
    prar_cur2, scar_cur1, scar_cur2, sr1, sr2, wpsn_cur1r, wpsn_cur2r,
};
use crate::soc::{Access, FieldSpec, Layout, Width, WriteModify};
use crate::time::{EventId, VirtualNanos};

/// The flash interrupt, position zero of its instance's table. RM0433 rev 9 Table 147 gives it line 4.
const IRQ: usize = 0;

/// Where the user flash begins, RM0433 rev 9 Table 15: bank 1 first, bank 2 a megabyte on.
const ARRAY_BASE: u64 = 0x0800_0000;
/// One bank's user flash, section 4.3.4: eight sectors of 128 Kbytes.
const BANK_BYTES: u64 = 1 << 20;
/// One sector, section 4.3.4.
const SECTOR_BYTES: u64 = 128 << 10;
/// The sectors of a bank, section 4.3.4.
const SECTORS: usize = 8;
/// One flash word, section 4.3.9: 256 bits, programmed whole.
const WORD_BYTES: usize = 32;
/// The widest piece the runtime programs at once, which is why every program and erase goes in these.
const PIECE_BYTES: u64 = 8;
/// What `PROT_AREA_START` and its siblings count in, section 4.4.6: blocks of 256 bytes.
const AREA_BLOCK_BYTES: u64 = 256;

/// RM0433 rev 9 section 4.5.1: `KEY1` then `KEY2` in `FLASH_KEYR1` or `FLASH_KEYR2` unlocks `FLASH_CR1` or
/// `FLASH_CR2`.
const CR_KEYS: (u64, u64) = (0x4567_0123, 0xCDEF_89AB);
/// RM0433 rev 9 section 4.5.1: `OPTKEY1` then `OPTKEY2` in `FLASH_OPTKEYR` unlocks `FLASH_OPTCR`.
const OPT_KEYS: (u64, u64) = (0x0819_2A3B, 0x4C5D_6E7F);

/// DS12110 rev 11 table 140 (revision V), the typical time to program one word in nanoseconds, by `PSIZE`:
/// parallelism x8, x16, x32 and x64 in the order of RM0433 rev 9 Table 18's encoding.
const PROGRAM_NANOS: [u64; 4] = [290_000, 180_000, 130_000, 100_000];
/// The same table's typical time to erase a 128 Kbyte sector, by `PSIZE`.
const SECTOR_ERASE_NANOS: [u64; 4] = [2_000_000_000, 1_800_000_000, 1_100_000_000, 1_000_000_000];
/// The same table's typical mass erase time, by `PSIZE`, which this model also takes for erasing one
/// bank. Section 4.3.10 gives a mass erase as two bank erases in parallel, so a bank erase takes as
/// long as the pair does. The datasheet gives no time for a single bank.
const BANK_ERASE_NANOS: [u64; 4] = [13_000_000_000, 8_000_000_000, 6_000_000_000, 5_000_000_000];
/// How long the model takes to commit the option bytes. RM0433 rev 9 section 4.4.3 says the change is
/// made in the non-volatile memory and DS12110 rev 11 gives no time for it, so this figure is the
/// model's own with no source behind it. It is far shorter than any erase the datasheet does time.
const OPTION_PROGRAM_NANOS: u64 = 20_000;

/// `FLASH_CR1` and `FLASH_CR2` after reset, sections 4.9.4 and 4.9.25: locked, and programming 64 bits
/// at a time.
const CR_RESET: u64 = cr1::PSIZE1.set(cr1::LOCK1.set(0, 1), 0b11);
/// `FLASH_OPTCR` after reset, section 4.9.7, bar `SWAP_BANK`, which is loaded from the option bytes:
/// locked.
const OPTCR_RESET: u64 = optcr::OPTLOCK.set(0, 1);
/// `FLASH_CRCCR1` and `FLASH_CRCCR2` after reset, sections 4.9.19 and 4.9.34.
const CRCCR_RESET: u64 = 0x001C_0000;

/// `LOCK1`, RM0433 rev 9 section 4.9.4: type `rs`, set by writing a one and cleared by the unlock
/// sequence alone.
pub static LOCK1: FieldSpec = cr1::LOCK1
    .with_access(Access::ReadWrite)
    .with_write(WriteModify::OneToSet);
/// `LOCK2`, RM0433 rev 9 section 4.9.25, the same rule as [`LOCK1`].
pub static LOCK2: FieldSpec = cr2::LOCK2
    .with_access(Access::ReadWrite)
    .with_write(WriteModify::OneToSet);
/// `OPTLOCK`, RM0433 rev 9 section 4.9.7, the same rule as [`LOCK1`]. Both mappings of `FLASH_OPTCR`
/// carry it.
pub static OPTLOCK: FieldSpec = optcr::OPTLOCK
    .with_access(Access::ReadWrite)
    .with_write(WriteModify::OneToSet);
/// `SWAP_BANK`, RM0433 rev 9 section 4.9.7: type `r`, loaded from the option bytes at reset and never
/// written by software. Both mappings of `FLASH_OPTCR` carry it.
pub static SWAP_BANK: FieldSpec = optcr::SWAP_BANK
    .with_access(Access::ReadOnly)
    .with_write(WriteModify::None);

/// The registers the vendor's file types read-write where RM0433 rev 9 types every bit `r`, which a
/// write must leave alone: the status registers of sections 4.9.5 and 4.9.26, the current option
/// status of 4.9.8, the current secure address registers of 4.9.13 and 4.9.30, and the CRC result
/// of 4.9.22. The part applies [`WriteModify::Modify`] to each, the rule that leaves the register as
/// the model holds it.
pub const READ_ONLY: [Register; 8] = [
    Register::Sr1,
    Register::Sr2,
    Register::OptsrCur,
    Register::OptsrCur_,
    Register::ScarCur1,
    Register::ScarCur2,
    Register::Crcdatar,
    Register::Crcdatar_,
];

/// The registers each mapped twice, section 4.3.13's Table 20: the one at the lower offset, and its
/// copy at `0x100` more. Bank swapping would not move them, so they sit at two addresses.
const ALIASES: [(Register, Register); 9] = [
    (Register::Acr, Register::Acr_),
    (Register::Optkeyr, Register::Optkeyr_),
    (Register::Optcr, Register::Optcr_),
    (Register::OptsrCur, Register::OptsrCur_),
    (Register::OptsrPrg, Register::OptsrPrg_),
    (Register::Optccr, Register::Optccr_),
    (Register::BootCurr, Register::BootCurr_),
    (Register::BootPrgr, Register::BootPrgr_),
    (Register::Crcdatar, Register::Crcdatar_),
];

/// Every register that holds an option byte, current or programming, under both of its addresses
/// where it has two. The part gives each the factory value of [`OptionBytes::FACTORY`] out of reset.
pub const OPTION_REGISTERS: [Register; 20] = [
    Register::OptsrCur,
    Register::OptsrCur_,
    Register::OptsrPrg,
    Register::OptsrPrg_,
    Register::BootCurr,
    Register::BootCurr_,
    Register::BootPrgr,
    Register::BootPrgr_,
    Register::PrarCur1,
    Register::PrarPrg1,
    Register::ScarCur1,
    Register::ScarPrg1,
    Register::WpsnCur1r,
    Register::WpsnPrg1r,
    Register::PrarCur2,
    Register::PrarPrg2,
    Register::ScarCur2,
    Register::ScarPrg2,
    Register::WpsnCur2r,
    Register::WpsnPrg2r,
];

/// Told when a firmware's unlock sequence goes wrong. Section 4.5.1 answers it with a bus error, which a
/// model that is called after the write has landed cannot give.
const BAD_KEY: &str = "RM0433 rev 9 section 4.5.1: a wrong unlock sequence locks the register until the next system reset";
/// Told when a firmware writes another register of the bank between the two keys.
const KEY_INTERRUPTED: &str = "RM0433 rev 9 section 4.5.1: writing another register between the two keys locks the register until the next system reset";
/// Told when `WRHIGHFREQ` changes under a pending operation.
const WRHIGHFREQ_BUSY: &str = "RM0433 rev 9 section 4.3.9: changing WRHIGHFREQ while flash is programming or erasing might corrupt it";
/// Told when `PSIZE` changes under a pending operation.
const PSIZE_BUSY: &str = "RM0433 rev 9 section 4.3.9: changing PSIZE while flash is programming or erasing might corrupt it";
/// Told when a firmware starts a CRC, which the model does not compute.
const CRC_NOT_MODELED: &str =
    "RM0433 rev 9 section 4.3.12: the flash CRC is not computed, so START_CRC starts nothing";

/// One status flag, the bit in `CR` that enables its interrupt, and the bit in `CCR` that clears it.
#[derive(Debug, Clone, Copy)]
struct Flag {
    status: &'static FieldSpec,
    enable: &'static FieldSpec,
    clear: &'static FieldSpec,
}

const fn flag(
    status: &'static FieldSpec,
    enable: &'static FieldSpec,
    clear: &'static FieldSpec,
) -> Flag {
    Flag {
        status,
        enable,
        clear,
    }
}

/// A bank's flags, RM0433 rev 9 Table 27. The six the model raises are named, and the rest, which
/// nothing here raises, are the ones a firmware can still read and clear.
struct Flags {
    eop: Flag,
    wrperr: Flag,
    pgserr: Flag,
    strberr: Flag,
    incerr: Flag,
    operr: Flag,
    unraised: &'static [Flag],
}

impl Flags {
    fn each(&self) -> impl Iterator<Item = &Flag> {
        [
            &self.eop,
            &self.wrperr,
            &self.pgserr,
            &self.strberr,
            &self.incerr,
            &self.operr,
        ]
        .into_iter()
        .chain(self.unraised)
    }
}

/// What differs between the two banks: where each sits, which registers are its own, and which fields of
/// them.
///
/// Bank 2's fields come from the generated tables under their own names, including the three the
/// vendor's file gets wrong: `CR1`'s `SNECCERR1` is the enable that bank 2 calls `SNECCERRIE2`, and
/// `CCR2` names the clear bits of `RDSERR2` and `DBECCERR2` `CLR_RDSERR1` and `CLR_DBECCERR1`.
struct Wiring {
    base: u64,
    keyr: Register,
    cr: Register,
    sr: Register,
    ccr: Register,
    prar_cur: Register,
    prar_prg: Register,
    scar_cur: Register,
    scar_prg: Register,
    wpsn_cur: Register,
    wpsn_prg: Register,
    crccr: Register,
    crcsadd: Register,
    crceadd: Register,
    ecc_fa: Register,
    lock: &'static FieldSpec,
    pg: &'static FieldSpec,
    ser: &'static FieldSpec,
    ber: &'static FieldSpec,
    psize: &'static FieldSpec,
    fw: &'static FieldSpec,
    start: &'static FieldSpec,
    snb: &'static FieldSpec,
    crc_en: &'static FieldSpec,
    bsy: &'static FieldSpec,
    wbne: &'static FieldSpec,
    qw: &'static FieldSpec,
    prar_start: &'static FieldSpec,
    prar_end: &'static FieldSpec,
    dmep: &'static FieldSpec,
    scar_start: &'static FieldSpec,
    scar_end: &'static FieldSpec,
    dmes: &'static FieldSpec,
    wrps: &'static FieldSpec,
    flags: Flags,
}

impl Wiring {
    /// Whether `register` is one of this bank's own, other than its key register: the ones section 4.5.1 says
    /// a write to between the keys locks.
    fn owns(&self, register: Register) -> bool {
        [
            self.cr,
            self.sr,
            self.ccr,
            self.prar_cur,
            self.prar_prg,
            self.scar_cur,
            self.scar_prg,
            self.wpsn_cur,
            self.wpsn_prg,
            self.crccr,
            self.crcsadd,
            self.crceadd,
            self.ecc_fa,
        ]
        .contains(&register)
    }
}

static BANKS: [Wiring; 2] = [
    Wiring {
        base: ARRAY_BASE,
        keyr: Register::Keyr1,
        cr: Register::Cr1,
        sr: Register::Sr1,
        ccr: Register::Ccr1,
        prar_cur: Register::PrarCur1,
        prar_prg: Register::PrarPrg1,
        scar_cur: Register::ScarCur1,
        scar_prg: Register::ScarPrg1,
        wpsn_cur: Register::WpsnCur1r,
        wpsn_prg: Register::WpsnPrg1r,
        crccr: Register::Crccr1,
        crcsadd: Register::Crcsadd1r,
        crceadd: Register::Crceadd1r,
        ecc_fa: Register::EccFa1r,
        lock: &LOCK1,
        pg: cr1::PG1,
        ser: cr1::SER1,
        ber: cr1::BER1,
        psize: cr1::PSIZE1,
        fw: cr1::FW1,
        start: cr1::START1,
        snb: cr1::SNB1,
        crc_en: cr1::CRC_EN,
        bsy: sr1::BSY1,
        wbne: sr1::WBNE1,
        qw: sr1::QW1,
        prar_start: prar_cur1::PROT_AREA_START1,
        prar_end: prar_cur1::PROT_AREA_END1,
        dmep: prar_cur1::DMEP1,
        scar_start: scar_cur1::SEC_AREA_START1,
        scar_end: scar_cur1::SEC_AREA_END1,
        dmes: scar_cur1::DMES1,
        wrps: wpsn_cur1r::WRPSN1,
        flags: Flags {
            eop: flag(sr1::EOP1, cr1::EOPIE1, ccr1::CLR_EOP1),
            wrperr: flag(sr1::WRPERR1, cr1::WRPERRIE1, ccr1::CLR_WRPERR1),
            pgserr: flag(sr1::PGSERR1, cr1::PGSERRIE1, ccr1::CLR_PGSERR1),
            strberr: flag(sr1::STRBERR1, cr1::STRBERRIE1, ccr1::CLR_STRBERR1),
            incerr: flag(sr1::INCERR1, cr1::INCERRIE1, ccr1::CLR_INCERR1),
            operr: flag(sr1::OPERR1, cr1::OPERRIE1, ccr1::CLR_OPERR1),
            unraised: &[
                flag(sr1::RDPERR1, cr1::RDPERRIE1, ccr1::CLR_RDPERR1),
                flag(sr1::RDSERR1, cr1::RDSERRIE1, ccr1::CLR_RDSERR1),
                flag(sr1::SNECCERR, cr1::SNECCERR1, ccr1::CLR_SNECCERR1),
                flag(sr1::DBECCERR1, cr1::DBECCERRIE1, ccr1::CLR_DBECCERR1),
                flag(sr1::CRCEND1, cr1::CRCENDIE1, ccr1::CLR_CRCEND1),
                flag(sr1::CRCRDERR1, cr1::CRCRDERRIE1, ccr1::CLR_CRCRDERR1),
            ],
        },
    },
    Wiring {
        base: ARRAY_BASE + BANK_BYTES,
        keyr: Register::Keyr2,
        cr: Register::Cr2,
        sr: Register::Sr2,
        ccr: Register::Ccr2,
        prar_cur: Register::PrarCur2,
        prar_prg: Register::PrarPrg2,
        scar_cur: Register::ScarCur2,
        scar_prg: Register::ScarPrg2,
        wpsn_cur: Register::WpsnCur2r,
        wpsn_prg: Register::WpsnPrg2r,
        crccr: Register::Crccr2,
        crcsadd: Register::Crcsadd2r,
        crceadd: Register::Crceadd2r,
        ecc_fa: Register::EccFa2r,
        lock: &LOCK2,
        pg: cr2::PG2,
        ser: cr2::SER2,
        ber: cr2::BER2,
        psize: cr2::PSIZE2,
        fw: cr2::FW2,
        start: cr2::START2,
        snb: cr2::SNB2,
        crc_en: cr2::CRC_EN,
        bsy: sr2::BSY2,
        wbne: sr2::WBNE2,
        qw: sr2::QW2,
        prar_start: prar_cur2::PROT_AREA_START2,
        prar_end: prar_cur2::PROT_AREA_END2,
        dmep: prar_cur2::DMEP2,
        scar_start: scar_cur2::SEC_AREA_START2,
        scar_end: scar_cur2::SEC_AREA_END2,
        dmes: scar_cur2::DMES2,
        wrps: wpsn_cur2r::WRPSN2,
        flags: Flags {
            eop: flag(sr2::EOP2, cr2::EOPIE2, ccr2::CLR_EOP2),
            wrperr: flag(sr2::WRPERR2, cr2::WRPERRIE2, ccr2::CLR_WRPERR2),
            pgserr: flag(sr2::PGSERR2, cr2::PGSERRIE2, ccr2::CLR_PGSERR2),
            strberr: flag(sr2::STRBERR2, cr2::STRBERRIE2, ccr2::CLR_STRBERR2),
            incerr: flag(sr2::INCERR2, cr2::INCERRIE2, ccr2::CLR_INCERR2),
            operr: flag(sr2::OPERR2, cr2::OPERRIE2, ccr2::CLR_OPERR2),
            unraised: &[
                flag(sr2::RDPERR2, cr2::RDPERRIE2, ccr2::CLR_RDPERR2),
                flag(sr2::RDSERR2, cr2::RDSERRIE2, ccr2::CLR_RDSERR1),
                flag(sr2::SNECCERR2, cr2::SNECCERRIE2, ccr2::CLR_SNECCERR2),
                flag(sr2::DBECCERR2, cr2::DBECCERRIE2, ccr2::CLR_DBECCERR1),
                flag(sr2::CRCEND2, cr2::CRCENDIE2, ccr2::CLR_CRCEND2),
            ],
        },
    },
];

/// The bits of `CRCCR1` that start something and read back zero, section 4.9.19. Bank 2's register lays
/// them out alike, section 4.9.34.
const CRC_ONE_SHOT: u64 = crccr1::START_CRC.mask()
    | crccr1::CLEAN_CRC.mask()
    | crccr1::CLEAN_SECT.mask()
    | crccr1::ADD_SECT.mask()
    | crccr1::ALL_BANK.mask();

/// The option bytes, as the words the option registers hold. The current and the programming register
/// of each pair read the same after a commit, so one word stands for both.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct OptionBytes {
    /// `FLASH_OPTSR_CUR` and `FLASH_OPTSR_PRG`, bar the two bits of the current register that are flags.
    pub optsr: u64,
    /// `FLASH_BOOT_CURR` and `FLASH_BOOT_PRGR`.
    pub boot: u64,
    /// `FLASH_PRAR_CUR1` and `FLASH_PRAR_PRG1`, then bank 2's.
    pub prar: [u64; 2],
    /// `FLASH_SCAR_CUR1` and `FLASH_SCAR_PRG1`, then bank 2's.
    pub scar: [u64; 2],
    /// `FLASH_WPSN_CUR1R` and `FLASH_WPSN_PRG1R`, then bank 2's.
    pub wpsn: [u64; 2],
}

impl OptionBytes {
    /// What the part leaves ST with, RM0433 rev 9 Table 21's default factory values, where Table 28 gives
    /// every one of these registers' reset value as `X`: readout protection level 0, the independent
    /// watchdog on software control and running in Stop and Standby, no reset on entering either, the
    /// lowest brownout level, and no bank swapping. Boot at `0x0800` with the pin low and `0x1FF0` high.
    /// The protected areas disabled, with their start above their end, the secure-only areas' erase
    /// enabled, and every sector writable.
    ///
    /// Table 21 gives `ST_RAM_SIZE`, which the manual says must stay at its default, and the reserved
    /// bits 28 and 27 as `X`. This takes them as zero. It gives the reserved bit 5 as one, which this
    /// keeps.
    pub const FACTORY: Self = Self {
        optsr: 0x0006_AAF0,
        boot: 0x1FF0_0800,
        prar: [0x0000_00FF; 2],
        scar: [0x8000_00FF; 2],
        wpsn: [0x0000_00FF; 2],
    };

    /// The word `register` holds, or what it resets to in the vendor's file where it holds no option byte.
    #[must_use]
    pub fn word(&self, register: Register) -> u64 {
        match register {
            Register::OptsrCur | Register::OptsrCur_ | Register::OptsrPrg | Register::OptsrPrg_ => {
                self.optsr
            }
            Register::BootCurr | Register::BootCurr_ | Register::BootPrgr | Register::BootPrgr_ => {
                self.boot
            }
            Register::PrarCur1 | Register::PrarPrg1 => self.prar[0],
            Register::PrarCur2 | Register::PrarPrg2 => self.prar[1],
            Register::ScarCur1 | Register::ScarPrg1 => self.scar[0],
            Register::ScarCur2 | Register::ScarPrg2 => self.scar[1],
            Register::WpsnCur1r | Register::WpsnPrg1r => self.wpsn[0],
            Register::WpsnCur2r | Register::WpsnPrg2r => self.wpsn[1],
            other => other.spec().reset,
        }
    }
}

/// Whether loading the option bytes into the registers loads the programming registers too.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Programming {
    /// Only the current registers, as a commit does.
    Kept,
    /// The programming registers as well, as a reset does: they "reflect the current values".
    Loaded,
}

/// Whether `register` is one of the programming registers, which the drivers write.
fn is_programming(register: Register) -> bool {
    matches!(
        register,
        Register::OptsrPrg
            | Register::OptsrPrg_
            | Register::BootPrgr
            | Register::BootPrgr_
            | Register::PrarPrg1
            | Register::PrarPrg2
            | Register::ScarPrg1
            | Register::ScarPrg2
            | Register::WpsnPrg1r
            | Register::WpsnPrg2r
    )
}

/// A step the model has asked the runtime for, and which one it comes back as.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
    Read,
    Program,
}

/// What a request the model made carries back to it: the bank, the step, and the 8-byte piece of the
/// word it concerns.
#[derive(Debug, Clone, Copy)]
struct Token {
    bank: usize,
    step: Step,
    piece: u64,
}

impl Token {
    fn encode(self) -> u64 {
        let step = u64::from(self.step == Step::Program);
        (self.piece * 2 + count(self.bank)) * 2 + step
    }

    fn decode(token: u64) -> Self {
        let step = if token.is_multiple_of(2) {
            Step::Read
        } else {
            Step::Program
        };
        let rest = token / 2;
        Self {
            bank: index(rest % 2),
            step,
            piece: rest / 2,
        }
    }
}

/// An operation the interface has been asked for and not yet carried out, in the order of its bank's queue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Command {
    /// One flash word, with `psize` as `PSIZE` held when its last byte arrived.
    Program {
        word: u64,
        data: [u8; WORD_BYTES],
        psize: usize,
    },
    /// One 128 Kbyte sector of the bank.
    EraseSector { sector: usize, psize: usize },
    /// The whole bank, with the protection removal of section 4.3.10 if `removal`.
    EraseBank { psize: usize, removal: bool },
    /// The option byte change of section 4.4.3, which belongs to bank 1.
    Options,
}

impl Command {
    /// How long the operation takes, by the datasheet's typical figures.
    fn nanos(self) -> u64 {
        match self {
            Self::Program { psize, .. } => PROGRAM_NANOS[psize],
            Self::EraseSector { psize, .. } => SECTOR_ERASE_NANOS[psize],
            Self::EraseBank { psize, .. } => BANK_ERASE_NANOS[psize],
            Self::Options => OPTION_PROGRAM_NANOS,
        }
    }
}

/// Where a running operation is: waiting out its time, or waiting on the runtime to put its bytes into
/// the array.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Phase {
    Timing,
    Landing,
}

/// The operation a bank is carrying out.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Running {
    event: EventId,
    command: Command,
    phase: Phase,
    /// How many answers from the runtime the operation is still waiting on.
    waiting: u32,
    /// Whether the runtime refused some part of it.
    failed: bool,
}

/// A bank's 256-bit write buffer, section 4.3.9, with which of its bytes have been written.
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Buffer {
    word: u64,
    data: [u8; WORD_BYTES],
    written: [bool; WORD_BYTES],
}

impl Buffer {
    fn occupied(&self) -> bool {
        self.written.contains(&true)
    }

    fn full(&self) -> bool {
        !self.written.contains(&false)
    }
}

/// Progress through a two-key unlock sequence, section 4.5.1.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct KeyLock {
    expecting_second: bool,
    bricked: bool,
}

/// What a write to a key register did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Key {
    /// The register is unlocked.
    Unlocked,
    /// The first key arrived.
    Waiting,
    /// The register is, and stays, locked until the next system reset, and this write did it.
    Bricked,
    /// The register was already locked up, and this changes nothing.
    Ignored,
}

impl KeyLock {
    /// Takes `written`, with the register `locked` or not. A key written to a register already unlocked is
    /// section 4.5.1's third key, and section 4.9.4's sequence performed twice.
    fn take(&mut self, locked: bool, written: u64, keys: (u64, u64)) -> Key {
        if self.bricked {
            return Key::Ignored;
        }
        if locked {
            if self.expecting_second {
                self.expecting_second = false;
                if written == keys.1 {
                    return Key::Unlocked;
                }
            } else if written == keys.0 {
                self.expecting_second = true;
                return Key::Waiting;
            }
        }
        self.brick()
    }

    fn brick(&mut self) -> Key {
        self.expecting_second = false;
        self.bricked = true;
        Key::Bricked
    }
}

/// One bank's state: its unlock, the word being filled, and the operations in line.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct Bank {
    key: KeyLock,
    buffer: Buffer,
    queue: VecDeque<Command>,
    running: Option<Running>,
}

impl Bank {
    /// Whether anything is pending or running, which section 4.3.9 says to wait out before changing
    /// the timing parameters.
    fn busy(&self) -> bool {
        self.running.is_some() || !self.queue.is_empty()
    }
}

/// A run of bytes of one flash word that a store brought.
struct Chunk<'a> {
    word: u64,
    first: usize,
    bytes: &'a [u8],
}

/// The embedded flash memory interface of the STM32H743, RM0433 rev 9 chapter 4.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Flash {
    banks: [Bank; 2],
    opt_key: KeyLock,
    /// The option bytes the last completed commit left, which a reset keeps.
    options: OptionBytes,
    /// Writes to the interface's registers made while an option change was ongoing, in order, as their
    /// row and the value written.
    held: VecDeque<(usize, u64)>,
    /// Every register as the last call left it, which a model needs to put back what a write must
    /// not have changed: it sees the value after the write has landed and not the one before.
    shadow: Vec<u64>,
    interrupt: Level,
}

impl Default for Flash {
    fn default() -> Self {
        Self::new()
    }
}

impl Flash {
    /// The interface fresh out of reset, with the option bytes ST ships.
    #[must_use]
    pub fn new() -> Self {
        Self::with_options(OptionBytes::FACTORY)
    }

    fn with_options(options: OptionBytes) -> Self {
        Self {
            banks: [Bank::default(), Bank::default()],
            opt_key: KeyLock::default(),
            options,
            held: VecDeque::new(),
            shadow: Self::seeded(&options),
            interrupt: Level::Low,
        }
    }

    /// Every register as a reset leaves it, with the option registers holding `options`.
    fn seeded(options: &OptionBytes) -> Vec<u64> {
        Register::ALL
            .iter()
            .map(|&register| match register {
                Register::Cr1 | Register::Cr2 => CR_RESET,
                Register::Optcr | Register::Optcr_ => {
                    optcr::SWAP_BANK.set(OPTCR_RESET, optsr_prg::SWAP_BANK_OPT.get(options.optsr))
                }
                Register::Crccr1 | Register::Crccr2 => CRCCR_RESET,
                other => options.word(other),
            })
            .collect()
    }

    /// A system reset keeping the option bytes the last completed commit left, RM0433 rev 9 section 4.3.14:
    /// "all registers, except for option byte registers, are cleared", and a change that a reset
    /// interrupts leaves the old bytes. `OPTLOCK` comes back set, and `SWAP_BANK` loads the bytes'
    /// `SWAP_BANK_OPT`, section 4.9.7. The part calls it on its flash registers after it has reset
    /// them, with what [`Flash::committed_options`] held before.
    pub fn keep_options(&mut self, options: OptionBytes, registers: &mut RegisterFile) {
        self.options = options;
        self.load_options(Programming::Loaded, registers);
        let swap = optsr_prg::SWAP_BANK_OPT.get(options.optsr);
        put(
            registers,
            Register::Optcr,
            optcr::SWAP_BANK.set(OPTCR_RESET, swap),
        );
        self.remember(registers);
    }

    /// The option bytes the last completed commit left, for a system reset to carry to the part it
    /// rebuilds through [`Flash::keep_options`].
    #[must_use]
    pub const fn committed_options(&self) -> OptionBytes {
        self.options
    }
}

/// The index of a small count, which every one here is.
fn index(value: u64) -> usize {
    usize::try_from(value).expect("a count that fits an index")
}

fn count(value: usize) -> u64 {
    u64::try_from(value).expect("a count that fits a word")
}

/// The bank holding `address`, or none for an address outside the user flash.
fn bank_at(address: u64) -> Option<usize> {
    let offset = address.checked_sub(ARRAY_BASE)?;
    (offset < 2 * BANK_BYTES).then(|| index(offset / BANK_BYTES))
}

/// The sector of its bank that `address` falls in.
fn sector_at(address: u64) -> usize {
    index((address - ARRAY_BASE) % BANK_BYTES / SECTOR_BYTES)
}

/// Every bit the register's declared fields cover, which are the ones the manual defines.
fn defined_bits(register: Register) -> u64 {
    register
        .spec()
        .fields
        .iter()
        .fold(0, |bits, field| bits | field.mask())
}

/// `written` over `kept` in the bits of `mask` alone, which is how a register whose reserved bits "must be kept
/// at reset value" takes a write.
const fn merge(kept: u64, written: u64, mask: u64) -> u64 {
    (kept & !mask) | (written & mask)
}

/// Sets `register`, and the second address it is mapped at where it has one.
fn put(registers: &mut RegisterFile, register: Register, value: u64) {
    registers.set(register, value);
    if let Some(&(_, alias)) = ALIASES.iter().find(|(primary, _)| *primary == register) {
        registers.set(alias, value);
    }
}

/// The register a write to `register` is handled as: the lower address of a pair.
fn primary(register: Register) -> Register {
    ALIASES
        .iter()
        .find(|(_, alias)| *alias == register)
        .map_or(register, |&(primary, _)| primary)
}

/// Raises a bank's `flag` in its status register.
fn raise(registers: &mut RegisterFile, wiring: &Wiring, flag: &Flag) {
    let status = flag.status.set(registers.get(wiring.sr), 1);
    registers.set(wiring.sr, status);
}

/// Which readout protection level the option word gives, section 4.5.3's Table 23.
fn rdp_level(optsr: u64) -> u8 {
    match optsr_prg::RDP.get(optsr) {
        0xAA => 0,
        0xCC => 2,
        _ => 1,
    }
}

/// The span of a bank, in bytes from its start, that a start and end in blocks of 256 bytes cover, or
/// none: sections 4.9.11 and 4.9.13. An end below the start protects nothing, an equal pair covers the whole bank.
fn area(start: u64, end: u64) -> Option<std::ops::RangeInclusive<u64>> {
    match start.cmp(&end) {
        std::cmp::Ordering::Greater => None,
        std::cmp::Ordering::Equal => Some(0..=BANK_BYTES - 1),
        std::cmp::Ordering::Less => {
            Some(start * AREA_BLOCK_BYTES..=(end + 1) * AREA_BLOCK_BYTES - 1)
        }
    }
}

/// Which sectors of a bank cannot be programmed or erased: those write-protected, section 4.5.2, and
/// those a valid PCROP or secure-only area touches even in part, sections 4.7.2, 4.5.4 and 4.5.5. The
/// secure-only areas bind only with `SECURITY` set, section 4.5.5, and a model cannot tell whether
/// the code running is the secure application's, so it takes it as not.
fn protected_sectors(wiring: &Wiring, registers: &RegisterFile) -> [bool; SECTORS] {
    let mut protected = [false; SECTORS];
    let writable = wiring.wrps.get(registers.get(wiring.wpsn_cur));
    let prar = registers.get(wiring.prar_cur);
    let scar = registers.get(wiring.scar_cur);
    let secure = optsr_cur::SECURITY.is_set(registers.get(Register::OptsrCur));
    let areas = [
        area(wiring.prar_start.get(prar), wiring.prar_end.get(prar)),
        area(wiring.scar_start.get(scar), wiring.scar_end.get(scar)).filter(|_| secure),
    ];
    for (sector, locked) in protected.iter_mut().enumerate() {
        let first = count(sector) * SECTOR_BYTES;
        let last = first + SECTOR_BYTES - 1;
        let touched = areas
            .iter()
            .flatten()
            .any(|span| *span.start() <= last && first <= *span.end());
        *locked = (writable >> sector) & 1 == 0 || touched;
    }
    protected
}

impl Device for Flash {
    type Register = Register;

    fn write(
        &mut self,
        register: Register,
        written: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        // Table 20: the second address of a pair is the same register, handled as the first.
        let handled = primary(register);
        if handled != register {
            registers.set(handled, registers.get(register));
        }
        if self.option_change_pending() {
            // Sections 4.9.7 and 4.9.8: writes wait for the change, since the core can't be stalled.
            self.held.push_back((handled.index(), written));
            put(registers, handled, self.shadow_of(handled));
        } else {
            self.apply(handled, written, registers, context);
        }
        self.settled(registers, context);
    }

    fn write_region(
        &mut self,
        address: u64,
        width: Width,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) -> bool {
        if bank_at(address).is_none() {
            return false;
        }
        let bytes = value.to_le_bytes();
        let length = index(u64::from(width.bytes()));
        let mut done = 0;
        while done < length {
            let at = address + count(done);
            // A store that crosses a flash word is two stores of the bus, one to each word.
            let first = index(at % count(WORD_BYTES));
            let taken = (WORD_BYTES - first).min(length - done);
            if let Some(bank) = bank_at(at) {
                let chunk = Chunk {
                    word: at - count(first),
                    first,
                    bytes: &bytes[done..done + taken],
                };
                self.store(bank, &chunk, registers, context);
            }
            done += taken;
        }
        self.settled(registers, context);
        true
    }

    fn on_event(
        &mut self,
        event: EventId,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        // Banks that end at one instant share an event id, so every bank is asked.
        for bank in 0..BANKS.len() {
            let due = self.banks[bank]
                .running
                .is_some_and(|running| running.event == event && running.phase == Phase::Timing);
            if due {
                self.land(bank, registers, context);
            }
        }
        self.settled(registers, context);
    }

    fn on_access(
        &mut self,
        token: u64,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let token = Token::decode(token);
        let landing = self.banks[token.bank]
            .running
            .filter(|running| running.phase == Phase::Landing);
        let Some(running) = landing else {
            return;
        };
        match (token.step, running.command) {
            (Step::Read, Command::Program { word, data, .. }) => {
                // Section 4.3.9: programming only clears bits, so the cells keep the zeros of both.
                let first = index(token.piece * PIECE_BYTES);
                let new = u64::from_le_bytes(
                    data[first..first + index(PIECE_BYTES)]
                        .try_into()
                        .expect("eight bytes"),
                );
                let address = word + token.piece * PIECE_BYTES;
                let step = Token {
                    step: Step::Program,
                    ..token
                };
                context.program(address, Width::W64, value & new, step.encode());
            }
            (Step::Program, _) => {
                if self.answered(token.bank, false, registers, context) {
                    self.settled(registers, context);
                }
            }
            (Step::Read, _) => {}
        }
    }

    fn on_refused(
        &mut self,
        token: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let token = Token::decode(token);
        let landing = self.banks[token.bank]
            .running
            .is_some_and(|running| running.phase == Phase::Landing);
        if landing && self.answered(token.bank, true, registers, context) {
            self.settled(registers, context);
        }
    }

    fn reset(&mut self) {
        *self = Self::with_options(self.options);
    }
}

impl Flash {
    /// What a write to one register does. `register` is the lower address of a pair, and `written` is
    /// what the bus carried.
    ///
    /// The arms cite their sections, and the groups are these. The programming registers are sections
    /// 4.9.9, 4.9.12, 4.9.14, 4.9.16, 4.9.18, 4.9.29, 4.9.31 and 4.9.33. The status flags only hardware
    /// sets, which the clear registers clear, are 4.9.5 and 4.9.26. The current option bytes and the
    /// results, which only a commit or an operation changes, are 4.9.8, 4.9.11, 4.9.13, 4.9.15, 4.9.17,
    /// 4.9.22, 4.9.23, 4.9.28, 4.9.30, 4.9.32 and 4.9.37.
    fn apply(
        &mut self,
        register: Register,
        written: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        self.interrupted_unlock(register, context);
        match register {
            // Section 4.9.1.
            Register::Acr | Register::Acr_ => self.write_acr(written, registers, context),
            // Sections 4.9.2 and 4.9.24.
            Register::Keyr1 => self.write_keyr(0, written, registers, context),
            Register::Keyr2 => self.write_keyr(1, written, registers, context),
            // Section 4.9.3.
            Register::Optkeyr | Register::Optkeyr_ => {
                self.write_optkeyr(written, registers, context);
            }
            // Sections 4.9.4 and 4.9.25.
            Register::Cr1 => self.write_cr(0, registers, context),
            Register::Cr2 => self.write_cr(1, registers, context),
            // Sections 4.9.6 and 4.9.27.
            Register::Ccr1 => Self::write_ccr(0, written, registers),
            Register::Ccr2 => Self::write_ccr(1, written, registers),
            // Section 4.9.7.
            Register::Optcr | Register::Optcr_ => self.write_optcr(registers, context),
            // The programming registers take a write while `OPTLOCK` is clear.
            Register::OptsrPrg
            | Register::OptsrPrg_
            | Register::PrarPrg1
            | Register::PrarPrg2
            | Register::ScarPrg1
            | Register::ScarPrg2
            | Register::WpsnPrg1r
            | Register::WpsnPrg2r
            | Register::BootPrgr
            | Register::BootPrgr_ => self.write_programming(register, written, registers),
            // Section 4.9.10.
            Register::Optccr | Register::Optccr_ => Self::write_optccr(written, registers),
            // Sections 4.9.19 and 4.9.34.
            Register::Crccr1 => self.write_crccr(0, registers, context),
            Register::Crccr2 => self.write_crccr(1, registers, context),
            // Sections 4.9.20, 4.9.21, 4.9.35 and 4.9.36: stored, being read by nothing here.
            Register::Crcsadd1r
            | Register::Crceadd1r
            | Register::Crcsadd2r
            | Register::Crceadd2r => {
                let value = merge(self.shadow_of(register), written, defined_bits(register));
                registers.set(register, value);
            }
            // Read-only: the part keeps a write off every one of them.
            Register::Sr1
            | Register::Sr2
            | Register::OptsrCur
            | Register::OptsrCur_
            | Register::PrarCur1
            | Register::PrarCur2
            | Register::ScarCur1
            | Register::ScarCur2
            | Register::WpsnCur1r
            | Register::WpsnCur2r
            | Register::BootCurr
            | Register::BootCurr_
            | Register::Crcdatar
            | Register::Crcdatar_
            | Register::EccFa1r
            | Register::EccFa2r => {}
        }
    }

    /// Keeps every register's mirror, the status the queues imply, and the interrupt line true to what
    /// the call changed, then remembers the registers for the next call to put back.
    fn settled(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        for (first, second) in ALIASES {
            registers.set(second, registers.get(first));
        }
        self.refresh_status(registers);
        self.refresh_interrupt(registers, context);
        self.remember(registers);
    }

    fn remember(&mut self, registers: &RegisterFile) {
        self.shadow.clear();
        self.shadow.extend(
            Register::ALL
                .iter()
                .map(|&register| registers.get(register)),
        );
    }

    fn shadow_of(&self, register: Register) -> u64 {
        self.shadow[register.index()]
    }

    /// Whether a commit of the option bytes is waiting or running, which is `OPT_BUSY`.
    fn option_change_pending(&self) -> bool {
        let bank = &self.banks[0];
        bank.queue.contains(&Command::Options)
            || bank
                .running
                .is_some_and(|running| running.command == Command::Options)
    }

    /// `BSY`, `QW` and `WBNE` of both banks and `OPT_BUSY`, which only hardware sets, from the state that
    /// implies them. Sections 4.9.5, 4.9.8 and 4.9.26.
    fn refresh_status(&self, registers: &mut RegisterFile) {
        for (bank, wiring) in self.banks.iter().zip(&BANKS) {
            let mut status = registers.get(wiring.sr);
            status = wiring.bsy.set(status, u64::from(bank.running.is_some()));
            status = wiring.qw.set(status, u64::from(bank.busy()));
            status = wiring.wbne.set(status, u64::from(bank.buffer.occupied()));
            registers.set(wiring.sr, status);
        }
        let current = registers.get(Register::OptsrCur);
        let busy = u64::from(self.option_change_pending());
        put(
            registers,
            Register::OptsrCur,
            optsr_cur::OPT_BUSY.set(current, busy),
        );
    }

    /// Section 4.8: the one flash interrupt stands while any flag of either bank stands with its
    /// enable set, and `OPTCHANGEERR` with `OPTCHANGEERRIE`.
    fn refresh_interrupt(&mut self, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
        let flagged = BANKS.iter().any(|wiring| {
            let status = registers.get(wiring.sr);
            let control = registers.get(wiring.cr);
            wiring
                .flags
                .each()
                .any(|flag| flag.status.is_set(status) && flag.enable.is_set(control))
        });
        let option_error = optsr_cur::OPTCHANGEERR.is_set(registers.get(Register::OptsrCur))
            && optcr::OPTCHANGEERRIE.is_set(registers.get(Register::Optcr));
        let wanted = Level::from(flagged || option_error);
        if wanted != self.interrupt {
            self.interrupt = wanted;
            context.interrupt(IRQ, wanted);
        }
    }

    /// Section 4.5.1: a write to another register of a bank, between its two keys, locks its control
    /// register until reset, and so does any write to a register but `FLASH_OPTKEYR` between the option
    /// keys.
    fn interrupted_unlock(&mut self, register: Register, context: &mut DeviceContext<'_>) {
        for (bank, wiring) in self.banks.iter_mut().zip(&BANKS) {
            if bank.key.expecting_second && wiring.owns(register) {
                bank.key.brick();
                context.tell(wiring.keyr.spec().name, KEY_INTERRUPTED);
            }
        }
        if self.opt_key.expecting_second && register != Register::Optkeyr {
            self.opt_key.brick();
            context.tell(Register::Optkeyr.spec().name, KEY_INTERRUPTED);
        }
    }

    /// `FLASH_ACR`, section 4.9.1: `LATENCY` and `WRHIGHFREQ` are stored. The manual's caution against
    /// changing `WRHIGHFREQ` under an operation is told.
    fn write_acr(
        &mut self,
        written: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let before = self.shadow_of(Register::Acr);
        let value = merge(before, written, defined_bits(Register::Acr));
        registers.set(Register::Acr, value);
        let changed = acr::WRHIGHFREQ.get(before) != acr::WRHIGHFREQ.get(value);
        if changed && self.banks.iter().any(Bank::busy) {
            context.tell(Register::Acr.spec().name, WRHIGHFREQ_BUSY);
        }
    }

    /// `FLASH_KEYR1` and `FLASH_KEYR2`, sections 4.9.2, 4.9.24 and 4.5.1.
    fn write_keyr(
        &mut self,
        bank: usize,
        written: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let wiring = &BANKS[bank];
        registers.set(wiring.keyr, 0);
        let control = registers.get(wiring.cr);
        let locked = wiring.lock.is_set(control);
        match self.banks[bank].key.take(locked, written, CR_KEYS) {
            Key::Unlocked => registers.set(wiring.cr, wiring.lock.set(control, 0)),
            Key::Bricked => {
                registers.set(wiring.cr, wiring.lock.set(control, 1));
                context.tell(wiring.keyr.spec().name, BAD_KEY);
            }
            Key::Waiting | Key::Ignored => {}
        }
    }

    /// `FLASH_OPTKEYR`, sections 4.9.3 and 4.5.1.
    fn write_optkeyr(
        &mut self,
        written: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        put(registers, Register::Optkeyr, 0);
        let control = registers.get(Register::Optcr);
        let locked = OPTLOCK.is_set(control);
        match self.opt_key.take(locked, written, OPT_KEYS) {
            Key::Unlocked => registers.set(Register::Optcr, OPTLOCK.set(control, 0)),
            Key::Bricked => {
                registers.set(Register::Optcr, OPTLOCK.set(control, 1));
                context.tell(Register::Optkeyr.spec().name, BAD_KEY);
            }
            Key::Waiting | Key::Ignored => {}
        }
    }

    /// `FLASH_CR1` and `FLASH_CR2`, sections 4.9.4 and 4.9.25: every field but `LOCK` takes a write only while
    /// `LOCK` is clear. `START` and `FW` are acknowledged at once, which clears them, and `PG` falling
    /// drops a partial write buffer.
    fn write_cr(
        &mut self,
        bank: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let wiring = &BANKS[bank];
        let before = self.shadow_of(wiring.cr);
        if wiring.lock.is_set(before) {
            registers.set(wiring.cr, before);
            return;
        }
        let landed = registers.get(wiring.cr);
        let value = merge(before, landed, defined_bits(wiring.cr));
        let changed = wiring.psize.get(before) != wiring.psize.get(value);
        if changed && self.banks[bank].busy() {
            context.tell(wiring.cr.spec().name, PSIZE_BUSY);
        }
        if wiring.pg.is_set(before) && !wiring.pg.is_set(value) {
            self.banks[bank].buffer = Buffer::default();
        }
        if wiring.crc_en.is_set(before) && !wiring.crc_en.is_set(value) {
            Self::clear_crc(wiring, registers);
        }
        let force = wiring.fw.is_set(value);
        let start = wiring.start.is_set(value);
        let acknowledged = wiring.start.set(wiring.fw.set(value, 0), 0);
        registers.set(wiring.cr, acknowledged);
        if force {
            self.force_write(bank, registers, context);
        }
        if start {
            self.start_erase(bank, acknowledged, registers, context);
        }
    }

    /// Section 4.9.4: clearing `CRC_EN` clears the CRC configuration and result.
    fn clear_crc(wiring: &Wiring, registers: &mut RegisterFile) {
        registers.set(wiring.crccr, CRCCR_RESET);
        registers.set(wiring.crcsadd, 0);
        registers.set(wiring.crceadd, 0);
        put(registers, Register::Crcdatar, 0);
    }

    /// `FLASH_CCR1` and `FLASH_CCR2`, sections 4.9.6 and 4.9.27: a written one clears its flag, and the
    /// register reads zero.
    fn write_ccr(bank: usize, written: u64, registers: &mut RegisterFile) {
        let wiring = &BANKS[bank];
        let mut status = registers.get(wiring.sr);
        for flag in wiring.flags.each() {
            if flag.clear.is_set(written) {
                status = flag.status.set(status, 0);
            }
        }
        registers.set(wiring.sr, status);
        registers.set(wiring.ccr, 0);
    }

    /// `FLASH_CRCCR1` and `FLASH_CRCCR2`, sections 4.9.19 and 4.9.34: written only while `CRC_EN` is set.
    /// The bits that start something read zero. The computation itself is not modeled.
    fn write_crccr(
        &mut self,
        bank: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let wiring = &BANKS[bank];
        let before = self.shadow_of(wiring.crccr);
        if !wiring.crc_en.is_set(registers.get(wiring.cr)) {
            registers.set(wiring.crccr, before);
            return;
        }
        let landed = registers.get(wiring.crccr);
        let value = merge(before, landed, defined_bits(wiring.crccr));
        if crccr1::START_CRC.is_set(value) {
            context.tell(wiring.crccr.spec().name, CRC_NOT_MODELED);
        }
        if crccr1::CLEAN_CRC.is_set(value) {
            put(registers, Register::Crcdatar, 0);
        }
        registers.set(wiring.crccr, value & !CRC_ONE_SHOT);
    }

    /// `FLASH_OPTCR`, section 4.9.7: written only while `OPTLOCK` is clear. `MER` and `OPTSTART` start
    /// an operation and read zero.
    fn write_optcr(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        let before = self.shadow_of(Register::Optcr);
        if OPTLOCK.is_set(before) {
            registers.set(Register::Optcr, before);
            return;
        }
        let landed = registers.get(Register::Optcr);
        let value = merge(before, landed, defined_bits(Register::Optcr));
        let erase = optcr::MER.is_set(value);
        let start = optcr::OPTSTART.is_set(value);
        let acknowledged = optcr::OPTSTART.set(optcr::MER.set(value, 0), 0);
        registers.set(Register::Optcr, acknowledged);
        if erase {
            self.mass_erase(registers, context);
        }
        if start {
            self.start_option_change(registers, context);
        }
    }

    /// `FLASH_OPTCCR`, section 4.9.10: write-only, and a written one clears `OPTCHANGEERR`.
    fn write_optccr(written: u64, registers: &mut RegisterFile) {
        if optccr::CLR_OPTCHANGEERR.is_set(written) {
            let current = registers.get(Register::OptsrCur);
            put(
                registers,
                Register::OptsrCur,
                optsr_cur::OPTCHANGEERR.set(current, 0),
            );
        }
        put(registers, Register::Optccr, 0);
    }

    /// The programming registers, sections 4.4.3 and 4.5.1: `FLASH_OPTCR`'s lock holds them, and only
    /// the bits the manual defines take a write.
    fn write_programming(
        &mut self,
        register: Register,
        written: u64,
        registers: &mut RegisterFile,
    ) {
        let kept = self.shadow_of(register);
        let value = if OPTLOCK.is_set(registers.get(Register::Optcr)) {
            kept
        } else {
            merge(kept, written, defined_bits(register))
        };
        registers.set(register, value);
    }

    /// A store of the firmware into a bank's user flash, section 4.3.9: it fills the bank's write buffer
    /// when `PG` is set and is rejected when it is not.
    fn store(
        &mut self,
        bank: usize,
        chunk: &Chunk<'_>,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let wiring = &BANKS[bank];
        let flags = &wiring.flags;
        let status = registers.get(wiring.sr);
        if !wiring.pg.is_set(registers.get(wiring.cr)) {
            // Section 4.3.9: rejected with no bus error, and flagged.
            self.banks[bank].buffer = Buffer::default();
            raise(registers, wiring, &flags.pgserr);
            return;
        }
        if flags.pgserr.status.is_set(status) {
            // Section 4.7.3: a standing PGSERR blocks any new program operation.
            self.banks[bank].buffer = Buffer::default();
            return;
        }
        if flags.incerr.status.is_set(status) {
            // Section 4.7.3: INCERR left standing before a new write is a sequence error.
            self.banks[bank].buffer = Buffer::default();
            raise(registers, wiring, &flags.pgserr);
            return;
        }
        let buffer = &mut self.banks[bank].buffer;
        if buffer.occupied() && buffer.word != chunk.word {
            // Section 4.7.5: a write to another word before this one is full. What was gathered is lost.
            *buffer = Buffer::default();
            raise(registers, wiring, &flags.incerr);
            return;
        }
        let end = chunk.first + chunk.bytes.len();
        let strobe = buffer.written[chunk.first..end].contains(&true);
        buffer.word = chunk.word;
        buffer.data[chunk.first..end].copy_from_slice(chunk.bytes);
        buffer.written[chunk.first..end].fill(true);
        let full = buffer.full();
        if strobe {
            // Section 4.7.4: the new byte replaces the old, and the error is flagged.
            raise(registers, wiring, &flags.strberr);
        }
        if full {
            self.queue_buffer(bank, registers, context);
        }
    }

    /// Queues the bank's write buffer as a program operation, at the `PSIZE` held now.
    fn queue_buffer(
        &mut self,
        bank: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let wiring = &BANKS[bank];
        let buffer = std::mem::take(&mut self.banks[bank].buffer);
        let psize = index(wiring.psize.get(registers.get(wiring.cr)));
        let command = Command::Program {
            word: buffer.word,
            data: buffer.data,
            psize,
        };
        self.enqueue(bank, command, registers, context);
    }

    /// `FW`, section 4.9.4: writes the buffer with the bytes not written set to ones. It has no effect on an
    /// empty buffer, nor where nothing in the buffer is cleared, section 4.3.9.
    fn force_write(
        &mut self,
        bank: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let buffer = &mut self.banks[bank].buffer;
        let cleared = buffer
            .data
            .iter()
            .zip(&buffer.written)
            .any(|(&byte, &written)| written && byte != 0xFF);
        if !cleared {
            return;
        }
        for (byte, written) in buffer.data.iter_mut().zip(&mut buffer.written) {
            if !*written {
                *byte = 0xFF;
                *written = true;
            }
        }
        self.queue_buffer(bank, registers, context);
    }

    /// `START`, sections 4.3.10, 4.9.4 and 4.9.25: a bank erase beats a sector erase when both are asked.
    /// With neither asked, the manual says nothing, and nothing starts.
    fn start_erase(
        &mut self,
        bank: usize,
        control: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let wiring = &BANKS[bank];
        let psize = index(wiring.psize.get(control));
        let command = if wiring.ber.is_set(control) {
            let removal = self.removal_requested(&[bank], registers);
            Command::EraseBank { psize, removal }
        } else if wiring.ser.is_set(control) {
            let sector = index(wiring.snb.get(control));
            Command::EraseSector { sector, psize }
        } else {
            return;
        };
        self.enqueue(bank, command, registers, context);
    }

    /// `MER`, sections 4.3.10 and 4.9.7: sets `BER` and `START` of every bank whose control register is
    /// unlocked, which is a bank erase on each.
    fn mass_erase(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        let unlocked: Vec<usize> = (0..BANKS.len())
            .filter(|&bank| !BANKS[bank].lock.is_set(registers.get(BANKS[bank].cr)))
            .collect();
        let removal = self.removal_requested(&unlocked, registers);
        for bank in unlocked {
            let wiring = &BANKS[bank];
            let control = wiring.ber.set(registers.get(wiring.cr), 1);
            registers.set(wiring.cr, control);
            let psize = index(wiring.psize.get(control));
            self.enqueue(
                bank,
                Command::EraseBank { psize, removal },
                registers,
                context,
            );
        }
    }

    /// Whether a bank erase of `banks` is the "automatic protection-removal" one of section 4.3.10: the
    /// programming registers ask for no protection left, for the erase of the areas that have one, and
    /// change no other option byte.
    fn removal_requested(&self, banks: &[usize], registers: &RegisterFile) -> bool {
        let pending = self.pending_options(registers);
        let kept = &self.options;
        if pending.optsr != kept.optsr || pending.boot != kept.boot {
            return false;
        }
        BANKS.iter().enumerate().all(|(bank, wiring)| {
            if !banks.contains(&bank) {
                return pending.prar[bank] == kept.prar[bank]
                    && pending.scar[bank] == kept.scar[bank]
                    && pending.wpsn[bank] == kept.wpsn[bank];
            }
            let prar = |word: u64| area(wiring.prar_start.get(word), wiring.prar_end.get(word));
            let scar = |word: u64| area(wiring.scar_start.get(word), wiring.scar_end.get(word));
            let pcrop_gone = prar(pending.prar[bank]).is_none()
                && (prar(kept.prar[bank]).is_none()
                    || wiring.dmep.is_set(pending.prar[bank] | kept.prar[bank]));
            let secure_gone = scar(pending.scar[bank]).is_none()
                && (scar(kept.scar[bank]).is_none()
                    || wiring.dmes.is_set(pending.scar[bank] | kept.scar[bank]));
            let writable = wiring.wrps.get(pending.wpsn[bank]) == wiring.wrps.get(u64::MAX);
            pcrop_gone && secure_gone && writable
        })
    }

    /// The option bytes the programming registers hold now, over the ones last committed.
    fn pending_options(&self, registers: &RegisterFile) -> OptionBytes {
        let held = |kept: u64, register: Register| {
            merge(kept, registers.get(register), defined_bits(register))
        };
        let kept = &self.options;
        OptionBytes {
            optsr: held(kept.optsr, Register::OptsrPrg),
            boot: held(kept.boot, Register::BootPrgr),
            prar: [
                held(kept.prar[0], Register::PrarPrg1),
                held(kept.prar[1], Register::PrarPrg2),
            ],
            scar: [
                held(kept.scar[0], Register::ScarPrg1),
                held(kept.scar[1], Register::ScarPrg2),
            ],
            wpsn: [
                held(kept.wpsn[0], Register::WpsnPrg1r),
                held(kept.wpsn[1], Register::WpsnPrg2r),
            ],
        }
    }

    /// `OPTSTART`, section 4.4.3: a change is made only if a programming register differs from its current
    /// one. [`Flash::refuses_change`] says when it's `OPTCHANGEERR` instead, and the area it would
    /// have changed is kept.
    fn start_option_change(
        &mut self,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let pending = self.pending_options(registers);
        if pending == self.options {
            return;
        }
        if Self::refuses_change(&self.options, &pending) {
            let current = registers.get(Register::OptsrCur);
            put(
                registers,
                Register::OptsrCur,
                optsr_cur::OPTCHANGEERR.set(current, 1),
            );
            return;
        }
        self.enqueue(0, Command::Options, registers, context);
    }

    /// Whether section 4.4.3's "Changing security option bytes" refuses the change from `kept` to
    /// `pending`: at level 2 anything but the bank swap, and anything that breaks the rules for the
    /// protected areas.
    fn refuses_change(kept: &OptionBytes, pending: &OptionBytes) -> bool {
        let swap = optsr_prg::SWAP_BANK_OPT;
        let mut without_swap = *pending;
        without_swap.optsr = swap.set(pending.optsr, swap.get(kept.optsr));
        let locked = rdp_level(kept.optsr) == 2 && without_swap != *kept;
        locked || Self::breaks_area_rules(kept, pending)
    }

    /// The rules of section 4.4.3 for the PCROP and secure-only areas, which the model enforces by
    /// whether a level 1 to level 0 regression comes with the change. A bank erase with protection
    /// removal does not come through `OPTSTART`. The rules, with the model's reading of each:
    ///
    /// - An area can be removed or reduced only with a regression, and then only with its erase enable
    ///   (`DMEP` or `DMES`) set in the current or the programming register. The manual says it of a PCROP
    ///   area "removed or reduced" and of a secure-only area "removed". The model takes both the same.
    /// - An erase enable goes from one to zero only with a regression.
    /// - `SECURITY` goes from one to zero, with an area standing, only with a regression and every standing
    ///   area's erase enable set.
    ///
    /// The erase a regression performs is left out, below the table in the module doc.
    fn breaks_area_rules(kept: &OptionBytes, pending: &OptionBytes) -> bool {
        let regression = rdp_level(kept.optsr) == 1 && rdp_level(pending.optsr) == 0;
        let mut standing = false;
        let mut every_erase_enabled = true;
        for (bank, wiring) in BANKS.iter().enumerate() {
            let kinds = [
                (
                    kept.prar[bank],
                    pending.prar[bank],
                    wiring.prar_start,
                    wiring.prar_end,
                    wiring.dmep,
                ),
                (
                    kept.scar[bank],
                    pending.scar[bank],
                    wiring.scar_start,
                    wiring.scar_end,
                    wiring.dmes,
                ),
            ];
            for (old, new, start, end, erase) in kinds {
                let before = area(start.get(old), end.get(old));
                let after = area(start.get(new), end.get(new));
                let reduced = before.as_ref().is_some_and(|before| {
                    !after.as_ref().is_some_and(|after| {
                        after.start() <= before.start() && after.end() >= before.end()
                    })
                });
                let erase_cleared = erase.is_set(old) && !erase.is_set(new);
                let erase_enabled = erase.is_set(old | new);
                if ((reduced || erase_cleared) && !regression) || (reduced && !erase_enabled) {
                    return true;
                }
                if before.is_some() {
                    standing = true;
                    every_erase_enabled &= erase_enabled;
                }
            }
        }
        let security = optsr_prg::SECURITY;
        let cleared = security.is_set(kept.optsr) && !security.is_set(pending.optsr);
        cleared && standing && !(regression && every_erase_enabled)
    }

    /// Makes the programming registers' bytes the current ones, section 4.4.3, and reloads the registers.
    fn commit_options(&mut self, registers: &mut RegisterFile) {
        self.options = self.pending_options(registers);
        self.load_options(Programming::Kept, registers);
    }

    /// Makes one bank's protection words the current ones, as the erase of section 4.3.10 does.
    fn commit_protection(&mut self, bank: usize, registers: &mut RegisterFile) {
        let pending = self.pending_options(registers);
        self.options.prar[bank] = pending.prar[bank];
        self.options.scar[bank] = pending.scar[bank];
        self.options.wpsn[bank] = pending.wpsn[bank];
        self.load_options(Programming::Kept, registers);
    }

    /// Puts the committed option bytes in the current option registers, and in the programming ones too
    /// where `programming` says so, keeping the flags of the current status register. A commit
    /// leaves the programming registers alone: they hold what a driver wrote, which a protection
    /// removal of one bank may not yet have taken for the other.
    fn load_options(&self, programming: Programming, registers: &mut RegisterFile) {
        let flags = optsr_cur::OPT_BUSY.mask() | optsr_cur::OPTCHANGEERR.mask();
        for register in OPTION_REGISTERS {
            if programming == Programming::Kept && is_programming(register) {
                continue;
            }
            let kept = match register {
                Register::OptsrCur | Register::OptsrCur_ => registers.get(register) & flags,
                _ => 0,
            };
            registers.set(register, self.options.word(register) | kept);
        }
    }

    /// Queues an operation on a bank and starts it if the bank is idle.
    fn enqueue(
        &mut self,
        bank: usize,
        command: Command,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        self.banks[bank].queue.push_back(command);
        self.start_next(bank, registers, context);
    }

    /// Starts the bank's next operation, section 4.3.9: the protection of what it targets is checked
    /// "just before the effective write operation", and a violation cancels it with `WRPERR`.
    fn start_next(
        &mut self,
        bank: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let wiring = &BANKS[bank];
        while self.banks[bank].running.is_none() {
            let Some(command) = self.banks[bank].queue.pop_front() else {
                break;
            };
            if Self::refused(wiring, command, registers) {
                raise(registers, wiring, &wiring.flags.wrperr);
                continue;
            }
            let at = VirtualNanos(context.now().0 + command.nanos());
            self.banks[bank].running = Some(Running {
                event: context.schedule(at),
                command,
                phase: Phase::Timing,
                waiting: 0,
                failed: false,
            });
        }
    }

    /// Whether the protection of sections 4.5.2 and 4.7.2 stops `command`. A bank erase with the protection
    /// removal is not stopped by it.
    fn refused(wiring: &Wiring, command: Command, registers: &RegisterFile) -> bool {
        let protected = protected_sectors(wiring, registers);
        match command {
            Command::Program { word, .. } => protected[sector_at(word)],
            Command::EraseSector { sector, .. } => protected[sector],
            Command::EraseBank { removal, .. } => !removal && protected.contains(&true),
            Command::Options => false,
        }
    }

    /// An operation's time is up: the model asks the runtime to put its bytes in the array. A program
    /// reads the word first, since programming only clears bits.
    fn land(&mut self, bank: usize, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        let base = BANKS[bank].base;
        let Some(running) = self.banks[bank].running.as_mut() else {
            return;
        };
        let pieces = match running.command {
            Command::Program { word, .. } => {
                for piece in 0..count(WORD_BYTES) / PIECE_BYTES {
                    let token = Token {
                        bank,
                        step: Step::Read,
                        piece,
                    };
                    context.read_from(word + piece * PIECE_BYTES, Width::W64, token.encode());
                }
                u32::try_from(WORD_BYTES / index(PIECE_BYTES)).expect("a few pieces")
            }
            Command::EraseSector { sector, .. } => erase_span(
                context,
                bank,
                base + count(sector) * SECTOR_BYTES,
                SECTOR_BYTES,
            ),
            Command::EraseBank { .. } => erase_span(context, bank, base, BANK_BYTES),
            Command::Options => 0,
        };
        running.phase = Phase::Landing;
        running.waiting = pieces;
        if pieces == 0 {
            self.finish(bank, registers, context);
        }
    }

    /// One of the runtime's answers to a landing operation, or its refusal. Says whether it was the last,
    /// which finished the operation.
    fn answered(
        &mut self,
        bank: usize,
        refused: bool,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) -> bool {
        let Some(running) = self.banks[bank].running.as_mut() else {
            return false;
        };
        running.failed |= refused;
        running.waiting = running.waiting.saturating_sub(1);
        let last = running.waiting == 0;
        if last {
            self.finish(bank, registers, context);
        }
        last
    }

    /// An operation is done: `EOP`, or `OPERR` if the runtime refused part of it, and the next one starts.
    fn finish(
        &mut self,
        bank: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let wiring = &BANKS[bank];
        let Some(done) = self.banks[bank].running.take() else {
            return;
        };
        if done.failed {
            raise(registers, wiring, &wiring.flags.operr);
        } else {
            match done.command {
                Command::Options => self.commit_options(registers),
                Command::EraseBank { removal: true, .. } => self.commit_protection(bank, registers),
                _ => {}
            }
            raise(registers, wiring, &wiring.flags.eop);
        }
        self.start_next(bank, registers, context);
        self.land_held(registers, context);
    }

    /// Writes held for an option change, applied in order once none is pending.
    fn land_held(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        while !self.option_change_pending() {
            let Some((row, written)) = self.held.pop_front() else {
                break;
            };
            let register = Register::from_index(row).expect("a row the model held");
            registers.write_over_bus(register, written);
            self.apply(register, written, registers, context);
            self.remember(registers);
        }
    }
}

/// Asks the runtime to program ones over `bytes` from `start`, in pieces of 8 bytes, and gives how many.
fn erase_span(context: &mut DeviceContext<'_>, bank: usize, start: u64, bytes: u64) -> u32 {
    let token = Token {
        bank,
        step: Step::Program,
        piece: 0,
    };
    let pieces = bytes / PIECE_BYTES;
    for piece in 0..pieces {
        context.program(
            start + piece * PIECE_BYTES,
            Width::W64,
            u64::MAX,
            token.encode(),
        );
    }
    u32::try_from(pieces).expect("a bank's pieces fit")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::device::{InterruptChange, ResetCause, Told};
    use crate::emulator::{Error, Memory};
    use crate::mcu::{Mcu, Operate, Refused, Single};
    use crate::soc::Fault;
    use crate::soc::stm32h743::builder;
    use crate::soc::stm32h743::generated::FLASH;
    use crate::soc::stm32h743::generated::flash::{boot_curr, crccr2, crcsadd2r};

    /// Where bank 1 and bank 2 begin, RM0433 rev 9 Table 15.
    const BANK_1: u64 = 0x0800_0000;
    const BANK_2: u64 = 0x0810_0000;
    const START: VirtualNanos = VirtualNanos(0);

    /// The guest's flash the way the emulator keeps it: all ones once erased, and changed by a program
    /// alone, never by a write.
    struct Array {
        bytes: Vec<u8>,
        programmable: bool,
    }

    impl Array {
        fn new() -> Self {
            Self {
                bytes: vec![0xFF; 2 << 20],
                programmable: true,
            }
        }

        fn span(&self, address: u64, width: Width) -> Result<std::ops::Range<usize>, Error> {
            let start = address
                .checked_sub(BANK_1)
                .map(index)
                .filter(|&start| start + index(u64::from(width.bytes())) <= self.bytes.len())
                .ok_or(Error::Memory { address, width })?;
            Ok(start..start + index(u64::from(width.bytes())))
        }

        /// What the array holds at `address`, as the firmware would read a word.
        fn word(&mut self, address: u64) -> u64 {
            self.read(address, Width::W32).expect("inside the array")
        }

        /// Puts `value` in every byte of a span, as the image or an earlier program left it.
        fn fill(&mut self, address: u64, length: u64, value: u8) {
            let start = index(address - BANK_1);
            self.bytes[start..start + index(length)].fill(value);
        }

        /// Whether every byte of a span reads as erased.
        fn erased(&self, address: u64, length: u64) -> bool {
            self.bytes_at(address, index(length))
                .iter()
                .all(|&byte| byte == 0xFF)
        }

        fn bytes_at(&self, address: u64, length: usize) -> &[u8] {
            let start = index(address - BANK_1);
            &self.bytes[start..start + length]
        }
    }

    impl Memory for Array {
        fn read(&mut self, address: u64, width: Width) -> Result<u64, Error> {
            let span = self.span(address, width)?;
            let mut bytes = [0_u8; 8];
            bytes[..span.len()].copy_from_slice(&self.bytes[span]);
            Ok(u64::from_le_bytes(bytes))
        }

        fn write(&mut self, address: u64, width: Width, _value: u64) -> Result<(), Error> {
            Err(Error::Memory { address, width })
        }

        fn program(&mut self, address: u64, width: Width, value: u64) -> Result<(), Error> {
            let span = self.span(address, width)?;
            if !self.programmable {
                return Err(Error::Memory { address, width });
            }
            let length = span.len();
            self.bytes[span].copy_from_slice(&value.to_le_bytes()[..length]);
            Ok(())
        }
    }

    /// The interface on a bus of its own, the guest's flash behind it, and the instant the test has reached.
    struct Rig {
        soc: Single<Flash>,
        array: Array,
        now: VirtualNanos,
        refused: Vec<Refused>,
    }

    impl Rig {
        fn new() -> Self {
            Self::with(Flash::new())
        }

        fn with(model: Flash) -> Self {
            Self {
                soc: Single::new(builder(), "Flash", model).expect("the bus builds"),
                array: Array::new(),
                now: START,
                refused: Vec::new(),
            }
        }

        fn address(register: Register) -> u64 {
            FLASH.base + u64::from(register.spec().offset)
        }

        fn settle(&mut self) {
            let refused = self.soc.settle(&mut self.array).expect("the settle runs");
            self.refused.extend(refused);
        }

        fn read(&mut self, register: Register) -> u64 {
            self.soc
                .read(self.now, Self::address(register), Width::W32)
                .expect("the register answers")
        }

        fn write(&mut self, register: Register, value: u64) {
            self.soc
                .write(self.now, Self::address(register), Width::W32, value)
                .expect("the register takes the write");
            self.settle();
        }

        /// A store of the firmware into the flash array.
        fn store(&mut self, address: u64, width: Width, value: u64) -> Result<(), Fault> {
            let stored = self.soc.write(self.now, address, width, value);
            self.settle();
            stored
        }

        fn store_word(&mut self, address: u64, value: u64) {
            self.store(address, Width::W32, value)
                .expect("the interface takes the store");
        }

        fn advance(&mut self, nanos: u64) {
            self.now = VirtualNanos(self.now.0 + nanos);
            self.soc.advance_to(self.now);
            self.settle();
        }

        /// Waits as a polling firmware does, one event at a time, until `done` holds.
        fn wait_until(&mut self, register: Register, done: impl Fn(u64) -> bool) {
            for _ in 0..1_000_000 {
                if done(self.read(register)) {
                    return;
                }
                let next = self.soc.next_event().expect("something is pending");
                self.now = next.max(self.now);
                self.soc.advance_to(self.now);
                self.settle();
            }
            panic!("{register:?} never reached the state the test waits for");
        }

        fn unlock(&mut self, bank: usize) {
            let key = [Register::Keyr1, Register::Keyr2][bank];
            self.write(key, CR_KEYS.0);
            self.write(key, CR_KEYS.1);
        }

        fn unlock_options(&mut self) {
            self.write(Register::Optkeyr, OPT_KEYS.0);
            self.write(Register::Optkeyr, OPT_KEYS.1);
        }

        /// Sets bits of a register by reading it and writing it back, as `|=` does.
        fn set_bits(&mut self, register: Register, bits: u64) {
            let current = self.read(register);
            self.write(register, current | bits);
        }

        fn status(&mut self, bank: usize) -> u64 {
            self.read(BANKS[bank].sr)
        }

        /// Changes option bytes the way a driver does: unlock, write the programming registers, start the
        /// change, wait for `OPT_BUSY` to clear and lock again.
        fn commit(&mut self, words: &[(Register, u64)]) {
            self.unlock_options();
            for &(register, value) in words {
                self.write(register, value);
            }
            self.set_bits(Register::Optcr, optcr::OPTSTART.mask());
            self.wait_until(Register::OptsrCur, |value| {
                !optsr_cur::OPT_BUSY.is_set(value)
            });
            self.write(Register::Optcr, OPTLOCK.mask());
        }

        fn told(&mut self) -> Vec<Told> {
            self.soc.drain_told()
        }

        fn registers(&mut self) -> &mut RegisterFile {
            Single::registers(&mut self.soc)
        }

        /// The protected-area words the model has committed for each bank.
        fn committed_prar(&self) -> [u64; 2] {
            self.soc.model.committed_options().prar
        }

        /// A system reset the way a part does it: every register back to its reset value and the model
        /// told, then the option bytes the last commit left put back.
        fn reset(&mut self) {
            let kept = self.soc.model.committed_options();
            self.soc.reset(self.now, ResetCause::Pin);
            let (model, registers) = self.soc.pair();
            model.keep_options(kept, registers);
        }
    }

    /// What a driver does before it stores: unlock the bank and enable its write buffer at `psize`.
    fn prepare_program(rig: &mut Rig, bank: usize, psize: u64) {
        rig.unlock(bank);
        let wiring = &BANKS[bank];
        rig.write(wiring.cr, wiring.pg.mask() | wiring.psize.set(0, psize));
    }

    /// Register writes that make one option change.
    type Change = Vec<(Register, u64)>;

    /// A case for the area rules: its label, the change that sets it up, the change tried, and the
    /// outcome the test of the case expects of it.
    type Case = (&'static str, Change, Change, bool);

    /// A PCROP area word, section 4.9.12: blocks of 256 bytes from `start` to `end`, with its erase enable.
    fn pcrop(start: u64, end: u64, erase: bool) -> u64 {
        let word = prar_cur1::PROT_AREA_START1.set(0, start);
        let word = prar_cur1::PROT_AREA_END1.set(word, end);
        prar_cur1::DMEP1.set(word, u64::from(erase))
    }

    /// A secure-only area word, section 4.9.14, the same shape.
    fn secure(start: u64, end: u64, erase: bool) -> u64 {
        let word = scar_cur1::SEC_AREA_START1.set(0, start);
        let word = scar_cur1::SEC_AREA_END1.set(word, end);
        scar_cur1::DMES1.set(word, u64::from(erase))
    }

    /// Commits as `Rig::commit` does after clearing `OPTCHANGEERR`, and answers whether the change was
    /// taken, which is the flag still clear.
    fn try_commit(rig: &mut Rig, words: &[(Register, u64)]) -> bool {
        rig.write(Register::Optccr, optccr::CLR_OPTCHANGEERR.mask());
        rig.commit(words);
        !optsr_cur::OPTCHANGEERR.is_set(rig.read(Register::OptsrCur))
    }

    /// What a driver does to erase a sector: unlock, write the control register with the sector number
    /// and `SER`, then set `START`.
    fn erase_sector(rig: &mut Rig, bank: usize, sector: u64, psize: u64) {
        let wiring = &BANKS[bank];
        rig.write(
            wiring.cr,
            wiring.ser.mask() | wiring.snb.set(0, sector) | wiring.psize.set(0, psize),
        );
        rig.set_bits(wiring.cr, wiring.start.mask());
    }

    /// Fills one flash word with eight words counting up from `seed`, by 32-bit stores.
    fn fill_word(rig: &mut Rig, address: u64, seed: u64) {
        for offset in 0..8 {
            rig.store_word(address + offset * 4, seed + offset);
        }
    }

    /// RM0433 rev 9 section 4.9.38's Table 28 and Table 21, register by register, as each reads after a
    /// reset. The option registers read the factory bytes, which Table 28 gives as `X`.
    #[test]
    fn reset_values_match_the_manual() {
        let factory_optsr = 0x0006_AAF0;
        let factory_boot = 0x1FF0_0800;
        let expected: [(Register, u64); 46] = [
            (Register::Acr, 0x37),
            (Register::Keyr1, 0),
            (Register::Optkeyr, 0),
            (Register::Cr1, 0x31),
            (Register::Sr1, 0),
            (Register::Ccr1, 0),
            (Register::Optcr, 1),
            (Register::OptsrCur, factory_optsr),
            (Register::OptsrPrg, factory_optsr),
            (Register::Optccr, 0),
            (Register::PrarCur1, 0xFF),
            (Register::PrarPrg1, 0xFF),
            (Register::ScarCur1, 0x8000_00FF),
            (Register::ScarPrg1, 0x8000_00FF),
            (Register::WpsnCur1r, 0xFF),
            (Register::WpsnPrg1r, 0xFF),
            (Register::BootCurr, factory_boot),
            (Register::BootPrgr, factory_boot),
            (Register::Crccr1, 0x001C_0000),
            (Register::Crcsadd1r, 0),
            (Register::Crceadd1r, 0),
            (Register::Crcdatar, 0),
            (Register::EccFa1r, 0),
            (Register::Acr_, 0x37),
            (Register::Keyr2, 0),
            (Register::Optkeyr_, 0),
            (Register::Cr2, 0x31),
            (Register::Sr2, 0),
            (Register::Ccr2, 0),
            (Register::Optcr_, 1),
            (Register::OptsrCur_, factory_optsr),
            (Register::OptsrPrg_, factory_optsr),
            (Register::Optccr_, 0),
            (Register::PrarCur2, 0xFF),
            (Register::PrarPrg2, 0xFF),
            (Register::ScarCur2, 0x8000_00FF),
            (Register::ScarPrg2, 0x8000_00FF),
            (Register::WpsnCur2r, 0xFF),
            (Register::WpsnPrg2r, 0xFF),
            (Register::BootCurr_, factory_boot),
            (Register::BootPrgr_, factory_boot),
            (Register::Crccr2, 0x001C_0000),
            (Register::Crcsadd2r, 0),
            (Register::Crceadd2r, 0),
            (Register::Crcdatar_, 0),
            (Register::EccFa2r, 0),
        ];
        let mut rig = Rig::new();
        for (register, value) in expected {
            assert_eq!(rig.read(register), value, "{register:?}");
        }
    }

    /// Table 21's default factory values taken field by field, which is the witness that
    /// [`OptionBytes::FACTORY`] says what the table does.
    #[test]
    fn the_factory_option_bytes_are_table_21s_by_field() {
        let mut rig = Rig::new();
        let optsr = rig.read(Register::OptsrCur);
        assert_eq!(
            optsr_cur::RDP.get(optsr),
            0xAA,
            "readout protection level 0"
        );
        assert_eq!(
            optsr_cur::IWDG1_SW.get(optsr),
            1,
            "software watchdog control"
        );
        assert_eq!(optsr_cur::IWDG_FZ_STOP.get(optsr), 1);
        assert_eq!(optsr_cur::IWDG_FZ_SDBY.get(optsr), 1);
        assert_eq!(optsr_cur::NRST_STOP_D1.get(optsr), 1, "no reset on DStop");
        assert_eq!(
            optsr_cur::NRST_STBY_D1.get(optsr),
            1,
            "no reset on DStandby"
        );
        assert_eq!(optsr_cur::BOR_LEV.get(optsr), 0);
        assert_eq!(optsr_cur::SECURITY.get(optsr), 0);
        assert_eq!(optsr_cur::SWAP_BANK_OPT.get(optsr), 0);
        assert_eq!(optsr_cur::IO_HSLV.get(optsr), 0);
        assert_eq!(optsr_cur::OPT_BUSY.get(optsr), 0);
        assert_eq!(optsr_cur::OPTCHANGEERR.get(optsr), 0);
        let boot = rig.read(Register::BootCurr);
        assert_eq!(boot_curr::BOOT_ADD0.get(boot), 0x0800);
        assert_eq!(boot_curr::BOOT_ADD1.get(boot), 0x1FF0);
        for wiring in &BANKS {
            let prar = rig.read(wiring.prar_cur);
            assert_eq!(wiring.prar_start.get(prar), 0x0FF);
            assert_eq!(wiring.prar_end.get(prar), 0x000);
            assert_eq!(wiring.dmep.get(prar), 0, "PCROP areas preserved");
            assert!(area(wiring.prar_start.get(prar), wiring.prar_end.get(prar)).is_none());
            let scar = rig.read(wiring.scar_cur);
            assert_eq!(wiring.scar_start.get(scar), 0x0FF);
            assert_eq!(wiring.scar_end.get(scar), 0x000);
            assert_eq!(wiring.dmes.get(scar), 1, "secure-only areas erased");
            assert_eq!(
                wiring.wrps.get(rig.read(wiring.wpsn_cur)),
                0xFF,
                "every sector writable"
            );
        }
    }

    /// Section 4.3.13's Table 20: `FLASH_ACR` and the option registers are one register each, at two
    /// addresses, and a write to either is seen by both.
    #[test]
    fn a_common_register_answers_alike_at_both_addresses() {
        let mut rig = Rig::new();
        rig.write(Register::Acr_, 0x02);
        assert_eq!(rig.read(Register::Acr), 0x02);
        rig.write(Register::Acr, 0x25);
        assert_eq!(rig.read(Register::Acr_), 0x25);

        // The option key register's second address takes the first key and the first address the second.
        rig.write(Register::Optkeyr_, OPT_KEYS.0);
        rig.write(Register::Optkeyr, OPT_KEYS.1);
        assert!(
            !OPTLOCK.is_set(rig.read(Register::Optcr_)),
            "unlocked at either address"
        );
        rig.write(Register::OptsrPrg_, 0x0006_AAF4);
        assert_eq!(rig.read(Register::OptsrPrg), 0x0006_AAF4);
        rig.write(Register::BootPrgr_, 0x1FF0_0900);
        assert_eq!(rig.read(Register::BootPrgr), 0x1FF0_0900);
    }

    /// Section 4.9.1: `LATENCY` and `WRHIGHFREQ` are stored, and the reserved bits above them stay clear.
    #[test]
    fn latency_and_wrhighfreq_are_stored() {
        let mut rig = Rig::new();
        rig.write(
            Register::Acr,
            acr::LATENCY.set(acr::WRHIGHFREQ.set(0, 2), 5),
        );
        let value = rig.read(Register::Acr);
        assert_eq!(acr::LATENCY.get(value), 5);
        assert_eq!(acr::WRHIGHFREQ.get(value), 2);
        rig.write(Register::Acr, u64::from(u32::MAX));
        assert_eq!(
            rig.read(Register::Acr),
            0x3F,
            "four bits and two, nothing reserved"
        );
    }

    /// Section 4.3.9's caution: changing `WRHIGHFREQ` while the flash programs or erases might corrupt
    /// it. The write has landed and there is nothing to refuse, so the session is told.
    #[test]
    fn changing_wrhighfreq_under_an_operation_is_told() {
        let mut rig = Rig::new();
        rig.write(Register::Acr, acr::WRHIGHFREQ.set(0, 1));
        assert!(rig.told().is_empty(), "idle, so nothing to corrupt");
        rig.unlock(0);
        rig.set_bits(Register::Cr1, cr1::SER1.mask() | cr1::START1.mask());
        rig.write(Register::Acr, acr::WRHIGHFREQ.set(0, 2));
        assert_eq!(
            rig.told(),
            vec![Told {
                instance: "Flash",
                register: "ACR",
                reason: WRHIGHFREQ_BUSY,
                at: START,
            }]
        );
        rig.write(Register::Acr, acr::WRHIGHFREQ.set(0, 2));
        assert!(rig.told().is_empty(), "unchanged, so nothing new");
    }

    /// Section 4.5.1: `KEY1` then `KEY2` clears `LOCK1`, and each bank has a lock of its own.
    #[test]
    fn the_unlock_sequence_clears_lock_of_its_own_bank_alone() {
        let mut rig = Rig::new();
        assert!(LOCK1.is_set(rig.read(Register::Cr1)));
        rig.unlock(0);
        assert!(!LOCK1.is_set(rig.read(Register::Cr1)));
        assert!(
            LOCK2.is_set(rig.read(Register::Cr2)),
            "bank 2 is locked still"
        );
        rig.unlock(1);
        assert!(!LOCK2.is_set(rig.read(Register::Cr2)));
        assert!(rig.told().is_empty());
    }

    fn bad_key(register: &'static str, reason: &'static str) -> Told {
        Told {
            instance: "Flash",
            register,
            reason,
            at: START,
        }
    }

    /// Section 4.5.1: "Any wrong sequence locks up the corresponding register/bit until the next system
    /// reset", with a bus error the model cannot give, so it tells the session, once.
    #[test]
    fn a_wrong_second_key_locks_the_register_until_reset() {
        let mut rig = Rig::new();
        rig.write(Register::Keyr1, CR_KEYS.0);
        rig.write(Register::Keyr1, 0);
        assert!(LOCK1.is_set(rig.read(Register::Cr1)));
        assert_eq!(rig.told(), vec![bad_key("KEYR1", BAD_KEY)]);
        rig.unlock(0);
        assert!(
            LOCK1.is_set(rig.read(Register::Cr1)),
            "a bricked sequence does not recover"
        );
        assert!(
            rig.told().is_empty(),
            "told on the write that did it, and not again"
        );
        rig.unlock(1);
        assert!(
            !LOCK2.is_set(rig.read(Register::Cr2)),
            "the other bank is its own"
        );
        rig.reset();
        rig.unlock(0);
        assert!(
            !LOCK1.is_set(rig.read(Register::Cr1)),
            "a reset gives it a new chance"
        );
    }

    /// A first word that is not `KEY1` is a wrong sequence as well.
    #[test]
    fn a_wrong_first_key_locks_the_register_until_reset() {
        let mut rig = Rig::new();
        rig.write(Register::Keyr2, CR_KEYS.1);
        assert_eq!(rig.told(), vec![bad_key("KEYR2", BAD_KEY)]);
        rig.unlock(1);
        assert!(LOCK2.is_set(rig.read(Register::Cr2)));
    }

    /// Section 4.5.1's third key, and section 4.9.4's "unlock sequence ... performed twice": a key
    /// written to a register already unlocked locks it again, until reset.
    #[test]
    fn unlocking_twice_or_a_third_key_locks_the_register_until_reset() {
        let mut rig = Rig::new();
        rig.unlock(0);
        rig.write(Register::Keyr1, CR_KEYS.0);
        assert!(LOCK1.is_set(rig.read(Register::Cr1)));
        assert_eq!(rig.told(), vec![bad_key("KEYR1", BAD_KEY)]);
        rig.unlock(0);
        assert!(LOCK1.is_set(rig.read(Register::Cr1)));
        assert!(rig.told().is_empty());
    }

    /// Section 4.9.4: `LOCK1` is set by writing one, and "a new unlock sequence is mandatory to unlock it".
    /// Locking by software is not a wrong sequence, so the next unlock works.
    #[test]
    fn lock_is_written_one_only_and_a_new_unlock_follows() {
        let mut rig = Rig::new();
        rig.unlock(0);
        rig.write(Register::Cr1, 0);
        assert!(
            !LOCK1.is_set(rig.read(Register::Cr1)),
            "a zero does not lock"
        );
        rig.write(Register::Cr1, LOCK1.mask());
        rig.write(Register::Cr1, 0);
        assert!(
            LOCK1.is_set(rig.read(Register::Cr1)),
            "and a zero does not unlock"
        );
        rig.unlock(0);
        assert!(!LOCK1.is_set(rig.read(Register::Cr1)));
        assert!(rig.told().is_empty());
    }

    /// Section 4.5.1: writing "to a different register belonging to the same bank than `FLASH_KEYR1/2`
    /// before `FLASH_CR1/2` has been completely unlocked" locks it. Another bank's registers and the
    /// common ones are not that bank's.
    #[test]
    fn a_write_to_another_register_of_the_bank_between_the_keys_locks_it() {
        let mut rig = Rig::new();
        rig.write(Register::Keyr1, CR_KEYS.0);
        rig.write(Register::Ccr2, 0);
        rig.write(Register::Acr, 0);
        assert!(
            rig.told().is_empty(),
            "bank 2's register and a common one are not bank 1's"
        );
        rig.write(Register::Keyr1, CR_KEYS.1);
        assert!(!LOCK1.is_set(rig.read(Register::Cr1)));

        let mut rig = Rig::new();
        rig.write(Register::Keyr1, CR_KEYS.0);
        rig.write(Register::Ccr1, 0);
        assert_eq!(rig.told(), vec![bad_key("KEYR1", KEY_INTERRUPTED)]);
        rig.write(Register::Keyr1, CR_KEYS.1);
        assert!(LOCK1.is_set(rig.read(Register::Cr1)));
    }

    /// Section 4.5.1, the option key register: the same sequence over `OPTLOCK`, and "writing to a
    /// different register before `FLASH_OPTCR` has been completely unlocked" locks it.
    #[test]
    fn the_option_unlock_sequence_clears_optlock() {
        let mut rig = Rig::new();
        assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
        rig.unlock_options();
        assert!(!OPTLOCK.is_set(rig.read(Register::Optcr)));
        assert!(rig.told().is_empty());

        rig.write(Register::Optcr, OPTLOCK.mask());
        rig.write(Register::Optcr, 0);
        assert!(
            OPTLOCK.is_set(rig.read(Register::Optcr)),
            "set by a one, kept by a zero"
        );
        rig.unlock_options();
        assert!(!OPTLOCK.is_set(rig.read(Register::Optcr)));
    }

    #[test]
    fn a_wrong_option_key_locks_the_option_registers_until_reset() {
        let mut rig = Rig::new();
        rig.write(Register::Optkeyr, OPT_KEYS.0);
        rig.write(Register::Optkeyr, OPT_KEYS.0);
        assert_eq!(rig.told(), vec![bad_key("OPTKEYR", BAD_KEY)]);
        rig.unlock_options();
        assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
        rig.reset();
        rig.unlock_options();
        assert!(!OPTLOCK.is_set(rig.read(Register::Optcr)));
    }

    #[test]
    fn a_third_option_key_or_a_stray_write_between_the_keys_locks_the_option_registers() {
        let mut rig = Rig::new();
        rig.unlock_options();
        rig.write(Register::Optkeyr, OPT_KEYS.0);
        assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
        assert_eq!(rig.told(), vec![bad_key("OPTKEYR", BAD_KEY)]);

        let mut rig = Rig::new();
        rig.write(Register::Optkeyr, OPT_KEYS.0);
        rig.write(Register::Acr, 0);
        assert_eq!(rig.told(), vec![bad_key("OPTKEYR", KEY_INTERRUPTED)]);
        rig.write(Register::Optkeyr, OPT_KEYS.1);
        assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
    }

    /// Sections 4.9.2, 4.9.3, 4.9.6 and 4.9.10: write-only registers read zero.
    #[test]
    fn the_key_and_clear_registers_read_zero() {
        let mut rig = Rig::new();
        for register in [
            Register::Keyr1,
            Register::Keyr2,
            Register::Optkeyr,
            Register::Optkeyr_,
            Register::Ccr1,
            Register::Ccr2,
            Register::Optccr,
            Register::Optccr_,
        ] {
            rig.write(register, 0x5555_5555);
            assert_eq!(rig.read(register), 0, "{register:?}");
        }
    }

    /// Section 4.9.4: every field of `FLASH_CR1` but `LOCK1` is writable only while it is clear, and
    /// locking again leaves the rest as it was.
    #[test]
    fn the_control_register_is_frozen_while_locked() {
        let mut rig = Rig::new();
        rig.write(
            Register::Cr1,
            cr1::PG1.mask() | cr1::EOPIE1.mask() | cr1::SNB1.set(0, 5),
        );
        assert_eq!(rig.read(Register::Cr1), 0x31, "the reset value stands");
        rig.unlock(0);
        let written =
            cr1::PG1.mask() | cr1::EOPIE1.mask() | cr1::SNB1.set(0, 5) | cr1::PSIZE1.set(0, 2);
        rig.write(Register::Cr1, written);
        assert_eq!(rig.read(Register::Cr1), written);
        rig.write(Register::Cr1, written | LOCK1.mask());
        assert_eq!(
            rig.read(Register::Cr1),
            written | LOCK1.mask(),
            "locking changes no other bit"
        );
        rig.write(Register::Cr1, 0);
        assert_eq!(
            rig.read(Register::Cr1),
            written | LOCK1.mask(),
            "and now nothing else does"
        );
    }

    /// Section 4.3.9: a word of 32 bytes programs for the datasheet's time at the parallelism `PSIZE`
    /// holds, `QW` and `BSY` standing the while, and `EOP` set when it is done.
    #[test]
    fn a_word_programs_after_its_time_by_psize() {
        for (psize, nanos) in [(0, 290_000), (1, 180_000), (2, 130_000), (3, 100_000)] {
            let mut rig = Rig::new();
            prepare_program(&mut rig, 0, psize);
            fill_word(&mut rig, BANK_1, 0x100);
            let status = rig.status(0);
            assert!(
                sr1::QW1.is_set(status) && sr1::BSY1.is_set(status),
                "PSIZE {psize}"
            );
            assert!(!sr1::WBNE1.is_set(status));
            rig.advance(nanos - 1);
            let status = rig.status(0);
            assert!(
                sr1::QW1.is_set(status) && !sr1::EOP1.is_set(status),
                "PSIZE {psize}"
            );
            assert_eq!(
                rig.array.word(BANK_1),
                u64::from(u32::MAX),
                "nothing lands early"
            );
            rig.advance(1);
            let status = rig.status(0);
            assert!(
                !sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status),
                "PSIZE {psize}"
            );
            assert!(sr1::EOP1.is_set(status));
            for offset in 0..8 {
                assert_eq!(rig.array.word(BANK_1 + offset * 4), 0x100 + offset);
            }
            assert_eq!(
                rig.array.word(BANK_1 + 32),
                u64::from(u32::MAX),
                "the next word is untouched"
            );
        }
    }

    /// Section 4.3.9: `WBNE` stands while the buffer waits for the rest of its word, and nothing is
    /// queued until it has all of it.
    #[test]
    fn wbne_stands_while_the_buffer_is_partial() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        for offset in 0..7 {
            rig.store_word(BANK_1 + offset * 4, offset);
            let status = rig.status(0);
            assert!(sr1::WBNE1.is_set(status), "after {} words", offset + 1);
            assert!(!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status));
        }
        rig.store_word(BANK_1 + 28, 7);
        let status = rig.status(0);
        assert!(!sr1::WBNE1.is_set(status));
        assert!(sr1::QW1.is_set(status));
    }

    /// Section 4.3.3: the stores come in any length the bus has, and the word fills the same.
    #[test]
    fn stores_of_every_width_fill_the_word() {
        let pattern: Vec<u8> = (0..32).map(|byte| 0xA0 + byte).collect();
        for (width, bytes) in [
            (Width::W8, 1),
            (Width::W16, 2),
            (Width::W32, 4),
            (Width::W64, 8),
        ] {
            let mut rig = Rig::new();
            prepare_program(&mut rig, 0, 3);
            for first in (0..32).step_by(bytes) {
                let mut value = [0_u8; 8];
                value[..bytes].copy_from_slice(&pattern[first..first + bytes]);
                rig.store(BANK_1 + first as u64, width, u64::from_le_bytes(value))
                    .expect("the interface takes the store");
            }
            rig.advance(100_000);
            assert_eq!(rig.array.bytes_at(BANK_1, 32), pattern, "{width:?}");
        }
    }

    /// A store that runs across two words is two stores of the bus. The first completes the word it
    /// begins in, and the second begins the next.
    #[test]
    fn a_store_across_two_words_finishes_one_and_starts_the_next() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        for offset in 0..7 {
            rig.store_word(BANK_1 + offset * 4, 0x1111_1111);
        }
        rig.store(BANK_1 + 28, Width::W64, 0x2222_2222_3333_3333)
            .expect("the interface takes the store");
        let status = rig.status(0);
        assert!(sr1::QW1.is_set(status), "the first word is complete");
        assert!(sr1::WBNE1.is_set(status), "and the second has begun");
        assert!(!sr1::INCERR1.is_set(status));
        rig.advance(100_000);
        assert_eq!(rig.array.word(BANK_1 + 28), 0x3333_3333);
        assert_eq!(
            rig.array.bytes_at(BANK_1 + 32, 4),
            [0xFF; 4],
            "the second is not yet whole"
        );
        for offset in 1..8 {
            rig.store_word(BANK_1 + 32 + offset * 4, 0x4444_4444);
        }
        rig.advance(100_000);
        assert_eq!(
            rig.array.bytes_at(BANK_1 + 32, 8),
            [0x22, 0x22, 0x22, 0x22, 0x44, 0x44, 0x44, 0x44]
        );
    }

    /// Section 4.3.9: `FW` writes the buffer with the bytes not written set to ones, and clears itself.
    #[test]
    fn fw_forces_a_partial_word_with_ones_in_the_rest() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        rig.store_word(BANK_1, 0x1111_1111);
        rig.store_word(BANK_1 + 4, 0x2222_2222);
        rig.set_bits(Register::Cr1, cr1::FW1.mask());
        let status = rig.status(0);
        assert!(!sr1::WBNE1.is_set(status));
        assert!(sr1::QW1.is_set(status));
        assert!(!cr1::FW1.is_set(rig.read(Register::Cr1)), "acknowledged");
        rig.advance(100_000);
        assert_eq!(rig.array.word(BANK_1), 0x1111_1111);
        assert_eq!(rig.array.word(BANK_1 + 4), 0x2222_2222);
        for offset in 2..8 {
            assert_eq!(
                rig.array.word(BANK_1 + offset * 4),
                0xFFFF_FFFF,
                "word {offset}"
            );
        }
    }

    /// Section 4.3.9: "If no bit in the write buffer is cleared to 0, the FW1/2 bit has no effect", and
    /// section 4.9.4: "Write forcing is effective only if the write buffer is not empty".
    #[test]
    fn fw_has_no_effect_on_an_empty_buffer_or_one_with_nothing_cleared() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        rig.set_bits(Register::Cr1, cr1::FW1.mask());
        assert!(!sr1::QW1.is_set(rig.status(0)), "nothing to force");
        rig.store_word(BANK_1, 0xFFFF_FFFF);
        rig.set_bits(Register::Cr1, cr1::FW1.mask());
        let status = rig.status(0);
        assert!(!sr1::QW1.is_set(status), "nothing in it is cleared");
        assert!(sr1::WBNE1.is_set(status), "and it still waits");
    }

    /// Section 4.9.4: clearing `PG1` disables the buffer, "and all the data stored in the buffer but not
    /// sent to the operation queue are lost". Section 4.6.2 lists it as a way to clear `WBNE`.
    #[test]
    fn clearing_pg_drops_a_partial_word() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        rig.store_word(BANK_1, 0x1234_5678);
        assert!(sr1::WBNE1.is_set(rig.status(0)));
        rig.write(Register::Cr1, cr1::PSIZE1.set(0, 3));
        let status = rig.status(0);
        assert!(!sr1::WBNE1.is_set(status) && !sr1::QW1.is_set(status));
        rig.write(Register::Cr1, cr1::PG1.mask() | cr1::PSIZE1.set(0, 3));
        fill_word(&mut rig, BANK_1 + 64, 7);
        assert!(
            !sr1::INCERR1.is_set(rig.status(0)),
            "a new word at another address is a new word"
        );
        rig.advance(100_000);
        assert_eq!(
            rig.array.word(BANK_1),
            0xFFFF_FFFF,
            "the dropped data never lands"
        );
        assert_eq!(rig.array.word(BANK_1 + 64), 7);
    }

    /// Section 4.3.9: "Any write access requested while the PG1/2 bit is cleared to 0 is rejected. In
    /// this case, no error is generated on the bus, but the PGSERR1/2 flag is raised."
    #[test]
    fn a_store_without_pg_is_rejected_with_pgserr_and_no_bus_error() {
        for unlocked in [false, true] {
            let mut rig = Rig::new();
            if unlocked {
                rig.unlock(0);
            }
            rig.store(BANK_1, Width::W32, 0x1234).expect("no bus error");
            let status = rig.status(0);
            assert!(sr1::PGSERR1.is_set(status), "unlocked {unlocked}");
            assert!(!sr1::QW1.is_set(status) && !sr1::WBNE1.is_set(status));
            rig.advance(1_000_000);
            assert_eq!(rig.array.word(BANK_1), 0xFFFF_FFFF);
        }
    }

    /// Section 4.7.3: "The PGSERR1/2 flag also blocks any new program operation", until it is cleared.
    #[test]
    fn a_standing_pgserr_blocks_stores_until_cleared() {
        let mut rig = Rig::new();
        rig.unlock(0);
        rig.store(BANK_1, Width::W32, 1).expect("no bus error");
        rig.write(Register::Cr1, cr1::PG1.mask() | cr1::PSIZE1.set(0, 3));
        fill_word(&mut rig, BANK_1, 0x10);
        assert!(!sr1::QW1.is_set(rig.status(0)), "blocked");
        rig.write(Register::Ccr1, ccr1::CLR_PGSERR1.mask());
        fill_word(&mut rig, BANK_1, 0x10);
        assert!(sr1::QW1.is_set(rig.status(0)));
        rig.advance(100_000);
        assert_eq!(rig.array.word(BANK_1 + 28), 0x17);
    }

    /// Section 4.7.5: a write to another word before the buffer is full is an inconsistency, and what
    /// was gathered is lost. Section 4.7.3: with it left standing, the next write is a sequence error.
    #[test]
    fn a_store_to_another_word_is_incerr_and_a_standing_incerr_makes_the_next_pgserr() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        rig.store_word(BANK_1, 1);
        rig.store_word(BANK_1 + 32, 2);
        let status = rig.status(0);
        assert!(sr1::INCERR1.is_set(status));
        assert!(!sr1::WBNE1.is_set(status), "the partial word is gone");
        assert!(!sr1::PGSERR1.is_set(status));
        rig.store_word(BANK_1 + 64, 3);
        assert!(
            sr1::PGSERR1.is_set(rig.status(0)),
            "INCERR was left standing"
        );
        rig.write(
            Register::Ccr1,
            ccr1::CLR_INCERR1.mask() | ccr1::CLR_PGSERR1.mask(),
        );
        fill_word(&mut rig, BANK_1 + 64, 3);
        rig.advance(100_000);
        assert_eq!(rig.array.word(BANK_1 + 64), 3);
        assert_eq!(rig.array.word(BANK_1), 0xFFFF_FFFF);
        assert_eq!(rig.array.word(BANK_1 + 32), 0xFFFF_FFFF);
    }

    /// Section 4.7.4: a byte written twice is a strobe error, "the current program operation is not
    /// aborted and new byte data replace the old ones."
    #[test]
    fn a_byte_written_twice_is_strobe_error_and_the_new_byte_replaces_the_old() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        rig.store(BANK_1, Width::W8, 0x12).expect("taken");
        rig.store(BANK_1, Width::W8, 0x34).expect("taken");
        assert!(sr1::STRBERR1.is_set(rig.status(0)));
        assert!(
            sr1::WBNE1.is_set(rig.status(0)),
            "the word is still being gathered"
        );
        for offset in 1..32 {
            rig.store(BANK_1 + offset, Width::W8, offset)
                .expect("taken");
        }
        rig.advance(100_000);
        assert_eq!(rig.array.bytes_at(BANK_1, 3), [0x34, 1, 2]);
        assert!(sr1::EOP1.is_set(rig.status(0)));
    }

    /// Section 4.3.9: programming "can change (reset) any memory bitcell to 0" and cannot return one to
    /// its virgin state, so a word programmed over holds only the bits both asked for.
    #[test]
    fn programming_a_word_that_is_not_virgin_only_clears_bits() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        for offset in 0..8 {
            rig.store_word(BANK_1 + offset * 4, 0xAAAA_AAAA);
        }
        rig.advance(100_000);
        for offset in 0..8 {
            rig.store_word(BANK_1 + offset * 4, 0x5555_FFFF);
        }
        rig.advance(100_000);
        assert_eq!(rig.array.word(BANK_1), 0x0000_AAAA);
        assert_eq!(rig.array.word(BANK_1 + 28), 0x0000_AAAA);
    }

    /// Section 4.7.2: a program to a write-protected sector is canceled with `WRPERR`, "nothing is
    /// changed in the corresponding bank", and the flag does not block the next program.
    #[test]
    fn programming_a_write_protected_sector_is_canceled_with_wrperr() {
        let mut rig = Rig::new();
        rig.commit(&[(Register::WpsnPrg1r, 0xFD)]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        prepare_program(&mut rig, 0, 3);
        fill_word(&mut rig, BANK_1 + 0x2_0000, 5);
        let status = rig.status(0);
        assert!(sr1::WRPERR1.is_set(status));
        assert!(
            !sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status),
            "nothing queued to run"
        );
        rig.advance(100_000);
        assert!(!sr1::EOP1.is_set(rig.status(0)));
        assert_eq!(rig.array.word(BANK_1 + 0x2_0000), 0xFFFF_FFFF);
        fill_word(&mut rig, BANK_1 + 0x4_0000, 5);
        rig.advance(100_000);
        assert_eq!(
            rig.array.word(BANK_1 + 0x4_0000),
            5,
            "section 4.3.9: the flag blocks nothing"
        );
    }

    /// Section 4.9.4: the buffer is enabled "even if a sector or bank erase is ongoing", and the word
    /// programs when the erase has finished.
    #[test]
    fn a_program_waits_in_the_queue_behind_an_erase() {
        let mut rig = Rig::new();
        rig.unlock(0);
        let erase =
            cr1::SER1.mask() | cr1::SNB1.set(0, 0) | cr1::PSIZE1.set(0, 2) | cr1::PG1.mask();
        rig.write(Register::Cr1, erase);
        rig.set_bits(Register::Cr1, cr1::START1.mask());
        fill_word(&mut rig, BANK_1 + 0x2_0000, 9);
        assert!(sr1::QW1.is_set(rig.status(0)));
        rig.advance(1_100_000_000 - 1);
        assert!(!sr1::EOP1.is_set(rig.status(0)));
        rig.advance(1);
        let status = rig.status(0);
        assert!(sr1::EOP1.is_set(status), "the erase is done");
        assert!(
            sr1::QW1.is_set(status) && sr1::BSY1.is_set(status),
            "and the word has begun"
        );
        assert_eq!(rig.array.word(BANK_1 + 0x2_0000), 0xFFFF_FFFF);
        rig.advance(130_000);
        assert!(!sr1::QW1.is_set(rig.status(0)));
        assert_eq!(rig.array.word(BANK_1 + 0x2_0000), 9);
    }

    /// Section 4.3.11: the two banks run their operations at once, and each has registers of its own.
    #[test]
    fn the_two_banks_program_in_parallel_with_registers_of_their_own() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 2);
        prepare_program(&mut rig, 1, 2);
        fill_word(&mut rig, BANK_1, 1);
        fill_word(&mut rig, BANK_2, 2);
        assert!(sr1::QW1.is_set(rig.status(0)) && sr2::QW2.is_set(rig.status(1)));
        rig.advance(130_000);
        assert!(sr1::EOP1.is_set(rig.status(0)));
        assert!(sr2::EOP2.is_set(rig.status(1)));
        assert_eq!(rig.array.word(BANK_1), 1);
        assert_eq!(rig.array.word(BANK_2), 2);
        assert!(!sr1::QW1.is_set(rig.status(0)) && !sr2::QW2.is_set(rig.status(1)));
    }

    /// Bank 2 finishing before bank 1 is its own instant.
    #[test]
    fn a_bank_that_is_busy_longer_finishes_after_the_other() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 0);
        prepare_program(&mut rig, 1, 3);
        fill_word(&mut rig, BANK_1, 1);
        fill_word(&mut rig, BANK_2, 2);
        rig.advance(100_000);
        assert!(sr2::EOP2.is_set(rig.status(1)));
        assert!(!sr1::EOP1.is_set(rig.status(0)));
        assert!(sr1::BSY1.is_set(rig.status(0)));
        rig.advance(190_000);
        assert!(sr1::EOP1.is_set(rig.status(0)));
    }

    /// If the runtime will not put a word in the array, the operation is an operation error, section
    /// 4.7.6, and not a success.
    #[test]
    fn a_program_the_runtime_refuses_is_an_operation_error() {
        let mut rig = Rig::new();
        rig.array.programmable = false;
        prepare_program(&mut rig, 0, 3);
        fill_word(&mut rig, BANK_1, 1);
        rig.advance(100_000);
        let status = rig.status(0);
        assert!(sr1::OPERR1.is_set(status));
        assert!(!sr1::EOP1.is_set(status));
        assert!(
            !sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status),
            "and the bank is free"
        );
        assert_eq!(rig.refused.len(), 4, "four pieces of the word");
    }

    /// Section 4.3.10: a sector erase takes the datasheet's time at the parallelism `PSIZE` holds, then the
    /// sector reads as ones. `START` clears when the erase is acknowledged.
    #[test]
    fn a_sector_erase_takes_the_datasheets_time_by_psize() {
        for (psize, nanos) in [
            (0, 2_000_000_000),
            (1, 1_800_000_000),
            (2, 1_100_000_000),
            (3, 1_000_000_000),
        ] {
            let mut rig = Rig::new();
            let sector = BANK_1 + 3 * SECTOR_BYTES;
            rig.array.fill(BANK_1, 8 * SECTOR_BYTES, 0);
            rig.unlock(0);
            erase_sector(&mut rig, 0, 3, psize);
            let control = rig.read(Register::Cr1);
            assert!(!cr1::START1.is_set(control), "acknowledged, PSIZE {psize}");
            assert!(
                cr1::SER1.is_set(control),
                "and the rest of the request stands"
            );
            let status = rig.status(0);
            assert!(sr1::QW1.is_set(status) && sr1::BSY1.is_set(status));
            rig.advance(nanos - 1);
            assert!(sr1::BSY1.is_set(rig.status(0)), "PSIZE {psize}");
            assert!(
                !rig.array.erased(sector, SECTOR_BYTES),
                "nothing lands early"
            );
            rig.advance(1);
            let status = rig.status(0);
            assert!(!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status));
            assert!(sr1::EOP1.is_set(status));
            assert!(rig.array.erased(sector, SECTOR_BYTES), "the sector is ones");
            assert!(
                !rig.array.erased(sector - SECTOR_BYTES, SECTOR_BYTES),
                "the one before is not"
            );
            assert!(
                !rig.array.erased(sector + SECTOR_BYTES, SECTOR_BYTES),
                "nor the one after"
            );
        }
    }

    /// Section 4.3.10: a bank erase has the mass erase time, since two banks erased together are two
    /// bank erases in parallel, and it erases the whole bank and the other bank not at all.
    #[test]
    fn a_bank_erase_takes_the_mass_erase_time_by_psize() {
        for (psize, nanos) in [
            (0, 13_000_000_000),
            (1, 8_000_000_000),
            (2, 6_000_000_000),
            (3, 5_000_000_000),
        ] {
            let mut rig = Rig::new();
            rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
            rig.unlock(1);
            rig.write(Register::Cr2, cr2::BER2.mask() | cr2::PSIZE2.set(0, psize));
            rig.set_bits(Register::Cr2, cr2::START2.mask());
            rig.advance(nanos - 1);
            assert!(sr2::BSY2.is_set(rig.status(1)), "PSIZE {psize}");
            rig.advance(1);
            let status = rig.status(1);
            assert!(sr2::EOP2.is_set(status) && !sr2::QW2.is_set(status));
            assert!(rig.array.erased(BANK_2, BANK_BYTES), "bank 2 is ones");
            assert!(!rig.array.erased(BANK_1, BANK_BYTES), "bank 1 is not");
            assert!(!sr1::EOP1.is_set(rig.status(0)));
        }
    }

    /// Section 4.9.4: "BER1 has a higher priority than SER1: if both are set, the embedded flash memory
    /// executes a bank erase."
    #[test]
    fn ber_beats_ser() {
        let mut rig = Rig::new();
        rig.array.fill(BANK_1, BANK_BYTES, 0);
        rig.unlock(0);
        rig.write(
            Register::Cr1,
            cr1::BER1.mask() | cr1::SER1.mask() | cr1::SNB1.set(0, 2) | cr1::PSIZE1.set(0, 3),
        );
        rig.set_bits(Register::Cr1, cr1::START1.mask());
        rig.advance(1_000_000_000);
        assert!(
            sr1::BSY1.is_set(rig.status(0)),
            "the sector's time has passed and the bank's has not"
        );
        rig.advance(4_000_000_000);
        assert!(rig.array.erased(BANK_1, BANK_BYTES));
    }

    /// Section 4.3.10: an erase request leaves the bank's queue in order, one at a time.
    #[test]
    fn erases_queued_in_a_bank_run_one_after_the_other() {
        let mut rig = Rig::new();
        rig.array.fill(BANK_1, BANK_BYTES, 0);
        rig.unlock(0);
        erase_sector(&mut rig, 0, 1, 2);
        erase_sector(&mut rig, 0, 5, 2);
        rig.advance(1_100_000_000);
        let status = rig.status(0);
        assert!(
            sr1::QW1.is_set(status) && sr1::BSY1.is_set(status),
            "the second has begun"
        );
        assert!(rig.array.erased(BANK_1 + SECTOR_BYTES, SECTOR_BYTES));
        assert!(!rig.array.erased(BANK_1 + 5 * SECTOR_BYTES, SECTOR_BYTES));
        rig.advance(1_100_000_000);
        assert!(!sr1::QW1.is_set(rig.status(0)));
        assert!(rig.array.erased(BANK_1 + 5 * SECTOR_BYTES, SECTOR_BYTES));
    }

    /// Section 4.9.25 and the bank's registers: bank 2's sector numbers are its own, and they number
    /// from its first sector.
    #[test]
    fn a_bank_two_sector_erases_like_bank_one() {
        let mut rig = Rig::new();
        rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
        rig.unlock(1);
        erase_sector(&mut rig, 1, 7, 2);
        rig.advance(1_100_000_000);
        assert!(sr2::EOP2.is_set(rig.status(1)));
        assert!(rig.array.erased(BANK_2 + 7 * SECTOR_BYTES, SECTOR_BYTES));
        assert!(
            !rig.array.erased(BANK_1 + 7 * SECTOR_BYTES, SECTOR_BYTES),
            "not bank 1's seventh"
        );
    }

    /// The manual says nothing of a `START` with neither `SER` nor `BER`, so nothing starts, and `START`
    /// is acknowledged all the same.
    #[test]
    fn start_with_neither_sector_nor_bank_asked_starts_nothing() {
        let mut rig = Rig::new();
        rig.unlock(0);
        rig.set_bits(Register::Cr1, cr1::START1.mask());
        assert!(!cr1::START1.is_set(rig.read(Register::Cr1)));
        assert_eq!(rig.status(0), 0);
        assert_eq!(rig.soc.next_event(), None);
    }

    /// Section 4.7.2: an erase of a sector locked by `WRPSn` is rejected with `WRPERR`, and a bank erase
    /// with any sector locked is, section 4.9.4. Nothing is erased, and nothing is signaled done.
    #[test]
    fn an_erase_of_a_write_protected_sector_is_canceled_with_wrperr() {
        let mut rig = Rig::new();
        rig.commit(&[(Register::WpsnPrg1r, 0xF7)]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        rig.array.fill(BANK_1, BANK_BYTES, 0);
        rig.unlock(0);
        erase_sector(&mut rig, 0, 3, 3);
        let status = rig.status(0);
        assert!(sr1::WRPERR1.is_set(status));
        assert!(!sr1::QW1.is_set(status) && !sr1::BSY1.is_set(status));
        rig.advance(2_000_000_000);
        assert!(!sr1::EOP1.is_set(rig.status(0)));
        assert!(!rig.array.erased(BANK_1 + 3 * SECTOR_BYTES, SECTOR_BYTES));

        rig.write(Register::Ccr1, ccr1::CLR_WRPERR1.mask());
        rig.write(Register::Cr1, cr1::BER1.mask() | cr1::PSIZE1.set(0, 3));
        rig.set_bits(Register::Cr1, cr1::START1.mask());
        assert!(
            sr1::WRPERR1.is_set(rig.status(0)),
            "a bank erase with a protected sector"
        );
        assert_eq!(rig.soc.next_event(), None);

        rig.write(Register::Ccr1, ccr1::CLR_WRPERR1.mask());
        erase_sector(&mut rig, 0, 4, 3);
        rig.advance(1_000_000_000);
        assert!(
            rig.array.erased(BANK_1 + 4 * SECTOR_BYTES, SECTOR_BYTES),
            "an unprotected sector still erases"
        );
    }

    /// Sections 4.5.4 and 4.7.2: a valid PCROP area is erase-protected, "including the sector containing
    /// the area start address and the end address", so every sector it touches even in part.
    #[test]
    fn a_pcrop_area_protects_every_sector_it_touches() {
        let mut rig = Rig::new();
        let prar = prar_cur1::PROT_AREA_START1.set(prar_cur1::PROT_AREA_END1.set(0, 0x800), 0x7FF);
        rig.commit(&[(Register::PrarPrg1, prar)]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        rig.unlock(0);
        for (sector, protected) in [(2, false), (3, true), (4, true), (5, false)] {
            erase_sector(&mut rig, 0, sector, 3);
            assert_eq!(
                sr1::WRPERR1.is_set(rig.status(0)),
                protected,
                "sector {sector}"
            );
            rig.write(Register::Ccr1, ccr1::CLR_WRPERR1.mask());
            if !protected {
                rig.advance(1_000_000_000);
            }
        }
    }

    /// Section 4.9.11: a start equal to the end covers the whole bank, and an end below the start covers
    /// nothing.
    #[test]
    fn an_area_whose_start_equals_its_end_covers_the_bank() {
        let mut rig = Rig::new();
        let prar = prar_cur1::PROT_AREA_START1.set(prar_cur1::PROT_AREA_END1.set(0, 0x123), 0x123);
        rig.commit(&[(Register::PrarPrg1, prar)]);
        rig.unlock(0);
        for sector in 0..8 {
            erase_sector(&mut rig, 0, sector, 3);
            assert!(sr1::WRPERR1.is_set(rig.status(0)), "sector {sector}");
        }
        rig.unlock(1);
        erase_sector(&mut rig, 1, 0, 3);
        assert!(!sr2::WRPERR2.is_set(rig.status(1)), "bank 2 is its own");
    }

    /// Section 4.5.5: a secure-only area is erase-protected, but the feature is available only with
    /// `SECURITY` set, and a model cannot tell secure code from the rest, so it counts all code as not.
    #[test]
    fn a_secure_only_area_protects_its_sectors_only_with_security_set() {
        let mut rig = Rig::new();
        let scar = scar_cur1::SEC_AREA_START1.set(
            scar_cur1::SEC_AREA_END1.set(scar_cur1::DMES1.mask(), 0x3FF),
            0,
        );
        rig.commit(&[(Register::ScarPrg1, scar)]);
        rig.unlock(0);
        erase_sector(&mut rig, 0, 0, 3);
        assert!(!sr1::WRPERR1.is_set(rig.status(0)), "SECURITY is clear");
        rig.advance(1_000_000_000);
        let current = rig.read(Register::OptsrCur);
        rig.commit(&[(Register::OptsrPrg, optsr_prg::SECURITY.set(current, 1))]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        erase_sector(&mut rig, 0, 0, 3);
        assert!(sr1::WRPERR1.is_set(rig.status(0)), "SECURITY is set");
        rig.write(Register::Ccr1, ccr1::CLR_WRPERR1.mask());
        erase_sector(&mut rig, 0, 2, 3);
        assert!(
            !sr1::WRPERR1.is_set(rig.status(0)),
            "the sector past the area"
        );
    }

    /// Sections 4.3.10 and 4.9.7: `MER` "automatically sets BER1, BER2, START1 and START2 to 1", a bank
    /// erase on each, in parallel, and it reads back zero.
    #[test]
    fn mer_erases_both_banks() {
        let mut rig = Rig::new();
        rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
        rig.unlock(0);
        rig.unlock(1);
        rig.unlock_options();
        rig.set_bits(Register::Optcr, optcr::MER.mask());
        assert!(
            !optcr::MER.is_set(rig.read(Register::Optcr)),
            "MER is write-only"
        );
        assert!(
            cr1::BER1.is_set(rig.read(Register::Cr1)) && cr2::BER2.is_set(rig.read(Register::Cr2))
        );
        assert!(sr1::BSY1.is_set(rig.status(0)) && sr2::BSY2.is_set(rig.status(1)));
        rig.advance(5_000_000_000);
        assert!(sr1::EOP1.is_set(rig.status(0)) && sr2::EOP2.is_set(rig.status(1)));
        assert!(rig.array.erased(BANK_1, 2 * BANK_BYTES));
    }

    /// Section 4.9.7: `FLASH_OPTCR`, `FLASH_CR1` and `FLASH_CR2` must be unlocked for `MER`. A locked
    /// `OPTCR` does not take the write, and a locked bank does not take its `BER`, so it does not erase.
    #[test]
    fn mer_needs_the_option_register_and_each_banks_control_register_unlocked() {
        let mut rig = Rig::new();
        rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
        rig.unlock(0);
        rig.write(Register::Optcr, optcr::MER.mask());
        assert_eq!(rig.soc.next_event(), None, "FLASH_OPTCR is locked");
        rig.unlock_options();
        rig.set_bits(Register::Optcr, optcr::MER.mask());
        rig.advance(5_000_000_000);
        assert!(rig.array.erased(BANK_1, BANK_BYTES));
        assert!(
            !rig.array.erased(BANK_2, BANK_BYTES),
            "bank 2's register was locked"
        );
        assert!(!cr2::BER2.is_set(rig.read(Register::Cr2)));
    }

    /// An erase the runtime will not put in the array is an operation error, and the bank is free.
    #[test]
    fn an_erase_the_runtime_refuses_is_an_operation_error() {
        let mut rig = Rig::new();
        rig.array.programmable = false;
        rig.unlock(0);
        erase_sector(&mut rig, 0, 0, 3);
        rig.advance(1_000_000_000);
        let status = rig.status(0);
        assert!(sr1::OPERR1.is_set(status) && !sr1::EOP1.is_set(status));
        assert!(!sr1::QW1.is_set(status));
        assert_eq!(rig.refused.len(), 16_384, "every piece of the sector");
    }

    /// What ArduPilot's `stm32_flash_unprotect_flash` does for bank 1, from section 4.3.10's "bank erase
    /// with automatic protection-removal sequence": the programming registers ask for no area and
    /// every sector writable, then a bank erase. The protected sectors are erased too, and the
    /// protections are gone when it is done.
    #[test]
    fn a_bank_erase_with_protection_removal_erases_protected_sectors_and_lifts_the_protection() {
        let mut rig = Rig::new();
        rig.commit(&[
            (Register::WpsnPrg1r, 0x7E),
            (Register::PrarPrg1, prar_cur1::PROT_AREA_END1.set(0, 0x10)),
        ]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        rig.array.fill(BANK_1, BANK_BYTES, 0);

        let none = prar_cur1::DMEP1.mask() | prar_cur1::PROT_AREA_START1.set(0, 0xFF);
        rig.unlock_options();
        rig.write(Register::PrarPrg1, none);
        rig.write(Register::ScarPrg1, none);
        rig.write(Register::WpsnPrg1r, 0xFF);
        rig.unlock(0);
        rig.set_bits(Register::Cr1, cr1::BER1.mask());
        rig.set_bits(Register::Cr1, cr1::START1.mask());
        assert!(
            sr1::BSY1.is_set(rig.status(0)),
            "not refused, though sectors 0 and 7 are protected"
        );
        rig.advance(5_000_000_000);
        let status = rig.status(0);
        assert!(sr1::EOP1.is_set(status) && !sr1::WRPERR1.is_set(status));
        assert!(
            rig.array.erased(BANK_1, BANK_BYTES),
            "protected sectors included"
        );
        assert_eq!(rig.read(Register::WpsnCur1r), 0xFF);
        assert_eq!(rig.read(Register::PrarCur1), none);
        assert_eq!(rig.read(Register::ScarCur1), none);
        assert_eq!(optsr_cur::OPTCHANGEERR.get(rig.read(Register::OptsrCur)), 0);
        assert_eq!(rig.committed_prar(), [none, 0xFF]);
    }

    /// Section 4.3.10's caution: if any other option byte is changed too, "a simple bank erase occurs,
    /// no option byte change is performed and no option change error is set", so the protection
    /// refuses it.
    #[test]
    fn a_bank_erase_that_changes_another_option_byte_is_a_simple_erase() {
        let mut rig = Rig::new();
        rig.commit(&[(Register::WpsnPrg1r, 0x7E)]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        rig.array.fill(BANK_1, BANK_BYTES, 0);
        rig.unlock_options();
        rig.write(Register::WpsnPrg1r, 0xFF);
        rig.write(Register::BootPrgr, 0x1FF0_0900);
        rig.unlock(0);
        rig.set_bits(Register::Cr1, cr1::BER1.mask());
        rig.set_bits(Register::Cr1, cr1::START1.mask());
        assert!(sr1::WRPERR1.is_set(rig.status(0)));
        assert_eq!(
            rig.read(Register::WpsnCur1r),
            0x7E,
            "no option byte change is performed"
        );
        assert_eq!(optsr_cur::OPTCHANGEERR.get(rig.read(Register::OptsrCur)), 0);
        assert!(!rig.array.erased(BANK_1, BANK_BYTES));
    }

    /// Sections 4.9.5 and 4.9.26: every bit of the status registers is `r`, so a write leaves them as
    /// they are, whatever it holds. A driver writes ones to them all the same.
    #[test]
    fn the_status_registers_ignore_writes() {
        let mut rig = Rig::new();
        rig.store(BANK_1, Width::W32, 1).expect("taken");
        let before = rig.status(0);
        assert!(sr1::PGSERR1.is_set(before));
        rig.write(Register::Sr1, 0);
        assert_eq!(rig.status(0), before);
        rig.write(Register::Sr1, u64::from(u32::MAX));
        rig.write(Register::Sr2, u64::from(u32::MAX));
        assert_eq!(rig.status(0), before);
        assert_eq!(rig.status(1), 0);
    }

    /// Sections 4.9.6 and 4.9.27: a written one clears its flag alone, and the register reads zero.
    #[test]
    fn ccr_clears_the_flag_of_each_bit_written_and_reads_zero() {
        for (bank, wiring) in BANKS.iter().enumerate() {
            let every = wiring
                .flags
                .each()
                .fold(0, |bits, flag| flag.status.set(bits, 1));
            for flag in wiring.flags.each() {
                let mut rig = Rig::new();
                rig.registers().set(wiring.sr, every);
                rig.write(wiring.ccr, flag.clear.mask());
                assert_eq!(
                    rig.read(wiring.sr),
                    flag.status.set(every, 0),
                    "bank {} {}",
                    bank + 1,
                    flag.status.name
                );
                assert_eq!(rig.read(wiring.ccr), 0);
            }
            let mut rig = Rig::new();
            rig.registers().set(wiring.sr, every);
            rig.write(wiring.ccr, u64::from(u32::MAX));
            assert_eq!(
                rig.read(wiring.sr),
                0,
                "a driver writes ones to clear them all"
            );
        }
    }

    /// Section 4.8, Table 27: each flag holds the one interrupt up while its enable bit is set, in either
    /// bank, and lowers it when the flag clears. Position zero of the instance's table is line 4.
    #[test]
    fn the_flash_interrupt_follows_each_flag_and_its_enable() {
        let raised = |level| InterruptChange {
            instance: "Flash",
            interrupt: 4,
            level,
        };
        for (bank, wiring) in BANKS.iter().enumerate() {
            for flag in wiring.flags.each() {
                let mut rig = Rig::new();
                rig.unlock(bank);
                rig.registers().set(wiring.sr, flag.status.mask());
                rig.write(wiring.ccr, 0);
                assert!(
                    rig.soc.drain_interrupts().is_empty(),
                    "{}: no enable",
                    flag.status.name
                );
                rig.write(wiring.cr, flag.enable.mask());
                assert_eq!(
                    rig.soc.drain_interrupts(),
                    [raised(Level::High)],
                    "{}",
                    flag.status.name
                );
                rig.write(wiring.cr, 0);
                assert_eq!(
                    rig.soc.drain_interrupts(),
                    [raised(Level::Low)],
                    "{}: enable cleared",
                    flag.status.name
                );
                rig.write(wiring.cr, flag.enable.mask());
                rig.soc.drain_interrupts();
                rig.write(wiring.ccr, flag.clear.mask());
                assert_eq!(
                    rig.soc.drain_interrupts(),
                    [raised(Level::Low)],
                    "{}: flag cleared",
                    flag.status.name
                );
            }
        }
    }

    /// Section 4.8: one interrupt serves both banks, so it stays up while either bank has a flag.
    #[test]
    fn the_interrupt_stays_up_while_either_bank_has_a_flag() {
        let mut rig = Rig::new();
        rig.unlock(0);
        rig.unlock(1);
        rig.write(Register::Cr1, cr1::PGSERRIE1.mask());
        rig.write(Register::Cr2, cr2::PGSERRIE2.mask());
        rig.store(BANK_1, Width::W32, 1).expect("taken");
        rig.store(BANK_2, Width::W32, 1).expect("taken");
        assert_eq!(
            rig.soc.drain_interrupts().len(),
            1,
            "raised once, by the first"
        );
        rig.write(Register::Ccr1, ccr1::CLR_PGSERR1.mask());
        assert!(
            rig.soc.drain_interrupts().is_empty(),
            "bank 2 still holds it"
        );
        rig.write(Register::Ccr2, ccr2::CLR_PGSERR2.mask());
        assert_eq!(rig.soc.drain_interrupts().len(), 1);
    }

    /// Section 4.9.5: `EOP1` is set when an operation completes whatever `EOPIE1` says, and the
    /// interrupt needs the enable, which can come after the flag.
    #[test]
    fn eop_is_set_either_way_and_the_interrupt_follows_eopie() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        fill_word(&mut rig, BANK_1, 1);
        rig.advance(100_000);
        assert!(sr1::EOP1.is_set(rig.status(0)));
        assert!(rig.soc.drain_interrupts().is_empty(), "EOPIE1 is clear");
        rig.set_bits(Register::Cr1, cr1::EOPIE1.mask());
        assert_eq!(rig.soc.drain_interrupts().len(), 1);
        fill_word(&mut rig, BANK_1 + 32, 1);
        rig.advance(100_000);
        assert!(
            rig.soc.drain_interrupts().is_empty(),
            "EOP1 stood already: nothing new to raise"
        );
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        assert_eq!(rig.soc.drain_interrupts().len(), 1, "and it lowers");
    }

    /// Section 4.4.3: `OPTSTART` programs the option bytes. It clears at once, `OPT_BUSY` stands for the
    /// time, and then the current registers hold what the programming ones did. The change is bank 1's
    /// operation, so `BSY1` and `QW1` stand for it too, and `EOP1` marks its end.
    #[test]
    fn optstart_commits_the_programming_registers_when_its_time_is_up() {
        let mut rig = Rig::new();
        rig.unlock_options();
        let optsr = optsr_prg::BOR_LEV.set(rig.read(Register::OptsrPrg), 2);
        rig.write(Register::OptsrPrg, optsr);
        rig.write(Register::BootPrgr, 0x1FF0_0900);
        rig.write(Register::WpsnPrg2r, 0xFE);
        rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
        assert!(
            !optcr::OPTSTART.is_set(rig.read(Register::Optcr)),
            "acknowledged"
        );
        let current = rig.read(Register::OptsrCur);
        assert!(optsr_cur::OPT_BUSY.is_set(current));
        assert_eq!(optsr_cur::BOR_LEV.get(current), 0, "not yet");
        let status = rig.status(0);
        assert!(sr1::BSY1.is_set(status) && sr1::QW1.is_set(status));
        rig.advance(OPTION_PROGRAM_NANOS - 1);
        assert!(optsr_cur::OPT_BUSY.is_set(rig.read(Register::OptsrCur)));
        rig.advance(1);
        let current = rig.read(Register::OptsrCur);
        assert!(!optsr_cur::OPT_BUSY.is_set(current));
        assert_eq!(
            current, optsr,
            "OPT_BUSY clear, and the bytes are the programmed ones"
        );
        assert_eq!(
            rig.read(Register::OptsrCur_),
            current,
            "under both addresses"
        );
        assert_eq!(rig.read(Register::BootCurr), 0x1FF0_0900);
        assert_eq!(rig.read(Register::BootCurr_), 0x1FF0_0900);
        assert_eq!(rig.read(Register::WpsnCur2r), 0xFE);
        assert_eq!(rig.read(Register::WpsnCur1r), 0xFF, "a register left alone");
        let status = rig.status(0);
        assert!(sr1::EOP1.is_set(status) && !sr1::BSY1.is_set(status) && !sr1::QW1.is_set(status));
    }

    /// Section 4.4.3: the interface "checks if at least one option byte needs to be programmed by comparing
    /// the current values with the new ones", and starts a change only if one does.
    #[test]
    fn optstart_with_nothing_to_program_does_nothing() {
        let mut rig = Rig::new();
        rig.unlock_options();
        rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
        assert!(!optcr::OPTSTART.is_set(rig.read(Register::Optcr)));
        assert!(!optsr_cur::OPT_BUSY.is_set(rig.read(Register::OptsrCur)));
        assert_eq!(rig.soc.next_event(), None);
        assert_eq!(rig.status(0), 0);
    }

    /// Section 4.9.7: `OPTLOCK` "locks the `FLASH_OPTCR` register as well as all `_PRG` registers". With it
    /// clear they take a write, in the bits the manual defines, and the reserved bits keep their value.
    #[test]
    fn the_option_registers_are_frozen_while_optlock_stands() {
        let mut rig = Rig::new();
        for register in [
            Register::OptsrPrg,
            Register::BootPrgr,
            Register::PrarPrg1,
            Register::ScarPrg2,
            Register::WpsnPrg1r,
        ] {
            let before = rig.read(register);
            rig.write(register, 0);
            assert_eq!(rig.read(register), before, "{register:?} while locked");
        }
        rig.write(Register::Optcr, optcr::OPTCHANGEERRIE.mask());
        assert_eq!(rig.read(Register::Optcr), 1, "so is FLASH_OPTCR");
        rig.unlock_options();
        rig.write(Register::OptsrPrg, u64::from(u32::MAX));
        let programmed = rig.read(Register::OptsrPrg);
        assert_eq!(optsr_prg::RDP.get(programmed), 0xFF);
        let reserved = !defined_bits(Register::OptsrPrg);
        assert_eq!(
            programmed & reserved,
            OptionBytes::FACTORY.optsr & reserved,
            "the reserved bits keep the value they had"
        );
        rig.write(Register::Optcr, optcr::OPTCHANGEERRIE.mask());
        assert!(optcr::OPTCHANGEERRIE.is_set(rig.read(Register::Optcr)));
    }

    /// Sections 4.9.8, 4.9.13 and 4.9.17 and the rest: the current option registers are read-only.
    #[test]
    fn the_current_option_registers_and_the_results_ignore_writes() {
        let mut rig = Rig::new();
        rig.unlock_options();
        for register in [
            Register::OptsrCur,
            Register::OptsrCur_,
            Register::PrarCur1,
            Register::PrarCur2,
            Register::ScarCur1,
            Register::ScarCur2,
            Register::WpsnCur1r,
            Register::WpsnCur2r,
            Register::BootCurr,
            Register::BootCurr_,
            Register::Crcdatar,
            Register::Crcdatar_,
            Register::EccFa1r,
            Register::EccFa2r,
        ] {
            let before = rig.read(register);
            rig.write(register, 0);
            assert_eq!(rig.read(register), before, "{register:?}");
            rig.write(register, u64::from(u32::MAX));
            assert_eq!(rig.read(register), before, "{register:?}");
        }
    }

    /// Section 4.9.18 types `FLASH_BOOT_PRGR` read-write, where the vendor's file makes it read-only, so
    /// the register file would drop the write. The model takes it, at either address.
    #[test]
    fn boot_prgr_takes_a_write_though_the_vendors_file_makes_it_read_only() {
        let mut rig = Rig::new();
        rig.write(Register::BootPrgr, 0x1234_5678);
        assert_eq!(rig.read(Register::BootPrgr), 0x1FF0_0800, "locked");
        rig.unlock_options();
        rig.write(Register::BootPrgr, 0x1234_5678);
        assert_eq!(rig.read(Register::BootPrgr), 0x1234_5678);
        assert_eq!(rig.read(Register::BootPrgr_), 0x1234_5678);
        rig.write(Register::BootPrgr_, 0x1FF0_0800);
        assert_eq!(rig.read(Register::BootPrgr), 0x1FF0_0800);
    }

    /// Section 4.9.8: while `OPT_BUSY` stands, "all write accesses to flash registers are blocked until
    /// the option byte change completes". The model cannot stall the core, so it holds each write and
    /// applies them in order when the change ends.
    #[test]
    fn writes_made_during_an_option_change_land_when_it_ends() {
        let mut rig = Rig::new();
        rig.unlock_options();
        rig.write(Register::BootPrgr, 0x1FF0_0900);
        rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
        rig.write(Register::Acr, 0x05);
        assert_eq!(rig.read(Register::Acr), 0x37, "held");
        rig.write(Register::Acr, 0x02);
        rig.write(Register::Optcr, OPTLOCK.mask());
        assert!(!OPTLOCK.is_set(rig.read(Register::Optcr)), "held too");
        rig.advance(OPTION_PROGRAM_NANOS);
        assert_eq!(
            rig.read(Register::Acr),
            0x02,
            "the last of them, applied in order"
        );
        assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
        assert_eq!(rig.read(Register::BootCurr), 0x1FF0_0900);
    }

    /// Section 4.4.3: at level 2 "no changes are allowed (except for the SWAP bit)", and an attempt "raises"
    /// `OPTCHANGEERR`, "and all the programmed changes are ignored". The programming registers keep
    /// what was written. `OPTCCR` clears the flag, at either address.
    #[test]
    fn at_level_2_a_change_is_an_option_change_error_but_the_bank_swap() {
        let mut rig = Rig::new();
        let level_2 = optsr_prg::RDP.set(rig.read(Register::OptsrPrg), 0xCC);
        rig.commit(&[(Register::OptsrPrg, level_2)]);
        assert_eq!(optsr_cur::RDP.get(rig.read(Register::OptsrCur)), 0xCC);

        rig.unlock_options();
        let attempt = optsr_prg::BOR_LEV.set(level_2, 3);
        rig.write(Register::OptsrPrg, attempt);
        rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
        let current = rig.read(Register::OptsrCur);
        assert!(optsr_cur::OPTCHANGEERR.is_set(current));
        assert!(!optsr_cur::OPT_BUSY.is_set(current));
        assert_eq!(optsr_cur::BOR_LEV.get(current), 0, "ignored");
        assert_eq!(rig.read(Register::OptsrPrg), attempt, "and not overwritten");
        assert_eq!(rig.soc.next_event(), None);

        rig.soc.drain_interrupts();
        rig.write(Register::Optcr, optcr::OPTCHANGEERRIE.mask());
        assert_eq!(
            rig.soc.drain_interrupts().len(),
            1,
            "OPTCHANGEERRIE raises the interrupt"
        );
        rig.write(Register::Optccr_, optccr::CLR_OPTCHANGEERR.mask());
        assert!(!optsr_cur::OPTCHANGEERR.is_set(rig.read(Register::OptsrCur)));
        assert_eq!(
            rig.soc.drain_interrupts().len(),
            1,
            "and clearing it lowers it"
        );
        assert_eq!(rig.read(Register::Optccr), 0);

        let swap_alone = optsr_prg::SWAP_BANK_OPT.set(rig.read(Register::OptsrCur), 1);
        rig.write(Register::OptsrPrg, swap_alone);
        rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
        rig.advance(OPTION_PROGRAM_NANOS);
        let current = rig.read(Register::OptsrCur);
        assert!(!optsr_cur::OPTCHANGEERR.is_set(current));
        assert_eq!(
            optsr_cur::SWAP_BANK_OPT.get(current),
            1,
            "the swap is allowed at level 2"
        );
    }

    /// Sections 4.9.7 and 4.3.13: `SWAP_BANK` is read-only and "loaded with the `SWAP_BANK_OPT` bit ... only
    /// after reset", so a commit changes the option and not the swap, until a reset.
    #[test]
    fn swap_bank_is_loaded_from_the_option_bytes_at_reset() {
        let mut rig = Rig::new();
        let swapped = optsr_prg::SWAP_BANK_OPT.set(rig.read(Register::OptsrPrg), 1);
        rig.commit(&[(Register::OptsrPrg, swapped)]);
        assert_eq!(
            optsr_cur::SWAP_BANK_OPT.get(rig.read(Register::OptsrCur)),
            1
        );
        assert_eq!(
            optcr::SWAP_BANK.get(rig.read(Register::Optcr)),
            0,
            "not yet effective"
        );
        rig.unlock_options();
        rig.write(Register::Optcr, optcr::SWAP_BANK.mask());
        assert_eq!(
            optcr::SWAP_BANK.get(rig.read(Register::Optcr)),
            0,
            "and software cannot write it"
        );
        rig.reset();
        let control = rig.read(Register::Optcr);
        assert_eq!(optcr::SWAP_BANK.get(control), 1);
        assert!(OPTLOCK.is_set(control), "locked again by the reset");
        assert_eq!(rig.read(Register::Optcr_), control);
    }

    /// Section 4.3.14: "all registers, except for option byte registers, are cleared", and the option bytes
    /// are what the last commit left.
    #[test]
    fn the_option_registers_survive_a_system_reset() {
        let mut rig = Rig::new();
        rig.commit(&[
            (Register::WpsnPrg1r, 0xFE),
            (Register::BootPrgr, 0x1FF0_0900),
            (Register::PrarPrg2, 0x8000_0101),
        ]);
        rig.unlock(0);
        rig.write(Register::Acr, 0x05);
        rig.reset();
        assert_eq!(rig.read(Register::Acr), 0x37);
        assert_eq!(rig.read(Register::Cr1), 0x31, "locked again");
        for (register, value) in [
            (Register::WpsnCur1r, 0xFE),
            (Register::WpsnPrg1r, 0xFE),
            (Register::BootCurr, 0x1FF0_0900),
            (Register::BootPrgr_, 0x1FF0_0900),
            (Register::PrarCur2, 0x8000_0101),
            (Register::PrarPrg2, 0x8000_0101),
            (Register::ScarCur1, 0x8000_00FF),
        ] {
            assert_eq!(rig.read(register), value, "{register:?}");
        }
        assert!(OPTLOCK.is_set(rig.read(Register::Optcr)));
    }

    /// Section 4.3.14: "If a reset occurs while the option byte modification is ongoing, the old option
    /// byte values are kept." Nothing the reset interrupted lands afterwards.
    #[test]
    fn a_reset_during_a_commit_keeps_the_bytes_the_last_commit_left() {
        let mut rig = Rig::new();
        rig.commit(&[(Register::WpsnPrg1r, 0xFE)]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        rig.unlock_options();
        rig.write(Register::WpsnPrg1r, 0x7F);
        rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
        rig.advance(OPTION_PROGRAM_NANOS / 2);
        rig.reset();
        assert_eq!(rig.read(Register::WpsnCur1r), 0xFE);
        assert_eq!(
            rig.read(Register::WpsnPrg1r),
            0xFE,
            "the programming register reads the current one"
        );
        assert!(!optsr_cur::OPT_BUSY.is_set(rig.read(Register::OptsrCur)));
        rig.advance(OPTION_PROGRAM_NANOS);
        assert_eq!(rig.read(Register::WpsnCur1r), 0xFE);
        assert!(!sr1::EOP1.is_set(rig.status(0)));
    }

    /// A part that rebuilds itself on a reset gives the new model what the old one committed.
    #[test]
    fn a_fresh_model_given_the_committed_bytes_reads_what_the_old_one_did() {
        let mut old = Rig::new();
        old.commit(&[
            (Register::WpsnPrg2r, 0x0F),
            (Register::ScarPrg1, 0x8000_0101),
        ]);
        let kept = old.soc.model.committed_options();
        let mut fresh = Rig::new();
        let (model, registers) = fresh.soc.pair();
        model.keep_options(kept, registers);
        for register in OPTION_REGISTERS {
            assert_eq!(fresh.read(register), old.read(register), "{register:?}");
        }
        assert_eq!(fresh.soc.model.committed_options(), kept);
    }

    /// Sections 4.9.19 and 4.9.34: `FLASH_CRCCR1` "can be modified only if `CRC_EN` bit is set to 1" in
    /// `FLASH_CR1`, the bits that start something read zero, and the reserved bits keep their reset
    /// value. The computation is not modeled, so the model tells the session that `START_CRC` starts
    /// nothing.
    #[test]
    fn the_crc_configuration_takes_writes_only_while_crc_en_is_set() {
        let mut rig = Rig::new();
        rig.unlock(0);
        let reset = 0x001C_0000;
        rig.write(Register::Crccr1, crccr1::CRC_BURST.set(reset, 3));
        assert_eq!(rig.read(Register::Crccr1), reset, "CRC_EN is clear");
        rig.write(Register::Cr1, cr1::CRC_EN.mask());
        let configured = crccr1::CRC_SECT.set(
            crccr1::CRC_BY_SECT.set(crccr1::CRC_BURST.set(reset, 3), 1),
            5,
        );
        let one_shots =
            crccr1::ADD_SECT.mask() | crccr1::ALL_BANK.mask() | crccr1::CLEAN_SECT.mask();
        rig.write(Register::Crccr1, configured | one_shots);
        assert_eq!(
            rig.read(Register::Crccr1),
            configured,
            "the one-shot bits read zero"
        );
        assert!(rig.told().is_empty());
        rig.write(Register::Crccr1, configured | crccr1::START_CRC.mask());
        assert_eq!(rig.read(Register::Crccr1), configured);
        assert_eq!(
            rig.told(),
            vec![Told {
                instance: "Flash",
                register: "CRCCR1",
                reason: CRC_NOT_MODELED,
                at: START,
            }]
        );
        let status = rig.status(0);
        assert!(!sr1::CRC_BUSY1.is_set(status) && !sr1::CRCEND1.is_set(status));
    }

    /// Section 4.9.19: `CLEAN_CRC` clears the result in `FLASH_CRCDATAR`. Section 4.9.4: clearing `CRC_EN`
    /// "clears CRC configuration and resets the content of `FLASH_CRCDATAR`".
    #[test]
    fn clean_crc_and_clearing_crc_en_clear_the_result_and_the_configuration() {
        let mut rig = Rig::new();
        rig.unlock(0);
        rig.write(Register::Cr1, cr1::CRC_EN.mask());
        rig.registers().set(Register::Crcdatar, 0x1234_5678);
        rig.registers().set(Register::Crcdatar_, 0x1234_5678);
        rig.write(Register::Crccr1, 0x001C_0000 | crccr1::CLEAN_CRC.mask());
        assert_eq!(rig.read(Register::Crcdatar), 0);
        assert_eq!(
            rig.read(Register::Crcdatar_),
            0,
            "one register at two addresses"
        );

        rig.write(Register::Crccr1, 0x001C_0000 | crccr1::CRC_SECT.set(0, 3));
        rig.write(Register::Crcsadd1r, 0x0000_1000);
        rig.write(Register::Crceadd1r, 0x0000_2000);
        rig.registers().set(Register::Crcdatar, 0x9999);
        rig.write(Register::Cr1, 0);
        assert_eq!(rig.read(Register::Crccr1), 0x001C_0000);
        assert_eq!(rig.read(Register::Crcsadd1r), 0);
        assert_eq!(rig.read(Register::Crceadd1r), 0);
        assert_eq!(rig.read(Register::Crcdatar), 0);
    }

    /// Sections 4.9.20 and 4.9.21: the addresses are stored, in the bits the manual defines.
    #[test]
    fn the_crc_addresses_are_stored_in_their_defined_bits() {
        let mut rig = Rig::new();
        rig.write(Register::Crcsadd2r, u64::from(u32::MAX));
        rig.write(Register::Crceadd2r, 0x0000_0100);
        assert_eq!(
            rig.read(Register::Crcsadd2r),
            crcsadd2r::CRC_START_ADDR.mask()
        );
        assert_eq!(rig.read(Register::Crceadd2r), 0x0000_0100);
    }

    /// Tables 21 and 28 against the table the model seeds its own copy of the registers from: a model
    /// that put back a register to a value the bus does not reset it to would restore the wrong bits.
    #[test]
    fn the_models_seed_of_every_register_is_what_the_bus_resets_it_to() {
        let mut rig = Rig::new();
        let seed = Flash::seeded(&OptionBytes::FACTORY);
        for register in Register::ALL {
            assert_eq!(
                seed[register.index()],
                rig.registers().get(register),
                "{register:?}"
            );
        }
    }

    /// Sections 4.9.25 to 4.9.37 against 4.9.4 to 4.9.23: bank 2 repeats bank 1's registers at the same
    /// bits, except that bank 1's status and clear registers have a CRC read error bit that bank 2's
    /// do not, and bank 2's control register has `SPSS2`. Every place the model uses bank 1's shape for
    /// both, `CRC_ONE_SHOT` for one, is held to it here.
    #[test]
    fn bank_two_lays_its_registers_out_as_bank_one_does() {
        let pairs = [
            (Register::Cr1, Register::Cr2),
            (Register::Sr1, Register::Sr2),
            (Register::Ccr1, Register::Ccr2),
            (Register::Crccr1, Register::Crccr2),
            (Register::PrarCur1, Register::PrarCur2),
            (Register::PrarPrg1, Register::PrarPrg2),
            (Register::ScarCur1, Register::ScarCur2),
            (Register::ScarPrg1, Register::ScarPrg2),
            (Register::WpsnCur1r, Register::WpsnCur2r),
            (Register::WpsnPrg1r, Register::WpsnPrg2r),
            (Register::Crcsadd1r, Register::Crcsadd2r),
            (Register::Crceadd1r, Register::Crceadd2r),
            (Register::EccFa1r, Register::EccFa2r),
        ];
        let shape = |register: Register| -> Vec<(u8, u8)> {
            let mut fields: Vec<(u8, u8)> = register
                .spec()
                .fields
                .iter()
                .map(|field| (field.bit, field.width))
                .collect();
            fields.sort_unstable();
            fields
        };
        for (first, second) in pairs {
            let mut one = shape(first);
            let mut two = shape(second);
            match first {
                Register::Sr1 | Register::Ccr1 => one.retain(|&(bit, _)| bit != 28),
                Register::Cr1 => two.retain(|&(bit, _)| bit != 14),
                _ => {}
            }
            assert_eq!(one, two, "{first:?} against {second:?}");
        }
        let second = crccr2::START_CRC.mask()
            | crccr2::CLEAN_CRC.mask()
            | crccr2::CLEAN_SECT.mask()
            | crccr2::ADD_SECT.mask()
            | crccr2::ALL_BANK.mask();
        assert_eq!(CRC_ONE_SHOT, second);
    }

    /// Table 27 and the register pages: each flag has its status bit, its enable in the control register
    /// and its clear bit at one position, which is what lets one table of flags drive the interrupt and the
    /// clearing. The positions are written out here from the pages, as the second witness.
    #[test]
    fn every_flag_sits_where_the_manual_puts_it() {
        let positions = [16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28];
        for (bank, wiring) in BANKS.iter().enumerate() {
            let wanted = positions.iter().take(wiring.flags.each().count());
            for (flag, &position) in wiring.flags.each().zip(wanted) {
                let name = flag.status.name;
                assert_eq!(
                    (flag.status.bit, flag.enable.bit, flag.clear.bit),
                    (position, position, position),
                    "bank {} {name}",
                    bank + 1
                );
                assert_eq!(
                    (flag.status.width, flag.enable.width, flag.clear.width),
                    (1, 1, 1)
                );
            }
        }
        assert_eq!(BANKS[0].flags.each().count(), 12);
        assert_eq!(
            BANKS[1].flags.each().count(),
            11,
            "bank 2 has no CRC read error flag"
        );
    }

    /// The determinism audit's lesson from the clock controller: a test of the model's own copy of a field
    /// passes even if the part's correction is deleted. These read the shape the part declares.
    #[test]
    fn the_corrected_fields_are_what_the_part_declares() {
        let bus = builder().build().expect("the part assembles");
        let registers = bus.registers("Flash").expect("Flash is an instance");
        let field = |register: Register, name: &str| -> FieldSpec {
            *registers
                .fields(register.index())
                .iter()
                .find(|field| field.name == name)
                .unwrap_or_else(|| panic!("{register:?} declares {name}"))
        };
        for (register, name) in [
            (Register::Cr1, "LOCK1"),
            (Register::Cr2, "LOCK2"),
            (Register::Optcr, "OPTLOCK"),
            (Register::Optcr_, "OPTLOCK"),
        ] {
            assert_eq!(
                field(register, name).write,
                WriteModify::OneToSet,
                "{register:?}"
            );
        }
        for register in [Register::Optcr, Register::Optcr_] {
            assert_eq!(
                field(register, "SWAP_BANK").access,
                Access::ReadOnly,
                "{register:?}"
            );
        }
        for register in READ_ONLY {
            assert_eq!(
                registers.write_rule(register.index()),
                WriteModify::Modify,
                "{register:?}"
            );
        }
        assert_eq!(
            bus.peripheral("Flash").expect("an instance").interrupts,
            [4]
        );
    }

    /// An event id the model does not expect is ignored, there being no cancel.
    #[test]
    fn a_stale_event_is_ignored() {
        let mut rig = Rig::new();
        let bogus = rig
            .soc
            .drive(START, |_, _, context| context.schedule(VirtualNanos(1)));
        rig.soc.drive(START, |flash, registers, context| {
            Device::on_event(flash, bogus, registers, context);
        });
        assert_eq!(rig.status(0), 0, "nothing was pending");
        prepare_program(&mut rig, 0, 3);
        fill_word(&mut rig, BANK_1, 1);
        rig.soc.drive(START, |flash, registers, context| {
            Device::on_event(flash, bogus, registers, context);
        });
        rig.settle();
        assert!(
            sr1::BSY1.is_set(rig.status(0)),
            "a mismatched id left the real one pending"
        );
        rig.advance(100_000);
        assert!(
            sr1::EOP1.is_set(rig.status(0)),
            "and the real id still fires"
        );
    }

    /// The runtime hands the model a store only in the region the part names, but a model asked about an
    /// address outside the user flash says it is a gap.
    #[test]
    fn an_address_outside_the_user_flash_is_a_gap() {
        let mut rig = Rig::new();
        let taken = rig.soc.drive(START, |flash, registers, context| {
            flash.write_region(0x0820_0000, Width::W32, 0, registers, context)
        });
        assert!(!taken);
        let taken = rig.soc.drive(START, |flash, registers, context| {
            flash.write_region(0x0900_0000, Width::W32, 0, registers, context)
        });
        assert!(!taken);
    }

    /// Section 4.3.10's "flash mass erase with automatic protection-removal sequence": both banks' programming
    /// registers ask for no protection and every sector writable, then `MER`. Both banks erase, the
    /// protected sectors with them, and both banks' protections are gone.
    #[test]
    fn a_mass_erase_with_protection_removal_erases_both_banks_and_lifts_the_protection() {
        let mut rig = Rig::new();
        rig.commit(&[(Register::WpsnPrg1r, 0xFE), (Register::WpsnPrg2r, 0x7F)]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
        let none = prar_cur1::DMEP1.mask() | prar_cur1::PROT_AREA_START1.set(0, 0xFF);
        rig.unlock_options();
        for register in [
            Register::PrarPrg1,
            Register::PrarPrg2,
            Register::ScarPrg1,
            Register::ScarPrg2,
        ] {
            rig.write(register, none);
        }
        rig.write(Register::WpsnPrg1r, 0xFF);
        rig.write(Register::WpsnPrg2r, 0xFF);
        rig.unlock(0);
        rig.unlock(1);
        rig.set_bits(Register::Optcr, optcr::MER.mask());
        assert!(sr1::BSY1.is_set(rig.status(0)) && sr2::BSY2.is_set(rig.status(1)));
        rig.advance(5_000_000_000);
        assert!(rig.array.erased(BANK_1, 2 * BANK_BYTES));
        assert_eq!(rig.read(Register::WpsnCur1r), 0xFF);
        assert_eq!(rig.read(Register::WpsnCur2r), 0xFF);
        assert!(!sr1::WRPERR1.is_set(rig.status(0)) && !sr2::WRPERR2.is_set(rig.status(1)));
    }

    /// Section 4.3.10: a mass erase is a bank erase on each bank, so a protected bank refuses its own
    /// and the other erases.
    #[test]
    fn a_mass_erase_with_one_bank_protected_erases_only_the_other() {
        let mut rig = Rig::new();
        rig.commit(&[(Register::WpsnPrg2r, 0xFE)]);
        rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
        rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
        rig.unlock(0);
        rig.unlock(1);
        rig.unlock_options();
        rig.set_bits(Register::Optcr, optcr::MER.mask());
        rig.advance(5_000_000_000);
        assert!(sr1::EOP1.is_set(rig.status(0)));
        assert!(sr2::WRPERR2.is_set(rig.status(1)) && !sr2::EOP2.is_set(rig.status(1)));
        assert!(rig.array.erased(BANK_1, BANK_BYTES));
        assert!(!rig.array.erased(BANK_2, BANK_BYTES));
    }

    /// Two runs of one script are one run: the script commits an option byte, bricks a key, programs and
    /// erases in the second bank.
    #[test]
    fn two_runs_of_one_script_are_the_same_run() {
        fn scripted() -> Rig {
            let mut rig = Rig::new();
            rig.commit(&[(Register::WpsnPrg1r, 0xFE)]);
            rig.write(Register::Keyr1, CR_KEYS.0);
            rig.write(Register::Keyr1, 0);
            prepare_program(&mut rig, 1, 2);
            rig.set_bits(Register::Cr2, cr2::EOPIE2.mask());
            fill_word(&mut rig, BANK_2, 7);
            fill_word(&mut rig, BANK_2 + 32, 9);
            rig.advance(300_000);
            erase_sector(&mut rig, 1, 3, 2);
            rig.advance(1_100_000_000);
            rig
        }
        let mut first = scripted();
        let mut second = scripted();
        assert_eq!(first.told(), second.told());
        assert_eq!(first.soc.drain_interrupts(), second.soc.drain_interrupts());
        for register in Register::ALL {
            assert_eq!(
                first.registers().get(register),
                second.registers().get(register),
                "{register:?} disagrees between two runs of the same script"
            );
        }
        assert_eq!(first.array.bytes, second.array.bytes);
        assert_eq!(
            format!("{:?}", first.soc.model),
            format!("{:?}", second.soc.model)
        );
    }

    /// The model's state serializes, mid-operation, with a partial word, a queue and a held write in it.
    #[test]
    fn the_model_state_round_trips_through_a_snapshot() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        fill_word(&mut rig, BANK_1, 1);
        fill_word(&mut rig, BANK_1 + 32, 2);
        rig.store_word(BANK_1 + 64, 3);
        prepare_program(&mut rig, 1, 1);
        rig.store_word(BANK_2, 4);
        let bytes = postcard::to_stdvec(&rig.soc.model).expect("the model serializes");
        let restored: Flash = postcard::from_bytes(&bytes).expect("and deserializes");
        assert_eq!(format!("{restored:?}"), format!("{:?}", rig.soc.model));
    }

    /// Section 4.3.9's caution about `PSIZE`, told the same way.
    #[test]
    fn changing_psize_under_an_operation_is_told() {
        let mut rig = Rig::new();
        rig.unlock(0);
        erase_sector(&mut rig, 0, 0, 2);
        rig.write(Register::Cr1, cr1::SER1.mask() | cr1::PSIZE1.set(0, 1));
        assert_eq!(
            rig.told(),
            vec![Told {
                instance: "Flash",
                register: "CR1",
                reason: PSIZE_BUSY,
                at: START,
            }]
        );
        rig.write(Register::Cr1, cr1::SER1.mask() | cr1::PSIZE1.set(0, 1));
        assert!(rig.told().is_empty(), "unchanged");
    }

    /// Section 4.3.8: the write queue is two deep and a driver that waits for `QW` between words never fills
    /// it. A word that arrives while another programs waits its turn, and `QW` stands until the last.
    #[test]
    fn words_queued_behind_one_another_program_in_turn() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        fill_word(&mut rig, BANK_1, 1);
        fill_word(&mut rig, BANK_1 + 32, 2);
        rig.advance(100_000);
        assert!(sr1::QW1.is_set(rig.status(0)));
        assert_eq!(rig.array.word(BANK_1), 1);
        assert_eq!(rig.array.word(BANK_1 + 32), 0xFFFF_FFFF);
        rig.advance(100_000);
        assert!(!sr1::QW1.is_set(rig.status(0)));
        assert_eq!(rig.array.word(BANK_1 + 32), 2);
    }

    /// Section 4.3.14: a reset clears every register but the option bytes, so what was queued or being
    /// gathered, and a half-entered key, are gone, and nothing lands afterwards.
    #[test]
    fn a_reset_drops_what_was_pending() {
        let mut rig = Rig::new();
        prepare_program(&mut rig, 0, 3);
        fill_word(&mut rig, BANK_1, 1);
        rig.store_word(BANK_1 + 64, 2);
        rig.write(Register::Keyr2, CR_KEYS.0);
        rig.reset();
        assert_eq!(rig.status(0), 0);
        assert_eq!(rig.soc.next_event(), None);
        rig.advance(1_000_000);
        assert_eq!(rig.array.word(BANK_1), 0xFFFF_FFFF);
        rig.unlock(1);
        assert!(
            !LOCK2.is_set(rig.read(Register::Cr2)),
            "the key sequence began again"
        );
        prepare_program(&mut rig, 0, 3);
        fill_word(&mut rig, BANK_1 + 128, 3);
        assert!(
            !sr1::INCERR1.is_set(rig.status(0)),
            "and no partial word is left"
        );
    }

    /// Sections 4.5.4 and 4.5.5: "No mass erase can be performed if a single valid PCROP area is defined".
    /// The model reads that of the bank that has the area, a mass erase being a bank erase on each, so
    /// the other bank erases and the one with the area refuses its own with `WRPERR`.
    #[test]
    fn a_mass_erase_with_a_pcrop_area_in_one_bank_erases_only_the_other() {
        for (held, wiring) in BANKS.iter().enumerate() {
            let other = 1 - held;
            let mut rig = Rig::new();
            rig.commit(&[(wiring.prar_prg, pcrop(0x10, 0x20, false))]);
            rig.write(Register::Ccr1, ccr1::CLR_EOP1.mask());
            rig.array.fill(BANK_1, 2 * BANK_BYTES, 0);
            rig.unlock(0);
            rig.unlock(1);
            rig.unlock_options();
            rig.set_bits(Register::Optcr, optcr::MER.mask());
            rig.advance(5_000_000_000);
            let status = rig.status(held);
            assert!(
                wiring.flags.wrperr.status.is_set(status),
                "bank {}",
                held + 1
            );
            assert!(!wiring.flags.eop.status.is_set(status));
            assert!(BANKS[other].flags.eop.status.is_set(rig.status(other)));
            let bank_start = |bank: usize| BANK_1 + count(bank) * BANK_BYTES;
            assert!(rig.array.erased(bank_start(other), BANK_BYTES));
            assert!(!rig.array.erased(bank_start(held), BANK_BYTES));
        }
    }

    /// Section 4.4.3, "Changing security option bytes", with no regression to level 0 in the change: a
    /// valid PCROP or secure-only area cannot be removed or reduced, an erase enable cannot go from one
    /// to zero, and `SECURITY` cannot clear with an area standing. The change is refused with
    /// `OPTCHANGEERR`, the area is kept, and the programming registers keep what was written. Growing an
    /// area, setting an enable and clearing `SECURITY` with no area are taken.
    #[test]
    fn an_option_change_that_breaks_the_area_rules_is_an_option_change_error() {
        let factory = OptionBytes::FACTORY.optsr;
        let security = |on| optsr_prg::SECURITY.set(factory, on);
        let area = |erase| (Register::PrarPrg1, pcrop(0x10, 0x20, erase));
        let cases: [Case; 10] = [
            (
                "removing a PCROP area",
                vec![area(false)],
                vec![(Register::PrarPrg1, pcrop(0xFF, 0, false))],
                true,
            ),
            (
                "reducing a PCROP area",
                vec![area(false)],
                vec![(Register::PrarPrg1, pcrop(0x10, 0x18, false))],
                true,
            ),
            (
                "growing a PCROP area",
                vec![area(false)],
                vec![(Register::PrarPrg1, pcrop(0x08, 0x30, false))],
                false,
            ),
            ("clearing DMEP", vec![area(true)], vec![area(false)], true),
            ("setting DMEP", vec![area(false)], vec![area(true)], false),
            (
                "removing a PCROP area in bank 2",
                vec![(Register::PrarPrg2, pcrop(0x10, 0x20, false))],
                vec![(Register::PrarPrg2, pcrop(0xFF, 0, false))],
                true,
            ),
            (
                "removing a secure-only area",
                vec![(Register::ScarPrg1, secure(0, 0x3FF, true))],
                vec![(Register::ScarPrg1, secure(0xFF, 0, true))],
                true,
            ),
            (
                "clearing DMES",
                vec![(Register::ScarPrg1, secure(0, 0x3FF, true))],
                vec![(Register::ScarPrg1, secure(0, 0x3FF, false))],
                true,
            ),
            (
                "clearing SECURITY with an area standing",
                vec![area(false), (Register::OptsrPrg, security(1))],
                vec![(Register::OptsrPrg, security(0))],
                true,
            ),
            (
                "clearing SECURITY with no area",
                vec![(Register::OptsrPrg, security(1))],
                vec![(Register::OptsrPrg, security(0))],
                false,
            ),
        ];
        for (label, first, second, refused) in cases {
            let mut rig = Rig::new();
            assert!(
                try_commit(&mut rig, &first),
                "{label}: the first change is taken"
            );
            let kept = rig.soc.model.committed_options();
            assert_eq!(try_commit(&mut rig, &second), !refused, "{label}");
            if refused {
                assert_eq!(
                    rig.soc.model.committed_options(),
                    kept,
                    "{label}: the area is kept"
                );
                for (register, value) in second {
                    assert_eq!(
                        rig.read(register),
                        value,
                        "{label}: {register:?} keeps what was written"
                    );
                }
                assert!(!optsr_cur::OPT_BUSY.is_set(rig.read(Register::OptsrCur)));
            } else {
                assert_ne!(
                    rig.soc.model.committed_options(),
                    kept,
                    "{label}: the change is made"
                );
            }
        }
    }

    /// The same rules with the regression the manual asks for: from level 1 to level 0 an area can be
    /// removed, if its erase enable is set in the current or the programming register, and `SECURITY`
    /// can clear with an area standing if every standing area's enable is. The erase a regression does
    /// is left out, in the module doc.
    #[test]
    fn a_level_regression_may_remove_an_area_with_its_erase_enable_set() {
        let factory = OptionBytes::FACTORY.optsr;
        let level_1 = optsr_prg::RDP.set(factory, 0x55);
        let area = |erase| (Register::PrarPrg1, pcrop(0x10, 0x20, erase));
        let gone = |erase| (Register::PrarPrg1, pcrop(0xFF, 0, erase));
        let level_1_secure = optsr_prg::SECURITY.set(level_1, 1);
        let cases: [Case; 6] = [
            (
                "DMEP set in the current register",
                vec![(Register::OptsrPrg, level_1), area(true)],
                vec![(Register::OptsrPrg, factory), gone(true)],
                true,
            ),
            (
                "DMEP set in the programming register",
                vec![(Register::OptsrPrg, level_1), area(false)],
                vec![(Register::OptsrPrg, factory), gone(true)],
                true,
            ),
            (
                "DMEP set in neither",
                vec![(Register::OptsrPrg, level_1), area(false)],
                vec![(Register::OptsrPrg, factory), gone(false)],
                false,
            ),
            (
                "a secure-only area with DMES set",
                vec![
                    (Register::OptsrPrg, level_1),
                    (Register::ScarPrg1, secure(0, 0x3FF, true)),
                ],
                vec![
                    (Register::OptsrPrg, factory),
                    (Register::ScarPrg1, secure(0xFF, 0, true)),
                ],
                true,
            ),
            (
                "SECURITY cleared with the area's DMEP set",
                vec![(Register::OptsrPrg, level_1_secure), area(true)],
                vec![(Register::OptsrPrg, factory), area(true)],
                true,
            ),
            (
                "SECURITY cleared with the area's DMEP clear",
                vec![(Register::OptsrPrg, level_1_secure), area(false)],
                vec![(Register::OptsrPrg, factory), area(false)],
                false,
            ),
        ];
        for (label, first, second, taken) in cases {
            let mut rig = Rig::new();
            assert!(
                try_commit(&mut rig, &first),
                "{label}: the first change is taken"
            );
            assert_eq!(try_commit(&mut rig, &second), taken, "{label}");
        }
    }

    /// Writes held for an option change replay one after the other, each against what the one before
    /// left. `CR1 |= LOCK1` and then `CR1 |= PG1`, made while `OPT_BUSY` stands, both read the register
    /// unlocked, and the second must find the bank locked when it lands.
    #[test]
    fn held_writes_replay_against_the_state_the_one_before_them_left() {
        let mut rig = Rig::new();
        rig.unlock(0);
        rig.unlock_options();
        rig.write(Register::BootPrgr, 0x1FF0_0900);
        rig.set_bits(Register::Optcr, optcr::OPTSTART.mask());
        rig.set_bits(Register::Cr1, LOCK1.mask());
        rig.set_bits(Register::Cr1, cr1::PG1.mask());
        let control = rig.read(Register::Cr1);
        assert!(
            !LOCK1.is_set(control) && !cr1::PG1.is_set(control),
            "both are held"
        );
        rig.advance(OPTION_PROGRAM_NANOS);
        let control = rig.read(Register::Cr1);
        assert!(LOCK1.is_set(control), "the first landed");
        assert!(
            !cr1::PG1.is_set(control),
            "and the second found the bank locked"
        );
    }
}