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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The general-purpose I/O port of RM0433 rev 9 chapter 11, written against the `gpioa` layout, which
//! is the layout of all eleven ports, GPIOA to GPIOK. One of these answers for each of them. Every
//! citation is RM0433 rev 9 unless it names another document.
//!
//! Every register of section 11.4 and every configuration of section 11.3 is implemented, by the model
//! RM0090 rev 22 gives the STM32F427 too, in [`crate::soc::st::gpio`]. A pin's electrical level is
//! what the outside world would see on it. The outside world drives a pin through
//! [`Gpio::drive`] and a peripheral drives its alternate function through [`Gpio::drive_function`].
//! Each takes the port's registers and a context, because a level put on a pin reaches the external
//! interrupt controller at the instant it changes. Nothing here is register-only.
//!
//! **What the model handles and what falls to the register file.** `IDR` is the model's alone, sampled
//! from the pins at each read. `BSRR` and `LCKR` have an arm each, and the four configuration registers
//! and the two alternate function registers have one for the lock's freeze. `ODR` is stored as written
//! by the file and read back from it. The reset values come from the part's tables, where
//! `memory_map.rs` carries all thirty-three that differ by port.
//!
//! **How a pin reaches the external interrupt controller.** Section 11.3.8 says every port has external
//! interrupt capability when the pin is not analog. A pin whose level on the wire changes announces
//! it as a request line of its port, numbered by the pin: request `n` of `GPIOC` is PC`n`. That is the
//! same line a chip select is read from. The external interrupt controller reads every port's lines,
//! knows which port is which by [`PORTS`], and learns which pin the firmware routed to which of its
//! lines from `SYSCFG_EXTICRn` by a requested access. This model drives only the wire.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | Reset state | Every pin analog, except port A's debug pins, in their alternate function with their pulls, and port B's two of them. What a port wakes up as is its own, held in the part's corrections rather than here | 11.3.1, 11.4.1 to 11.4.4 | `port_a_resets_with_the_debug_pins_pulled`, `port_b_resets_with_its_debug_pins_in_alternate_function`, `every_other_port_resets_with_every_pin_analog` |
//! | `MODER` | Input, output, alternate function, or analog per pin | 11.4.1, Table 94 | `a_pin_is_what_its_mode_says` |
//! | `OTYPER` | Push-pull drives both levels, and open-drain drives low and releases high | 11.3.10, 11.4.2 | `open_drain_drives_low_and_releases_high` |
//! | `OSPEEDR` | Slew rate, with no observable value in the emulator. It's stored | 11.4.3 | `speed_is_stored_and_changes_nothing` |
//! | `PUPDR` | A released pin reads its pull, and a floating pin keeps its last level. Analog mode disables the pulls | 11.3.9, 11.3.13, 11.4.4 | `a_released_pin_reads_its_pull`, `analog_mode_disables_the_pull` |
//! | `IDR` | Every pin's level, sampled at the read. Zero in analog mode. Read-only | 11.3.9, 11.3.13, 11.4.5 | `idr_reads_the_pins_and_zero_for_analog`, `peek_answers_what_a_read_would_and_changes_nothing` |
//! | `ODR` | The level an output drives. A push-pull output beats what drives the pin. Reads the last written value | 11.3.10, 11.4.6 | `odr_drives_a_push_pull_output` |
//! | `BSRR` | Sets the low half's bits and clears the high half's, the set winning. Reads zero | 11.3.5, 11.4.7 | `bsrr_sets_and_clears_and_the_set_wins` |
//! | `LCKR` | The lock key sequence freezes the six configuration registers for the locked pins until reset. `LCKK` reads one after the first sequence | 11.3.6, 11.4.8 | `the_lock_sequence_freezes_the_configuration`, `a_broken_lock_sequence_aborts`, `a_reset_releases_the_lock` |
//! | Wire | A pin whose level on the wire changes announces it as the port's request line, numbered by the pin. It's announced after the write that changed it or at the instant the outside world drives it, and never on a read. Only while something holds the pin: an output stage, a function's driver, the outside world, or a pull. A floating pin announces nothing, because the level it keeps is section 11.4.5's convention rather than a wire. An analog pin is low whatever drives it, so it announces low and nothing else | 11.3.8, 11.3.9, 11.3.13 | `a_pin_announces_its_level_when_it_changes`, `nothing_is_announced_at_reset`, `a_pin_announces_the_level_it_becomes_an_output_at`, `a_read_announces_nothing`, `a_floating_pin_announces_nothing_and_a_pulled_one_its_pull`, `the_outside_world_driving_a_pin_announces_it_at_once`, `an_analog_pin_announces_nothing` |
//! | `AFRL`, `AFRH` | The alternate function a pin carries. Its peripheral drives the pin | 11.3.2, 11.3.7, 11.3.12, 11.4.9, 11.4.10 | `an_alternate_function_pin_is_driven_by_its_peripheral` |
//! | Input | An input follows what drives it and keeps the last level when released | 11.3.9 | `an_input_follows_what_drives_it` |
//! | Narrow access | Byte, half-word, and word access lands in its lane. On the part `LCKR` is written by word only, which the model can't see, the width staying on the bus | 11.4, 11.3.6, 11.4.8 | `the_registers_accept_narrow_access`, with the word-only rule pending |
//! | The port table | [`PORTS`] names the eleven in the order of `SYSCFG_EXTICRn`'s port field | 12.3.2, 11.4 | `the_ports_are_the_eleven_instances_in_order` |
//! | Reset | The lock and what was announced go back with the registers. What the outside world drives stays, and what a peripheral drove goes | 11.4.8 | `a_reset_releases_the_lock`, `a_reset_makes_a_held_pin_announce_again` |
//! | The model's state | It serializes, so the part's snapshot keeps the lock, the frozen registers and what was announced | n/a | `the_model_state_round_trips_through_a_snapshot` |
//!
//! **What the model leaves out, and why.**
//!
//! | Behavior | Source | Reason |
//! |---|---|---|
//! | The I/O compensation cell | 11.3.11 | It acts on slew rate, which has no observable value here, and its registers are `SYSCFG_CCCSR`, `SYSCFG_CCVR` and `SYSCFG_CCCR` in `syscfg.rs` |
//! | The oscillator pins as GPIO, PC14, PC15, PH0, PH1 | 11.3.14 | Not modeled. The oscillator takes the pins while `LSEON` or `HSEON` stands, and the port here never gives them up. What's on the other end of them is the RCC's |
//! | The backup domain pins, PC13, PC14, PC15, PI8, in Standby | 11.3.15 | Standby isn't modeled, so the pins never fall back to analog input |
//! | The analog switches of PA0, PA1, PC2 and PC3 to their `_C` pads | 11.3.13, Figure 76, 12.3.1 | The switches are `SYSCFG_PMCR`'s `PxySO` bits, stored there, and the pads have nothing behind them |
//! | `EVENTOUT` on AF15 | 11.3.2 | The core's event output, after `SEV`, has no model to take it |
//! | The clock enabling delay: up to two periods of the enabled clock between a port's enable bit and the clock's first edge | 8.5.10 | Not modeled, as a gate opens at the instant its bit is written. The part gates each port behind its `RCC_AHB4ENR` bit |
//! | `IDR` sampled every AHB clock | 11.3.1, 11.3.9 | The sample is taken at the read and at each configuration change. The manual gives no latency between a pin and the register, so none is modeled |
//! | A narrower access than the word `LCKR`'s sequence needs | 11.3.6, 11.4.8 | The register file lands a byte or half-word store in its lane regardless of what a register's own page requires |
//! | ES0392 rev 15 2.2.19: a GPIO assigned to a DAC output that connects only to an on-chip peripheral can't be an output | ES0392 rev 15 | Applicable to revision V, which Table 3 marks `N`, with no workaround. Pending: the output buffer's disabling follows `DAC_MCR`'s mode, and the DAC has no model, so a port can't read it. The pins stay ordinary outputs |
//! | No other ES0392 rev 15 item touches this instance | ES0392 rev 15 | The whole errata chapter was read for it |
//!
//! Where the manual leaves a value undefined, an input pin that floats with nothing driving it, section
//! 11.4.5's `0x0000 XXXX`, the model keeps the last level the pin had, low at reset, and says so here.
//!
//! **Determinism.** Nothing here reads a clock or draws a number. The same accesses and drives give
//! the same levels and the same announcements, and the model's state serializes, which
//! `the_model_state_round_trips_through_a_snapshot` shows.

use crate::device::Level;
use crate::soc::st::gpio::Port;
use crate::soc::stm32h743::generated::gpioa::Register;

pub use crate::soc::st::gpio::Pin;

/// The eleven ports of RM0433 rev 9 section 11.4, in the order `SYSCFG_EXTICRn` numbers them, section
/// 12.3.2: port A is 0 and port K is 10. It is also the order of their bases. The part holds one
/// [`Gpio`] per name, and the external interrupt controller recognizes a port by it.
pub const PORTS: [&str; 11] = [
    "GPIOA", "GPIOB", "GPIOC", "GPIOD", "GPIOE", "GPIOF", "GPIOG", "GPIOH", "GPIOI", "GPIOJ",
    "GPIOK",
];

/// A port of sixteen pins.
pub type Gpio = crate::soc::st::gpio::Gpio<Register>;

impl Port for Register {
    const MODER: Self = Self::Moder;
    const OTYPER: Self = Self::Otyper;
    const OSPEEDR: Self = Self::Ospeedr;
    const PUPDR: Self = Self::Pupdr;
    const IDR: Self = Self::Idr;
    const ODR: Self = Self::Odr;
    const BSRR: Self = Self::Bsrr;
    const LCKR: Self = Self::Lckr;
    const AFRL: Self = Self::Afrl;
    const AFRH: Self = Self::Afrh;
    // Every pin comes out of reset analog but the debug ones, 11.4.1, and an analog pin's input stage
    // forces its level to zero, 11.3.13.
    const AT_RESET: Option<Level> = Some(Level::Low);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mcu::{Mcu, Operate, Single};
    use crate::soc::FieldSpec;
    use crate::soc::Layout;
    use crate::soc::Width;
    use crate::soc::st::gpio::{
        MODE_ALTERNATE, MODE_ANALOG, MODE_INPUT, MODE_OUTPUT, OPEN_DRAIN, PULL_DOWN, PULL_UP,
    };
    use crate::soc::stm32h743::builder;
    use crate::soc::stm32h743::generated::GPIOA;
    use crate::soc::stm32h743::generated::gpioa::{bsrr, idr, lckr, moder, odr, otyper};
    use crate::time::VirtualNanos;

    const NOW: VirtualNanos = VirtualNanos(0);
    const PA5: Pin = pin(5);
    const PA6: Pin = pin(6);
    const PA12: Pin = pin(12);
    const TIM2_CH1: u64 = 1;

    const fn pin(index: u8) -> Pin {
        match Pin::new(index) {
            Some(pin) => pin,
            None => panic!("below sixteen"),
        }
    }

    fn port_named(name: &'static str) -> Single<Gpio> {
        Single::new(builder(), name, Gpio::default()).expect("the bus builds")
    }

    fn port() -> Single<Gpio> {
        port_named("GPIOA")
    }

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

    fn read(soc: &mut dyn Mcu, register: Register) -> u64 {
        soc.read(NOW, address(register), Width::W32).unwrap()
    }

    fn write(soc: &mut dyn Mcu, register: Register, value: u64) {
        soc.write(NOW, address(register), Width::W32, value)
            .unwrap();
    }

    /// The field of `register` for `pin`, the one the generated table names with the pin's number.
    fn field(register: Register, pin: Pin) -> &'static FieldSpec {
        register
            .spec()
            .fields
            .iter()
            .find(|field| {
                let number = field.name.trim_start_matches(|c: char| !c.is_ascii_digit());
                number.parse() == Ok(pin.bit())
            })
            .unwrap()
    }

    fn set_pin(soc: &mut dyn Mcu, register: Register, pin: Pin, value: u64) {
        let current = read(soc, register);
        write(soc, register, field(register, pin).set(current, value));
    }

    fn mode_of(soc: &mut dyn Mcu, pin: Pin, mode: u64) {
        set_pin(soc, Register::Moder, pin, mode);
    }

    fn pull_of(soc: &mut Single<Gpio>, pin: Pin, pull: u64) {
        set_pin(soc, Register::Pupdr, pin, pull);
    }

    fn output_type(soc: &mut Single<Gpio>, pin: Pin, kind: u64) {
        set_pin(soc, Register::Otyper, pin, kind);
    }

    fn odr_of(soc: &mut Single<Gpio>, pin: Pin, high: bool) {
        set_pin(soc, Register::Odr, pin, u64::from(high));
    }

    fn idr_bit(soc: &mut Single<Gpio>, pin: Pin) -> bool {
        field(Register::Idr, pin).is_set(read(soc, Register::Idr))
    }

    fn drive(soc: &mut Single<Gpio>, pin: Pin, level: Option<Level>) {
        soc.drive(NOW, |gpio, registers, context| {
            gpio.drive(pin, level, registers, context);
        });
    }

    fn drive_function(soc: &mut Single<Gpio>, pin: Pin, level: Option<Level>) {
        soc.drive(NOW, |gpio, registers, context| {
            gpio.drive_function(pin, level, registers, context);
        });
    }

    fn level(soc: &mut Single<Gpio>, pin: Pin) -> Level {
        let (gpio, registers) = soc.pair();
        gpio.level(pin, registers)
    }

    #[test]
    fn port_a_resets_with_the_debug_pins_pulled() {
        let mut soc = port();
        assert_eq!(
            read(&mut soc, Register::Moder),
            0xABFF_FFFF,
            "PA13 to PA15 in alternate function and the rest analog, 11.4.1"
        );
        assert_eq!(
            read(&mut soc, Register::Pupdr),
            0x6400_0000,
            "PA13 and PA15 pulled up, PA14 down, 11.4.4"
        );
        assert_eq!(
            read(&mut soc, Register::Ospeedr),
            0x0C00_0000,
            "PA13 at very high speed, 11.4.3"
        );
        let idr = read(&mut soc, Register::Idr);
        assert_eq!(
            idr,
            idr::ID13.mask() | idr::ID15.mask(),
            "the pulled-up debug pins read one, the pulled-down one reads zero and the analog pins zero, 11.3.1"
        );
        assert_eq!(level(&mut soc, PA5), Level::Low);
    }

    #[test]
    fn port_b_resets_with_its_debug_pins_in_alternate_function() {
        let mut soc = port_named("GPIOB");
        let base = crate::soc::stm32h743::generated::GPIOB.base;
        let word = |soc: &mut Single<Gpio>, register: Register| {
            soc.read(NOW, base + u64::from(register.spec().offset), Width::W32)
                .unwrap()
        };
        assert_eq!(
            word(&mut soc, Register::Moder),
            0xFFFF_FEBF,
            "PB3 and PB4 in alternate function, 11.4.1"
        );
        assert_eq!(
            word(&mut soc, Register::Ospeedr),
            0x0000_00C0,
            "PB3, 11.4.3"
        );
        assert_eq!(
            word(&mut soc, Register::Pupdr),
            0x0000_0100,
            "PB4 up, 11.4.4"
        );
        assert_eq!(
            word(&mut soc, Register::Idr),
            idr::ID4.mask(),
            "PB4 is pulled up and PB3 floats, 11.3.1"
        );
    }

    #[test]
    fn every_other_port_resets_with_every_pin_analog() {
        for name in &PORTS[2..] {
            let mut soc = port_named(name);
            let base = soc
                .bus()
                .peripheral(name)
                .expect("a port is an instance")
                .base;
            let word = |soc: &mut Single<Gpio>, register: Register| {
                soc.read(NOW, base + u64::from(register.spec().offset), Width::W32)
                    .unwrap()
            };
            assert_eq!(
                word(&mut soc, Register::Moder),
                0xFFFF_FFFF,
                "{name}, 11.4.1"
            );
            assert_eq!(word(&mut soc, Register::Ospeedr), 0, "{name}, 11.4.3");
            assert_eq!(word(&mut soc, Register::Pupdr), 0, "{name}, 11.4.4");
            assert_eq!(
                word(&mut soc, Register::Idr),
                0,
                "{name}, analog reads zero"
            );
        }
    }

    #[test]
    fn the_ports_are_the_eleven_instances_in_order() {
        let soc = builder().build().unwrap();
        let mut bases = Vec::new();
        for (number, name) in PORTS.iter().enumerate() {
            let instance = soc
                .peripheral(name)
                .unwrap_or_else(|| panic!("{name} is an instance"));
            assert_eq!(
                *name,
                format!("GPIO{}", char::from(b'A' + u8::try_from(number).unwrap())),
                "SYSCFG_EXTICRn numbers port A as 0 and port K as 10, 12.3.2"
            );
            assert!(
                std::ptr::eq(instance.registers, GPIOA.registers),
                "{name} has the gpioa layout"
            );
            bases.push(instance.base);
        }
        assert!(bases.windows(2).all(|pair| pair[0] < pair[1]), "{bases:x?}");
    }

    #[test]
    fn a_pin_is_what_its_mode_says() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        odr_of(&mut soc, PA5, true);
        assert!(
            idr_bit(&mut soc, PA5),
            "an output reads back what it drives, 11.3.10"
        );
        assert_eq!(level(&mut soc, PA5), Level::High);
        mode_of(&mut soc, PA5, MODE_ANALOG);
        drive(&mut soc, PA5, Some(Level::High));
        assert!(
            !idr_bit(&mut soc, PA5),
            "analog reads zero whatever the pin carries, 11.3.13"
        );
        mode_of(&mut soc, PA5, MODE_INPUT);
        assert!(
            idr_bit(&mut soc, PA5),
            "an input reads what drives it, 11.3.9"
        );
    }

    #[test]
    fn open_drain_drives_low_and_releases_high() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        output_type(&mut soc, PA5, OPEN_DRAIN);
        odr_of(&mut soc, PA5, true);
        assert_eq!(
            level(&mut soc, PA5),
            Level::Low,
            "released with no pull keeps the last level, low at reset"
        );
        pull_of(&mut soc, PA5, PULL_UP);
        assert_eq!(
            level(&mut soc, PA5),
            Level::High,
            "released, the pull-up holds it high, 11.3.10"
        );
        drive(&mut soc, PA5, Some(Level::Low));
        assert_eq!(
            level(&mut soc, PA5),
            Level::Low,
            "a driven line beats the weak pull"
        );
        drive(&mut soc, PA5, None);
        odr_of(&mut soc, PA5, false);
        assert_eq!(
            level(&mut soc, PA5),
            Level::Low,
            "the N-MOS drives low, the pull notwithstanding"
        );
        output_type(&mut soc, PA5, 0);
        odr_of(&mut soc, PA5, true);
        drive(&mut soc, PA5, Some(Level::Low));
        assert_eq!(
            level(&mut soc, PA5),
            Level::High,
            "push-pull drives high through the P-MOS"
        );
        assert_eq!(
            read(&mut soc, Register::Otyper) & otyper::OT5.mask(),
            0,
            "push-pull is the stored type"
        );
    }

    /// A debugger's look at `IDR` samples the pins as the firmware's read does, 11.3.9: one driven from
    /// outside, an output, and one held by its pull.
    #[test]
    fn peek_answers_what_a_read_would_and_changes_nothing() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_INPUT);
        mode_of(&mut soc, PA12, MODE_INPUT);
        drive(&mut soc, PA5, Some(Level::High));
        mode_of(&mut soc, PA6, MODE_OUTPUT);
        odr_of(&mut soc, PA6, true);
        pull_of(&mut soc, PA12, PULL_UP);
        let peeked = soc
            .peek(NOW, address(Register::Idr), Width::W32)
            .expect("the register answers");
        for pin in [PA5, PA6, PA12] {
            assert!(field(Register::Idr, pin).is_set(peeked), "{peeked:#x}");
        }
        assert_eq!(read(&mut soc, Register::Idr), peeked);
    }

    #[test]
    fn speed_is_stored_and_changes_nothing() {
        let mut soc = port();
        let before = read(&mut soc, Register::Idr);
        write(&mut soc, Register::Ospeedr, 0xFFFF_FFFF);
        assert_eq!(read(&mut soc, Register::Ospeedr), 0xFFFF_FFFF, "11.4.3");
        assert_eq!(read(&mut soc, Register::Idr), before);
    }

    #[test]
    fn a_released_pin_reads_its_pull() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_INPUT);
        pull_of(&mut soc, PA5, PULL_UP);
        assert!(idr_bit(&mut soc, PA5), "11.3.9");
        pull_of(&mut soc, PA5, PULL_DOWN);
        assert!(!idr_bit(&mut soc, PA5));
        pull_of(&mut soc, PA5, PULL_UP);
        pull_of(&mut soc, PA5, 0);
        assert!(
            idr_bit(&mut soc, PA5),
            "floating, the pin keeps the last level it had"
        );
    }

    #[test]
    fn analog_mode_disables_the_pull() {
        let mut soc = port();
        pull_of(&mut soc, PA5, PULL_UP);
        assert!(!idr_bit(&mut soc, PA5), "analog at reset, so zero, 11.3.13");
        mode_of(&mut soc, PA5, MODE_INPUT);
        assert!(idr_bit(&mut soc, PA5), "an input takes its pull, 11.3.9");
        mode_of(&mut soc, PA5, MODE_ANALOG);
        assert!(!idr_bit(&mut soc, PA5), "analog reads zero, 11.3.13");
        soc.drain_requests();
        pull_of(&mut soc, PA6, PULL_UP);
        assert!(
            soc.drain_requests().is_empty(),
            "a pull on an analog pin is disabled by hardware and holds nothing"
        );
    }

    #[test]
    fn idr_reads_the_pins_and_zero_for_analog() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_INPUT);
        mode_of(&mut soc, PA6, MODE_INPUT);
        drive(&mut soc, PA5, Some(Level::High));
        drive(&mut soc, PA6, Some(Level::High));
        mode_of(&mut soc, PA6, MODE_ANALOG);
        let idr = read(&mut soc, Register::Idr);
        assert!(idr::ID5.is_set(idr));
        assert!(!idr::ID6.is_set(idr), "11.3.13");
        write(&mut soc, Register::Idr, 0);
        assert_eq!(read(&mut soc, Register::Idr), idr, "read-only, 11.4.5");
    }

    #[test]
    fn odr_drives_a_push_pull_output() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        drive(&mut soc, PA5, Some(Level::High));
        assert_eq!(
            level(&mut soc, PA5),
            Level::Low,
            "the driver, not the outside, decides a push-pull pin"
        );
        odr_of(&mut soc, PA5, true);
        assert_eq!(level(&mut soc, PA5), Level::High);
        assert_eq!(
            read(&mut soc, Register::Odr) & odr::OD5.mask(),
            odr::OD5.mask(),
            "reads the last written value, 11.3.10"
        );
    }

    #[test]
    fn bsrr_sets_and_clears_and_the_set_wins() {
        let mut soc = port();
        write(&mut soc, Register::Bsrr, bsrr::BS5.mask());
        assert_eq!(
            read(&mut soc, Register::Odr),
            odr::OD5.mask(),
            "BS5 sets ODR5, 11.4.7"
        );
        write(&mut soc, Register::Bsrr, bsrr::BR5.mask());
        assert_eq!(read(&mut soc, Register::Odr), 0, "BR5 clears it");
        write(
            &mut soc,
            Register::Bsrr,
            bsrr::BS5.mask() | bsrr::BR5.mask(),
        );
        assert_eq!(
            read(&mut soc, Register::Odr),
            odr::OD5.mask(),
            "both named: BS has priority"
        );
        assert_eq!(
            read(&mut soc, Register::Bsrr),
            0,
            "a read returns zero after a write that set bits"
        );
        write(&mut soc, Register::Bsrr, 0);
        assert_eq!(
            read(&mut soc, Register::Odr),
            odr::OD5.mask(),
            "zero bits do nothing, 11.3.5"
        );
    }

    #[test]
    fn the_lock_sequence_freezes_the_configuration() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        let lock = lckr::LCK5.mask();
        write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, 1));
        assert_eq!(
            read(&mut soc, Register::Lckr),
            lock,
            "the key reads zero until the sequence completes, 11.4.8"
        );
        write(&mut soc, Register::Lckr, lock);
        write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, 1));
        assert_eq!(
            read(&mut soc, Register::Lckr),
            lckr::LCKK.set(lock, 1),
            "the fourth step, a read, confirms the lock"
        );
        mode_of(&mut soc, PA5, MODE_INPUT);
        mode_of(&mut soc, PA6, MODE_OUTPUT);
        let moder = read(&mut soc, Register::Moder);
        assert_eq!(
            moder::MODE5.get(moder),
            MODE_OUTPUT,
            "the locked pin's mode holds, 11.3.6"
        );
        assert_eq!(
            moder::MODE6.get(moder),
            MODE_OUTPUT,
            "the unlocked pin's changes"
        );
        output_type(&mut soc, PA5, OPEN_DRAIN);
        assert_eq!(read(&mut soc, Register::Otyper) & otyper::OT5.mask(), 0);
        set_pin(&mut soc, Register::Afrl, PA5, TIM2_CH1);
        assert_eq!(read(&mut soc, Register::Afrl), 0);
        write(&mut soc, Register::Lckr, 0);
        assert_eq!(
            read(&mut soc, Register::Lckr),
            lckr::LCKK.set(lock, 1),
            "the lock bits refuse writes while the key is set"
        );
        odr_of(&mut soc, PA5, true);
        assert_eq!(
            level(&mut soc, PA5),
            Level::High,
            "data registers are not frozen"
        );
    }

    #[test]
    fn a_broken_lock_sequence_aborts() {
        let mut soc = port();
        let lock = lckr::LCK5.mask();
        write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, 1));
        write(&mut soc, Register::Lckr, lock | lckr::LCK6.mask());
        write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, 1));
        assert_eq!(
            read(&mut soc, Register::Lckr),
            lock,
            "the value changed mid-sequence: no lock, 11.4.8"
        );
        let mut soc = port();
        let other = lckr::LCK6.mask();
        write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, 1));
        write(&mut soc, Register::Lckr, other);
        write(&mut soc, Register::Lckr, lckr::LCKK.set(other, 1));
        assert_eq!(
            read(&mut soc, Register::Lckr),
            other,
            "the value changed between the first write and the second, which the third repeats: no lock"
        );
        let mut soc = port();
        write(&mut soc, Register::Lckr, lock);
        write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, 1));
        write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, 1));
        assert_eq!(
            read(&mut soc, Register::Lckr),
            lock,
            "the order was wrong: no lock"
        );
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        assert_eq!(
            moder::MODE5.get(read(&mut soc, Register::Moder)),
            MODE_OUTPUT,
            "the configuration stays writable"
        );
    }

    #[test]
    fn a_reset_releases_the_lock() {
        let mut soc = port();
        let lock = lckr::LCK5.mask();
        for key in [1, 0, 1] {
            write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, key));
        }
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        soc.reset(NOW, crate::device::ResetCause::Pin);
        assert_eq!(
            read(&mut soc, Register::Lckr),
            0,
            "the lock lasts until the next MCU reset, 11.4.8"
        );
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        assert_eq!(
            moder::MODE5.get(read(&mut soc, Register::Moder)),
            MODE_OUTPUT,
            "and the configuration takes writes again"
        );
    }

    /// The models that heard a pin's level were reset with it, so a pin the outside world still holds
    /// announces its level again at the first write after the reset.
    #[test]
    fn a_reset_makes_a_held_pin_announce_again() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_INPUT);
        drive(&mut soc, PA5, Some(Level::High));
        assert_eq!(announced_by_pa5(&mut soc), [Level::High]);
        soc.reset(NOW, crate::device::ResetCause::Pin);
        mode_of(&mut soc, PA5, MODE_INPUT);
        assert_eq!(
            announced_by_pa5(&mut soc),
            [Level::High],
            "the board still drives it, and the readers forgot the level"
        );
    }

    #[test]
    fn an_alternate_function_pin_is_driven_by_its_peripheral() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_ALTERNATE);
        set_pin(&mut soc, Register::Afrl, PA5, TIM2_CH1);
        set_pin(&mut soc, Register::Afrh, PA12, 0xA);
        {
            let (gpio, registers) = soc.pair();
            assert_eq!(
                gpio.level(PA5, registers),
                Level::Low,
                "the peripheral drives nothing yet"
            );
        }
        drive_function(&mut soc, PA5, Some(Level::High));
        assert_eq!(level(&mut soc, PA5), Level::High, "11.3.12");
        assert!(
            idr_bit(&mut soc, PA5),
            "the input stage sees the function's level"
        );
        output_type(&mut soc, PA5, OPEN_DRAIN);
        pull_of(&mut soc, PA5, PULL_DOWN);
        assert_eq!(
            level(&mut soc, PA5),
            Level::Low,
            "open-drain releases the high level to the pull-down"
        );
    }

    #[test]
    fn an_input_follows_what_drives_it() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_INPUT);
        drive(&mut soc, PA5, Some(Level::High));
        assert!(idr_bit(&mut soc, PA5));
        drive(&mut soc, PA5, None);
        assert!(
            idr_bit(&mut soc, PA5),
            "released and floating, the last level stays"
        );
        drive(&mut soc, PA5, Some(Level::Low));
        assert!(!idr_bit(&mut soc, PA5));
    }

    #[test]
    fn the_registers_accept_narrow_access() {
        let mut soc = port();
        soc.write(NOW, address(Register::Bsrr), Width::W8, bsrr::BS5.mask())
            .unwrap();
        assert_eq!(
            read(&mut soc, Register::Odr),
            odr::OD5.mask(),
            "a byte write to BSRR's low byte sets PA5, 11.4.7"
        );
        // BR5 sits in the high half-word, so the lane's own value drops the field's offset.
        soc.write(
            NOW,
            address(Register::Bsrr) + 2,
            Width::W16,
            bsrr::BR5.mask() >> Width::W16.bits(),
        )
        .unwrap();
        assert_eq!(
            read(&mut soc, Register::Odr),
            0,
            "a half-word write to the high half clears it"
        );
        assert_eq!(
            soc.read(NOW, address(Register::Odr), Width::W8).unwrap(),
            0,
            "11.4"
        );
    }

    fn announced(soc: &mut dyn Mcu) -> Vec<(usize, Level)> {
        soc.drain_requests()
            .into_iter()
            .map(|change| (change.request, change.level))
            .collect()
    }

    /// What PA5 announced, apart from the port's debug pins, which announce their reset pulls at the first
    /// write and have their own test.
    fn announced_by_pa5(soc: &mut dyn Mcu) -> Vec<Level> {
        announced(soc)
            .into_iter()
            .filter(|(pin, _)| *pin == 5)
            .map(|(_, level)| level)
            .collect()
    }

    /// A pin whose level changes announces it once. A write that leaves the level alone announces nothing.
    #[test]
    fn a_pin_announces_its_level_when_it_changes() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        assert!(
            announced_by_pa5(&mut soc).is_empty(),
            "an output driving low is the level the pin was at, 11.3.13"
        );
        odr_of(&mut soc, PA5, true);
        assert_eq!(announced_by_pa5(&mut soc), [Level::High]);
        odr_of(&mut soc, PA5, true);
        assert!(
            announced(&mut soc).is_empty(),
            "the same level again is not a change"
        );
        odr_of(&mut soc, PA5, false);
        assert_eq!(announced_by_pa5(&mut soc), [Level::Low]);
    }

    /// At reset no pin is driven, so nothing has a level to announce.
    #[test]
    fn nothing_is_announced_at_reset() {
        let mut soc = port();
        assert!(announced(&mut soc).is_empty());
    }

    /// An output register bit set while the pin is still an input is not on the wire. The pin announces
    /// the level it comes up at when it becomes an output.
    #[test]
    fn a_pin_announces_the_level_it_becomes_an_output_at() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_INPUT);
        soc.drain_requests();
        odr_of(&mut soc, PA5, true);
        assert!(
            announced_by_pa5(&mut soc).is_empty(),
            "an input's output register drives nothing"
        );
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        assert_eq!(announced_by_pa5(&mut soc), [Level::High]);
    }

    /// Reading the input register samples the pins and changes no level, so a read announces nothing,
    /// even the first access to a port whose debug pins are pulled and have never been announced. The write
    /// that follows is what announces them, which is what says the reads did not.
    #[test]
    fn a_read_announces_nothing() {
        let mut soc = port();
        let _ = read(&mut soc, Register::Idr);
        let _ = read(&mut soc, Register::Odr);
        assert!(announced(&mut soc).is_empty());
        write(&mut soc, Register::Ospeedr, 0);
        assert_eq!(
            announced(&mut soc).len(),
            2,
            "the pulled-up pins waited for a write, and the pulled-down one is low already, 11.3.13"
        );
    }

    /// A floating input has no level on the wire, so it announces nothing however many writes the port
    /// takes. A pulled one has, and announces its pull the first time the port is written. Port A's debug
    /// pins come out of reset pulled (11.4.4's `PUPDR` reset value, PA13 up, PA14 down, PA15 up) and are
    /// the only ones that can speak at the first write, and PA14 matches the low every pin starts at.
    #[test]
    fn a_floating_pin_announces_nothing_and_a_pulled_one_its_pull() {
        let mut soc = port();
        write(&mut soc, Register::Ospeedr, 0);
        assert_eq!(
            announced(&mut soc),
            [(13, Level::High), (15, Level::High)],
            "the pulled-up debug pins and nothing else: PA14's pull-down is the low an analog pin held, 11.3.13"
        );
        write(&mut soc, Register::Ospeedr, 0);
        assert!(announced(&mut soc).is_empty());
    }

    /// An input driven from outside is on the wire at the instant it's driven, with no register write to
    /// carry the news, so the external interrupt controller sees the edge when it happens.
    #[test]
    fn the_outside_world_driving_a_pin_announces_it_at_once() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_INPUT);
        soc.drain_requests();
        drive(&mut soc, PA5, Some(Level::High));
        assert_eq!(announced_by_pa5(&mut soc), [Level::High], "11.3.8");
        drive(&mut soc, PA5, Some(Level::High));
        assert!(announced(&mut soc).is_empty(), "no change, no news");
        drive(&mut soc, PA5, Some(Level::Low));
        assert_eq!(announced_by_pa5(&mut soc), [Level::Low]);
        drive(&mut soc, PA5, None);
        assert!(
            announced(&mut soc).is_empty(),
            "released with no pull, the pin floats and announces nothing"
        );
        mode_of(&mut soc, PA6, MODE_ALTERNATE);
        soc.drain_requests();
        drive_function(&mut soc, PA6, Some(Level::High));
        assert_eq!(
            announced(&mut soc),
            [(6, Level::High)],
            "an alternate function's driver is on the wire too, 11.3.12"
        );
    }

    /// Section 11.3.13: an analog pin's Schmitt trigger output is forced to zero, so an external
    /// interrupt line sees it low whatever drives the pad, and leaving or entering analog mode is an edge.
    #[test]
    fn an_analog_pin_announces_nothing() {
        let mut soc = port();
        drive(&mut soc, PA5, Some(Level::High));
        assert!(
            announced_by_pa5(&mut soc).is_empty(),
            "PA5 resets analog and reads low whatever drives it, 11.3.13"
        );
        mode_of(&mut soc, PA5, MODE_INPUT);
        assert_eq!(
            announced_by_pa5(&mut soc),
            [Level::High],
            "leaving analog mode puts the level on the wire"
        );
        mode_of(&mut soc, PA5, MODE_ANALOG);
        assert_eq!(
            announced_by_pa5(&mut soc),
            [Level::Low],
            "entering analog mode forces the line low"
        );
        drive(&mut soc, PA5, Some(Level::Low));
        assert!(announced_by_pa5(&mut soc).is_empty());
    }

    #[test]
    fn the_model_state_round_trips_through_a_snapshot() {
        let mut soc = port();
        mode_of(&mut soc, PA5, MODE_OUTPUT);
        odr_of(&mut soc, PA5, true);
        let lock = lckr::LCK5.mask();
        for key in [1, 0, 1] {
            write(&mut soc, Register::Lckr, lckr::LCKK.set(lock, key));
        }
        let bytes = postcard::to_stdvec(&soc.model).expect("the state serializes");
        let restored: Gpio = postcard::from_bytes(&bytes).expect("the state deserializes");
        assert_eq!(
            postcard::to_stdvec(&restored).unwrap(),
            bytes,
            "the lock, the frozen registers and what was announced survive"
        );
    }
}