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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The universal synchronous/asynchronous receiver transmitter of RM0433 rev 9 chapter 48, written
//! against the `usart1` layout. It answers for all eight instances: USART1, USART2, USART3 and
//! USART6, and UART4, UART5, UART7 and UART8. They share one table, and Table 402 only takes the
//! synchronous and smartcard modes away from the second four, which the model leaves out for all
//! eight. [`INSTANCES`] names them.
//!
//! **What's on the far end is the caller's business.** The model sends and receives frames through
//! [`Peer`], hands the peer each word as its stop bit ends, and asks it for the next word whenever
//! the receiver is free: at the end of each frame, and at every stop of the target through
//! [`Device::poll`]. A chip, a host on a socket and a test's stand-in all hang there the same way,
//! and the model keeps its own time against `BRR`, `PRESC` and the kernel clock whatever is behind
//! it. A receiver that's off loses what the far end puts on the line, as a cut line does.
//!
//! **What the model handles and what falls to the register file.** The model answers a read of
//! `RDR`, which pops the receive FIFO, and writes the status it computes into `ISR` after every
//! change, so the file answers every read of `ISR` and the debugger's peek. Every register of the
//! chapter has an arm in [`Device::read`] and [`Device::write`]. The file stores `CR1`, `CR2`, `CR3`,
//! `BRR`, `GTPR` and `PRESC`, and the model puts back the bits section 48.8 says take a write only
//! while `UE` is clear. The file stores `RTOR` and nothing acts on it. `RQR` and `ICR` are write-only
//! and the model acts on what's written. `TDR` is stored by the file and the model queues the word.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | Reset state | `ISR` reads `TXE` and `TC` set and nothing else, and every other register reads zero. With `FIFOEN` set and `UE` clear `ISR` also reads `TXFE`, which is the manual's `0x0080 00C0` | 48.8.9, 48.8.10 | `reset_leaves_the_transmitter_empty_and_complete`, `with_the_fifo_enabled_and_the_usart_off_isr_shows_the_fifo_empty` |
//! | Instances | USART1, 2, 3 and 6, and UART4, 5, 7 and 8, answer from one table, and [`INSTANCES`] names them. Each has one interrupt, Table 147 | 48.4, Table 402, Table 147 | `every_serial_port_resolves_in_the_generated_tables` |
//! | The frame | A start bit, 7, 8 or 9 data bits by `M1` and `M0`, the parity bit in the top data bit under `PCE`, and 1, 0.5, 2 or 1.5 stop bits by `STOP`. A run of frames is timed from where it began so the rounding can't accumulate | 48.5.3, 48.5.5, 48.5.12, 48.8.1, 48.8.3 | `the_frame_time_follows_brr_over8_m_and_stop`, `a_run_of_frames_does_not_drift` |
//! | Baud rate | A bit is `USARTDIV` cycles of the prescaled kernel clock under 16x oversampling, which is `BRR` itself, and `USARTDIV` over two under `OVER8`, where `BRR[2:0]` is `USARTDIV[3:0]` shifted right once. `PRESC` divides the kernel clock by 1 to 256, and a reserved code divides by 256 | 48.5.7, 48.8.5, 48.8.14 | `the_frame_time_follows_brr_over8_m_and_stop`, `presc_divides_the_kernel_clock_and_a_reserved_code_divides_by_256` |
//! | `USARTDIV` below 16 | "In case of oversampling by 16 and 8, USARTDIV must be greater than or equal to 16." The part's behavior outside that is not given. The model times the frame by the formula and tells the session once as the USART is enabled | 48.5.7 | `a_usartdiv_below_16_is_told_once_and_still_times_by_the_formula` |
//! | Kernel clock | The rate `usart_ker_ck` runs at, which `USART16SEL` picks for USART1 and USART6 and `USART234578SEL` for the others, and `rcc_pclk2` or `rcc_pclk1` out of reset. The model follows it as the part's tree drives it, and runs at the rate it was built with until then. The next frame goes at the new rate, and the fraction a run carried is dropped with the rate it was a fraction of. Built with [`DEFAULT_KERNEL_HZ`] by [`Usart::new`] | 48.5.1, 48.5.6, 8.7.2, 8.7.21 | `a_change_of_clock_applies_from_the_next_frame`, `an_unwired_usart_runs_at_the_hsi_rate_it_was_built_with` |
//! | A stopped kernel clock | No frame on the wire ends, so neither `RXNE` nor `TC` rises, a word a peer sends meanwhile is lost, and `TEACK` and `REACK` wait for the clock | 48.5.1 | `a_stopped_kernel_clock_takes_nothing_a_peer_sends` |
//! | `UE` | Clear, the prescalers and outputs stop at once, every operation is discarded, both FIFOs empty, and `ISR` and the interrupt and request lines go back to their reset state. The configuration stays | 48.8.1, 48.8.2 | `clearing_ue_discards_the_operation_and_resets_the_flags` |
//! | `TE` and the idle frame | Setting `TE` sends one idle frame, a whole frame of ones including the stop bits, before the first word. A word written meanwhile waits behind it | 48.5.5, 48.8.1 | `a_word_written_goes_out_after_the_idle_frame_and_the_peer_hears_it_at_its_stop_bit` |
//! | `TEACK`, `REACK` | Each follows its enable once the USART is on and the kernel clock runs, and clears with `UE`. The manual gives no delay, so there is none | 48.8.9 | `teack_and_reack_follow_te_and_re_once_the_usart_runs` |
//! | Transmitter | With the FIFO off a write to `TDR` clears `TXE`. With nothing on the wire the word starts at once and `TXE` is set again, and with a frame on the wire it waits in `TDR` until that frame ends. The peer hears each word as its stop bit ends. A write while `TDR` is full replaces the word and the model tells the session once | 48.5.5, 48.8.13 | `a_second_word_waits_in_tdr_and_tc_rises_after_the_last`, `a_write_to_a_full_tdr_replaces_the_waiting_word_and_is_told` |
//! | `TC` | Set when a frame containing data ends with `TXE` set, or `TXFE` with the FIFO on. Cleared by a write to `TDR` or by `TCCF`. Set at once when `TE` is cleared with nothing queued | 48.5.5, 48.8.9, 48.8.11, Figure 573 | `a_second_word_waits_in_tdr_and_tc_rises_after_the_last`, `tccf_and_a_write_to_tdr_clear_tc`, `clearing_te_drops_the_word_in_flight_and_clearing_re_the_one_arriving` |
//! | `TE` before `TDR` | "The TE bit must be set before writing the data to be transmitted to the `USART_TDR` register." With `UE` clear the write is ignored, and with `TE` clear the word waits for `TE`. The model tells the session of each, once | 48.5.5 | `a_word_written_before_te_waits_and_one_written_with_ue_clear_is_ignored_and_both_are_told` |
//! | `SBKRQ`, `SBKF` | A break of 10, 11 or 9 low bits by the word length, then two stop bits, after the frame on the wire and ahead of any queued word. `SBKF` stands until the low bits end, which the model takes as "during the stop bits" | 48.5.5, 48.8.8, 48.8.9 | `a_break_goes_out_after_the_current_word_and_sbkf_clears_as_its_low_bits_end`, `a_break_is_as_long_as_the_word_length_says` |
//! | Receiver | With `RE` set the model asks the peer. A word it offers takes a frame to arrive and then lands in `RDR` with `RXNE`. A read of `RDR` answers it and clears `RXNE` | 48.5.6, 48.8.9, 48.8.12 | `a_word_the_peer_offers_lands_in_rdr_after_its_frame_and_raises_rxne` |
//! | A receiver that's off | A word the peer puts on the line while `UE` or `RE` is clear loses itself, and a silent far end's words are lost at every look | 48.5.6 | `a_disabled_receiver_loses_what_a_peer_puts_on_the_line`, `a_silent_far_end_hears_nothing_and_what_it_says_is_lost` |
//! | `ORE` | A word arriving with `RXNE` still set, or the FIFO and `RDR` full, sets `ORE`, keeps what's there, and loses the word. `OVRDIS` clears it, bypasses the FIFO, and lets the new word overwrite `RDR` | 48.5.6, 48.8.4 | `a_word_arriving_with_rxne_standing_sets_ore_and_keeps_rdr`, `ovrdis_overwrites_rdr_and_never_sets_ore` |
//! | `NF`, `FE` and `PE` | A garbled line, a board condition, is [`Errors`]: how often a word arrives with noise or a framing error, drawn as each frame ends. An errored word lands with `RXNE`, and its data bits, the parity bit among them, are flipped by the draw. Each entry carries its errors, and `ISR` shows them once the entry is in `RDR`. `PE` rises when the flipped word fails the parity check. `ONEBIT` hides `NF`. With `DMAR` set and `DDRE` clear the flag is set and the word is not transferred, `RXNE` staying clear. A word that overruns is lost, so it raises only `ORE` | 48.5.4, 48.5.6, 48.5.12, 48.8.4, 48.8.9 | `a_garbled_word_lands_flipped_with_its_flag_and_onebit_hides_the_noise`, `a_flipped_parity_bit_is_a_parity_error`, `an_errored_word_that_overruns_sets_only_ore`, `flags_follow_the_entry_that_reaches_rdr`, `an_errored_word_with_dmar_set_and_ddre_clear_is_not_transferred` |
//! | Two stop bits received | `RXNE` is set at the end of the first stop bit, a bit before the frame ends, and the next frame starts after the second | 48.5.6 | `with_two_stop_bits_rxne_comes_at_the_end_of_the_first` |
//! | `ICR` | A written one clears `PE`, `FE`, `NF`, `ORE`, `IDLE`, `TXFE`, `TC` or `CTSIF` by its own bit and the register reads zero. A write of the whole of `ISR` clears every flag it names | 48.8.11 | `icr_clears_the_flag_of_each_bit_written_and_reads_zero`, `writing_isr_back_to_icr_clears_every_flag_it_names` |
//! | `IDLE` | One frame with nothing arriving after a received word sets it, once, until another word has landed. A word lost to an overrun doesn't count | 48.5.6, 48.8.9 | `the_line_goes_idle_one_frame_after_the_last_word_and_not_again_until_the_next` |
//! | `BUSY` | Stands while a frame is arriving | 48.8.9 | `busy_stands_while_a_frame_is_arriving` |
//! | FIFOs | `FIFOEN` gives each direction 16 entries, Table 402. `TXFNF` stands until the transmit FIFO is full and a write to a full one is lost and told. The receive FIFO and `RDR` hold 17 words and the 18th overruns. `RXFNE` stands while any word is unread. `RXFF` stands at 17 | 48.4, 48.5.4, 48.8.9 | `the_transmit_fifo_takes_sixteen_words_behind_the_one_in_the_shifter`, `a_write_to_a_full_transmit_fifo_is_lost_and_told`, `the_receive_fifo_holds_seventeen_words_and_the_eighteenth_overruns` |
//! | FIFO thresholds | `RXFT` stands while the words unread, `RDR` included, reach the `RXFTCFG` share of 16: 2, 4, 8, 12, 14 or 16. `TXFT` stands while the empty places in the transmit FIFO reach the `TXFTCFG` share. A reserved code never reaches it | 48.5.4, 48.8.4, 48.8.9 | `rxft_follows_the_receive_threshold_in_every_configuration`, `txft_follows_the_transmit_threshold_in_every_configuration` |
//! | `TXFE` | Set when the last queued word moves to the shifter, at reset, and by `TXFRQ`. Cleared by a write to `TDR` and by `TXFECF` | 48.8.9, 48.8.11 | `txfe_is_set_as_the_fifo_empties_and_cleared_by_a_write_or_txfecf` |
//! | `RQR` | `RXFRQ` empties the receive FIFO and `RDR`. `TXFRQ` empties the transmit queue and sets `TXFE`. `SBKRQ` requests a break. `MMRQ` and `ABRRQ` act on modes the model leaves out and change nothing. With `UE` clear a request has nothing to act on | 48.8.8 | `rxfrq_and_txfrq_flush_the_two_fifos` |
//! | The interrupt | One line, Table 410: `TXE` or `TXFNF` under `TXEIE`, `TC` under `TCIE`, `RXNE` or `RXFNE` and `ORE` under `RXNEIE`, `IDLE` under `IDLEIE`, `PE` under `PEIE`, `CTSIF` under `CTSIE`, `FE`, `NF` and `ORE` under `EIE`, and with the FIFO on `TXFE` under `TXFEIE`, `RXFF` under `RXFFIE`, `TXFT` under `TXFTIE` and `RXFT` under `RXFTIE` | 48.7, Table 410, 48.8.4 | `each_enable_raises_the_line_for_its_own_flag`, `the_receive_threshold_interrupt_rises_at_the_threshold_and_falls_below_it`, `the_transmit_threshold_interrupt_rises_while_the_fifo_has_room` |
//! | DMA | `DMAR` drives the receive request off `RXNE` or `RXFNE`, and `DMAT` the transmit request off `TXE` or `TXFNF`. `DDRE` set lands an errored word and masks the receive request while `PE`, `FE` or `NF` stands. `UE` clear lowers both | 48.5.19, 48.8.1, 48.8.4 | `dmar_and_dmat_drive_the_two_requests_off_the_receive_and_transmit_flags`, `ddre_masks_the_receive_request_while_an_error_flag_stands` |
//! | `CTSE`, `CTS`, `CTSIF` | With `CTSE` set a frame doesn't start while the `CTS` pin is high, and a frame on the wire finishes. `CTS` is the inverted pin while the USART is on, and `CTSIF` rises when the pin toggles under `CTSE`. [`Usart::drive_cts`] is the pin, low until driven, which is a peer that's ready | 48.5.20, 48.8.9 | `a_frame_waits_for_cts_and_ctsif_marks_the_toggle` |
//! | `TE` and `RE` cleared | The frame on the wire is lost when `TE` clears and the one arriving when `RE` clears | 48.5.5, 48.5.6 | `clearing_te_drops_the_word_in_flight_and_clearing_re_the_one_arriving` |
//! | The far end between stops | A word the peer has by the instant the session polls at lands then, so a host's byte reaches a sleeping firmware | not applicable | `a_hosts_bytes_land_in_the_round_they_are_noticed_in` |
//! | A silent far end | A far end the board has silenced, a board condition, hears none of what the firmware sends | not applicable | `a_silent_far_end_hears_nothing_and_what_it_says_is_lost` |
//! | A reset | [`Device::reset`] puts everything the reset clears back and keeps the far end, the garble and the `CTS` pin. [`Usart::inherit`] hands them to a part built fresh | not applicable | `a_reset_puts_the_model_back_and_keeps_the_line`, `a_part_built_fresh_inherits_the_line` |
//! | The reset bit | A write that leaves the port's bit of `RCC_APB1LRSTR` or `RCC_APB2RSTR` set puts it back the same way, with its line and each request the multiplexer heard rise lowered at once | 8.4.3, 8.7.33, 8.7.35 | `a_reset_bit_lowers_the_request_the_multiplexer_heard_at_the_reset_itself` |
//! | Events and the snapshot | An event the model does not expect is ignored. The model's state serializes | not applicable | `a_stale_event_is_ignored`, `the_model_state_round_trips_through_a_snapshot` |
//! | A driver's whole sequences | ChibiOS's serial driver, `usart_init`, `usart_deinit` and `sd_lld_serve_interrupt`, replayed register access by register access: the start with the FIFO off and on, an interrupt-driven transmit and receive through a peer with each byte at its instant, a start on a port the bootloader left running, a stop and restart, ArduPilot's DMA receive setup, and its `CTSE` toggle with `UE` | 48.5.5, 48.5.6, 48.5.19, 48.7 | `chibios_serial_driver_starts_transmits_and_receives_with_the_fifo_off`, `chibios_serial_driver_starts_transmits_and_receives_with_the_fifo_on`, `chibios_start_on_a_port_the_bootloader_left_running_takes_the_new_baud_and_fifo`, `chibios_stop_and_start_judge_cr1_zero_against_the_new_ue`, `ardupilot_dma_receive_setup_moves_bytes_by_request_and_raises_the_line_on_idle`, `ardupilot_flow_control_toggle_clears_and_sets_ue_around_ctse` |
//!
//! **What the model leaves out, and why.**
//!
//! | Behavior | Source | Reason |
//! |---|---|---|
//! | A write with `UE` set to a bit documented as writable only while it is clear | 48.8.1 to 48.8.6, 48.8.14, 48.5.7 | The pages state a precondition and say nothing of what a write without it does, and 48.5.7 says the baud counters take a new `BRR` after a write. ChibiOS's start writes `BRR`, `CR2`, `CR3` and `CR1` without clearing `UE`, and the application's start after the bootloader's meets a running port, so the model takes the write, zeroes the runs' carries, and tells the session once. Test: `bits_that_need_ue_clear_take_a_write_while_the_usart_runs_and_it_is_told`. The bits: `FIFOEN`, `M1`, `M0`, `OVER8`, `WAKE`, `PCE`, `PS`, `DEAT` and `DEDT` of `CR1`. `STOP`, `SWAP`, the inversions, `MSBFIRST`, `LINEN`, `CLKEN`, `CPOL`, `CPHA`, `LBCL`, `LBDL` and `ADDM7` of `CR2`, and `ADD` while `RE` is set and `ABRMOD` while `ABREN` is set. `ONEBIT`, `OVRDIS`, `DDRE`, `CTSE`, `RTSE`, `HDSEL`, `DEM`, `DEP`, `SCEN`, `NACK`, `IREN`, `IRLP` and `WUS` of `CR3`. All of `BRR` and `PRESC`, and `PSC` and `GT` of `GTPR`. |
//! | Synchronous mode and SPI slave mode, `CLKEN`, `CPOL`, `CPHA`, `LBCL`, `SLVEN`, `DIS_NSS`, the `UDR` flag | 48.5.14 | A clock on the `CK` pin is a waveform, and a peer here is a word at a time. No driver on this firmware uses it. The bits are stored and frames cross as they would asynchronously |
//! | Smartcard mode, `SCEN`, `NACK`, `SCARCNT`, `GTPR`, `BLEN`, `TCBGT`, `EOBF` | 48.5.17 | The first board wires no smartcard. The bits are stored and `TCBGT` and `EOBF` never rise |
//! | `IrDA` SIR mode, `IREN`, `IRLP`, `PSC` | 48.5.18 | Nothing here is an infrared transceiver. The bits are stored |
//! | LIN mode, `LINEN`, `LBDL`, `LBDF` | 48.5.13 | A break is not a word on the seam, so the peer can't send one and nothing receives one. A break the firmware sends crosses to no peer. The bits are stored and `LBDF` never rises |
//! | Single-wire half-duplex, `HDSEL` | 48.5.15 | The seam has a direction each way, and no peer shares one wire with the transmitter. The hwdef sets no half-duplex port, and the driver clears `HDSEL` around each transmit when an option asks for it. The bit is stored and the frames cross as in full duplex, with no echo of the model's own frames |
//! | `RXINV`, `TXINV`, `TAINV` (the manual's `DATAINV`), `SWAP`, `MSBFIRST` | 48.8.3 | The seam carries words and not levels, so an inverted line, a swapped pair or a reversed bit order has no meaning on it. The hwdef sets none of them, and the driver sets them only for a port option. The bits are stored and the words cross as written |
//! | Mute mode, `MME`, `WAKE`, `MMRQ`, `RWU`, `ADD`, `ADDM7` | 48.5.10 | A network of USARTs on one line, and every line the first board has is point to point. `RWU` never rises |
//! | Character match, `CMF`, `CMIE`, and Modbus end-of-block by receiver timeout, `RTOEN`, `RTOR`, `RTOF`, `RTOIE` | 48.5.11, 48.5.16 | No driver on this firmware uses either. The page does not say when the timeout counts for a receiver that has not yet received a word. The bits are stored and the flags never rise |
//! | Auto baud rate detection, `ABREN`, `ABRMOD`, `ABRRQ`, `ABRF`, `ABRE` | 48.5.9 | The peer hands over a word, not a waveform to measure, and no driver on this firmware uses it |
//! | Driver enable, `DEM`, `DEP`, `DEAT`, `DEDT` | 48.5.20 | No RS-485 transceiver is wired, and the page does not say what the `DE` signal does between frames that follow back to back. The bits are stored and transmission is not delayed |
//! | Wake-up from low-power modes, `UESM`, `WUS`, `WUFIE`, `WUF`, and the `usart_wkup` output | 48.5.21, 48.6 | Power domains and Stop mode are not modeled. The bits are stored and `WUF` never rises |
//! | `M[1:0]` of `0b11` | 48.8.1 | The page does not define it. The model frames it as 8 data bits |
//! | `TXFTCFG` and `RXFTCFG` reserved codes | 48.8.4 | The page says reserved and gives no threshold. The flag never rises |
//! | The delay before `TEACK` and `REACK` follow `TE` and `RE` | 48.8.9 | The page says the value is taken into account by the USART and gives no number |
//! | Start bit detection and the sampling of 48.5.6 | 48.5.6 | A word arrives whole and takes a frame to do so. Noise and framing errors are drawn per word rather than sampled per bit |
//! | Receiver tolerance to clock deviation, Tables 406 and 407 | 48.5.8 | No clock deviates. A peer's word takes exactly a frame |
//! | A frame on the wire when the kernel clock changes | 48.5.7 | It finishes at the rate it began at, where the part would clock its remaining bits at the new one: a difference of less than one frame, once, and a tree isn't retuned with a frame in flight |
//! | The two clock domains and `usart_pclk` | 48.5.1 | A register access needs the bus clock and not the kernel clock. The bus clock is the part's gate on the instance |
//! | A low pulse on `TE` during transmission | 48.5.5, 48.8.1 | The page says both that the current word is lost and that a preamble follows the current word. The model drops the word, which is the warning in 48.5.5, since the firmware's own sequence waits for `TC` before clearing `TE` |
//! | ES0392 rev 15 2.20.1 | ES0392 rev 15 | SPI slave mode is not modeled. Not applicable to this part's revision V either: table 3 marks it present on revisions Y and W alone |
//! | ES0392 rev 15 2.20.2 | ES0392 rev 15 | SPI slave mode is not modeled. Present on revision V, with a workaround that waits for the clock line to idle |
//! | ES0392 rev 15 2.20.3: data corruption from a glitch to zero shorter than half a bit in the second half of the stop bit | ES0392 rev 15 | Present on revision V. The seam carries words, so a glitch on the line has no representation. A noisy line is [`Errors`], drawn per word. The workaround is a noiseless line |
//! | ES0392 rev 15 2.20.4: the DMA stream stays locked when a concurrent transfer meets the USART's request | ES0392 rev 15 | Present on revision V. The lock is in the DMA controller, which this model only asks. The workaround is `TRBUFF`, bit 20 of `DMA_SxCR`, which ArduPilot sets on its USART streams |
//! | ES0392 rev 15 2.20.5: received data corrupted by clearing `ABREN` | ES0392 rev 15 | Present on revision V (table 3 marks it A on every revision), with the workaround of never clearing `ABREN`. Auto baud rate detection is not modeled |
//! | ES0392 rev 15 2.20.6: `NF` is set by noise on the start bit although `ONEBIT` is set | ES0392 rev 15 | Present on revision V with no workaround. The model draws noise per word and cannot tell the start bit from a data bit, so under `ONEBIT` it never raises `NF`, where the part still does on a noisy start bit |
//!
//! **Where this model departs from the vendor's file.** None of the registers or fields needs a
//! correction: every reset value, access and offset of the file matches the pages. The file spells
//! the noise flag `NF` and its clear bit `NCF` where the manual says `NE` and `NECF`, `TAINV` where
//! it says `DATAINV`, splits `BRR` into `BRR_0_3` and `BRR_4_15`, and gives `DEAT` and `DEDT` as ten
//! one-bit fields, and the model reads them by the file's names. The file's `ISR` is the FIFO-off
//! view, and the bits the FIFO adds sit at the same places, so the model reads `TXE` as `TXFNF` and
//! `RXNE` as `RXFNE` under `FIFOEN`, as the manual's two views of `CR1` and `ISR` do.
//!
//! **The FIFO is 16 deep.** Table 402 gives "Tx/Rx FIFO size 16" and the notes on `RXFT` and `RXFF`
//! agree, so the model has 16 entries each way and `RDR` as a 17th place on the receive side.
//!
//! **Determinism.** `two_runs_of_one_script_are_the_same_run` drives two fresh instances through a
//! transmit, an errored receive, a flush and a break, and checks the interrupt lines, the requests,
//! every register and the model's whole state agree between the two. The garble is [`Errors`], keyed
//! by the run's seed, which `a_different_seed_garbles_a_different_pattern` and
//! `a_restored_model_draws_the_garble_where_the_saved_one_left_off` hold.

use std::collections::{BTreeSet, VecDeque};

use crate::chip::uart::{Errors, Peer};
use crate::chip::{Place, Placed, Timeline};
use crate::device::{Device, DeviceContext, Level, RegisterFile};
use crate::snapshot::store;
use crate::soc::stm32h743::generated::usart1::{
    Register, brr, cr1, cr2, cr3, gtpr, icr, isr, presc, rqr,
};
use crate::soc::{FieldSpec, Layout};
use crate::time::{EventId, NANOS_PER_SECOND, Run, VirtualNanos};

/// The request output `DMAR` drives, RM0433 rev 9 section 48.5.19.
pub const RECEIVE_REQUEST: usize = 0;
/// The request output `DMAT` drives.
pub const TRANSMIT_REQUEST: usize = 1;

// The instance's one interrupt. Table 147 gives each of the eight a line of its own.
const GLOBAL: usize = 0;

/// The depth of each FIFO, RM0433 rev 9 Table 402. The receive side holds one more word in `RDR`.
pub const FIFO_DEPTH: usize = 16;

/// The kernel clock a USART runs on until the part's tree drives it: `rcc_pclk1` or `rcc_pclk2`,
/// each of which is `sys_ck` undivided after reset (RM0433 rev 9 8.7.8, 8.7.9 and 8.7.21), and
/// `sys_ck` is the HSI at 64 MHz (8.7.2's `HSIDIV` and 8.7.7's `SW`).
pub const DEFAULT_KERNEL_HZ: u64 = 64_000_000;

// How many words the model remembers sending, oldest dropped first.
const REMEMBERED: usize = 64;

// `PRESC`, 48.8.14: the divisors of codes 0 to 11. The reserved codes divide by the last.
const PRESCALERS: [u64; 12] = [1, 2, 4, 6, 8, 10, 12, 16, 32, 64, 128, 256];

// `STOP`, 48.8.3, in half bits: 1, 0.5, 2 and 1.5 stop bits.
const STOP_HALF_BITS: [u64; 4] = [2, 1, 4, 3];

// The two stop bits that follow a break, 48.5.5, in half bits.
const BREAK_STOP_HALF_BITS: u64 = 4;

// `USARTDIV` below this isn't allowed, 48.5.7.
const MIN_USARTDIV: u64 = 16;

// `RXFTCFG` and `TXFTCFG`, 48.8.4, in eighths of the FIFO: 1/8, 1/4, 1/2, 3/4, 7/8 and the whole.
const THRESHOLD_EIGHTHS: [usize; 6] = [1, 2, 4, 6, 7, 8];

// The latched flags with the USART off or just reset: transmission complete, and the FIFO empty.
const RESET_FLAGS: u64 = isr::TC.mask() | isr::TXFE.mask();

// The flags the FIFO adds to `ISR`, which read zero with it off.
const FIFO_FLAGS: u64 = isr::TXFE.mask() | isr::RXFF.mask() | isr::RXFT.mask() | isr::TXFT.mask();

// The flags `ICR` clears and the bit that clears each, 48.8.11.
const CLEARS: [(&FieldSpec, &FieldSpec); 8] = [
    (icr::PECF, isr::PE),
    (icr::FECF, isr::FE),
    (icr::NCF, isr::NF),
    (icr::ORECF, isr::ORE),
    (icr::IDLECF, isr::IDLE),
    (icr::TXFECF, isr::TXFE),
    (icr::TCCF, isr::TC),
    (icr::CTSCF, isr::CTSIF),
];

// The registers with bits that take a write only while `UE` is clear, in the order of [`Usart`]'s
// copies of what they last held.
const GUARDED: [Register; 6] = [
    Register::Cr1,
    Register::Cr2,
    Register::Cr3,
    Register::Brr,
    Register::Gtpr,
    Register::Presc,
];

// `CR1`'s bits that need `UE` clear, 48.8.1: `FIFOEN`, `M1`, `DEAT`, `DEDT`, `OVER8`, `M0`, `WAKE`,
// `PCE` and `PS`.
const CR1_LOCKED: u64 = cr1::FIFOEN.mask()
    | cr1::M1.mask()
    | cr1::DEAT0.mask()
    | cr1::DEAT1.mask()
    | cr1::DEAT2.mask()
    | cr1::DEAT3.mask()
    | cr1::DEAT4.mask()
    | cr1::DEDT0.mask()
    | cr1::DEDT1.mask()
    | cr1::DEDT2.mask()
    | cr1::DEDT3.mask()
    | cr1::DEDT4.mask()
    | cr1::OVER8.mask()
    | cr1::M0.mask()
    | cr1::WAKE.mask()
    | cr1::PCE.mask()
    | cr1::PS.mask();

// `CR2`'s bits that need `UE` clear, 48.8.3.
const CR2_LOCKED: u64 = cr2::MSBFIRST.mask()
    | cr2::TAINV.mask()
    | cr2::TXINV.mask()
    | cr2::RXINV.mask()
    | cr2::SWAP.mask()
    | cr2::LINEN.mask()
    | cr2::STOP.mask()
    | cr2::CLKEN.mask()
    | cr2::CPOL.mask()
    | cr2::CPHA.mask()
    | cr2::LBCL.mask()
    | cr2::LBDL.mask()
    | cr2::ADDM7.mask();

// `ADD`, which takes a write while `RE` is clear or `UE` is, 48.8.3.
const ADDRESS: u64 = cr2::ADD0_3.mask() | cr2::ADD4_7.mask();

// `ABRMOD`, which takes a write while `ABREN` is clear or `UE` is, 48.8.3.
const AUTO_BAUD_MODE: u64 = cr2::ABRMOD0.mask() | cr2::ABRMOD1.mask();

// `CR3`'s bits that need `UE` clear, 48.8.4.
const CR3_LOCKED: u64 = cr3::DEP.mask()
    | cr3::DEM.mask()
    | cr3::DDRE.mask()
    | cr3::OVRDIS.mask()
    | cr3::ONEBIT.mask()
    | cr3::CTSE.mask()
    | cr3::RTSE.mask()
    | cr3::SCEN.mask()
    | cr3::NACK.mask()
    | cr3::HDSEL.mask()
    | cr3::IRLP.mask()
    | cr3::IREN.mask()
    | cr3::WUS.mask();

// `BRR`, `GTPR` and `PRESC` as wholes, 48.8.5, 48.8.6 and 48.8.14.
const BRR_LOCKED: u64 = brr::BRR_0_3.mask() | brr::BRR_4_15.mask();
const GTPR_LOCKED: u64 = gtpr::PSC.mask() | gtpr::GT.mask();
const PRESC_LOCKED: u64 = presc::PRESCALER.mask();

// What the model tells the session, each once as the condition begins. The register is the one the
// access wrote.
const LOCKED_WRITE: &str = "RM0433 rev 9 section 48.8: this bit field is documented as writable only while the USART is disabled (UE = 0), and the page says nothing of a write with UE set, so the model took it, and the baud counters take a new BRR at once (48.5.7)";
const SMALL_USARTDIV: &str =
    "RM0433 rev 9 section 48.5.7: USARTDIV must be greater than or equal to 16";
const WRITE_WITH_UE_CLEAR: &str = "RM0433 rev 9 section 48.8.1: UE = 0 discards all current operations, so a write to the transmit data register is ignored";
const WRITE_BEFORE_TE: &str = "RM0433 rev 9 section 48.5.5: the TE bit must be set before writing the data to be transmitted, so the word waits for TE";
const WRITE_TO_A_FULL_TDR: &str = "RM0433 rev 9 section 48.8.13: the transmit data register must be written only when TXE or TXFNF is set, so the write replaced or was lost";

/// The eight serial ports of chapter 48, in the order of ST's numbering: USART1, 2, 3, UART4, 5,
/// USART6, UART7, UART8. A part gives each one a model.
pub const INSTANCES: [&str; 8] = [
    "USART1", "USART2", "USART3", "UART4", "UART5", "USART6", "UART7", "UART8",
];

// A frame on the wire, ending at its event.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Frame {
    event: EventId,
    kind: FrameKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum FrameKind {
    // A word, framed as it goes on the wire.
    Data(u16),
    // The frame of ones `TE` sends first, 48.5.5.
    Idle,
    // The low bits of a break, 48.5.5.
    Break,
    // The two stop bits after a break.
    BreakStop,
}

// A word in the receive FIFO with the errors it came with, which `ISR` shows once it reaches `RDR`.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Received {
    word: u16,
    noise: bool,
    framing: bool,
    parity: bool,
}

// What `CR1` says is on: the USART, and its transmitter and receiver, which need it.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Power {
    usart: bool,
    transmitter: bool,
    receiver: bool,
}

impl Power {
    fn of(control: u64) -> Self {
        let usart = cr1::UE.is_set(control);
        Self {
            usart,
            transmitter: usart && cr1::TE.is_set(control),
            receiver: usart && cr1::RE.is_set(control),
        }
    }
}

// The firmware mistakes the model tells the session of, each once as the condition begins and not on
// every access held under it.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
enum Mistake {
    LockedWrite,
    SmallUsartdiv,
    WriteWithUeClear,
    WriteBeforeTe,
    WriteToAFullTdr,
}

/// One serial port of an STM32H743, RM0433 rev 9 chapter 48.
#[derive(Debug)]
pub struct Usart {
    kernel_hz: u64,
    peer: Option<Place<dyn Peer>>,
    errors: Errors,
    // What each of [`GUARDED`] last held, so a write while `UE` is set can put the locked bits back.
    kept: [u64; GUARDED.len()],
    // The flags hardware sets and a written one clears, at their `ISR` bits. The rest of `ISR`
    // follows the state.
    flags: u64,
    // The words waiting to go out, one with the FIFO off.
    transmit: VecDeque<u16>,
    sending: Option<Frame>,
    sent: VecDeque<u16>,
    // The words received and unread, the front being what `RDR` reads. One with the FIFO off.
    receive: VecDeque<Received>,
    // What `RDR` holds once everything is read.
    last_read: u16,
    receiving: Option<Frame>,
    idle: Option<EventId>,
    idle_armed: bool,
    outgoing: Option<Run>,
    incoming: Option<Run>,
    // `SBKF`: a break was requested and its low bits haven't finished.
    break_requested: bool,
    // The level of the `CTS` pin.
    cts: Level,
    // `TEACK` and `REACK`, in the shape of `CR1`'s enables.
    acked: Power,
    // The mistakes told since the USART was last off.
    told: BTreeSet<Mistake>,
    interrupt: Level,
    requests: [Level; 2],
}

store!(Usart {
    values: [
        kernel_hz,
        errors,
        kept,
        flags,
        transmit,
        sending,
        sent,
        receive,
        last_read,
        receiving,
        idle,
        idle_armed,
        outgoing,
        incoming,
        break_requested,
        cts,
        acked,
        told,
        interrupt,
        requests,
    ],
    parts: [peer],
    built: [],
});

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

impl Usart {
    /// A port on the kernel clock it wakes up on, [`DEFAULT_KERNEL_HZ`], until the part's tree drives
    /// it otherwise.
    #[must_use]
    pub fn new() -> Self {
        Self::with_clock(DEFAULT_KERNEL_HZ)
    }

    /// A port whose `usart_ker_ck` runs at `kernel_hz`, which is what `BRR` divides after `PRESC`,
    /// until the part's tree drives it otherwise.
    #[must_use]
    pub fn with_clock(kernel_hz: u64) -> Self {
        Self {
            kernel_hz,
            peer: None,
            errors: Errors::default(),
            kept: [0; GUARDED.len()],
            flags: RESET_FLAGS,
            transmit: VecDeque::new(),
            sending: None,
            sent: VecDeque::new(),
            receive: VecDeque::new(),
            last_read: 0,
            receiving: None,
            idle: None,
            idle_armed: false,
            outgoing: None,
            incoming: None,
            break_requested: false,
            cts: Level::Low,
            acked: Power::of(0),
            told: BTreeSet::new(),
            interrupt: Level::Low,
            requests: [Level::Low; 2],
        }
    }

    /// Hangs `peer` on the far end of the line, in place of whatever was there.
    pub fn attach(&mut self, peer: impl Peer) {
        self.attach_boxed(Box::new(peer));
    }

    /// Hangs a boxed peer, which is what a caller holding `dyn Peer` has.
    pub fn attach_boxed(&mut self, peer: Box<dyn Peer>) {
        self.peer = Some(Place::new(peer));
    }

    /// Takes the far end off `from`'s wire and hangs it on this one, silent and garbled if it was,
    /// with the `CTS` pin where the board left it.
    pub fn inherit(&mut self, from: &mut Self) {
        self.peer = from.peer.take();
        self.errors = from.errors;
        self.cts = from.cts;
    }

    /// How the line garbles what arrives on it, a board condition, for the board to set.
    pub fn errors_mut(&mut self) -> &mut Errors {
        &mut self.errors
    }

    /// Stops the far end answering, or lets it answer again: a board condition, [`Place::silence`].
    /// It hears none of what the firmware sends, and what it says goes nowhere, as down a cut line.
    /// Answers whether anything is on the far end.
    #[must_use]
    pub fn silence(&mut self, silent: bool) -> bool {
        self.peer
            .as_mut()
            .map(|place| place.silence(silent))
            .is_some()
    }

    /// The far end's place on the line, for a trigger to count and a one-shot fault to reach. Each
    /// word it sends is a transaction.
    pub fn place_mut(&mut self) -> Option<&mut dyn Placed> {
        self.peer.as_mut().map(|place| -> &mut dyn Placed { place })
    }

    /// Whether anything is on the far end.
    #[must_use]
    pub fn attached(&self) -> bool {
        self.peer.is_some()
    }

    /// The far end, to ask what it saw.
    #[must_use]
    pub fn peer(&self) -> Option<&dyn Peer> {
        self.peer.as_ref().map(Place::chip)
    }

    /// The far end.
    pub fn peer_mut(&mut self) -> Option<&mut dyn Peer> {
        self.peer.as_mut().map(Place::chip_mut)
    }

    /// The far end as the type it was hung as, to drive what it measures. `None` where nothing
    /// hangs there or another peer does. The board that hung the chip is what asks for it back.
    pub fn chip_mut<P: Peer>(&mut self) -> Option<&mut P> {
        self.peer.as_mut()?.chip_as()
    }

    /// Tells the far end that the part restarted, at the instant `context` gives.
    pub fn chips_restarted(&mut self, context: &mut DeviceContext<'_>) {
        if let Some(place) = &mut self.peer {
            place.chip_mut().restarted(&mut Timeline::new(context));
        }
    }

    /// The words the port has most recently sent, oldest first.
    #[must_use]
    pub fn sent(&self) -> Vec<u16> {
        self.sent.iter().copied().collect()
    }

    /// The `CTS` pin going to `level`, 48.5.20. The pin is low until driven, which is a far end that
    /// is ready. A change sets `CTSIF` if `CTSE` is set, and a pin that goes low lets a held frame
    /// start.
    pub fn drive_cts(
        &mut self,
        level: Level,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        if level == self.cts {
            return;
        }
        self.cts = level;
        if cr1::UE.is_set(registers.get(Register::Cr1))
            && cr3::CTSE.is_set(registers.get(Register::Cr3))
        {
            self.flags |= isr::CTSIF.mask();
        }
        self.start_sending(registers, context);
        self.refresh(registers, context);
    }

    // The word length in bits, `M[1:0]` of 48.8.1. The undefined `0b11` is 8.
    fn data_bits(registers: &RegisterFile) -> u32 {
        let control = registers.get(Register::Cr1);
        match (cr1::M1.is_set(control), cr1::M0.is_set(control)) {
            (true, false) => 7,
            (false, true) => 9,
            _ => 8,
        }
    }

    fn data_mask(registers: &RegisterFile) -> u16 {
        u16::MAX >> (u16::BITS - Self::data_bits(registers))
    }

    // `USARTDIV`, 48.5.7: `BRR` itself, or with `OVER8` `BRR[2:0]` shifted left once beside
    // `BRR[15:4]`, `BRR[3]` being kept clear.
    fn usartdiv(registers: &RegisterFile) -> u64 {
        let value = registers.get(Register::Brr);
        let high = brr::BRR_4_15.get(value) << 4;
        let low = brr::BRR_0_3.get(value);
        if cr1::OVER8.is_set(registers.get(Register::Cr1)) {
            high | ((low & 0b111) << 1)
        } else {
            high | low
        }
    }

    // One bit in cycles of the prescaled kernel clock, 48.5.7: `USARTDIV`, or half of it under
    // `OVER8`. Zero is a baud generator with nothing to divide by.
    fn bit_cycles(registers: &RegisterFile) -> u64 {
        let divider = Self::usartdiv(registers);
        if cr1::OVER8.is_set(registers.get(Register::Cr1)) {
            divider / 2
        } else {
            divider
        }
    }

    // The divisor `PRESC` gives, 48.8.14.
    fn prescaler(registers: &RegisterFile) -> u64 {
        let code = presc::PRESCALER.get(registers.get(Register::Presc));
        let code = usize::try_from(code).expect("four bits");
        PRESCALERS[code.min(PRESCALERS.len() - 1)]
    }

    // A frame in half bits: the start bit, the data, and `STOP`'s share. A break is its low bits and
    // the two stop bits that follow it, 48.5.5.
    fn half_bits(kind: FrameKind, registers: &RegisterFile) -> u64 {
        let stop = STOP_HALF_BITS
            [usize::try_from(cr2::STOP.get(registers.get(Register::Cr2))).expect("two bits")];
        let data = u64::from(Self::data_bits(registers));
        match kind {
            FrameKind::Break => 2 * (data + 2),
            FrameKind::BreakStop => BREAK_STOP_HALF_BITS,
            FrameKind::Data(_) | FrameKind::Idle => 2 + 2 * data + stop,
        }
    }

    // When a frame of `kind` starting no earlier than `from` ends, continuing `run` where it
    // stands, and the run as it then stands. `None` where there's nothing to time it by.
    fn frame_end(
        &self,
        run: Option<Run>,
        from: VirtualNanos,
        kind: FrameKind,
        registers: &RegisterFile,
    ) -> Option<(VirtualNanos, Run)> {
        let cycles = Self::bit_cycles(registers);
        if cycles == 0 || self.kernel_hz == 0 {
            return None;
        }
        let mut run = run.filter(|run| run.ends >= from).unwrap_or(Run::at(from));
        let nanos = run.extend(
            u128::from(Self::half_bits(kind, registers))
                * u128::from(cycles)
                * u128::from(Self::prescaler(registers)),
            2 * self.kernel_hz,
        );
        // A frame that rounds to no time would be re-armed at the instant it fired, forever.
        if nanos == 0 {
            return None;
        }
        Some((run.ends, run))
    }

    // The word as it goes on the wire: `M`'s bits, and under `PCE` the parity in the most
    // significant one, even or odd by `PS`, 48.5.12.
    fn framed(word: u16, registers: &RegisterFile) -> u16 {
        let control = registers.get(Register::Cr1);
        let mask = Self::data_mask(registers);
        let word = word & mask;
        if !cr1::PCE.is_set(control) {
            return word;
        }
        let top = mask ^ (mask >> 1);
        let ones = (word & (mask >> 1)).count_ones();
        let odd = cr1::PS.is_set(control);
        let parity = (ones % 2 == 1) != odd;
        if parity { word | top } else { word & !top }
    }

    fn fifo(registers: &RegisterFile) -> bool {
        cr1::FIFOEN.is_set(registers.get(Register::Cr1))
    }

    // How many words wait to go out: the FIFO's, or the one `TDR` holds.
    fn transmit_capacity(registers: &RegisterFile) -> usize {
        if Self::fifo(registers) { FIFO_DEPTH } else { 1 }
    }

    // How many words the receiver holds unread: the FIFO and `RDR`, or `RDR`. `OVRDIS` bypasses the
    // FIFO, 48.8.4.
    fn receive_capacity(registers: &RegisterFile) -> usize {
        let bypassed = cr3::OVRDIS.is_set(registers.get(Register::Cr3));
        if Self::fifo(registers) && !bypassed {
            FIFO_DEPTH + 1
        } else {
            1
        }
    }

    // How many words an `RXFTCFG` or `TXFTCFG` code stands for, 48.8.4, or none for a reserved code.
    fn threshold(code: u64) -> Option<usize> {
        let eighths = THRESHOLD_EIGHTHS.get(usize::try_from(code).ok()?)?;
        Some(FIFO_DEPTH * eighths / 8)
    }

    // Whether the direction `on` says is enabled has a clock and a rate to time a frame by.
    fn open(&self, on: bool, registers: &RegisterFile) -> bool {
        on && self.kernel_hz != 0 && Self::bit_cycles(registers) != 0
    }

    // Whether `CTSE` and a high `CTS` pin hold the next frame back, 48.5.20.
    fn cts_holds(&self, registers: &RegisterFile) -> bool {
        cr3::CTSE.is_set(registers.get(Register::Cr3)) && self.cts == Level::High
    }

    // The bits of `register` the pages document as writable only while `UE` is clear, if the USART
    // stays on after the write that landed in `control` and was on before it.
    fn locked_bits(&self, register: Register, control: u64) -> u64 {
        if !cr1::UE.is_set(control) || !cr1::UE.is_set(self.kept[0]) {
            return 0;
        }
        match register {
            Register::Cr1 => CR1_LOCKED,
            Register::Cr2 => {
                let address = if cr1::RE.is_set(control) { ADDRESS } else { 0 };
                let mode = if cr2::ABREN.is_set(self.kept[1]) {
                    AUTO_BAUD_MODE
                } else {
                    0
                };
                CR2_LOCKED | address | mode
            }
            Register::Cr3 => CR3_LOCKED,
            Register::Brr => BRR_LOCKED,
            Register::Gtpr => GTPR_LOCKED,
            Register::Presc => PRESC_LOCKED,
            _ => 0,
        }
    }

    // Tells the session of `mistake` in an access to `register`, unless it already has.
    fn tell(
        &mut self,
        mistake: Mistake,
        register: Register,
        reason: &'static str,
        context: &mut DeviceContext<'_>,
    ) {
        if self.told.insert(mistake) {
            context.tell(register.spec().name, reason);
        }
    }

    // Tells the session once when a write changes bits the pages document as writable only while `UE`
    // is clear and the USART stays on, and remembers what the register holds. The write stands, and
    // the carries of the runs were a fraction of the old rate.
    fn note_locked_bits(
        &mut self,
        register: Register,
        registers: &RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let Some(slot) = GUARDED.iter().position(|&guarded| guarded == register) else {
            return;
        };
        let locked = self.locked_bits(register, registers.get(Register::Cr1));
        let landed = registers.get(register);
        if landed & locked != self.kept[slot] & locked {
            self.tell(Mistake::LockedWrite, register, LOCKED_WRITE, context);
            self.drop_carries();
        }
        self.kept[slot] = landed;
    }

    fn drop_carries(&mut self) {
        for run in [&mut self.outgoing, &mut self.incoming]
            .into_iter()
            .flatten()
        {
            run.drop_carry();
        }
    }

    // Puts a frame of `kind` on the wire, if the transmitter is on and the wire is free.
    fn send(
        &mut self,
        kind: FrameKind,
        registers: &RegisterFile,
        context: &mut DeviceContext<'_>,
    ) -> bool {
        if self.sending.is_some()
            || !self.open(
                Power::of(registers.get(Register::Cr1)).transmitter,
                registers,
            )
        {
            return false;
        }
        let Some((at, run)) = self.frame_end(self.outgoing, context.now(), kind, registers) else {
            return false;
        };
        self.outgoing = Some(run);
        self.sending = Some(Frame {
            event: context.schedule(at),
            kind,
        });
        true
    }

    // Moves the break `SBKRQ` asked for, or the word at the front of the queue, onto a free wire,
    // 48.5.5. The break goes ahead of data even when the FIFO is full.
    fn start_sending(&mut self, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
        if self.sending.is_some() {
            return;
        }
        if self.break_requested && self.send(FrameKind::Break, registers, context) {
            return;
        }
        if self.cts_holds(registers) {
            return;
        }
        let Some(&word) = self.transmit.front() else {
            return;
        };
        if self.send(FrameKind::Data(word), registers, context) {
            self.transmit.pop_front();
            if self.transmit.is_empty() {
                self.flags |= isr::TXFE.mask();
            }
        }
    }

    // The frame on the wire has ended.
    fn finish_sending(
        &mut self,
        kind: FrameKind,
        registers: &RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        self.sending = None;
        match kind {
            FrameKind::Data(word) => {
                if self.sent.len() == REMEMBERED {
                    self.sent.pop_front();
                }
                self.sent.push_back(word);
                if let Some(peer) = self.peer.as_mut().and_then(Place::answering) {
                    peer.receive(word, &mut Timeline::new(context));
                }
            }
            FrameKind::Break => {
                self.break_requested = false;
                if self.send(FrameKind::BreakStop, registers, context) {
                    return;
                }
            }
            FrameKind::Idle | FrameKind::BreakStop => {}
        }
        self.start_sending(registers, context);
        if self.sending.is_none() {
            self.outgoing = None;
            if matches!(kind, FrameKind::Data(_)) && self.transmit.is_empty() {
                self.flags |= isr::TC.mask();
            }
        }
    }

    // Asks the far end for a word to put on the wire, if the receiver is free, 48.5.6. A receiver
    // that's off, and a silent far end, lose what the far end says at every look.
    fn receive_next(&mut self, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
        let now = context.now();
        if let Some(place) = &mut self.peer {
            place.lose_while_silent(now);
        }
        if self.receiving.is_some() {
            return;
        }
        if !self.open(Power::of(registers.get(Register::Cr1)).receiver, registers) {
            if let Some(place) = &mut self.peer {
                while let Some(word) = place.answering().and_then(|chip| chip.transmit(now)) {
                    let _ = place.sent(u32::from(word));
                }
            }
            return;
        }
        let Some(word) = self.peer.as_mut().and_then(|place| {
            loop {
                let word = place.answering()?.transmit(now)?;
                if let Some(crossed) = place.sent(u32::from(word)) {
                    let crossed = crossed & u32::from(u16::MAX);
                    break Some(u16::try_from(crossed).expect("masked to a word"));
                }
            }
        }) else {
            self.arm_idle(registers, context);
            return;
        };
        let Some((ends, run)) =
            self.frame_end(self.incoming, now, FrameKind::Data(word), registers)
        else {
            return;
        };
        let at = self.landing(ends, registers);
        self.incoming = Some(run);
        self.idle = None;
        self.receiving = Some(Frame {
            event: context.schedule(at),
            kind: FrameKind::Data(word),
        });
    }

    // 48.5.6: with two stop bits RXNE is set at the end of the first, a bit before the frame ends.
    fn landing(&self, ends: VirtualNanos, registers: &RegisterFile) -> VirtualNanos {
        if cr2::STOP.get(registers.get(Register::Cr2)) != 0b10 {
            return ends;
        }
        let bit = u128::from(Self::bit_cycles(registers))
            * u128::from(Self::prescaler(registers))
            * u128::from(NANOS_PER_SECOND)
            / u128::from(self.kernel_hz);
        VirtualNanos(
            ends.0
                .saturating_sub(u64::try_from(bit).expect("a bit fits the clock")),
        )
    }

    // One idle frame after the last word with nothing arriving sets `IDLE` once per burst, 48.8.9.
    fn arm_idle(&mut self, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
        if !self.idle_armed || self.idle.is_some() {
            return;
        }
        let Some((at, _)) =
            self.frame_end(self.incoming, context.now(), FrameKind::Idle, registers)
        else {
            return;
        };
        self.idle = Some(context.schedule(at));
    }

    // The frame arriving has ended: the word lands with any error it came with, or `ORE` if there
    // is no room. How it came is drawn before the overrun is, so the pattern of errors doesn't move
    // with when the firmware reads.
    fn finish_receiving(
        &mut self,
        word: u16,
        registers: &RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        self.receiving = None;
        let arrival = self.errors.next(Self::data_bits(registers));
        let arrived = Self::framed(word, registers) ^ arrival.flipped;
        let capacity = Self::receive_capacity(registers);
        let bypassed = cr3::OVRDIS.is_set(registers.get(Register::Cr3));
        let control = registers.get(Register::Cr1);
        let control3 = registers.get(Register::Cr3);
        let entry = Received {
            word: arrived,
            noise: arrival.noise && !cr3::ONEBIT.is_set(control3),
            framing: arrival.framing,
            parity: cr1::PCE.is_set(control) && Self::framed(arrived, registers) != arrived,
        };
        let errored = entry.noise || entry.framing || entry.parity;
        let dma_drops_errors = cr3::DMAR.is_set(control3) && !cr3::DDRE.is_set(control3);
        if self.receive.len() >= capacity && !bypassed {
            self.flags |= isr::ORE.mask();
        } else if errored && dma_drops_errors {
            // 48.8.4 DDRE: the flag is set, RXNE is kept clear and the word isn't transferred.
            self.flags |= Self::error_flags(entry);
        } else {
            if self.receive.len() >= capacity {
                self.receive.clear();
            }
            self.receive.push_back(entry);
            if self.receive.len() == 1 {
                self.promote();
            }
            self.idle_armed = true;
        }
        self.receive_next(registers, context);
        if self.receiving.is_none() {
            self.incoming = self.incoming.filter(|run| run.ends >= context.now());
        }
    }

    // The flags an entry raises.
    fn error_flags(entry: Received) -> u64 {
        let mut flags = 0;
        if entry.noise {
            flags |= isr::NF.mask();
        }
        if entry.framing {
            flags |= isr::FE.mask();
        }
        if entry.parity {
            flags |= isr::PE.mask();
        }
        flags
    }

    // The entry at the front is the one in `RDR`, and its errors are the ones `ISR` shows, 48.5.4.
    fn promote(&mut self) {
        if let Some(&front) = self.receive.front() {
            self.flags |= Self::error_flags(front);
        }
    }

    // `UE` rose: the USART starts from the reset state of its flags, 48.8.1.
    fn power_up(&mut self, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
        self.flags = RESET_FLAGS;
        if Self::usartdiv(registers) < MIN_USARTDIV {
            self.tell(
                Mistake::SmallUsartdiv,
                Register::Brr,
                SMALL_USARTDIV,
                context,
            );
        }
    }

    // `UE` fell: the prescalers and outputs stop at once and all current operations are discarded,
    // and the status flags are reset, 48.8.1. The configuration stays.
    fn power_down(&mut self) {
        self.sending = None;
        self.receiving = None;
        self.idle = None;
        self.idle_armed = false;
        self.outgoing = None;
        self.incoming = None;
        self.transmit.clear();
        self.receive.clear();
        self.break_requested = false;
        self.flags = RESET_FLAGS;
        self.acked = Power::of(0);
        self.told.clear();
    }

    // `TEACK` and `REACK` take `TE` and `RE` once the USART is on and its kernel clock runs, 48.8.9.
    fn follow_enables(&mut self, registers: &RegisterFile) {
        if self.kernel_hz == 0 {
            return;
        }
        self.acked = Power::of(registers.get(Register::Cr1));
    }

    // `CR1`: the USART's enable, the transmitter's and the receiver's, and the idle frame `TE`
    // begins with, 48.5.5, 48.5.6 and 48.8.1.
    fn write_cr1(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        let before = Power::of(self.kept[0]);
        self.note_locked_bits(Register::Cr1, registers, context);
        let now = Power::of(registers.get(Register::Cr1));
        if now.usart && !before.usart {
            self.power_up(registers, context);
        }
        if !now.usart {
            if before.usart {
                self.power_down();
            }
            return;
        }
        if now.transmitter && !before.transmitter {
            self.send(FrameKind::Idle, registers, context);
        }
        if !now.transmitter && before.transmitter {
            self.sending = None;
            self.outgoing = None;
            if self.transmit.is_empty() {
                self.flags |= isr::TC.mask();
            }
        }
        if !now.receiver && before.receiver {
            self.receiving = None;
            self.incoming = None;
            self.idle = None;
        }
        self.follow_enables(registers);
        self.start_sending(registers, context);
        self.receive_next(registers, context);
    }

    // A write to `TDR`, 48.8.13.
    fn write_tdr(&mut self, value: u64, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
        let control = registers.get(Register::Cr1);
        if !cr1::UE.is_set(control) {
            self.tell(
                Mistake::WriteWithUeClear,
                Register::Tdr,
                WRITE_WITH_UE_CLEAR,
                context,
            );
            return;
        }
        if !cr1::TE.is_set(control) {
            self.tell(
                Mistake::WriteBeforeTe,
                Register::Tdr,
                WRITE_BEFORE_TE,
                context,
            );
        }
        let word = Self::framed(
            u16::try_from(value & u64::from(u16::MAX)).expect("masked to a word"),
            registers,
        );
        self.flags &= !isr::TC.mask();
        if self.transmit.len() < Self::transmit_capacity(registers) {
            self.transmit.push_back(word);
            self.flags &= !isr::TXFE.mask();
        } else {
            self.tell(
                Mistake::WriteToAFullTdr,
                Register::Tdr,
                WRITE_TO_A_FULL_TDR,
                context,
            );
            if let Some(waiting) = self.transmit.front_mut().filter(|_| !Self::fifo(registers)) {
                *waiting = word;
            }
        }
        self.start_sending(registers, context);
    }

    // A write to `RQR`, 48.8.8.
    fn write_rqr(&mut self, value: u64, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
        if !cr1::UE.is_set(registers.get(Register::Cr1)) {
            return;
        }
        if rqr::RXFRQ.is_set(value) {
            self.receive.clear();
        }
        if rqr::TXFRQ.is_set(value) {
            self.transmit.clear();
            self.flags |= isr::TXFE.mask();
        }
        if rqr::SBKRQ.is_set(value) {
            self.break_requested = true;
            self.start_sending(registers, context);
        }
    }

    // A write to `ICR`: each written one clears the flag its bit names, 48.8.11.
    fn clear_flags(&mut self, value: u64) {
        for (clear, flag) in CLEARS {
            if clear.is_set(value) {
                self.flags &= !flag.mask();
            }
        }
    }

    // What `ISR` reads, 48.8.9 and 48.8.10. With `UE` clear every flag is in its reset state.
    fn status_word(&self, registers: &RegisterFile) -> u64 {
        let control = registers.get(Register::Cr1);
        let fifo = cr1::FIFOEN.is_set(control);
        if !cr1::UE.is_set(control) {
            let word = isr::TC.mask() | isr::TXE.mask() | isr::TXFE.mask();
            return if fifo { word } else { word & !FIFO_FLAGS };
        }
        let control3 = registers.get(Register::Cr3);
        let unread = self.receive.len();
        let empty_places = Self::transmit_capacity(registers).saturating_sub(self.transmit.len());
        let receive_reached =
            Self::threshold(cr3::RXFTCFG.get(control3)).is_some_and(|reached| unread >= reached);
        let transmit_reached = Self::threshold(cr3::TXFTCFG.get(control3))
            .is_some_and(|reached| empty_places >= reached);
        let derived = [
            (isr::RXNE, unread > 0),
            (isr::TXE, empty_places > 0),
            (isr::CTS, self.cts == Level::Low),
            (isr::BUSY, self.receiving.is_some()),
            (isr::SBKF, self.break_requested),
            (isr::TEACK, self.acked.transmitter),
            (isr::REACK, self.acked.receiver),
            (isr::RXFF, unread > FIFO_DEPTH),
            (isr::RXFT, receive_reached),
            (isr::TXFT, transmit_reached),
        ];
        let word = derived
            .into_iter()
            .filter(|&(_, on)| on)
            .fold(self.flags, |word, (field, _)| word | field.mask());
        if fifo { word } else { word & !FIFO_FLAGS }
    }

    // The line of Table 410 and the two requests of 48.5.19, each following the flags that feed it.
    // The model keeps the level it last drove, so a change that changes nothing reports nothing.
    // The enables sit at the same bits with the FIFO on and off, and the flags the FIFO adds read
    // zero with it off, so one list serves both.
    fn refresh(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        let status = self.status_word(registers);
        registers.set(Register::Isr, status);
        let control = registers.get(Register::Cr1);
        let control3 = registers.get(Register::Cr3);
        let on = cr1::UE.is_set(control);
        // Told again once there is room for the word the firmware lost.
        if isr::TXE.is_set(status) {
            self.told.remove(&Mistake::WriteToAFullTdr);
        }
        let reception_errors = isr::PE.mask() | isr::FE.mask() | isr::NF.mask();
        let masked = cr3::DDRE.is_set(control3) && status & reception_errors != 0;
        for (output, wanted) in [
            (
                RECEIVE_REQUEST,
                cr3::DMAR.is_set(control3) && isr::RXNE.is_set(status) && !masked,
            ),
            (
                TRANSMIT_REQUEST,
                cr3::DMAT.is_set(control3) && isr::TXE.is_set(status),
            ),
        ] {
            let wanted = Level::from(on && wanted);
            if wanted != self.requests[output] {
                self.requests[output] = wanted;
                context.request(output, wanted);
            }
        }
        let errors = isr::FE.mask() | isr::NF.mask() | isr::ORE.mask();
        let raised = (cr1::TXEIE.is_set(control) && isr::TXE.is_set(status))
            || (cr1::TCIE.is_set(control) && isr::TC.is_set(status))
            || (cr1::RXNEIE.is_set(control)
                && (isr::RXNE.is_set(status) || isr::ORE.is_set(status)))
            || (cr1::IDLEIE.is_set(control) && isr::IDLE.is_set(status))
            || (cr1::PEIE.is_set(control) && isr::PE.is_set(status))
            || (cr3::CTSIE.is_set(control3) && isr::CTSIF.is_set(status))
            || (cr3::EIE.is_set(control3) && status & errors != 0)
            || (cr1::TXFEIE.is_set(control) && isr::TXFE.is_set(status))
            || (cr1::RXFFIE.is_set(control) && isr::RXFF.is_set(status))
            || (cr3::TXFTIE.is_set(control3) && isr::TXFT.is_set(status))
            || (cr3::RXFTIE.is_set(control3) && isr::RXFT.is_set(status));
        let wanted = Level::from(on && raised);
        if wanted != self.interrupt {
            self.interrupt = wanted;
            context.interrupt(GLOBAL, wanted);
        }
    }
}

impl Device for Usart {
    type Register = Register;

    /// Everything a reset clears goes back to its reset state, and the far end, the line's garble and
    /// the `CTS` pin stay, since they're the board's. The kernel clock stays too, since the clock
    /// controller that drives it doesn't reset with the port. A system reset builds the part afresh.
    fn reset(&mut self) {
        let peer = self.peer.take();
        let errors = self.errors;
        let cts = self.cts;
        *self = Self::with_clock(self.kernel_hz);
        self.peer = peer;
        self.errors = errors;
        self.cts = cts;
    }

    /// The port's reset line, section 8.4.3: the port goes back as a reset puts it, and each request
    /// the multiplexer heard rise falls at once.
    fn reset_line(&mut self, _registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        context.lower_requests(&self.requests);
        self.reset();
    }

    /// The kernel clock has changed. A frame on the wire keeps its end. The runs' carries were a
    /// fraction of the old rate and mean nothing at the new one.
    fn on_clock(&mut self, hz: u64, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        self.kernel_hz = hz;
        // ceiling: a frame on the wire when the clock stops is dropped, not frozen; upgrade when a
        // firmware gates a port mid-frame and waits for the rest of the word.
        if hz == 0 {
            self.sending = None;
            self.receiving = None;
            self.idle = None;
            self.outgoing = None;
            self.incoming = None;
            self.refresh(registers, context);
            return;
        }
        self.drop_carries();
        self.follow_enables(registers);
        self.start_sending(registers, context);
        self.receive_next(registers, context);
        self.refresh(registers, context);
    }

    /// Only `RDR` has a read of its own, which takes the oldest unread word, 48.8.12. Every flag
    /// is cleared through `ICR`, so a read of `ISR` changes nothing.
    fn read(
        &mut self,
        register: Register,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) -> Option<u64> {
        match register {
            // 48.8.12
            Register::Rdr => {
                let word = self
                    .receive
                    .pop_front()
                    .map_or(self.last_read, |entry| entry.word);
                self.last_read = word;
                self.promote();
                self.refresh(registers, context);
                Some(u64::from(word))
            }
            // 48.8.1, 48.8.3 to 48.8.7, 48.8.9, 48.8.13, 48.8.14: the file's. 48.8.8, 48.8.11: write-only.
            Register::Cr1
            | Register::Cr2
            | Register::Cr3
            | Register::Brr
            | Register::Gtpr
            | Register::Rtor
            | Register::Rqr
            | Register::Isr
            | Register::Icr
            | Register::Tdr
            | Register::Presc => None,
        }
    }

    /// `RDR` is the word a read would take. Everything else reads as the file holds it.
    fn peek(
        &self,
        register: Register,
        _registers: &RegisterFile,
        _now: VirtualNanos,
    ) -> Option<u64> {
        (register == Register::Rdr).then(|| {
            u64::from(
                self.receive
                    .front()
                    .map_or(self.last_read, |entry| entry.word),
            )
        })
    }

    fn write(
        &mut self,
        register: Register,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        match register {
            // 48.8.1, 48.8.2
            Register::Cr1 => self.write_cr1(registers, context),
            // 48.8.3, 48.8.4, 48.8.5, 48.8.6, 48.8.14
            Register::Cr2 | Register::Cr3 | Register::Brr | Register::Gtpr | Register::Presc => {
                self.note_locked_bits(register, registers, context);
            }
            // 48.8.8
            Register::Rqr => self.write_rqr(value, registers, context),
            // 48.8.11
            Register::Icr => self.clear_flags(value),
            // 48.8.13
            Register::Tdr => self.write_tdr(value, registers, context),
            // 48.8.7: stored, and no function here acts on it. 48.8.9 and 48.8.12 are read-only.
            Register::Rtor | Register::Isr | Register::Rdr => {}
        }
        self.refresh(registers, context);
    }

    fn on_event(
        &mut self,
        event: EventId,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        // An instant fires once per instance, so one event can end both frames and the idle line.
        let mut ended = false;
        if let Some(frame) = self.sending.filter(|frame| frame.event == event) {
            self.finish_sending(frame.kind, registers, context);
            ended = true;
        }
        if let Some(frame) = self.receiving.filter(|frame| frame.event == event)
            && let FrameKind::Data(word) = frame.kind
        {
            self.finish_receiving(word, registers, context);
            ended = true;
        }
        if self.idle == Some(event) {
            self.idle = None;
            self.idle_armed = false;
            self.flags |= isr::IDLE.mask();
            ended = true;
        }
        if ended {
            self.refresh(registers, context);
        }
        if let Some(place) = &mut self.peer {
            place
                .chip_mut()
                .on_event(event, &mut Timeline::new(context));
        }
    }

    /// At every stop the far end is asked again, which is how a host's byte arrives.
    fn poll(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        if self.peer.is_none() {
            return;
        }
        self.receive_next(registers, context);
        self.refresh(registers, context);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chip::uart::{Pattern, Rate};
    use crate::mcu::{Operate, Single};
    use crate::snapshot;
    use crate::soc::Width;
    use crate::soc::stm32h743::builder;
    use crate::soc::stm32h743::generated::USART2;

    const KERNEL_HZ: u64 = 16_000_000;
    const US: u64 = 1_000;

    fn write(soc: &mut Single<Usart>, micros: u64, register: Register, value: u64) {
        let now = VirtualNanos(micros * US);
        soc.advance_to(now);
        soc.write(
            now,
            USART2.base + u64::from(register.spec().offset),
            Width::W32,
            value,
        )
        .expect("the register takes the write");
    }

    // A port with FIFOs on, a far end offering words, a line that garbles each, and three words queued,
    // run to 25 microseconds: two words received, a third arriving, and a frame on the wire.
    fn mid_transfer() -> Single<Usart> {
        let mut soc =
            Single::new(builder(), "USART2", Usart::with_clock(KERNEL_HZ)).expect("the bus builds");
        soc.model.attach(Pattern::answering(0..5));
        let errors = soc.model.errors_mut();
        errors.noise = Rate {
            name: "line.noise_errors",
            per_million: Rate::EVERY_WORD,
        };
        errors.seed = 4;
        write(&mut soc, 0, Register::Brr, 16);
        write(
            &mut soc,
            0,
            Register::Cr1,
            cr1::UE.mask() | cr1::TE.mask() | cr1::RE.mask() | cr1::FIFOEN.mask(),
        );
        for word in 0..3 {
            write(&mut soc, 1, Register::Tdr, word);
        }
        soc.advance_to(VirtualNanos(25 * US));
        soc
    }

    // The model's state serializes mid-transfer, with words queued both ways, a frame on the wire, a
    // frame arriving and the line's count of words, and a model restored from it is the same model.
    #[test]
    fn the_model_state_round_trips_through_a_snapshot() {
        let soc = mid_transfer();
        let saved = snapshot::stored(&soc.model).expect("the model is kept");
        let mut restored = Usart::with_clock(KERNEL_HZ);
        restored.attach(Pattern::default());
        snapshot::load(&mut restored, snapshot::keep(saved)).expect("and put back");
        assert_eq!(format!("{restored:?}"), format!("{:?}", soc.model));
    }

    // The garble is keyed by the seed and by how many words the line has carried, so a model put back
    // from a snapshot draws the next word's errors as the saved one would have.
    #[test]
    fn a_restored_model_draws_the_garble_where_the_saved_one_left_off() {
        let mut soc = mid_transfer();
        let saved = snapshot::stored(&soc.model).expect("the model is kept");
        let mut restored = Usart::with_clock(KERNEL_HZ);
        restored.attach(Pattern::default());
        snapshot::load(&mut restored, snapshot::keep(saved)).expect("and put back");
        let mut carried = *soc.model.errors_mut();
        let mut resumed = *restored.errors_mut();
        let draws: Vec<_> = (0..16).map(|_| carried.next(8)).collect();
        assert!(
            draws.iter().any(|arrival| arrival.noise),
            "the line garbles and the draws show it"
        );
        for expected in draws {
            assert_eq!(resumed.next(8), expected);
        }
    }
}