Skip to main content

nros/
level_wake.rs

1//! The deadlines a run-to-completion level runner wakes its
2//! levels for (`levels::RunToCompletionLevels`), kept apart from it because
3//! this half is pure arithmetic over atomics and needs no executor or platform
4//! port, so its tests run in the lane that links none.
5
6use core::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering};
7
8/// Each level's next timer deadline, as the low 32 bits of a microsecond
9/// clock, compared by wrapping difference: 32-bit atomics, since a Cortex-M3
10/// has no 64-bit ones.
11pub struct LevelWakeTimes {
12    wake_at: [AtomicU32; crate::MAX_LEVELS],
13    armed: [AtomicBool; crate::MAX_LEVELS],
14    boot: AtomicU8,
15}
16
17impl LevelWakeTimes {
18    /// The furthest a deadline is armed ahead: half the 32-bit microsecond
19    /// range (~35 min), so a wrapping difference stays unambiguous. A longer
20    /// one wakes the level early and it re-arms the rest.
21    pub const HORIZON_US: u32 = i32::MAX as u32;
22
23    /// No level armed, boot level 0.
24    pub const fn new() -> Self {
25        Self {
26            wake_at: [const { AtomicU32::new(0) }; crate::MAX_LEVELS],
27            armed: [const { AtomicBool::new(false) }; crate::MAX_LEVELS],
28            boot: AtomicU8::new(0),
29        }
30    }
31
32    /// Which level boots. Its deadline never arms the wake: its own timers
33    /// bound its own park.
34    pub fn set_boot(&self, level: u8) {
35        self.boot.store(level, Ordering::Relaxed);
36    }
37
38    /// Record `level`'s next deadline, `after_us` microseconds after `now`
39    /// (`None`: its band arms no timer).
40    pub fn set(&self, level: u8, after_us: Option<u64>, now: u32) {
41        let i = usize::from(level);
42        if i >= crate::MAX_LEVELS {
43            return;
44        }
45        match after_us {
46            Some(d) => {
47                let d = d.min(u64::from(Self::HORIZON_US)) as u32;
48                self.wake_at[i].store(now.wrapping_add(d), Ordering::Release);
49                self.armed[i].store(true, Ordering::Release);
50            }
51            None => self.armed[i].store(false, Ordering::Release),
52        }
53    }
54
55    /// Microseconds from `now` to the earliest armed non-boot deadline (0 when
56    /// one is already due); `None` when none is armed.
57    pub fn soonest_after(&self, now: u32) -> Option<u32> {
58        let boot = usize::from(self.boot.load(Ordering::Relaxed));
59        (0..crate::MAX_LEVELS)
60            .filter(|i| *i != boot && self.armed[*i].load(Ordering::Acquire))
61            .map(|i| remaining(self.wake_at[i].load(Ordering::Acquire), now))
62            .min()
63    }
64
65    /// Whether `level`'s deadline has passed at `now`.
66    pub fn is_due(&self, level: u8, now: u32) -> bool {
67        let i = usize::from(level);
68        i < crate::MAX_LEVELS
69            && self.armed[i].load(Ordering::Acquire)
70            && remaining(self.wake_at[i].load(Ordering::Acquire), now) == 0
71    }
72}
73
74impl Default for LevelWakeTimes {
75    fn default() -> Self {
76        Self::new()
77    }
78}
79
80/// Microseconds from `now` to `at`, 0 once `at` has passed (both the low 32
81/// bits of one clock).
82fn remaining(at: u32, now: u32) -> u32 {
83    let d = at.wrapping_sub(now) as i32;
84    if d > 0 { d as u32 } else { 0 }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::LevelWakeTimes;
90
91    /// The board one-shot is armed at the earliest NON-boot deadline: the boot
92    /// level's own timers bound its own park, so its deadline never arms it.
93    #[test]
94    fn the_wake_is_armed_at_the_earliest_non_boot_deadline() {
95        let t = LevelWakeTimes::new();
96        t.set_boot(2);
97        assert_eq!(t.soonest_after(1_000), None, "nothing armed: disarm");
98        t.set(2, Some(10), 1_000);
99        assert_eq!(
100            t.soonest_after(1_000),
101            None,
102            "the boot level's deadline is not the wake's"
103        );
104        t.set(0, Some(500), 1_000);
105        t.set(1, Some(200), 1_000);
106        assert_eq!(t.soonest_after(1_000), Some(200));
107        assert_eq!(t.soonest_after(1_300), Some(0), "already due fires at once");
108        t.set(1, None, 1_300);
109        assert_eq!(
110            t.soonest_after(1_300),
111            Some(200),
112            "a band with no timer leaves the wake"
113        );
114    }
115
116    /// Due means the deadline has passed by the clock's own wrapping
117    /// difference, so a deadline just past a 32-bit wrap is still ahead and
118    /// one just before it is still due.
119    #[test]
120    fn due_survives_the_32_bit_wrap() {
121        let t = LevelWakeTimes::new();
122        t.set_boot(1);
123        t.set(0, Some(16), u32::MAX - 10);
124        assert!(!t.is_due(0, u32::MAX - 10), "16 us ahead, across the wrap");
125        assert_eq!(t.soonest_after(u32::MAX - 10), Some(16));
126        assert!(t.is_due(0, 6), "past the deadline after the wrap");
127        assert!(!t.is_due(1, 6), "an unarmed level is never due");
128    }
129
130    /// A deadline past the horizon is armed AT the horizon, so the wrapping
131    /// difference never reads it as passed.
132    #[test]
133    fn a_deadline_past_the_horizon_is_clamped_not_wrapped() {
134        let t = LevelWakeTimes::new();
135        t.set_boot(1);
136        t.set(0, Some(u64::from(u32::MAX) * 4), 0);
137        assert_eq!(t.soonest_after(0), Some(LevelWakeTimes::HORIZON_US));
138        assert!(!t.is_due(0, 0));
139    }
140}