Skip to main content

nros_node/executor/
scheduler.rs

1// Copyright (c) 2026, NEWSLab NTU.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The scheduler /
5//! worker split.
6//!
7//! The original per-sched-task dispatcher was one value that both ORDERED ready work
8//! and was the unit of PREEMPTION. The preemption-level model splits it in two:
9//!
10//! - a per-core [`Scheduler`]: the ordered ready set over the core's callback
11//!   slots, each slot's dispatch level, and the band table that says which
12//!   worker owns which levels;
13//! - a per-level [`Worker`]: one contiguous [`Band`] of dispatch levels, its
14//!   park (the deadline sources, the primitive that blocks, and
15//!   what the last park did) and its stack record (the headroom rule's
16//!   bound and state). A worker is the thread that runs its band.
17//!
18//! **One level is today's executor.** [`Executor`](super::Executor) stays the
19//! one-level facade: it holds one [`Worker`] whose band is every level
20//! ([`Band::ALL`]), so its dispatch order, its park and its stack rule are the
21//! ones it always had. The worker's fields are the park and stack fields the
22//! executor used to hold inline, moved and not changed.
23//!
24//! **Preemption between bands is the kernel's**. Each worker
25//! runs at its band's kernel priority and picks only its own band, most
26//! urgent level first, registration order within a level. On one core a less
27//! urgent worker runs only while every more urgent one is parked, so an
28//! arrival in a more urgent band preempts a running callback of a less urgent
29//! one, and the members of one band never preempt each other: an arrival in
30//! the band of the running worker waits for its current callback to return.
31//!
32//! **Waking.** An arrival the transport attributes to its slot
33//! wakes only the worker of that slot's band
34//! ([`Scheduler::arrive`]). An unattributed arrival can only say "something
35//! on this session", so it wakes the most urgent parked worker, which
36//! re-picks ([`Scheduler::arrive_unattributed`]).
37//!
38//! The scheduler's run-time half takes `&self` and is lock-free (one atomic
39//! word of ready bits, one parked flag per worker), so the workers of one core
40//! and the transport's arrival path may all reach it at once. Its set-up half
41//! ([`Scheduler::add_worker`], [`Scheduler::bind_slot`]) takes `&mut self`
42//! and runs before any worker starts.
43//!
44//! Crate-private until the level runners open a scheduler and
45//! its levels through the FFI; until then the executor uses only its one
46//! [`Worker`], and the [`Scheduler`] is driven by its own tests.
47
48// The multi-level half has no in-crate caller before P9.
49#![cfg_attr(not(test), allow(dead_code))]
50
51use core::ffi::c_void;
52
53use portable_atomic::{AtomicBool, AtomicU8, Ordering::SeqCst};
54
55use super::slot_mask::{AtomicSlotMask, SlotMask};
56
57use super::spin::{MAX_WAKE_SOURCES, ParkUntilFn, WakeSourceId, WakeSourceSlot};
58
59const _: () = assert!(MAX_WAKE_SOURCES < 256, "Worker::wake_source_count is a u8");
60
61/// The least urgent dispatch level ([`Priority::dispatch_level`]: `Critical`
62/// 0, `Normal` 1 + rank, `BestEffort` 31).
63///
64/// [`Priority::dispatch_level`]: super::sched_context::Priority::dispatch_level
65pub const MAX_DISPATCH_LEVEL: u8 = 31;
66
67/// Callback slots one scheduler orders: as many as the entity wake's ready
68/// words name (the image's callback count in whole machine words).
69pub const SCHEDULER_SLOTS: usize = super::slot_mask::ATOMIC_SLOTS;
70
71/// Workers (preemption levels) one scheduler can host: the
72/// `CONFIG_NROS_EXECUTOR_MAX_LEVELS` range's upper end.
73pub const MAX_WORKERS: usize = 32;
74
75/// A slot bound to no level yet.
76const UNBOUND: u8 = u8::MAX;
77
78/// A contiguous range of dispatch levels, inclusive at both ends; level 0 is
79/// the most urgent.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct Band {
82    /// The most urgent level in the band: its threshold.
83    pub most_urgent: u8,
84    /// The least urgent level in the band: its floor.
85    pub least_urgent: u8,
86}
87
88impl Band {
89    /// Every level: the one-level executor.
90    pub const ALL: Band = Band {
91        most_urgent: 0,
92        least_urgent: MAX_DISPATCH_LEVEL,
93    };
94
95    /// The band `[most_urgent, least_urgent]`, or `None` when it is empty or
96    /// reaches past the least urgent dispatch level (31).
97    pub const fn new(most_urgent: u8, least_urgent: u8) -> Option<Band> {
98        if most_urgent > least_urgent || least_urgent > MAX_DISPATCH_LEVEL {
99            None
100        } else {
101            Some(Band {
102                most_urgent,
103                least_urgent,
104            })
105        }
106    }
107
108    /// Whether `level` is in the band.
109    pub const fn contains(&self, level: u8) -> bool {
110        level >= self.most_urgent && level <= self.least_urgent
111    }
112}
113
114/// One preemption level: its band, its park and its stack record.
115///
116/// The park (RFC-0106: the platform deadline sources, the one primitive that
117/// blocks, and what the last park asked for and got) and the stack record
118/// (the headroom rule's declared bound and state, phase-436 E3/E4) moved here
119/// from [`Executor`](super::Executor) unchanged; the executor's park and
120/// stack methods read and write its worker's. The fields stay flat, not in a
121/// park and a stack sub-struct, so their small members share padding as they
122/// did inline in the executor.
123pub(crate) struct Worker {
124    /// The level's index in the image, 0 the most urgent (phase-509 P7):
125    /// what [`Executor::level`](super::Executor::level) answers and the
126    /// level its spins check in as.
127    pub(crate) level: u8,
128    /// The dispatch levels this worker runs.
129    pub(crate) band: Band,
130    // ---- the park (RFC-0106) ----
131    /// phase-436 -- the bound the last park was computed with, in us, and the
132    /// source that won it. See `WakeSourceId`.
133    pub(crate) last_park_bound_us: u64,
134    pub(crate) last_park_source: WakeSourceId,
135    /// phase-436 W2 -- the park bound after rounding UP to what the
136    /// platform's wake primitive can express. Kept beside the request rather
137    /// than replacing it: reporting both is what makes the rounding auditable
138    /// instead of silent (issue 1194).
139    pub(crate) last_park_achieved_us: u64,
140    /// phase-436 W6 -- registered platform deadline sources, and how many are
141    /// live. Inline table: no allocator on the targets this exists for.
142    pub(crate) wake_sources: [Option<WakeSourceSlot>; MAX_WAKE_SOURCES],
143    /// A `u8` (it was a `usize` inline in the executor) so it shares the
144    /// worker's small fields' padding: `MAX_WAKE_SOURCES` is far below 256.
145    pub(crate) wake_source_count: u8,
146    /// The single thing that actually blocks. Many sources say WHEN; one
147    /// primitive does the waiting.
148    pub(crate) park_primitive: Option<(ParkUntilFn, *mut c_void)>,
149    /// phase-521 W8 (c) (RFC-0113 D9) -- the last park answered
150    /// [`PARK_YIELDED`](super::spin::PARK_YIELDED) with no wake pending: the
151    /// park slot handed the wait to its framework's scheduler, so the pass
152    /// that ran the park returns without scanning. Cleared by that pass.
153    pub(crate) park_yielded: bool,
154    /// phase-436 W7.b (issue 1242) -- the finest park the INSTALLED primitive
155    /// can actually express, in microseconds. `0` = none installed, fall back
156    /// to the `wake_wait_ms` ABI floor.
157    pub(crate) park_granularity_declared_us: u64,
158    // ---- the stack record (phase-436 E3/E4) ----
159    /// Declared minimum stack headroom in bytes for the thread this worker
160    /// runs on; `0` (default) disables the rule. The entry that spawned the
161    /// thread is the one that knows what it gave it.
162    pub(crate) min_stack_headroom_bytes: usize,
163    /// Lowest headroom already reported, so the rule fires on new lows only.
164    /// `usize::MAX` = nothing reported yet.
165    pub(crate) stack_headroom_reported: usize,
166    /// phase-436 E3 -- a minimum is set but the port reports no stack data,
167    /// so the rule will skip every tick.
168    pub(crate) stack_headroom_blind: bool,
169    /// phase-436 E4 -- when the headroom query last ran (`None` = never; a
170    /// clockless build stores `Some(0)` to mean "has run"), spins since, and
171    /// how many queries actually reached the port.
172    pub(crate) stack_headroom_last_check_us: Option<u64>,
173    pub(crate) stack_headroom_spins_since_check: u32,
174    pub(crate) stack_headroom_checks: u32,
175    /// phase-509 P9b item 4 -- the level that owns callbacks registered now
176    /// (`Executor::set_registering_level`); [`NO_OWNING_LEVEL`] until a level
177    /// runner first sets one, which is every image's band-of-levels mode. An
178    /// executor-wide fact, kept here among the worker's small fields so it
179    /// shares their padding.
180    pub(crate) registering_level: u8,
181    /// Issue 2018 -- the scheduling context the callbacks registered now
182    /// bind to when no node or group binding names one: the registering
183    /// level's own (`Executor::set_level_sched_context`), else 0, the
184    /// default. Reset to 0 whenever the registering level changes.
185    pub(crate) registering_sched: u8,
186}
187
188/// phase-509 P9b item 4 -- no level owns slots by registration.
189pub(crate) const NO_OWNING_LEVEL: u8 = u8::MAX;
190
191impl Worker {
192    /// The one-level executor's worker: every dispatch level, nothing parked
193    /// or recorded yet.
194    pub(crate) const fn one_level() -> Self {
195        Self {
196            level: 0,
197            band: Band::ALL,
198            last_park_bound_us: 0,
199            last_park_source: WakeSourceId::CallerBudget,
200            last_park_achieved_us: 0,
201            wake_sources: [None; MAX_WAKE_SOURCES],
202            wake_source_count: 0,
203            park_primitive: None,
204            park_yielded: false,
205            park_granularity_declared_us: 0,
206            min_stack_headroom_bytes: 0,
207            stack_headroom_reported: usize::MAX,
208            stack_headroom_blind: false,
209            stack_headroom_last_check_us: None,
210            stack_headroom_spins_since_check: 0,
211            stack_headroom_checks: 0,
212            registering_level: NO_OWNING_LEVEL,
213            registering_sched: 0,
214        }
215    }
216}
217
218/// How a band worker waits on its own wake object:
219/// at most `us` microseconds, returning early when the object is signalled
220/// (`WorkerWakeFn`). The answer is ignored: either way the worker re-scans.
221pub type BandWaitFn = unsafe extern "C" fn(ctx: *mut c_void, us: u64) -> i32;
222
223/// A band worker's
224/// wake object and the slots it answers for. The transport's arrival path
225/// reads it without the executor's lock, so it is `'static` and its fields
226/// are atomics or fixed at construction; it is linked into the executor's
227/// arrival routing by [`Executor::attach_band_worker`](super::Executor::attach_band_worker)
228/// and never unlinked.
229pub struct BandWaiter {
230    /// The band's slots, as the worker's last pass saw them. An arrival on
231    /// one of them wakes this worker only.
232    pub(crate) slots: AtomicSlotMask,
233    /// Signals the wake object (`k_sem_give`, a futex post).
234    #[cfg_attr(not(all(feature = "alloc", feature = "rmw-cffi")), allow(dead_code))]
235    // the arrival path
236    pub(crate) wake: WorkerWakeFn,
237    /// Issue 2696 -- signals it from an interrupt handler (or, on POSIX, a
238    /// signal handler): `xSemaphoreGiveFromISR`, `k_sem_give`, an RTIC
239    /// `spawn`. What [`GuardCondition::trigger_from_isr`](super::GuardCondition::trigger_from_isr)
240    /// reaches, so an interrupt never calls a thread-only `wake`.
241    #[cfg_attr(not(all(feature = "alloc", feature = "rmw-cffi")), allow(dead_code))]
242    pub(crate) wake_from_isr: WorkerWakeFn,
243    /// Waits on it, bounded.
244    pub(crate) wait: BandWaitFn,
245    pub(crate) ctx: *mut c_void,
246    /// The next waiter of the same executor.
247    #[cfg_attr(not(all(feature = "alloc", feature = "rmw-cffi")), allow(dead_code))]
248    // the arrival path
249    pub(crate) next: portable_atomic::AtomicPtr<BandWaiter>,
250}
251
252// SAFETY: `ctx` is the port's wake object, handed in with the two functions
253// that use it, callable from any thread (as `Scheduler::add_worker`'s wake);
254// everything else is atomic.
255unsafe impl Sync for BandWaiter {}
256// SAFETY: as above.
257unsafe impl Send for BandWaiter {}
258
259impl BandWaiter {
260    /// A waiter over the port's wake object at `ctx`.
261    // Issue 2696.
262    /// Every waiter states its interrupt-safe wake: a band an
263    /// interrupt cannot wake would wait out its park instead. Pass `wake`
264    /// again where the port's thread wake is already interrupt-safe.
265    ///
266    /// # Safety
267    /// `wake` and `wait` are callable from any thread with `ctx`, and
268    /// `wake_from_isr` from an interrupt handler (on POSIX, a signal
269    /// handler) with it. `ctx` outlives every executor the waiter is attached
270    /// to.
271    pub const unsafe fn new(
272        wake: WorkerWakeFn,
273        wake_from_isr: WorkerWakeFn,
274        wait: BandWaitFn,
275        ctx: *mut c_void,
276    ) -> Self {
277        Self {
278            slots: AtomicSlotMask::new(),
279            wake,
280            wake_from_isr,
281            wait,
282            ctx,
283            next: portable_atomic::AtomicPtr::new(core::ptr::null_mut()),
284        }
285    }
286
287    /// Signal the worker.
288    #[cfg_attr(not(all(feature = "alloc", feature = "rmw-cffi")), allow(dead_code))] // the arrival path
289    pub(crate) fn signal(&self) {
290        // SAFETY: `new`'s contract.
291        unsafe { (self.wake)(self.ctx) };
292    }
293
294    // Issue 2696.
295    /// Signal the worker from an interrupt handler.
296    #[cfg_attr(not(all(feature = "alloc", feature = "rmw-cffi")), allow(dead_code))]
297    pub(crate) fn signal_from_isr(&self) {
298        // SAFETY: `new`'s contract.
299        unsafe { (self.wake_from_isr)(self.ctx) };
300    }
301
302    /// Wait at most `us` microseconds, or until signalled.
303    pub(crate) fn wait_us(&self, us: u64) {
304        // SAFETY: `new`'s contract.
305        let _ = unsafe { (self.wait)(self.ctx, us) };
306    }
307}
308
309/// A worker of one band
310/// over an executor it shares with other workers: the record its own thread
311/// owns and hands to [`Executor::spin_band_once`](super::Executor::spin_band_once).
312///
313/// A band pass runs only the band's callbacks, and credits the band's timers
314/// with the time since this worker's own previous pass, so two workers never
315/// split one timer's elapsed time between them. With a [`BandWaiter`]
316/// (item 3) it parks on its own wake object until its band's next timer is
317/// due or an arrival in its band signals it.
318#[derive(Clone, Copy, Debug)]
319pub struct BandWorker {
320    /// The level's index in the image, 0 the most urgent: what its passes
321    /// check in as (`level_liveness`).
322    pub(crate) level: u8,
323    /// The dispatch levels this worker runs.
324    pub(crate) band: Band,
325    /// When this worker's previous pass read the clock; `None` before its
326    /// first.
327    pub(crate) last_spin_end_us: Option<u64>,
328    /// phase-509 P9b item 3 -- its wake object, if it parks.
329    pub(crate) waiter: Option<&'static BandWaiter>,
330}
331
332impl core::fmt::Debug for BandWaiter {
333    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
334        f.debug_struct("BandWaiter")
335            .field("slots", &self.slots.load())
336            .finish_non_exhaustive()
337    }
338}
339
340impl BandWorker {
341    /// The worker of `band` at image level `level`, polling (no park).
342    pub const fn new(level: u8, band: Band) -> Self {
343        Self {
344            level,
345            band,
346            last_spin_end_us: None,
347            waiter: None,
348        }
349    }
350
351    /// The same worker, parking on `waiter`. Attach
352    /// it to the executor ([`Executor::attach_band_worker`](super::Executor::attach_band_worker))
353    /// so its band's arrivals signal it.
354    pub const fn with_waiter(self, waiter: &'static BandWaiter) -> Self {
355        Self {
356            waiter: Some(waiter),
357            ..self
358        }
359    }
360
361    /// The band this worker runs.
362    pub const fn band(&self) -> Band {
363        self.band
364    }
365
366    /// The image level this worker checks in as, 0 the most
367    /// urgent: whose components' ticks its passes run.
368    pub const fn level(&self) -> u8 {
369        self.level
370    }
371}
372
373/// How a scheduler signals a worker's wake object (`NodeWake` on a real
374/// port; a mock kernel in the tests).
375pub type WorkerWakeFn = unsafe extern "C" fn(ctx: *mut c_void);
376
377/// A worker's index in its scheduler, 0 the most urgent.
378#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
379pub struct WorkerId(pub u8);
380
381/// Why a scheduler refused a set-up step.
382#[derive(Clone, Copy, Debug, PartialEq, Eq)]
383pub enum LevelSetupError {
384    /// [`MAX_WORKERS`] workers are already added.
385    TooManyWorkers,
386    /// The band does not start right after the previous worker's (the first
387    /// at level 0): bands partition the levels, most urgent first.
388    NotContiguous { expected_most_urgent: u8, got: u8 },
389    /// The slot is past [`SCHEDULER_SLOTS`], or the level past
390    /// [`MAX_DISPATCH_LEVEL`].
391    OutOfRange,
392}
393
394struct Seat {
395    band: Band,
396    wake: Option<(WorkerWakeFn, *mut c_void)>,
397    parked: AtomicBool,
398}
399
400/// The per-core half: the ordered ready set and the band table.
401pub struct Scheduler {
402    /// Each slot's dispatch level; [`UNBOUND`] when no callback is bound.
403    slot_level: [AtomicU8; SCHEDULER_SLOTS],
404    /// One bit per slot with work queued.
405    ready: AtomicSlotMask,
406    seats: [Option<Seat>; MAX_WORKERS],
407    workers: u8,
408}
409
410// SAFETY: the raw wake contexts are handed in by the port together with the
411// function that reads them, and must be callable from any thread (the same
412// contract as a backend's wake callback). Everything else is atomic or set up
413// through `&mut self` before the workers start.
414unsafe impl Sync for Scheduler {}
415// SAFETY: as above; nothing in it is tied to the creating thread.
416unsafe impl Send for Scheduler {}
417
418impl Default for Scheduler {
419    fn default() -> Self {
420        Self::new()
421    }
422}
423
424impl Scheduler {
425    pub const fn new() -> Self {
426        Self {
427            slot_level: [const { AtomicU8::new(UNBOUND) }; SCHEDULER_SLOTS],
428            ready: AtomicSlotMask::new(),
429            seats: [const { None }; MAX_WORKERS],
430            workers: 0,
431        }
432    }
433
434    /// Add the next worker, less urgent than every one added before it. Its
435    /// band must start right after the previous band's floor (the first at
436    /// level 0): the bands partition the levels and are contiguous.
437    /// `wake` signals its wake object; `None` for a worker nothing has
438    /// to wake (a test, or a worker that polls).
439    pub fn add_worker(
440        &mut self,
441        band: Band,
442        wake: Option<(WorkerWakeFn, *mut c_void)>,
443    ) -> Result<WorkerId, LevelSetupError> {
444        let idx = self.workers as usize;
445        if idx >= MAX_WORKERS {
446            return Err(LevelSetupError::TooManyWorkers);
447        }
448        let expected = match idx {
449            0 => 0,
450            _ => match &self.seats[idx - 1] {
451                Some(prev) => prev.band.least_urgent + 1,
452                None => 0,
453            },
454        };
455        if band.most_urgent != expected {
456            return Err(LevelSetupError::NotContiguous {
457                expected_most_urgent: expected,
458                got: band.most_urgent,
459            });
460        }
461        self.seats[idx] = Some(Seat {
462            band,
463            wake,
464            parked: AtomicBool::new(false),
465        });
466        self.workers += 1;
467        Ok(WorkerId(idx as u8))
468    }
469
470    /// Workers added.
471    pub fn worker_count(&self) -> usize {
472        self.workers as usize
473    }
474
475    /// Bind callback `slot` to dispatch `level`.
476    pub fn bind_slot(&mut self, slot: usize, level: u8) -> Result<(), LevelSetupError> {
477        if slot >= SCHEDULER_SLOTS || level > MAX_DISPATCH_LEVEL {
478            return Err(LevelSetupError::OutOfRange);
479        }
480        self.slot_level[slot].store(level, SeqCst);
481        Ok(())
482    }
483
484    /// The worker whose band holds `level`; `None` when no band does.
485    pub fn worker_of(&self, level: u8) -> Option<WorkerId> {
486        self.seats[..self.workers as usize]
487            .iter()
488            .position(|s| s.as_ref().is_some_and(|s| s.band.contains(level)))
489            .map(|i| WorkerId(i as u8))
490    }
491
492    /// The band `worker` runs.
493    pub fn band(&self, worker: WorkerId) -> Option<Band> {
494        self.seat(worker).map(|s| s.band)
495    }
496
497    fn seat(&self, worker: WorkerId) -> Option<&Seat> {
498        self.seats
499            .get(worker.0 as usize)
500            .and_then(Option::as_ref)
501            .filter(|_| (worker.0) < self.workers)
502    }
503
504    fn wake(&self, worker: WorkerId) {
505        if let Some(seat) = self.seat(worker)
506            && let Some((wake, ctx)) = seat.wake
507        {
508            // SAFETY: the port handed `wake` and `ctx` in together, callable
509            // from any thread (see `add_worker`).
510            unsafe { wake(ctx) };
511        }
512    }
513
514    /// An arrival attributed to `slot` queues it and wakes only
515    /// the worker of its band. Returns that worker; `None` when the slot is
516    /// bound to no level a band holds, which is then woken as an
517    /// unattributed arrival would be.
518    pub fn arrive(&self, slot: usize) -> Option<WorkerId> {
519        let Some(level) = self.slot_level.get(slot).map(|l| l.load(SeqCst)) else {
520            return self.arrive_unattributed();
521        };
522        // The bit first, so a worker the wake reaches sees it.
523        self.ready.set(slot);
524        match self.worker_of(level) {
525            Some(w) => {
526                self.wake(w);
527                Some(w)
528            }
529            None => self.arrive_unattributed(),
530        }
531    }
532
533    /// An arrival nothing attributes wakes the most urgent
534    /// parked worker, which re-picks. `None` when no worker is parked: a
535    /// running worker re-picks after its current callback anyway.
536    pub fn arrive_unattributed(&self) -> Option<WorkerId> {
537        let w = self.seats[..self.workers as usize]
538            .iter()
539            .position(|s| s.as_ref().is_some_and(|s| s.parked.load(SeqCst)))
540            .map(|i| WorkerId(i as u8))?;
541        self.wake(w);
542        Some(w)
543    }
544
545    /// Record that `worker` is parked (`true`) or running (`false`).
546    pub fn set_parked(&self, worker: WorkerId, parked: bool) {
547        if let Some(seat) = self.seat(worker) {
548            seat.parked.store(parked, SeqCst);
549        }
550    }
551
552    /// Whether `worker` is parked.
553    pub fn is_parked(&self, worker: WorkerId) -> bool {
554        self.seat(worker).is_some_and(|s| s.parked.load(SeqCst))
555    }
556
557    /// Whether any slot in `worker`'s band has work queued.
558    pub fn has_work(&self, worker: WorkerId) -> bool {
559        let Some(band) = self.band(worker) else {
560            return false;
561        };
562        self.ready
563            .load()
564            .iter_ones()
565            .any(|s| band.contains(self.slot_level[s].load(SeqCst)))
566    }
567
568    /// Take the most urgent queued slot of `worker`'s band: the lowest
569    /// dispatch level, registration (slot) order within a level. `None`
570    /// when its band has nothing queued.
571    pub fn pick(&self, worker: WorkerId) -> Option<usize> {
572        let band = self.band(worker)?;
573        loop {
574            let ready: SlotMask = self.ready.load();
575            let mut best: Option<(u8, usize)> = None;
576            for s in ready.iter_ones() {
577                let level = self.slot_level[s].load(SeqCst);
578                if band.contains(level) && best.is_none_or(|(l, _)| level < l) {
579                    best = Some((level, s));
580                }
581            }
582            let (_, slot) = best?;
583            // One compare-exchange on the word holding the slot: it is taken
584            // only if that word is still as read, as the one word was.
585            if self.ready.clear_if_word_unchanged(slot, &ready) {
586                return Some(slot);
587            }
588        }
589    }
590
591    /// Run `worker`'s band until it has nothing queued: pick, dispatch, pick
592    /// again from the ready set as it is now. Returns how many
593    /// callbacks ran.
594    pub fn run(&self, worker: WorkerId, mut dispatch: impl FnMut(usize)) -> usize {
595        let mut ran = 0;
596        while let Some(slot) = self.pick(worker) {
597            dispatch(slot);
598            ran += 1;
599        }
600        ran
601    }
602}
603
604#[cfg(test)]
605mod tests {
606    use super::*;
607    use std::{boxed::Box, cell::RefCell, format, string::String, vec, vec::Vec};
608
609    /// A worker index carried as a wake context.
610    fn ctx(i: usize) -> *mut c_void {
611        core::ptr::without_provenance_mut(i)
612    }
613
614    #[test]
615    fn bands_partition_the_levels_most_urgent_first() {
616        let mut s = Scheduler::new();
617        assert_eq!(
618            s.add_worker(Band::new(1, 3).unwrap(), None),
619            Err(LevelSetupError::NotContiguous {
620                expected_most_urgent: 0,
621                got: 1
622            })
623        );
624        assert_eq!(
625            s.add_worker(Band::new(0, 3).unwrap(), None),
626            Ok(WorkerId(0))
627        );
628        assert!(matches!(
629            s.add_worker(Band::new(5, 9).unwrap(), None),
630            Err(LevelSetupError::NotContiguous { .. })
631        ));
632        assert_eq!(
633            s.add_worker(Band::new(4, 31).unwrap(), None),
634            Ok(WorkerId(1))
635        );
636        assert_eq!(s.worker_count(), 2);
637        assert_eq!(s.worker_of(2), Some(WorkerId(0)));
638        assert_eq!(s.worker_of(4), Some(WorkerId(1)));
639        assert_eq!(Band::new(3, 2), None);
640        assert_eq!(Band::new(0, 32), None);
641    }
642
643    /// One band is today's order: most urgent level first, registration
644    /// order within a level.
645    #[test]
646    fn one_band_picks_by_level_then_registration() {
647        let mut s = Scheduler::new();
648        s.add_worker(Band::ALL, None).unwrap();
649        for (slot, level) in [(0, 3), (1, 1), (2, 3), (3, 1)] {
650            s.bind_slot(slot, level).unwrap();
651        }
652        for slot in [2, 0, 3, 1] {
653            s.arrive(slot);
654        }
655        let mut order = vec![];
656        s.run(WorkerId(0), |slot| order.push(slot));
657        assert_eq!(order, [1, 3, 0, 2]);
658    }
659
660    /// D7: an attributed arrival wakes only its band's worker; an
661    /// unattributed one the most urgent parked worker.
662    #[test]
663    fn an_arrival_wakes_only_its_bands_worker() {
664        static WOKEN: [AtomicU8; 2] = [AtomicU8::new(0), AtomicU8::new(0)];
665        unsafe extern "C" fn wake(ctx: *mut c_void) {
666            WOKEN[ctx as usize].fetch_add(1, SeqCst);
667        }
668        let mut s = Scheduler::new();
669        s.add_worker(Band::new(0, 1).unwrap(), Some((wake, ctx(0))))
670            .unwrap();
671        s.add_worker(Band::new(2, 31).unwrap(), Some((wake, ctx(1))))
672            .unwrap();
673        s.bind_slot(0, 1).unwrap();
674        s.bind_slot(1, 5).unwrap();
675        assert_eq!(s.arrive(1), Some(WorkerId(1)));
676        assert_eq!(
677            (WOKEN[0].load(SeqCst), WOKEN[1].load(SeqCst)),
678            (0, 1),
679            "a band-1 arrival does not wake band 0"
680        );
681        assert_eq!(s.arrive(0), Some(WorkerId(0)));
682        assert_eq!((WOKEN[0].load(SeqCst), WOKEN[1].load(SeqCst)), (1, 1));
683        // Nobody parked: an unattributed arrival wakes nobody (each running
684        // worker re-picks after its callback).
685        assert_eq!(s.arrive_unattributed(), None);
686        s.set_parked(WorkerId(1), true);
687        assert!(s.is_parked(WorkerId(1)) && !s.is_parked(WorkerId(0)));
688        assert_eq!(s.arrive_unattributed(), Some(WorkerId(1)));
689        s.set_parked(WorkerId(0), true);
690        assert_eq!(s.arrive_unattributed(), Some(WorkerId(0)));
691        // Each worker picks only its own band.
692        assert_eq!(s.pick(WorkerId(0)), Some(0));
693        assert_eq!(s.pick(WorkerId(0)), None);
694        assert!(s.has_work(WorkerId(1)));
695        assert_eq!(s.pick(WorkerId(1)), Some(1));
696    }
697
698    // ---- a deterministic one-core kernel -------------------------------
699    //
700    // Fixed-priority preemptive, one core, no time: a woken worker more
701    // urgent than the one running runs at once (nested inside the running
702    // callback, which is where a real kernel would preempt it); any other
703    // wake is pending until the running worker returns. Each callback is a
704    // script of arrivals it raises mid-run.
705
706    struct Kernel {
707        sched: &'static Scheduler,
708        running: Vec<WorkerId>,
709        pending: Vec<WorkerId>,
710        scripts: Vec<Vec<usize>>,
711        trace: Vec<String>,
712    }
713
714    std::thread_local! {
715        static KERNEL: RefCell<Option<Kernel>> = const { RefCell::new(None) };
716    }
717
718    fn with<R>(f: impl FnOnce(&mut Kernel) -> R) -> R {
719        KERNEL.with(|k| f(k.borrow_mut().as_mut().expect("kernel installed")))
720    }
721
722    unsafe extern "C" fn kernel_wake(ctx: *mut c_void) {
723        let w = WorkerId(ctx as usize as u8);
724        let preempts = with(|k| {
725            let current = k.running.last().copied();
726            if current.is_none_or(|c| w < c) {
727                true
728            } else {
729                if !k.pending.contains(&w) && current != Some(w) {
730                    k.pending.push(w);
731                }
732                false
733            }
734        });
735        if preempts {
736            run_worker(w);
737        }
738    }
739
740    fn run_worker(w: WorkerId) {
741        let sched = with(|k| {
742            k.running.push(w);
743            k.sched
744        });
745        sched.set_parked(w, false);
746        sched.run(w, |slot| {
747            let script = with(|k| {
748                k.trace.push(format!("start {slot}"));
749                k.scripts[slot].clone()
750            });
751            for raised in script {
752                sched.arrive(raised);
753            }
754            with(|k| k.trace.push(format!("end {slot}")));
755        });
756        sched.set_parked(w, true);
757        with(|k| k.running.pop());
758        // The kernel's next pick: the most urgent pending worker.
759        loop {
760            let next = with(|k| {
761                k.pending.sort();
762                if k.pending.is_empty() {
763                    None
764                } else {
765                    Some(k.pending.remove(0))
766                }
767            });
768            match next {
769                Some(n) => run_worker(n),
770                None => break,
771            }
772        }
773    }
774
775    /// Band 0 (levels 0-1) holds `H`; band 1 (levels 2-31) holds `A` and
776    /// `B`, `B` the more urgent of the two. Slots: H 0, A 1, B 2.
777    fn two_bands(scripts: Vec<Vec<usize>>) -> &'static Scheduler {
778        let mut s = Scheduler::new();
779        s.add_worker(Band::new(0, 1).unwrap(), Some((kernel_wake, ctx(0))))
780            .unwrap();
781        s.add_worker(Band::new(2, 31).unwrap(), Some((kernel_wake, ctx(1))))
782            .unwrap();
783        s.bind_slot(0, 1).unwrap(); // H
784        s.bind_slot(1, 6).unwrap(); // A
785        s.bind_slot(2, 4).unwrap(); // B
786        let s: &'static Scheduler = Box::leak(Box::new(s));
787        s.set_parked(WorkerId(0), true);
788        s.set_parked(WorkerId(1), true);
789        KERNEL.with(|k| {
790            *k.borrow_mut() = Some(Kernel {
791                sched: s,
792                running: vec![],
793                pending: vec![],
794                scripts,
795                trace: vec![],
796            })
797        });
798        s
799    }
800
801    fn trace() -> Vec<String> {
802        with(|k| k.trace.clone())
803    }
804
805    /// RFC-0108 P6 acceptance: an arrival in the more urgent band preempts a
806    /// running callback of the less urgent band.
807    #[test]
808    fn a_more_urgent_bands_arrival_preempts_a_running_callback() {
809        // A raises H mid-run.
810        let s = two_bands(vec![vec![], vec![0], vec![]]);
811        s.arrive(1);
812        assert_eq!(trace(), ["start 1", "start 0", "end 0", "end 1"]);
813    }
814
815    /// RFC-0108 P6 acceptance: members of one band never preempt each other.
816    /// `B` is more urgent than `A` but in its band, so it waits for `A`.
817    #[test]
818    fn members_of_one_band_never_preempt_each_other() {
819        // A raises B mid-run.
820        let s = two_bands(vec![vec![], vec![2], vec![]]);
821        s.arrive(1);
822        assert_eq!(trace(), ["start 1", "end 1", "start 2", "end 2"]);
823    }
824
825    /// A less urgent band's arrival raised by the more urgent band waits
826    /// for it, and the band's own order holds when both of its members are
827    /// queued: `B` before `A`.
828    #[test]
829    fn a_less_urgent_arrival_waits_and_the_band_keeps_its_order() {
830        // H raises A and B mid-run.
831        let s = two_bands(vec![vec![1, 2], vec![], vec![]]);
832        s.arrive(0);
833        assert_eq!(
834            trace(),
835            ["start 0", "end 0", "start 2", "end 2", "start 1", "end 1"]
836        );
837    }
838}