Skip to main content

nros/
levels.rs

1//! The Rust sched task runners' LEVEL
2//! core: one executor per core, a worker per level over it.
3//!
4//! The C-ABI runners reach this through `nros-cpp`'s scheduler FFI
5//! (`nros_cpp_level_open`, `nros_cpp_level_spin_once`); a Rust runner holds
6//! the core's `ExecutorNodeRuntime` itself and uses the same three steps:
7//!
8//! 1. `LevelCore::new` -- the boot level's runtime, leaked for the image's
9//!    life, with the port's recursive priority-inheriting mutex and the
10//!    calling thread's identity installed as the executor's lock
11//!    ([`nros_node::executor::exec_lock::ExecLock`]) when more than one level
12//!    runs, the level count stated, and the boot level made current.
13//! 2. `LevelCore::open_level` + `LevelCore::with_runtime` -- on a level's
14//!    own thread: its worker record (leaked with the level), its waiter
15//!    linked into the executor's arrival routing, then the image's setup run
16//!    on the shared runtime with the level's groups active and the level
17//!    registering, all under the lock.
18//! 3. `LevelCore::spin_level_once` / `LevelCore::spin_boot_once` -- one
19//!    pass of a level's worker (its band, the lock released around each
20//!    callback, then the ticks of the components its level registered) or
21//!    of the boot level (the executor's own worker: transport, executor-wide
22//!    chores, the boot level's component ticks). A component
23//!    ticks on the level that registered it, never on two.
24//!
25//! 4. `LevelCore::into_runtime`: once every other level's
26//!    thread has stopped and been joined, the boot level takes the runtime
27//!    back (the lock removed), so a hosted runner can close its session and
28//!    return. An RTOS runner never calls it: its levels spin for the image's
29//!    life.
30//!
31//! Every access goes through the raw runtime pointer with the lock taken
32//! first, so no reference to the runtime or its executor is live across
33//! another thread's pass.
34
35use core::{ffi::c_void, time::Duration};
36
37// phase-562 W10 -- re-exported for the `nros::main!` RTIC level runner, which
38// builds each level's waiter as a `static`.
39use nros_node::executor::{
40    Band, BandWorker,
41    exec_lock::{ExecGuard, ExecLock, ExecLockFn, ThreadIdFn},
42};
43pub use nros_node::executor::{BandWaitFn, BandWaiter, WorkerWakeFn};
44
45use crate::{Executor, node_runtime::ExecutorNodeRuntime};
46
47/// The core's runtime, shared by every level of the image. `Copy`: each
48/// level's thread carries the handle.
49#[derive(Clone, Copy)]
50pub struct LevelCore {
51    rt: *mut ExecutorNodeRuntime,
52}
53
54// SAFETY: every access takes the executor's lock first (module docs).
55unsafe impl Send for LevelCore {}
56unsafe impl Sync for LevelCore {}
57
58/// Why a level could not be set up.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum LevelError {
61    /// More levels than `MAX_LEVELS`, or a level past the count.
62    BadLevel,
63    /// The port's mutex was NULL or would not initialise.
64    NoLock,
65}
66
67impl LevelCore {
68    /// Make `runtime` the core's level runtime (leaked for the image's life).
69    ///
70    /// `n_levels` is the image's level count and `boot_level` the level of
71    /// the calling thread. With more than one level, `mutex` must be an
72    /// initialised recursive priority-inheriting mutex that `lock` / `unlock`
73    /// take and give and `thread_id` must name the calling thread: the
74    /// executor carries them so every pass releases the lock around its
75    /// callbacks and the levels preempt each other on one executor.
76    ///
77    /// # Safety
78    /// Called before any second thread can reach the runtime. `mutex` lives
79    /// for the image's life; `thread_id` is equal on one thread and distinct
80    /// across live threads.
81    pub unsafe fn new(
82        runtime: ExecutorNodeRuntime,
83        n_levels: u8,
84        boot_level: u8,
85        mutex: *mut c_void,
86        lock: ExecLockFn,
87        unlock: ExecLockFn,
88        thread_id: ThreadIdFn,
89    ) -> Result<Self, LevelError> {
90        if usize::from(n_levels) > crate::MAX_LEVELS || boot_level >= n_levels.max(1) {
91            return Err(LevelError::BadLevel);
92        }
93        let rt: &'static mut ExecutorNodeRuntime =
94            alloc::boxed::Box::leak(alloc::boxed::Box::new(runtime));
95        if !crate::set_level_count(n_levels.max(1)) {
96            return Err(LevelError::BadLevel);
97        }
98        let exec = rt.executor_mut();
99        if n_levels > 1 {
100            // SAFETY: the caller's contract on `mutex` and `thread_id`.
101            let Some(l) = (unsafe { ExecLock::new(mutex, lock, unlock) }) else {
102                return Err(LevelError::NoLock);
103            };
104            exec.set_exec_lock(Some(unsafe { l.with_thread_id(thread_id) }));
105        }
106        if !exec.set_level(boot_level) {
107            return Err(LevelError::BadLevel);
108        }
109        exec.set_registering_level(boot_level);
110        Ok(Self { rt })
111    }
112
113    /// The core's executor, through the raw pointer (no reference made).
114    fn exec(&self) -> *mut Executor<'static> {
115        // SAFETY: `rt` is the leaked runtime; only the field address is taken.
116        unsafe { ExecutorNodeRuntime::executor_ptr(self.rt) }
117    }
118
119    /// Run `f` on the core's runtime with the lock held.
120    ///
121    /// # Safety
122    /// No reference to the runtime obtained here outlives `f`.
123    pub unsafe fn with_runtime<R>(&self, f: impl FnOnce(&mut ExecutorNodeRuntime) -> R) -> R {
124        // SAFETY: the executor is live; the lock is taken before the reference.
125        let _g = unsafe { ExecGuard::acquire(self.exec()) };
126        // SAFETY: under the lock no other thread touches the runtime (the
127        // callback windows of a pass touch only the executor's own state).
128        f(unsafe { &mut *self.rt })
129    }
130
131    /// Open level `level` on the calling thread: its worker (leaked with the
132    /// level) attached to the executor's arrival routing and the level made
133    /// the registering one. Returns the worker the thread's passes use.
134    ///
135    /// # Safety
136    /// Called once per level, on the level's own thread.
137    pub unsafe fn open_level(&self, level: u8) -> Result<&'static mut BandWorker, LevelError> {
138        unsafe { self.open_level_with(level, BandWaiter::platform()) }
139    }
140
141    // phase-562 W10.
142    /// [`Self::open_level`] with the level's own waiter, for a
143    /// runner whose levels cannot wait on the platform's wake object (an RTIC
144    /// level runs to completion: its waiter's `wake` spawns its task, and its
145    /// `wait` returns at once).
146    ///
147    /// # Safety
148    /// As [`Self::open_level`].
149    // The worker is LEAKED here (`Box::leak`), so the `&'static mut` is new
150    // and unaliased; it borrows nothing from `waiter`, which the worker only
151    // links to.
152    #[allow(clippy::mut_from_ref)]
153    pub unsafe fn open_level_with(
154        &self,
155        level: u8,
156        waiter: Option<&'static BandWaiter>,
157    ) -> Result<&'static mut BandWorker, LevelError> {
158        if usize::from(level) >= crate::MAX_LEVELS {
159            return Err(LevelError::BadLevel);
160        }
161        let worker = match waiter {
162            Some(w) => BandWorker::new(level, Band::ALL).with_waiter(w),
163            None => BandWorker::new(level, Band::ALL),
164        };
165        let worker: &'static mut BandWorker =
166            alloc::boxed::Box::leak(alloc::boxed::Box::new(worker));
167        // SAFETY: as `with_runtime`.
168        unsafe {
169            self.with_runtime(|rt| {
170                let exec = rt.executor_mut();
171                exec.attach_band_worker(worker);
172                exec.set_registering_level(level);
173            })
174        };
175        Ok(worker)
176    }
177
178    /// One pass of a spawned level's worker: it parks (its waiter, the lock
179    /// released) for at most `timeout` or until its band's next timer or an
180    /// arrival, then runs its band's ready callbacks and the
181    /// ticks of the components its level registered -- the executor's
182    /// enrolled ones inside the band pass, the runtime's own after it, the
183    /// lock held. Returns the pass's counts.
184    ///
185    /// # Safety
186    /// `worker` is the calling thread's, from [`Self::open_level`].
187    pub unsafe fn spin_level_once(
188        &self,
189        worker: &mut BandWorker,
190        timeout: Duration,
191    ) -> nros_node::SpinOnceResult {
192        let exec = self.exec();
193        // SAFETY: the lock is held once; no reference to the executor lives.
194        let _g = unsafe { ExecGuard::acquire(exec) };
195        let result = unsafe { Executor::spin_band_once(exec, worker, timeout) };
196        // SAFETY: under the lock no other thread touches the runtime.
197        unsafe { (*self.rt).run_ticks_for(Some(worker.level())) };
198        result
199    }
200
201    /// The teardown: take the runtime back from the levels,
202    /// the executor's lock removed, for the caller to close its session
203    /// (`Executor::close`) and drop it. The level workers stay leaked, as
204    /// they were for the image's life, and the level count stays stated.
205    ///
206    /// # Safety
207    /// Called once, on the boot level's thread, after every other thread
208    /// that reached the runtime (each level's worker, any callback it ran)
209    /// has stopped and been joined; no copy of this `LevelCore` is used
210    /// afterwards.
211    pub unsafe fn into_runtime(self) -> ExecutorNodeRuntime {
212        // SAFETY: `rt` came from `Box::leak` in `new`, and the caller's
213        // contract makes this the only live handle to it.
214        let mut rt = unsafe { alloc::boxed::Box::from_raw(self.rt) };
215        rt.executor_mut().set_exec_lock(None);
216        *rt
217    }
218
219    /// The budget a level runner passes to
220    /// [`Self::spin_level_once`] / [`Self::spin_boot_once`]: the runtime's
221    /// [`ExecutorNodeRuntime::entry_spin_budget`]. Each park already ends at
222    /// the level's next deadline or on an arrival, so the budget is not a
223    /// cadence; passing the tier's period instead woke every idle level once a
224    /// period. Ask it after the levels' setup, which is what registers the
225    /// components whose ticks keep the short budget.
226    ///
227    /// # Safety
228    /// As [`Self::with_runtime`].
229    pub unsafe fn entry_spin_budget(&self) -> Duration {
230        // SAFETY: the caller's contract.
231        unsafe { self.with_runtime(|rt| rt.entry_spin_budget()) }
232    }
233
234    // Issue 2967.
235    /// Declare the boot level's cadence, its sched task's `spin_period_us`, as
236    /// the period of the release grid its [`Self::spin_boot_once`] loop runs
237    /// on (`Executor::set_spin_nominal_wait_paced_us`).
238    ///
239    /// The boot level spins the executor's own pass, which judges release
240    /// jitter against a grid. With no cadence declared that grid's period is
241    /// the timeout, and the timeout is now [`Self::entry_spin_budget`], which
242    /// is not a cadence. Declared, the grid is the period in microseconds and
243    /// the budget stays a bound on each wait. A spawned level's pass keeps no
244    /// grid and needs none.
245    ///
246    /// # Safety
247    /// As [`Self::with_runtime`].
248    pub unsafe fn set_boot_cadence_us(&self, spin_period_us: u64) {
249        // SAFETY: the caller's contract.
250        unsafe {
251            self.with_runtime(|rt| {
252                rt.executor_mut()
253                    .set_spin_nominal_wait_paced_us(spin_period_us)
254            })
255        }
256    }
257
258    /// Wake every level's worker and the boot level, for a
259    /// runner that is stopping them: a level parked on the long budget would
260    /// otherwise see its stop flag only at its next deadline. Lock-free.
261    pub fn wake_all(&self) {
262        // SAFETY: the runtime is live for the image's life (leaked in `new`);
263        // `wake_all_workers` reads the executor's wake context, written at
264        // open and never replaced, and signals lock-free.
265        unsafe { (*self.exec()).wake_all_workers() }
266    }
267
268    /// One pass of the boot level: the executor's own worker (transport,
269    /// executor-wide chores), then the boot level's components' ticks, the
270    /// lock held except around each callback.
271    ///
272    /// # Safety
273    /// Called from the boot level's thread only.
274    pub unsafe fn spin_boot_once(&self, timeout: Duration) -> nros_node::SpinOnceResult {
275        // SAFETY: as `spin_level_once`; the ticks run under the same guard.
276        unsafe { ExecutorNodeRuntime::spin_once_shared(self.rt, timeout) }
277    }
278}
279
280// phase-562 W10.
281/// Levels that RUN TO COMPLETION: one pass per wake, never a
282/// blocking wait.
283///
284/// An RTIC level is a software task at its own hardware priority. A level
285/// that parked on a timed wait, as a threaded RTOS's level does, would hold
286/// its priority and starve every level below it, the boot level's transport
287/// included. So each non-boot level's task does ONE band pass
288/// ([`LevelCore::spin_level_once`] with a zero timeout) per wake, and two
289/// things wake it:
290///
291/// * an arrival in its band, through the level's [`BandWaiter`], whose `wake`
292///   the image points at "spawn this level's task" ([`LevelCore::open_level_with`]);
293/// * its band's next timer, through ONE board one-shot armed at the earliest
294///   deadline over the non-boot levels ([`Self::rearm`]). Without it a higher
295///   band's due timer would wait out the boot level's park, which is bounded
296///   by the boot band's own timers only.
297///
298/// A band's deadline is read at the end of that level's own pass, the one
299/// moment it is exact (a band's timers are credited their elapsed time by its
300/// own passes), and kept as an absolute time per level.
301///
302/// A `const` static: the image's boot task [`Self::install`]s the core once,
303/// before any level runs, and every level and the wake interrupt read it
304/// after.
305pub struct RunToCompletionLevels {
306    core: core::cell::UnsafeCell<Option<LevelCore>>,
307    installed: core::sync::atomic::AtomicBool,
308    workers: [core::sync::atomic::AtomicPtr<BandWorker>; crate::MAX_LEVELS],
309    /// Each level's next timer deadline.
310    times: crate::level_wake::LevelWakeTimes,
311}
312
313// SAFETY: `core` is written once, by `install`, before `installed` is set,
314// and only read after it is observed set; everything else is atomic.
315unsafe impl Sync for RunToCompletionLevels {}
316
317impl RunToCompletionLevels {
318    /// An empty runner, for a `static`.
319    pub const fn new() -> Self {
320        Self {
321            core: core::cell::UnsafeCell::new(None),
322            installed: core::sync::atomic::AtomicBool::new(false),
323            workers: [const { core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()) };
324                crate::MAX_LEVELS],
325            times: crate::level_wake::LevelWakeTimes::new(),
326        }
327    }
328
329    /// Hand the runner its core, once, before any level task runs. `false`
330    /// when it already has one.
331    ///
332    /// # Safety
333    /// No level task or wake interrupt reads this runner until it returns.
334    pub unsafe fn install(&self, core: LevelCore, boot_level: u8) -> bool {
335        use core::sync::atomic::Ordering;
336        if self.installed.load(Ordering::Acquire) {
337            return false;
338        }
339        unsafe { *self.core.get() = Some(core) };
340        self.times.set_boot(boot_level);
341        self.installed.store(true, Ordering::Release);
342        true
343    }
344
345    /// The core, once installed.
346    pub fn core(&self) -> Option<&LevelCore> {
347        if self.installed.load(core::sync::atomic::Ordering::Acquire) {
348            // SAFETY: written once before `installed` was set (`install`).
349            unsafe { (*self.core.get()).as_ref() }
350        } else {
351            None
352        }
353    }
354
355    /// Record `level`'s band worker (from [`LevelCore::open_level_with`]).
356    pub fn set_worker(&self, level: u8, worker: &'static mut BandWorker) {
357        if let Some(slot) = self.workers.get(usize::from(level)) {
358            slot.store(worker, core::sync::atomic::Ordering::Release);
359        }
360    }
361
362    /// One pass of `level`'s band, then its next deadline is recorded and the
363    /// board one-shot re-armed through `arm`. A level with no worker (or a
364    /// runner not yet installed) does nothing.
365    ///
366    /// # Safety
367    /// Called only from `level`'s own task, never re-entered for one level.
368    pub unsafe fn pass(&self, level: u8, arm: fn(Option<u64>)) {
369        use core::sync::atomic::Ordering;
370        let (Some(core), Some(slot)) = (self.core(), self.workers.get(usize::from(level))) else {
371            return;
372        };
373        let worker = slot.load(Ordering::Acquire);
374        if worker.is_null() {
375            return;
376        }
377        // SAFETY: the worker is this level's alone, and its task is the only
378        // caller for this level.
379        let worker = unsafe { &mut *worker };
380        let _ = unsafe { core.spin_level_once(worker, Duration::ZERO) };
381        let next =
382            unsafe { core.with_runtime(|rt| rt.executor().next_timer_deadline_of_level_us(level)) };
383        self.times.set(level, next, crate::time::now_us() as u32);
384        self.rearm(arm);
385    }
386
387    /// Arm the board one-shot at the earliest deadline over the non-boot
388    /// levels, or disarm it when none has a timer.
389    pub fn rearm(&self, arm: fn(Option<u64>)) {
390        arm(self
391            .times
392            .soonest_after(crate::time::now_us() as u32)
393            .map(u64::from));
394    }
395
396    /// Whether `level`'s next timer is due at `now` (the wake interrupt
397    /// spawns exactly these).
398    pub fn is_due(&self, level: u8, now: u64) -> bool {
399        self.times.is_due(level, now as u32)
400    }
401}
402
403impl Default for RunToCompletionLevels {
404    fn default() -> Self {
405        Self::new()
406    }
407}