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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The timers of RM0090 rev 22 chapters 17 and 18 and RM0433 rev 9 chapters 38 to 42, which give them
//! the same registers at the same offsets with the same bits, and the same time base, channels, slave
//! controller and break, RM0433 adding to them. Each part's `tim` module holds the table of what its
//! manual says and the tests that show it, and builds the model with what its silicon decides: the
//! layouts and kinds of timer it has through [`Family`] and [`Kind`], and what its manual and errata
//! sheet give it and not the other part through [`Part`]. Citations here name the RM0090 section,
//! then the RM0433 one.
//!
//! A register is named by what it does and found in a layout by the offset the part's tables give
//! it, so a register one part has and the other hasn't, `TIMx_OR` at `0x50` on the STM32F427 and
//! `TIMx_CCMR3` at `0x54` on the STM32H743, answers on the part that has it. A field only RM0433
//! gives reads zero on the STM32F427, so its four-bit `OCxM`, `SMS[3]`, `UIFREMAP`, `MMS2`, `TISEL`,
//! `ETRSEL`, channels 5 and 6 and `BRK2` are the STM32H743's without a branch.
//!
//! The counter lives on counter-clock cycles. While the internal clock drives it, a cycle has an
//! instant on the virtual clock, and the model asks to be woken at the next one that matters. While
//! an external clock drives it, a cycle is an edge arriving through an input method. Every entry point
//! settles the timer up to `now` first, so the event queue is only a wake-up and the arithmetic is the
//! same whichever clock counts.

use std::marker::PhantomData;

use crate::device::{Level, RegisterFile};
use crate::soc::FieldSpec;
use crate::time::{EventId, VirtualNanos};

mod access;
mod breaks;
mod count;
pub(crate) mod family;
mod fields;
mod inputs;
mod outputs;

pub use family::{
    CHANNEL_REQUESTS, COMMUTATION_REQUEST, Counter, Errata, Family, Flags, Instance, Kind, Part,
    Spelling, TRIGGER_REQUEST, Timer, UPDATE_REQUEST, Wakeups,
};
use family::{Map, SLOTS, Slot, offsets};

const HALF_WORD: u64 = 0xFFFF;
const WORD: u64 = u32::MAX as u64;
const CHANNEL_COUNT: u8 = 6;
const CHANNELS: usize = CHANNEL_COUNT as usize;
// 18.3.4 and 38.3.6
const INPUTS: usize = 4;
// 38.3.6
const TI_SOURCES: usize = 16;
// 38.4.26
const ETR_SOURCES: usize = 16;
const BREAKS: usize = 2;
const BREAK_SOURCES: usize = 4;
const MAX_LINES: usize = 4;
const REQUESTS: usize = 7;

/// A capture/compare channel, 1 to 6. Channels 5 and 6 are RM0433 rev 9's advanced timers', with no
/// pin.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub struct Channel(u8);

impl Channel {
    /// Channel `number`, 1 to 6.
    #[must_use]
    pub const fn new(number: u8) -> Option<Self> {
        if number >= 1 && number <= CHANNEL_COUNT {
            Some(Self(number - 1))
        } else {
            None
        }
    }

    /// The channel's number, 1 to 6.
    #[must_use]
    pub const fn number(self) -> u8 {
        self.0 + 1
    }

    const fn index(self) -> usize {
        self.0 as usize
    }

    const fn partner(self) -> Self {
        Self(self.0 ^ 1)
    }

    const fn has_input(self) -> bool {
        self.index() < INPUTS
    }

    const fn ccr(self) -> Slot {
        [
            Slot::Ccr1,
            Slot::Ccr2,
            Slot::Ccr3,
            Slot::Ccr4,
            Slot::Ccr5,
            Slot::Ccr6,
        ][self.index()]
    }

    const fn ccmr(self) -> Slot {
        [Slot::Ccmr1, Slot::Ccmr2, Slot::Ccmr3][self.index() / 2]
    }
}

fn present(count: u8) -> impl Iterator<Item = Channel> {
    (0..count).map(Channel)
}

/// Which of a timer's break inputs a level is driven on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakInput {
    /// `BRK`, which every timer with a break has.
    First,
    /// `BRK2`, RM0433 rev 9's advanced timers' second.
    Second,
}

impl BreakInput {
    const fn index(self) -> usize {
        self as usize
    }
}

/// What a break gathers: the `BKIN` pin, and on RM0433 rev 9's timers either comparator and the
/// digital filter's analog watchdog, section 38.3.16.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakSource {
    /// The `BKIN` pin through the alternate function controller.
    Pin,
    /// The first comparator's output.
    Comparator1,
    /// The second comparator's output.
    Comparator2,
    /// The digital filter's break output.
    Dfsdm,
}

impl BreakSource {
    const fn index(self) -> usize {
        self as usize
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Direction {
    Up,
    Down,
}

// Why an update event happened, which decides the flag under `URS` and the counter's reinitialization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum UpdateSource {
    Overflow,
    Underflow,
    Software,
    Trigger,
}

#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
struct Input {
    level: Level,
    filtered: Level,
    pending: Option<(u128, Level)>,
}

#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
struct ChannelState {
    shadow: u64,
    reference: bool,
    pin: Level,
    pin_since: u128,
    cleared_for_updates: u8,
    matched_since_clear: bool,
    armed: bool,
    prescaled_edges: u64,
    last_match: Option<(u128, u64)>,
    selection: u64,
}

/// DMA requests made so far, by source, 18.4.4 and 38.4.4. The same events raise the request outputs
/// [`UPDATE_REQUEST`], [`CHANNEL_REQUESTS`], [`TRIGGER_REQUEST`] and [`COMMUTATION_REQUEST`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct DmaRequests {
    /// `UDE`.
    pub update: u64,
    /// `CCxDE`, channels 1 to 4.
    pub channels: [u64; INPUTS],
    /// `TDE`.
    pub trigger: u64,
    /// `COMDE`.
    pub commutation: u64,
}

// 17.3.14 and 38.3.19
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Controls {
    ccer: u64,
    ccmr: [u64; 2],
}

#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Epoch {
    at: VirtualNanos,
    cycle: u128,
}

impl Default for Epoch {
    fn default() -> Self {
        Self {
            at: VirtualNanos(0),
            cycle: 0,
        }
    }
}

#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
struct Sources {
    ti: [[Level; TI_SOURCES]; INPUTS],
    etr: [Level; ETR_SOURCES],
    breaks: [[Option<Level>; BREAK_SOURCES]; BREAKS],
}

impl Sources {
    fn at_rest(break_pin: Option<Level>) -> Self {
        let mut breaks = [[None; BREAK_SOURCES]; BREAKS];
        for input in &mut breaks {
            input[BreakSource::Pin.index()] = break_pin;
        }
        Self {
            ti: [[Level::Low; TI_SOURCES]; INPUTS],
            etr: [Level::Low; ETR_SOURCES],
            breaks,
        }
    }
}

// 17.3.3, 17.3.11 to 17.3.14, 38.3.3 and 38.3.15 to 38.3.19
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct PowerStage {
    repetition: u64,
    controls: Option<Controls>,
    filters: [Input; BREAKS],
    active: [bool; BREAKS],
    lock_frozen: bool,
    kept: [u64; SLOTS],
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CounterEvent {
    Boundary(UpdateSource),
    Match(Match),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Match {
    channel: Channel,
    cycle: u128,
    value: u64,
}

impl CounterEvent {
    // At one cycle the boundary comes first, so a match at the new count sees the new segment.
    const fn order(self) -> u8 {
        match self {
            Self::Boundary(_) => 0,
            Self::Match(..) => 1,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum FilterEvent {
    Input(usize),
    Etr,
    Break(usize),
}

#[derive(Debug, Clone, Copy)]
enum Pending {
    Counter(u128, CounterEvent),
    Filter(FilterEvent),
}

/// A timer of RM0090 rev 22 chapters 17 and 18 or RM0433 rev 9 chapters 38 to 42, by its [`Family`]
/// and [`Kind`].
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(bound(deserialize = "'de: 'static"))]
pub struct Tim<F: Family> {
    family: PhantomData<F>,
    width: Counter,
    kind: Kind,
    map: Map,
    clock_hz: u64,
    // A change of rate moves it, so earlier cycles stand and later ones come at the new rate.
    epoch: Epoch,
    external: bool,
    counting: bool,
    paused: u128,
    stopped_at: u128,
    external_cycles: u128,
    psc: u64,
    arr: u64,
    segment_cycle: u128,
    segment_count: u64,
    direction: Direction,
    channels: [ChannelState; CHANNELS],
    group: u64,
    inputs: [Input; INPUTS],
    sources: Sources,
    etr_polarized: Level,
    etr_edges: u64,
    etr: Input,
    trigger: Level,
    trigger_output: Level,
    trigger_pulses: u64,
    trigger2_output: Level,
    trigger2_pulses: u64,
    dma_requests: DmaRequests,
    requested: [bool; REQUESTS],
    driven: [Level; REQUESTS],
    burst_index: u64,
    interrupts: [Level; MAX_LINES],
    seen: VirtualNanos,
    wakeup: Option<(VirtualNanos, EventId)>,
    power: PowerStage,
    system_breaks: Vec<(&'static str, usize)>,
    // In an array so serde doesn't borrow the field whole.
    name: [Option<&'static str>; 1],
}

impl<F: Family> Tim<F> {
    const OFFSETS: [Option<u32>; SLOTS] = offsets(F::PART);

    /// The timer `instance` whose `CK_INT` runs at `clock_hz` until the part's clock tree drives it
    /// otherwise.
    ///
    /// # Panics
    ///
    /// Panics when the instance is a kind of timer the family doesn't carry, which is a wrong row in
    /// the part's table.
    #[must_use]
    pub fn with_clock(clock_hz: u64, instance: F::Instance) -> Self {
        let kind = instance.kind().unwrap_or(F::KINDS[0]);
        assert!(
            F::KINDS.contains(&kind),
            "{} is a {kind:?} timer, which {} does not carry",
            instance.name().unwrap_or("the instance"),
            std::any::type_name::<F>(),
        );
        let mut tim = Self::build(clock_hz, instance.counter(), kind);
        tim.name = [instance.name()];
        tim
    }

    fn build(clock_hz: u64, width: Counter, kind: Kind) -> Self {
        Self {
            family: PhantomData,
            width,
            kind,
            map: Map::of(F::layout(width), &Self::OFFSETS),
            clock_hz,
            epoch: Epoch::default(),
            external: false,
            counting: false,
            paused: 0,
            stopped_at: 0,
            external_cycles: 0,
            psc: 0,
            arr: width.mask(),
            segment_cycle: 0,
            segment_count: 0,
            direction: Direction::Up,
            channels: [ChannelState::default(); CHANNELS],
            group: 0,
            inputs: [Input::default(); INPUTS],
            sources: Sources::at_rest(F::PART.break_pin),
            etr_polarized: Level::Low,
            etr_edges: 0,
            etr: Input::default(),
            trigger: Level::Low,
            trigger_output: Level::Low,
            trigger_pulses: 0,
            trigger2_output: Level::Low,
            trigger2_pulses: 0,
            dma_requests: DmaRequests::default(),
            requested: [false; REQUESTS],
            driven: [Level::Low; REQUESTS],
            burst_index: 0,
            interrupts: [Level::Low; MAX_LINES],
            seen: VirtualNanos(0),
            wakeup: None,
            power: PowerStage {
                repetition: 0,
                controls: None,
                filters: [Input::default(); BREAKS],
                active: [false; BREAKS],
                lock_frozen: false,
                kept: Self::reset_values(kind, width),
            },
            system_breaks: Vec::new(),
            name: [None],
        }
    }

    // 18.4.12, 38.4.14, and 38.4.26 to 38.4.29
    fn reset_values(kind: Kind, width: Counter) -> [u64; SLOTS] {
        let mut kept = [0; SLOTS];
        kept[Slot::Arr.index()] = width.mask();
        if kind.gathers_break_sources() {
            kept[Slot::Af1.index()] = Self::BKINE.mask();
            kept[Slot::Af2.index()] = Self::BK2INE.mask();
        }
        kept
    }

    /// Takes the pulse on `request` of `instance` as a system break, 17.3.12 and 38.3.16, of which a
    /// clock failure the clock security system detects is one. The part wires each source it has, so
    /// this can be called once for each.
    #[must_use]
    pub fn breaks_on(mut self, instance: &'static str, request: usize) -> Self {
        self.system_breaks.push((instance, request));
        self
    }

    fn slot_at(offset: u32) -> Option<Slot> {
        Slot::ALL
            .into_iter()
            .find(|slot| Self::OFFSETS[slot.index()] == Some(offset))
    }

    fn own(&self, slot: Slot) -> Option<F::Register> {
        self.map
            .row(slot)
            .and_then(<F::Register as crate::soc::Layout>::from_index)
    }

    fn reg(&self, registers: &RegisterFile, slot: Slot) -> u64 {
        self.own(slot).map_or(0, |own| registers.get(own))
    }

    fn put(&self, registers: &mut RegisterFile, slot: Slot, value: u64) {
        if let Some(own) = self.own(slot) {
            registers.set(own, value);
        }
    }

    fn flag(&self, registers: &mut RegisterFile, field: &FieldSpec) {
        let status = self.reg(registers, Slot::Sr);
        self.put(registers, Slot::Sr, field.set(status, 1));
    }

    fn count_register(&self, registers: &RegisterFile, now: VirtualNanos) -> u64 {
        let count = self.count_now(now);
        if Self::UIFREMAP.is_set(self.reg(registers, Slot::Cr1)) {
            let copy = u64::from(Self::UIF.is_set(self.reg(registers, Slot::Sr)));
            Self::UIFCPY.set(count, copy)
        } else {
            count
        }
    }

    /// `TRGO`: its level for the level modes of `MMS`, and the pulses sent so far for the pulse
    /// modes, 18.4.2 and 38.4.2.
    #[must_use]
    pub fn trigger_output(&self) -> (Level, u64) {
        (self.trigger_output, self.trigger_pulses)
    }

    /// `TRGO2`, which RM0433 rev 9's advanced timers send the converters: its level for the level modes
    /// of `MMS2`, and the pulses sent so far for the pulse modes, 38.4.2.
    #[must_use]
    pub fn trigger2_output(&self) -> (Level, u64) {
        (self.trigger2_output, self.trigger2_pulses)
    }

    /// DMA requests made so far.
    #[must_use]
    pub fn dma_requests(&self) -> DmaRequests {
        self.dma_requests
    }
}