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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The capture/compare channels' output side: compare matches and their flags, the references of every
//! output mode, the pin each reference reaches through the break and the dead-time, and the pulse a
//! board reads off a pin.

use crate::device::{Level, RegisterFile};
use crate::edge::Pulse;
use crate::time::{NANOS_PER_SECOND, VirtualNanos};

use super::count::TriggerEvent;
use super::family::{CHANNEL_REQUESTS, Family, Slot};
use super::fields::{
    CCS_OUTPUT, CMS_FLAGS_DOWN, CMS_FLAGS_UP, MMS2_OC4_EDGES, MMS2_OC4_OR_OC6_RISING,
    MMS2_OC4_RISING_OC6_FALLING, MMS2_OC5_OR_OC6_RISING, MMS2_OC5_RISING_OC6_FALLING,
    MMS2_OC6_EDGES, OCM_ACTIVE_ON_MATCH, OCM_ASYMMETRIC_1, OCM_ASYMMETRIC_2, OCM_COMBINED_1,
    OCM_COMBINED_2, OCM_FROZEN, OCM_INACTIVE_ON_MATCH, OCM_PWM_1, OCM_PWM_2, OCM_RETRIGGERABLE_1,
    OCM_RETRIGGERABLE_2, OCM_TOGGLE,
};
use super::{CHANNELS, Channel, Direction, Match, Tim, UpdateSource, present};

const FIFTH: usize = 4;

impl<F: Family> Tim<F> {
    pub(super) const GROUP_MASK: u64 =
        Self::GROUP[0].mask() | Self::GROUP[1].mask() | Self::GROUP[2].mask();

    // The written value with the modes `CCPC` took at the last commutation, 17.3.14 and 38.3.19.
    pub(super) fn control(&self, channel: Channel, registers: &RegisterFile) -> u64 {
        let written = self.reg(registers, channel.ccmr());
        let pair = channel.index() / 2;
        match self.power.controls {
            Some(controls) if pair < controls.ccmr.len() => {
                let held = self.preloaded_modes(pair);
                (written & !held) | (controls.ccmr[pair] & held)
            }
            _ => written,
        }
    }

    pub(super) fn channel_selection(&self, channel: Channel, registers: &RegisterFile) -> u64 {
        if channel.has_input() {
            Self::CC_S[channel.index()].get(self.reg(registers, channel.ccmr()))
        } else {
            CCS_OUTPUT
        }
    }

    pub(super) fn output_mode(&self, channel: Channel, registers: &RegisterFile) -> u64 {
        let mode = Self::OC_M[channel.index()].get(self.control(channel, registers));
        if self.kind.has_mode(mode) {
            mode
        } else {
            OCM_FROZEN
        }
    }

    fn grouped(&self, channel: Channel) -> bool {
        Self::GROUP
            .get(channel.index())
            .is_some_and(|field| field.is_set(self.group))
    }

    pub(super) fn load_group(&mut self, registers: &RegisterFile, at_update: bool) {
        if self.kind.channels() < 5 {
            return;
        }
        let written = self.reg(registers, Slot::Ccr5);
        for channel in present(Self::GROUP.len().try_into().expect("three channels")) {
            let preloaded = Self::OC_PE[channel.index()].is_set(self.control(channel, registers));
            if preloaded == at_update {
                let field = Self::GROUP[channel.index()];
                self.group = field.set(self.group, field.get(written));
            }
        }
    }

    // 38.3.12 and 38.3.13, the second of a pair mirroring what the manual gives the first.
    fn combined_reference(&self, channel: Channel, registers: &RegisterFile) -> bool {
        let own = self.channels[channel.index()].reference;
        let partner = self.channels[channel.partner().index()].reference;
        let combined = match self.output_mode(channel, registers) {
            OCM_COMBINED_1 => own || partner,
            OCM_COMBINED_2 => own && partner,
            OCM_ASYMMETRIC_1 | OCM_ASYMMETRIC_2 => match self.direction {
                Direction::Up => own,
                Direction::Down => partner,
            },
            _ => own,
        };
        if self.grouped(channel) {
            combined && self.channels[FIFTH].reference
        } else {
            combined
        }
    }

    // `clock` is when a dead-time starts, 17.3.11 and 38.3.15.
    pub(super) fn set_reference(
        &mut self,
        channel: Channel,
        active: bool,
        clock: u128,
        registers: &RegisterFile,
    ) {
        self.channels[channel.index()].reference = active;
        self.note_pins(clock, registers);
    }

    pub(super) fn note_pins(&mut self, clock: u128, registers: &RegisterFile) {
        let mut edges = [None; CHANNELS];
        for channel in present(self.kind.channels()) {
            let new = Level::from(self.combined_reference(channel, registers));
            let state = &mut self.channels[channel.index()];
            if new != state.pin {
                state.pin = new;
                state.pin_since = clock;
                edges[channel.index()] = Some(new == Level::High);
            }
        }
        for (index, rising) in edges.into_iter().enumerate() {
            if let Some(rising) = rising {
                self.second_trigger_edge(index, rising, registers);
            }
        }
    }

    // 38.4.2's `MMS2` 1010 to 1111
    fn second_trigger_edge(&mut self, index: usize, rising: bool, registers: &RegisterFile) {
        let (oc4, oc5, oc6) = (3, 4, 5);
        let selected = match Self::MMS2.get(self.reg(registers, Slot::Cr2)) {
            MMS2_OC4_EDGES => index == oc4,
            MMS2_OC6_EDGES => index == oc6,
            MMS2_OC4_OR_OC6_RISING => rising && (index == oc4 || index == oc6),
            MMS2_OC4_RISING_OC6_FALLING => (index == oc4 && rising) || (index == oc6 && !rising),
            MMS2_OC5_OR_OC6_RISING => rising && (index == oc5 || index == oc6),
            MMS2_OC5_RISING_OC6_FALLING => (index == oc5 && rising) || (index == oc6 && !rising),
            _ => false,
        };
        if selected && self.kind.second_trigger() {
            self.trigger2_pulses += 1;
        }
    }

    // 18.3.8, 18.3.9, 38.3.9 and 38.3.11
    pub(super) fn compare_match(
        &mut self,
        found: Match,
        counted: Option<Direction>,
        registers: &mut RegisterFile,
    ) {
        let Match {
            channel,
            cycle,
            value,
        } = found;
        let missed = self.missed_consecutive(channel, cycle, value, registers);
        self.channels[channel.index()].last_match = Some((cycle, value));
        let cms = Self::CMS.get(self.reg(registers, Slot::Cr1));
        let gated = self.kind.up_down()
            && matches!(
                (cms, counted),
                (CMS_FLAGS_DOWN, Some(Direction::Up)) | (CMS_FLAGS_UP, Some(Direction::Down))
            );
        let lost = missed && self.center_aligned(registers);
        if !gated && !lost {
            self.flag_compare(channel, registers);
        }
        let mode = self.output_mode(channel, registers);
        let state = &mut self.channels[channel.index()];
        if !missed {
            state.matched_since_clear = true;
        }
        let reference = state.reference;
        let clock = cycle + self.paused;
        match mode {
            OCM_ACTIVE_ON_MATCH => self.set_reference(channel, true, clock, registers),
            OCM_INACTIVE_ON_MATCH => self.set_reference(channel, false, clock, registers),
            OCM_TOGGLE if !missed => self.set_reference(channel, !reference, clock, registers),
            _ => {}
        }
        self.refresh_pwm(channel, cycle, registers);
    }

    pub(super) fn flag_compare(&mut self, channel: Channel, registers: &mut RegisterFile) {
        self.flag(registers, Self::CC_IF[channel.index()]);
        if channel.has_input() && self.kind.dma() {
            let on_update = Self::CCDS.is_set(self.reg(registers, Slot::Cr2));
            let enabled = Self::CC_DE[channel.index()].is_set(self.reg(registers, Slot::Dier));
            if enabled && !on_update {
                self.dma_requests.channels[channel.index()] += 1;
                self.requested[CHANNEL_REQUESTS[channel.index()]] = true;
            }
        }
        if channel.index() == 0 {
            self.trigger_pulse(registers, TriggerEvent::Compare);
        }
    }

    // `Errata::consecutive_compare_missed`'s three patterns, "when TIMx_RCR = 0" center-aligned.
    fn missed_consecutive(
        &self,
        channel: Channel,
        cycle: u128,
        value: u64,
        registers: &RegisterFile,
    ) -> bool {
        if !F::PART.errata.consecutive_compare_missed {
            return false;
        }
        let Some((last_cycle, last_value)) = self.channels[channel.index()].last_match else {
            return false;
        };
        if cycle != last_cycle + u128::from(self.psc) + 1 || value == last_value {
            return false;
        }
        if self.center_aligned(registers) {
            // The direction has already turned at the crest and the valley, so the values say which.
            self.repetitions(registers) == 0
                && ((last_value + 1 == self.arr && value == self.arr)
                    || (last_value == 1 && value == 0))
        } else {
            last_value == self.arr && value == 0
        }
    }

    // `counted` is `None` at the crest and the valley, where the flag rises whatever `CMS` says.
    pub(super) fn matches_at_segment_start(
        &mut self,
        counted: Option<Direction>,
        registers: &mut RegisterFile,
    ) {
        let cycle = self.segment_cycle;
        for channel in present(self.kind.channels()) {
            if self.channel_selection(channel, registers) != CCS_OUTPUT {
                continue;
            }
            let value = self.channels[channel.index()].shadow;
            let already = matches!(self.channels[channel.index()].last_match, Some((last, _)) if last >= cycle);
            if value == self.segment_count && !already {
                let found = Match {
                    channel,
                    cycle,
                    value,
                };
                self.compare_match(found, counted, registers);
            }
        }
        for channel in present(self.kind.channels()) {
            self.refresh_pwm(channel, self.segment_cycle, registers);
        }
    }

    // 18.3.9 and 38.3.11, unless an `ETRF` clear holds it, 18.3.11 and 38.3.18.
    pub(super) fn refresh_pwm(&mut self, channel: Channel, cycle: u128, registers: &RegisterFile) {
        let mode = self.output_mode(channel, registers);
        let count = self.count_at(cycle);
        let state = &self.channels[channel.index()];
        let value = state.shadow;
        let up = self.direction == Direction::Up;
        let first_mode = |count: u64| if up { count < value } else { count <= value };
        let second_mode = |count: u64| if up { count >= value } else { count > value };
        let second = matches!(mode, OCM_PWM_2 | OCM_COMBINED_2 | OCM_ASYMMETRIC_2)
            || (mode == OCM_RETRIGGERABLE_2 && up);
        let active = match mode {
            OCM_RETRIGGERABLE_1 if state.armed => up,
            OCM_RETRIGGERABLE_2 if state.armed => !up,
            OCM_PWM_1 | OCM_COMBINED_1 | OCM_ASYMMETRIC_1 | OCM_RETRIGGERABLE_1 | OCM_PWM_2
            | OCM_COMBINED_2 | OCM_ASYMMETRIC_2 | OCM_RETRIGGERABLE_2 => {
                if second {
                    second_mode(count)
                } else {
                    first_mode(count)
                }
            }
            _ => return,
        };
        if state.cleared_for_updates == 0 {
            self.set_reference(channel, active, cycle + self.paused, registers);
        }
    }

    pub(super) fn rearm_outputs(&mut self, source: UpdateSource, registers: &RegisterFile) {
        if source == UpdateSource::Trigger {
            return;
        }
        for channel in present(self.kind.channels()) {
            if matches!(
                self.output_mode(channel, registers),
                OCM_RETRIGGERABLE_1 | OCM_RETRIGGERABLE_2
            ) {
                self.channels[channel.index()].armed = true;
            }
        }
    }

    pub(super) fn disarm_outputs(&mut self) {
        for state in &mut self.channels {
            state.armed = false;
        }
    }

    pub(super) fn start_pulses(&mut self, cycle: u128, registers: &RegisterFile) {
        let waiting = self.channels.map(|state| state.armed);
        self.disarm_outputs();
        for channel in present(self.kind.channels()) {
            if waiting[channel.index()] {
                self.refresh_pwm(channel, cycle, registers);
            }
        }
    }

    // 18.4.5 and 38.4.5
    pub(super) fn flag_capture(&mut self, channel: Channel, registers: &mut RegisterFile) {
        if channel.has_input() && Self::CC_IF[channel.index()].is_set(self.reg(registers, Slot::Sr))
        {
            self.flag(registers, Self::CC_OF[channel.index()]);
        }
        self.flag_compare(channel, registers);
    }

    fn complementary_enabled(&self, index: usize, ccer_value: u64) -> bool {
        index < self.kind.complementary() && Self::CC_NE[index].is_set(ccer_value)
    }

    fn outputs(
        &self,
        channel: Channel,
        registers: &RegisterFile,
    ) -> (Option<Level>, Option<Level>) {
        let index = channel.index();
        if !channel.has_input() || !self.has_channel(channel) {
            return (None, None);
        }
        let ccer_value = self.ccer(registers);
        let enabled = Self::CC_E[index].is_set(ccer_value);
        let active_low = Self::CC_P[index].is_set(ccer_value);
        let reference = self.channels[index].pin == Level::High;
        if self.kind.breaks() == 0 {
            return (enabled.then(|| Level::from(reference != active_low)), None);
        }
        let complementary = self.complementary_enabled(index, ccer_value);
        let complementary_low = Self::CC_NP[index].is_set(ccer_value);
        let bdtr_value = self.reg(registers, Slot::Bdtr);
        let cr2_value = self.reg(registers, Slot::Cr2);
        if !Self::MOE.is_set(bdtr_value) {
            if !Self::OSSI.is_set(bdtr_value) || (!enabled && !complementary) {
                return (None, None);
            }
            if self.power.active[1] && !self.power.active[0] {
                // Break 2 disables the outputs and leaves them at their inactive level, 38.3.16.
                return (
                    Some(Level::from(active_low)),
                    Some(Level::from(complementary_low)),
                );
            }
            let idle = Level::from(Self::OIS[index].is_set(cr2_value));
            let idle_n = Self::OIS_N
                .get(index)
                .map(|field| Level::from(field.is_set(cr2_value)));
            return (Some(idle), idle_n);
        }
        let off_state = Self::OSSR.is_set(bdtr_value);
        let settled = self
            .clock_cycle(self.seen)
            .saturating_sub(self.channels[index].pin_since)
            >= self.dead_time(registers);
        match (enabled, complementary) {
            (false, false) => (None, None),
            (false, true) => (
                off_state.then(|| Level::from(active_low)),
                Some(Level::from(reference != complementary_low)),
            ),
            (true, false) => (
                Some(Level::from(reference != active_low)),
                (off_state && index < self.kind.complementary())
                    .then(|| Level::from(complementary_low)),
            ),
            (true, true) => (
                Some(Level::from((reference && settled) != active_low)),
                Some(Level::from((!reference && settled) != complementary_low)),
            ),
        }
    }

    /// The `OCx` output of `channel` as of the last instant the timer settled to: its reference through
    /// its polarity when enabled, or `None` while the pin isn't driven. On a timer with a break it's
    /// RM0090 rev 22 table 95 or RM0433 rev 9 Tables 337 and 350, with `MOE`, the off-states, the
    /// idle levels and the dead-time. Channels 5 and 6 have no pin.
    #[must_use]
    pub fn output(&self, channel: Channel, registers: &RegisterFile) -> Option<Level> {
        self.outputs(channel, registers).0
    }

    /// The `OCxN` output of `channel`, or `None` where the timer or the channel has none or the pin
    /// isn't driven.
    #[must_use]
    pub fn complementary_output(
        &self,
        channel: Channel,
        registers: &RegisterFile,
    ) -> Option<Level> {
        self.outputs(channel, registers).1
    }

    /// `OCxREFC` of `channel`, the level the output stage works from and `TRGO` and `TRGO2` can carry.
    /// It's the one way to read channels 5 and 6, which have no pin.
    #[must_use]
    pub fn reference(&self, channel: Channel) -> Level {
        if self.has_channel(channel) {
            self.channels[channel.index()].pin
        } else {
            Level::Low
        }
    }

    /// The pulse `OCx` repeats as the shadows stand, 18.3.9 and 38.3.11: on a counter running from
    /// `CK_INT`, counting edge-aligned in either direction, with `channel` enabled in PWM mode 1 or 2
    /// and its pin driven, the high time and the period on the virtual clock, through the polarity,
    /// less the dead-time of 17.3.11 and 38.3.15 where the complementary output is enabled too. `None`
    /// for a pin that isn't driven or a waveform that isn't one of these: a level, a capture, a
    /// combined or retriggerable waveform, a channel grouped with channel 5 and a center-aligned
    /// pulse aren't read.
    #[must_use]
    pub fn pulse(&self, channel: Channel, registers: &RegisterFile) -> Option<Pulse> {
        self.pulse_of(channel, registers, false)
    }

    /// The pulse `OCxN` repeats, read as [`Tim::pulse`] reads `OCx`. An output enabled alone isn't
    /// complemented, so it carries the reference's pulse, and one enabled beside `OCx` carries the
    /// reference's inverse, each rising edge delayed by the dead-time, 17.3.11 and 38.3.15.
    #[must_use]
    pub fn complementary_pulse(&self, channel: Channel, registers: &RegisterFile) -> Option<Pulse> {
        self.pulse_of(channel, registers, true)
    }

    fn pulse_of(
        &self,
        channel: Channel,
        registers: &RegisterFile,
        complementary: bool,
    ) -> Option<Pulse> {
        let driven = if complementary {
            self.complementary_output(channel, registers)
        } else {
            self.output(channel, registers)
        };
        driven?;
        let index = channel.index();
        let ccer_value = self.ccer(registers);
        let pair = self.complementary_enabled(index, ccer_value);
        let enabled = if complementary {
            pair
        } else {
            Self::CC_E[index].is_set(ccer_value)
        };
        let plain = self.counting
            && !self.external
            && self.clock_hz != 0
            && !self.center_aligned(registers)
            && self.channel_selection(channel, registers) == CCS_OUTPUT
            && enabled
            && !self.grouped(channel)
            && (self.kind.breaks() == 0 || Self::MOE.is_set(self.reg(registers, Slot::Bdtr)));
        if !plain {
            return None;
        }
        let period = self.arr + 1;
        let compare = self.channels[index].shadow;
        let below = match self.direction {
            Direction::Up => compare.min(period),
            Direction::Down => (compare + 1).min(period),
        };
        let active = match self.output_mode(channel, registers) {
            OCM_PWM_1 => below,
            OCM_PWM_2 => period - below,
            _ => return None,
        };
        let per_count = u128::from(self.psc) + 1;
        let period_cycles = u128::from(period) * per_count;
        let active_cycles = u128::from(active) * per_count;
        let both = pair && Self::CC_E[index].is_set(ccer_value);
        let dead = self.dead_time(registers);
        let (carried, inverted) = if complementary {
            let own = if Self::CC_E[index].is_set(ccer_value) {
                period_cycles - active_cycles
            } else {
                active_cycles
            };
            (
                if both { own.saturating_sub(dead) } else { own },
                Self::CC_NP[index].is_set(ccer_value),
            )
        } else {
            (
                if pair {
                    active_cycles.saturating_sub(dead)
                } else {
                    active_cycles
                },
                Self::CC_P[index].is_set(ccer_value),
            )
        };
        let high_cycles = if inverted {
            period_cycles - carried
        } else {
            carried
        };
        let nanos = |cycles: u128| {
            VirtualNanos(
                u64::try_from(cycles * u128::from(NANOS_PER_SECOND) / u128::from(self.clock_hz))
                    .expect("a period fits the virtual clock"),
            )
        };
        Some(Pulse {
            width: nanos(high_cycles),
            period: nanos(period_cycles),
        })
    }
}