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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The general-purpose I/O port of RM0090 rev 22 chapter 8 and RM0433 rev 9 chapter 11, which give
//! it the same ten registers and the same behavior. Each part's `gpio` module holds the table of what
//! its manual says and the tests that show it, and gives the port its layout through [`Port`].
//! Citations here name the RM0090 section, then the RM0433 one.
//!
//! 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 at the instant of its context. A pin whose level on the wire
//! changes announces it as a request line of its port, numbered by the pin: what a chip select on a
//! serial interface reads, and what an external interrupt controller edge-detects.

use std::marker::PhantomData;

use crate::device::{Device, DeviceContext, Level, RegisterFile};
use crate::soc::{FieldSpec, Layout};
use crate::time::VirtualNanos;

const PIN_COUNT: u8 = 16;
const PINS: usize = PIN_COUNT as usize;
pub(crate) const MODE_INPUT: u64 = 0b00;
pub(crate) const MODE_OUTPUT: u64 = 0b01;
pub(crate) const MODE_ALTERNATE: u64 = 0b10;
pub(crate) const MODE_ANALOG: u64 = 0b11;
pub(crate) const PULL_UP: u64 = 0b01;
pub(crate) const PULL_DOWN: u64 = 0b10;
pub(crate) const OPEN_DRAIN: u64 = 1;
const MODE_BITS: u32 = 2;
const FUNCTION_BITS: u32 = 4;
const FUNCTIONS_PER_REGISTER: u8 = 8;
// `LCKK` follows the sixteen `LCKx` bits, 8.4.8 and 11.4.8.
const LCKK_BIT: u32 = PIN_COUNT as u32;

/// A part's port registers in its own generated layout, the ten of RM0090 rev 22 section 8.4 and
/// RM0433 rev 9 section 11.4.
pub trait Port: Layout + PartialEq + 'static {
    /// `GPIOx_MODER`.
    const MODER: Self;
    /// `GPIOx_OTYPER`.
    const OTYPER: Self;
    /// `GPIOx_OSPEEDR`.
    const OSPEEDR: Self;
    /// `GPIOx_PUPDR`.
    const PUPDR: Self;
    /// `GPIOx_IDR`.
    const IDR: Self;
    /// `GPIOx_ODR`.
    const ODR: Self;
    /// `GPIOx_BSRR`.
    const BSRR: Self;
    /// `GPIOx_LCKR`.
    const LCKR: Self;
    /// `GPIOx_AFRL`.
    const AFRL: Self;
    /// `GPIOx_AFRH`.
    const AFRH: Self;
    /// What a pin's request line carries before the port first announces it, which the part's
    /// reset state decides: nothing where the pins come out of reset floating, and low where they
    /// come out analog, since the input stage forces an analog pin's level to zero.
    const AT_RESET: Option<Level>;
}

/// One of the port's sixteen pins.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub struct Pin(u8);

impl Pin {
    /// The pin at `index`, 0 to 15.
    #[must_use]
    pub const fn new(index: u8) -> Option<Self> {
        if index < PIN_COUNT {
            Some(Self(index))
        } else {
            None
        }
    }

    fn all() -> impl Iterator<Item = Self> {
        (0..PIN_COUNT).map(Self)
    }

    /// The pin's number, which is also its request line's number on the port.
    #[must_use]
    pub const fn index(self) -> usize {
        self.0 as usize
    }

    /// The pin's number, its bit in every one-bit-per-pin register, 8.4 and 11.4.
    #[must_use]
    pub const fn bit(self) -> u32 {
        self.0 as u32
    }
}

// The lock key write sequence of 8.4.8 and 11.4.8, with the `LCK[15:0]` it was started with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
enum Lock {
    #[default]
    Open,
    KeyWritten(u64),
    KeyCleared(u64),
    Locked(u64),
}

// The registers as they were when the lock took hold, which each later write puts back.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Frozen {
    moder: u64,
    otyper: u64,
    ospeedr: u64,
    pupdr: u64,
    afrl: u64,
    afrh: u64,
}

/// A port of sixteen pins.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(bound = "")]
pub struct Gpio<P> {
    external: [Option<Level>; PINS],
    function: [Option<Level>; PINS],
    sampled: [Level; PINS],
    /// The level each pin last announced on its request line, [`Port::AT_RESET`] before its first.
    announced: [Option<Level>; PINS],
    lock: Lock,
    frozen: Option<Frozen>,
    port: PhantomData<P>,
}

impl<P: Port> Default for Gpio<P> {
    fn default() -> Self {
        Self {
            external: [None; PINS],
            function: [None; PINS],
            sampled: [Level::Low; PINS],
            announced: [P::AT_RESET; PINS],
            lock: Lock::Open,
            frozen: None,
            port: PhantomData,
        }
    }
}

impl<P: Port> Gpio<P> {
    /// What the outside world drives on `pin`, or `None` when nothing does. A change of the level on
    /// the wire is announced at `context`'s instant.
    pub fn drive(
        &mut self,
        pin: Pin,
        level: Option<Level>,
        registers: &RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        self.external[pin.index()] = level;
        self.remember(pin, level);
        self.announce(registers, context);
    }

    /// What the peripheral selected by the alternate function drives on `pin`, or `None` when it
    /// drives nothing, 8.3.11 and 11.3.12. A change of the level on the wire is announced at
    /// `context`'s instant.
    pub fn drive_function(
        &mut self,
        pin: Pin,
        level: Option<Level>,
        registers: &RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        self.function[pin.index()] = level;
        self.remember(pin, level);
        self.announce(registers, context);
    }

    // A level put on a pin is the level a floating pin keeps once it's released. The input stage
    // samples every clock, so the pin saw it whether or not the firmware read it.
    fn remember(&mut self, pin: Pin, level: Option<Level>) {
        if let Some(level) = level {
            self.sampled[pin.index()] = level;
        }
    }

    /// The electrical level on `pin` now, what a wire soldered to it would see.
    #[must_use]
    pub fn level(&self, pin: Pin, registers: &RegisterFile) -> Level {
        self.input_level(pin, registers)
            .unwrap_or_else(|| self.external[pin.index()].unwrap_or(self.sampled[pin.index()]))
    }

    /// The alternate function number `pin` is configured to carry, when its mode is alternate
    /// function.
    #[must_use]
    pub fn function(pin: Pin, registers: &RegisterFile) -> Option<u8> {
        (mode::<P>(pin, registers) == MODE_ALTERNATE).then(|| {
            let (register, bit) = function_field::<P>(pin);
            let number = field_at(register, bit).get(registers.get(register));
            u8::try_from(number).expect("a four-bit field fits a byte")
        })
    }

    // An analog pin has no level to sample, and `IDR` reads zero, 8.3.12 and 11.3.13.
    fn sample(&mut self, pin: Pin, registers: &RegisterFile) -> Option<Level> {
        let level = self.input_level(pin, registers);
        if let Some(level) = level {
            self.sampled[pin.index()] = level;
        }
        level
    }

    // A floating pin has no wire level. An analog pin's Schmitt trigger output is forced to zero and
    // its pulls are disabled, so what the edge detector sees is low, 8.3.12 and 11.3.13.
    fn held(&self, pin: Pin, registers: &RegisterFile) -> Option<Level> {
        let index = pin.index();
        let held = match mode::<P>(pin, registers) {
            MODE_ANALOG => return Some(Level::Low),
            MODE_OUTPUT => true,
            MODE_ALTERNATE => self.function[index].is_some(),
            _ => false,
        } || self.external[index].is_some()
            || pull::<P>(pin, registers).is_some();
        held.then(|| self.level(pin, registers))
    }

    fn input_level(&self, pin: Pin, registers: &RegisterFile) -> Option<Level> {
        let index = pin.index();
        let driven = match mode::<P>(pin, registers) {
            MODE_ANALOG => return None,
            MODE_OUTPUT => Some(Level::from(
                field_at(P::ODR, pin.bit()).is_set(registers.get(P::ODR)),
            )),
            MODE_ALTERNATE => self.function[index],
            MODE_INPUT => None,
            unknown => unreachable!("a two-bit field holds {unknown}"),
        };
        let open_drain = field_at(P::OTYPER, pin.bit()).get(registers.get(P::OTYPER)) == OPEN_DRAIN;
        let level = match driven {
            Some(Level::Low) => Level::Low,
            Some(Level::High) if !open_drain => Level::High,
            _ => self.external[index]
                .or_else(|| pull::<P>(pin, registers))
                .unwrap_or(self.sampled[index]),
        };
        Some(level)
    }

    fn input_data(&mut self, registers: &RegisterFile) -> u64 {
        input_bits::<P>(|pin| self.sample(pin, registers))
    }

    // Only a change is announced, and a floating pin has none: the level it keeps is a convention for
    // the undefined value of 8.4.5 and 11.4.5, not a wire.
    fn announce(&mut self, registers: &RegisterFile, context: &mut DeviceContext<'_>) {
        for pin in Pin::all() {
            let Some(level) = self.held(pin, registers) else {
                continue;
            };
            if self.announced[pin.index()] != Some(level) {
                self.announced[pin.index()] = Some(level);
                context.request(pin.index(), level);
            }
        }
    }

    fn lock(&mut self, value: u64, registers: &mut RegisterFile) {
        let key = field_at(P::LCKR, LCKK_BIT).is_set(value);
        let bits = lock_bits::<P>(value);
        self.lock = match (self.lock, key) {
            (Lock::Locked(mask), _) => Lock::Locked(mask),
            (Lock::KeyCleared(same), true) if same == bits => {
                self.frozen = Some(Frozen {
                    moder: registers.get(P::MODER),
                    otyper: registers.get(P::OTYPER),
                    ospeedr: registers.get(P::OSPEEDR),
                    pupdr: registers.get(P::PUPDR),
                    afrl: registers.get(P::AFRL),
                    afrh: registers.get(P::AFRH),
                });
                Lock::Locked(same)
            }
            (_, true) => Lock::KeyWritten(bits),
            (Lock::KeyWritten(same), false) if same == bits => Lock::KeyCleared(same),
            (_, false) => Lock::Open,
        };
        let shown = match self.lock {
            Lock::Locked(mask) => field_at(P::LCKR, LCKK_BIT).set(mask, 1),
            _ => bits,
        };
        registers.set(P::LCKR, shown);
    }

    // Puts the locked pins' bits of a configuration register back after a write, 8.3.6 and 11.3.6.
    fn hold_frozen(&self, register: P, registers: &mut RegisterFile) {
        let (Lock::Locked(mask), Some(frozen)) = (self.lock, self.frozen) else {
            return;
        };
        let held = [
            (P::MODER, frozen.moder),
            (P::OTYPER, frozen.otyper),
            (P::OSPEEDR, frozen.ospeedr),
            (P::PUPDR, frozen.pupdr),
            (P::AFRL, frozen.afrl),
            (P::AFRH, frozen.afrh),
        ]
        .into_iter()
        .find_map(|(frozen, value)| (frozen == register).then_some(value));
        let Some(held) = held else {
            return;
        };
        let bits = Pin::all()
            .filter(|pin| field_at(P::LCKR, pin.bit()).is_set(mask))
            .filter_map(|pin| configuration_field(register, pin))
            .fold(0, |bits, field| bits | field.mask());
        let written = registers.get(register);
        registers.set(register, (written & !bits) | (held & bits));
    }
}

impl<P: Port> Device for Gpio<P> {
    type Register = P;

    fn read(
        &mut self,
        register: P,
        registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) -> Option<u64> {
        (register == P::IDR).then(|| self.input_data(registers))
    }

    /// `IDR` as a read would sample it, with no sample kept.
    fn peek(&self, register: P, registers: &RegisterFile, _now: VirtualNanos) -> Option<u64> {
        (register == P::IDR).then(|| input_bits::<P>(|pin| self.input_level(pin, registers)))
    }

    fn write(
        &mut self,
        register: P,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        if register == P::BSRR {
            // BSx sets and BRx resets, and BSx wins when both are written, 8.4.7 and 11.4.7.
            let output = Pin::all().fold(registers.get(P::ODR), |output, pin| {
                let set = field_at(P::BSRR, pin.bit()).is_set(value);
                let reset = field_at(P::BSRR, u32::from(PIN_COUNT) + pin.bit()).is_set(value);
                match (set, reset) {
                    (true, _) => field_at(P::ODR, pin.bit()).set(output, 1),
                    (false, true) => field_at(P::ODR, pin.bit()).set(output, 0),
                    (false, false) => output,
                }
            });
            registers.set(P::ODR, output);
        } else if register == P::LCKR {
            self.lock(value, registers);
        } else {
            self.hold_frozen(register, registers);
        }
        // The input stage samples every AHB clock, 8.3.9 and 11.3.9, and no event stands for that
        // here, so a change takes effect at the write.
        self.input_data(registers);
        self.announce(registers, context);
    }

    /// A reset releases the lock, 8.4.8 and 11.4.8: "until the next MCU reset or peripheral reset".
    /// Each pin goes back to what it carried at reset, since the models that heard it were reset too,
    /// and the peripherals that drove a function reset with the part. What the outside world drives
    /// stays.
    fn reset(&mut self) {
        self.lock = Lock::Open;
        self.frozen = None;
        self.announced = [P::AT_RESET; PINS];
        self.function = [None; PINS];
    }
}

fn input_bits<P: Port>(mut level: impl FnMut(Pin) -> Option<Level>) -> u64 {
    Pin::all()
        .filter(|&pin| level(pin) == Some(Level::High))
        .map(|pin| field_at(P::IDR, pin.bit()).mask())
        .sum()
}

fn mode<P: Port>(pin: Pin, registers: &RegisterFile) -> u64 {
    field_at(P::MODER, pin.bit() * MODE_BITS).get(registers.get(P::MODER))
}

fn pull<P: Port>(pin: Pin, registers: &RegisterFile) -> Option<Level> {
    match field_at(P::PUPDR, pin.bit() * MODE_BITS).get(registers.get(P::PUPDR)) {
        PULL_UP => Some(Level::High),
        PULL_DOWN => Some(Level::Low),
        _ => None,
    }
}

fn function_field<P: Port>(pin: Pin) -> (P, u32) {
    if pin.0 < FUNCTIONS_PER_REGISTER {
        (P::AFRL, pin.bit() * FUNCTION_BITS)
    } else {
        (
            P::AFRH,
            (pin.bit() - u32::from(FUNCTIONS_PER_REGISTER)) * FUNCTION_BITS,
        )
    }
}

fn field_at<P: Port>(register: P, bit: u32) -> &'static FieldSpec {
    register
        .field_at(bit)
        .expect("every pin has its field in every GPIO register")
}

fn lock_bits<P: Port>(value: u64) -> u64 {
    Pin::all().fold(0, |bits, pin| {
        bits | (value & field_at(P::LCKR, pin.bit()).mask())
    })
}

// A pin's function lives in one of `AFRL` and `AFRH`, and the other has no field for it.
fn configuration_field<P: Port>(register: P, pin: Pin) -> Option<&'static FieldSpec> {
    if [P::MODER, P::OSPEEDR, P::PUPDR].contains(&register) {
        Some(field_at(register, pin.bit() * MODE_BITS))
    } else if register == P::OTYPER {
        Some(field_at(register, pin.bit()))
    } else if register == P::AFRL || register == P::AFRH {
        let (holder, bit) = function_field::<P>(pin);
        (holder == register).then(|| field_at(holder, bit))
    } else {
        None
    }
}