Skip to main content

nros_platform/board/
sched_task.rs

1//! Per-sched-task scheduling descriptors.
2//!
3//! A [`SchedTaskSpec`] names one RTOS task that an `Executor` will run on a
4//! shared RMW session. The orchestration `main()` (codegen-emitted)
5//! passes a `&[SchedTaskSpec]` to the board's `run_sched_tasks(...)`; the board
6//! opens the session once, then spawns one task per spec — each task
7//! opens an `Executor` over the *same* session (the `Borrowed` store),
8//! sets its `active_groups` filter, registers nodes (only its sched task's
9//! callbacks take), and spins. The LEAST urgent sched task runs on the boot
10//! task itself ([`boot_sched_task_index`]); the rest are spawned.
11//!
12//! That last sentence used to read "the highest-priority sched task
13//! runs on the boot task", and it was both wrong and harmful. Boards took
14//! `sched_tasks[0]`, and `resolve_sched_tasks` orders by RAW number descending WITHOUT
15//! inverting per kernel, so `sched_tasks[0]` is the most urgent sched task on
16//! bigger-number-wins kernels (NuttX, FreeRTOS, POSIX) and the least urgent on
17//! smaller-number-wins ones (Zephyr, ThreadX). Which sched task owned the session
18//! therefore depended on the kernel's number direction, which nobody chose.
19//!
20//! On a uniprocessor with FIFO scheduling, an owner that outranks its peers and
21//! then spins starves them: a lower-priority sched task runs only in whatever gap the
22//! owner's `spin_once` happens to leave. Measured on NuttX at 1 of 5 runs
23//! reaching a spawned sched task's first statement at all. `sched_yield` cannot fix
24//! it — under SCHED_FIFO a yield rotates the caller within its OWN priority
25//! queue and never lets a lower-priority thread run, which is why two partial
26//! fixes moved the rate to 4 of 6 and could not converge.
27//!
28//! So the owner is chosen, not inherited from an ordering: it is the sched task that
29//! outranks nothing.
30//!
31//! [`SchedTaskSpec::priority`] is a RAW kernel priority, not a
32//! normalized one. This module doc used to say priorities are declared on a
33//! normalized 0-31 scale: 0 = idle, 12 = normal, 31 = critical,
34//! lowered per RTOS by the mappers below. That has not been true of the
35//! codegen path for a long time - `[tasks.<name>.<rtos>] priority` is written
36//! in the target kernel's own numbering, `resolve_sched_tasks` copies it through
37//! without inverting, and the boards pass it straight to `k_thread_create` /
38//! `xTaskCreate`. The note above about `sched_tasks[0]` depending on the kernel's
39//! direction is that same fact, seen from the other side.
40//!
41//! Where the number COMES FROM: it is allocated out of the board's
42//! priority address plan (`[board.priority_plan]` /
43//! `[priority_plan]` in the descriptors, resolved per image for Zephyr), whose
44//! `pool.app` band a derived sched task is placed in by
45//! `nros-orchestration-ir::rtos_realizer`. An authored sched task is judged against
46//! the same plan by `scripts/check-sched-task-priority-plan*.py`.
47//!
48//! The normalized 0-255 band that DOES exist is the platform ABI's
49//! (`NROS_PLATFORM_PRIORITY_MAX`), and it is the transport's, not a sched task's.
50
51/// One sched task: an RTOS task running an `Executor` over the
52/// shared session, admitting only the listed callback groups.
53///
54/// All fields are literal-constructible so the codegen emitter can bake
55/// a `const`/`static` array of these straight from the resolved sched task
56/// table in `nros-plan.json`.
57#[derive(Clone, Copy, Debug)]
58pub struct SchedTaskSpec<'a> {
59    /// Sched task name (matches the `system.toml [tasks.<name>]` key); used
60    /// for the spawned task's debug name.
61    pub name: &'a str,
62    /// Callback groups admitted on this sched task, as `(node name, node namespace,
63    /// group)`. Passed verbatim to `Executor::set_active_groups`; an empty
64    /// slice = wildcard.
65    ///
66    /// The group id ALONE was ambiguous: two nodes may declare
67    /// the same one on different sched tasks, and the filter admitted both. The C
68    /// side carries the same information as a FLAT array of 3N strings so
69    /// `nros_native_sched_task_spec_t` stays byte-identical; Rust uses a tuple so
70    /// the compiler enforces the grouping instead of a convention doing it.
71    ///
72    /// (the original note follows)
73    /// Passed verbatim to
74    /// `Executor::set_active_groups`; an empty slice = wildcard
75    /// (admit every group — the single-sched-task degenerate case).
76    pub groups: &'a [(&'a str, &'a str, &'a str)],
77    /// **Raw per-RTOS** task priority — the value passed straight to the
78    /// native spawn call. The system author writes it in
79    /// `[tasks.<name>.<rtos>].priority`, so it is already in the target
80    /// kernel's scale (FreeRTOS 0–7, ThreadX 0–31 lower=higher, …);
81    /// `i64` admits Zephyr's negative coop priorities. (The
82    /// `*_priority_for` mappers in this module are a separate utility for
83    /// authors who prefer a normalized 0–31 scale; the codegen path uses
84    /// the raw value verbatim.)
85    pub priority: i64,
86    /// Task stack size in bytes. `0` = let the board pick its default.
87    pub stack_bytes: usize,
88    /// Spin period for this sched task's `spin_once` loop, in microseconds.
89    pub spin_period_us: u64,
90    // -- RFC-0052 / phase-296 W2 — the previously-dropped sched task fields ride
91    // -- the spec end-to-end. Boards consume what their kernel offers; the
92    // -- bake already rejected platform-inapplicable knobs (fail-loud), so
93    // -- an unconsumed Some(..) here is a board TODO, not a silent config
94    // -- loss.
95    /// CPU core to pin the sched task to (SMP boards); `None` = unpinned.
96    pub core: Option<u32>,
97    /// ThreadX preemption threshold (ThreadX targets only; bake-validated).
98    pub preempt_threshold: Option<i64>,
99    /// Round-robin time slice in µs: `Some` requests time-slicing among
100    /// same-priority sched tasks. ThreadX-only today (bake-validated); `None` = FIFO.
101    pub time_slice_us: Option<u64>,
102    /// Scheduling class: `"best_effort"` | `"real_time"` |
103    /// `"time_triggered"` (bake rejects `"interrupt"`); `None` = plain
104    /// priority sched task.
105    pub class: Option<&'a str>,
106    /// Callback period (µs) — `time_triggered` window period / sporadic
107    /// replenishment period.
108    pub period_us: Option<u64>,
109    /// Execution-time budget (µs) — sporadic-server budget (W3 wires it
110    /// into the executor's `SchedContext`).
111    pub budget_us: Option<u64>,
112    /// Relative deadline (µs) for the deadline monitor (W3).
113    pub deadline_us: Option<u64>,
114    /// On deadline miss: `"ignore"` | `"warn"` | `"skip"` | `"fault"`.
115    pub deadline_policy: Option<&'a str>,
116}
117
118/// Which way a kernel's raw priority numbers run.
119///
120/// `SchedTaskSpec::priority` is RAW — the number the system author wrote in
121/// `[tasks.<name>.<rtos>].priority`, already in the target kernel's scale — so
122/// only the board knows which end is urgent.
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub enum PriorityDirection {
125    /// NuttX (1..=255), FreeRTOS (0..=7), POSIX SCHED_FIFO: bigger wins.
126    BiggerIsMoreUrgent,
127    /// Zephyr (negative = cooperative), ThreadX (0..=31): smaller wins.
128    SmallerIsMoreUrgent,
129}
130
131/// Index of the sched task the BOOT task should run: the least urgent one.
132///
133/// The boot task owns the session and spins forever, so it must
134/// not outrank the sched tasks it spawned. See the module docs for what happened when
135/// it did.
136///
137/// * **Ties keep the earliest index**, so a table whose sched tasks all declare the
138///   same priority (or none) behaves exactly as `sched_tasks[0]` did.
139/// * **An undeclared priority is least urgent, but only where 0 is out of
140///   range.** On bigger-wins kernels the valid range starts at 1 and `0` is the
141///   "inherit" sentinel every board already tests for, so a sched task that declared
142///   nothing makes no claim and is the safest owner. On smaller-wins kernels 0
143///   is a REAL priority — a very urgent one on ThreadX — and treating it as a
144///   sentinel would hand the session to the most urgent sched task, which is the bug
145///   this function exists to prevent.
146#[must_use]
147pub fn boot_sched_task_index(
148    sched_tasks: &[SchedTaskSpec<'_>],
149    direction: PriorityDirection,
150) -> usize {
151    /// Bigger = more urgent, in one comparable scale.
152    fn urgency(priority: i64, direction: PriorityDirection) -> i64 {
153        match direction {
154            PriorityDirection::BiggerIsMoreUrgent if priority <= 0 => i64::MIN,
155            PriorityDirection::BiggerIsMoreUrgent => priority,
156            // Negate rather than subtract: the range is the kernel's, and any
157            // fixed origin would be one more number to keep in step with it.
158            PriorityDirection::SmallerIsMoreUrgent => priority.saturating_neg(),
159        }
160    }
161    let mut best = 0;
162    for (i, sched_task) in sched_tasks.iter().enumerate().skip(1) {
163        if urgency(sched_task.priority, direction) < urgency(sched_tasks[best].priority, direction)
164        {
165            best = i;
166        }
167    }
168    best
169}
170
171impl<'a> SchedTaskSpec<'a> {
172    /// A degenerate single sched task: wildcard groups, normal priority, the
173    /// board's default stack. Equivalent to today's single-task entry.
174    pub const fn single() -> SchedTaskSpec<'static> {
175        SchedTaskSpec {
176            name: "default",
177            groups: &[],
178            priority: 0,
179            stack_bytes: 0,
180            spin_period_us: 1_000,
181            core: None,
182            preempt_threshold: None,
183            time_slice_us: None,
184            class: None,
185            period_us: None,
186            budget_us: None,
187            deadline_us: None,
188            deadline_policy: None,
189        }
190    }
191}
192
193/// FreeRTOS native priority (0..=`configMAX_PRIORITIES-1`, here 0–7)
194/// for a normalized 0–31 priority. Linear
195/// interpolation `(n*7 + 15) / 31` (round-to-nearest), so 0→0 (idle)
196/// and 31→7 (highest). Higher number = higher priority on FreeRTOS.
197pub const fn freertos_priority_for(normalized: u8) -> u8 {
198    let n = clamp31(normalized) as u32;
199    ((n * 7 + 15) / 31) as u8
200}
201
202/// ThreadX native priority (0..=31, **lower = higher priority**) for a
203/// normalized 0–31 priority. Inverted scale `31 - n`, so the
204/// normalized idle (0) maps to ThreadX 31 (lowest) and normalized
205/// critical (31) maps to ThreadX 0 (highest).
206pub const fn threadx_priority_for(normalized: u8) -> u8 {
207    31 - clamp31(normalized)
208}
209
210/// POSIX `nice` value (`-20`..=`19`, **lower = more CPU**) for a
211/// normalized 0–31 priority. Best-effort: native preemption normally
212/// uses the default scheduler (strict ordering needs `SCHED_FIFO` +
213/// privileges), so this is an advisory niceness, linear over the scale
214/// and clamped, with idle (0) pinned to the maximum `19`. Anchors track
215/// the normalized scale (12→0 normal, 31→-20 critical).
216pub const fn posix_nice_for(normalized: u8) -> i32 {
217    let n = clamp31(normalized) as i32;
218    if n == 0 {
219        return 19;
220    }
221    // Slope ≈ -1.25 nice/step around the normal anchor (n=12 → 0).
222    let nice = (-5 * (n - 12)) / 4;
223    if nice > 19 {
224        19
225    } else if nice < -20 {
226        -20
227    } else {
228        nice
229    }
230}
231
232// ============================================================================
233// Issue 0636 option 3 — the sched task spin loop's scheduled gap
234// ============================================================================
235//
236// [`boot_sched_task_index`] stopped the starvation by making the session owner the
237// sched task that outranks nothing. That is correct and it is what fixed the issue,
238// but the guarantee it gives rests entirely on the priority ORDER being right:
239// any sched task that outranks another and then spins without blocking can still hold
240// a uniprocessor forever, because under SCHED_FIFO a thread yields the CPU only
241// by blocking (`sched_yield` rotates within the caller's own priority queue and
242// never reaches a lower one).
243//
244// Whether a spin blocks is, today, a property of the TRANSPORT rather than of
245// the sched task. `Executor::spin_once` takes the blocking arm only when nothing has
246// already woken it:
247//
248//     if !was_woken && has_async_wake && node_wake => wake.wait_ms(timeout)
249//     else                                        => drive_io(timeout_ms)
250//
251// The `was_woken` arm drives I/O with a ZERO timeout — deliberately, because a
252// wake means there is data to drain. So under sustained arrival every iteration
253// takes the non-blocking arm, and the loop has no blocking point exactly when
254// the system is busiest. That is the "transport luck" this type removes.
255//
256// # The rule
257//
258// A sched task loop may not run for longer than one INTERVAL without either blocking
259// in its own spin or taking a bounded gap. Both halves are derived from what
260// the author already declared, so there is no new knob:
261//
262// * **interval** = `max(spin_period_us, 10 ms)`. The gap costs 1 ms, so the
263//   floor is what caps the worst-case overhead at 10 %; a sched task that declares a
264//   longer period pays proportionally less.
265// * **"it blocked"** = an iteration took at least half the declared spin
266//   period. A spin that waited its timeout is near the period; a free-running
267//   one is orders of magnitude shorter. Half is the midpoint between them, not
268//   a tuned constant.
269// * **the gap** = `nros_platform_sleep_ms(1)`. Deliberately NOT `sleep_us`:
270//   that one's ABI contract says it may SPIN when the platform has no
271//   sub-millisecond timer, and a spin is not a scheduling point — it would
272//   satisfy the code and not the requirement. 1 ms is the smallest sleep the
273//   ABI guarantees actually blocks.
274//
275// Cost is zero on the blocking path: a loop whose spins wait never opens a
276// window without a block in it, so it never sleeps here.
277//
278// # Why the state is one `u64`
279//
280// The C sched task runners (`*_run_sched_tasks.c`) and the Rust ones must share ONE
281// implementation — a second spelling per language is how the sched-task-priority
282// marker drifted in the first place (see the module docs above). A shared
283// STRUCT would be a hand-mirrored FFI layout, which this repo has been bitten
284// by three times, so the state is a single opaque `u64` that C keeps and passes
285// back: the window's start timestamp with bit 0 carrying "something blocked in
286// this window". One nanosecond of timestamp resolution is the whole cost.
287
288/// Overhead ceiling for the gap: 1 ms of sleep per 10 ms of free-running spin.
289const GAP_INTERVAL_FLOOR_US: u64 = 10_000;
290
291/// The gap itself. The smallest sleep the platform ABI guarantees will BLOCK
292/// rather than spin — see the module note on `sleep_us`.
293const GAP_MS: usize = 1;
294
295/// Gap window length for a sched task that declared `spin_period_us`.
296#[must_use]
297pub const fn gap_interval_us(spin_period_us: u64) -> u64 {
298    let p = spin_period_us;
299    if p > GAP_INTERVAL_FLOOR_US {
300        p
301    } else {
302        GAP_INTERVAL_FLOOR_US
303    }
304}
305
306/// Did this iteration BLOCK? True when it lasted at least half the declared
307/// spin period — see the module note for why half.
308#[must_use]
309pub const fn iteration_blocked(iter_ns: u64, spin_period_us: u64) -> bool {
310    let half_us = spin_period_us / 2;
311    // A sched task declaring a period under 2 us has no meaningful "half"; treat any
312    // measurable time as a block rather than gapping such a loop every window.
313    if half_us == 0 {
314        return iter_ns > 0;
315    }
316    iter_ns >= half_us.saturating_mul(1_000)
317}
318
319/// The whole decision, as a pure function of the clock — so it is testable on a
320/// host with no platform linked, which is the only way the arithmetic below
321/// gets exercised at all (every caller is an RTOS image).
322///
323/// Returns the next state and whether the caller must sleep. `state` is the
324/// value returned by the previous call, or `0` to start a window.
325#[must_use]
326pub const fn gap_step(state: u64, iter_ns: u64, now_ns: u64, spin_period_us: u64) -> (u64, bool) {
327    let window_start_ns = state & !STATE_FLAGS;
328    let blocked_in_window =
329        (state & STATE_BLOCKED) != 0 || iteration_blocked(iter_ns, spin_period_us);
330
331    // First ever call: open a window at `now` and decide nothing yet.
332    //
333    // "Open" is its own BIT, not `state != 0`. The clock's epoch is
334    // platform-defined and a port may legitimately hand out 0 (or 1) on the
335    // first read — and with the timestamp alone as the state, such a port
336    // re-entered this branch on every iteration and the gap never fired at all.
337    // Found by the unit test below, not on a target.
338    if state & STATE_OPEN == 0 {
339        return (open_state(now_ns, blocked_in_window), false);
340    }
341
342    if now_ns.saturating_sub(window_start_ns) < gap_interval_us(spin_period_us) * 1_000 {
343        return (open_state(window_start_ns, blocked_in_window), false);
344    }
345
346    // Window closed. Gap only if nothing in it blocked. Either way the next
347    // window starts here; the caller re-stamps after sleeping (see `SchedTaskSpinGap`)
348    // so the sleep is not charged to the window it opens.
349    (open_state(now_ns, false), !blocked_in_window)
350}
351
352/// Window-open marker — see [`gap_step`] for why the timestamp alone will not do.
353const STATE_OPEN: u64 = 1;
354/// "Something blocked in this window."
355const STATE_BLOCKED: u64 = 2;
356const STATE_FLAGS: u64 = STATE_OPEN | STATE_BLOCKED;
357
358/// Pack a window start (2 ns of resolution given up to the two flag bits).
359#[must_use]
360const fn open_state(window_start_ns: u64, blocked: bool) -> u64 {
361    (window_start_ns & !STATE_FLAGS) | STATE_OPEN | if blocked { STATE_BLOCKED } else { 0 }
362}
363
364/// One sched task spin loop's scheduled gap. Construct beside the loop, call
365/// [`SchedTaskSpinGap::after_spin`] at the bottom of every iteration.
366///
367/// ```ignore
368/// let mut gap = SchedTaskSpinGap::new(sched task.spin_period_us);
369/// loop {
370///     let t0 = gap.mark();
371///     crt.spin_once(period);
372///     gap.after_spin(t0);
373/// }
374/// ```
375#[derive(Debug)]
376pub struct SchedTaskSpinGap {
377    state: u64,
378    spin_period_us: u64,
379    gaps: u64,
380}
381
382unsafe extern "C" {
383    fn nros_platform_clock_ns() -> u64;
384    fn nros_platform_sleep_ms(ms: usize);
385}
386
387impl SchedTaskSpinGap {
388    #[must_use]
389    pub const fn new(spin_period_us: u64) -> Self {
390        Self {
391            state: 0,
392            spin_period_us,
393            gaps: 0,
394        }
395    }
396
397    /// Timestamp for the start of an iteration.
398    #[must_use]
399    pub fn mark(&self) -> u64 {
400        // SAFETY: a bare monotonic read with no preconditions, defined by
401        // whichever platform port linked this image.
402        unsafe { nros_platform_clock_ns() }
403    }
404
405    /// Close out one iteration, sleeping if this one closed a window in which
406    /// nothing blocked.
407    pub fn after_spin(&mut self, iter_start_ns: u64) {
408        let now = self.mark();
409        let (state, sleep) = gap_step(
410            self.state,
411            now.saturating_sub(iter_start_ns),
412            now,
413            self.spin_period_us,
414        );
415        self.state = state;
416        if sleep {
417            // SAFETY: no preconditions; blocks the calling task for >= 1 ms.
418            unsafe { nros_platform_sleep_ms(GAP_MS) };
419            self.gaps = self.gaps.saturating_add(1);
420            // Re-stamp so the sleep itself is not charged to the new window.
421            self.state = open_state(self.mark(), false);
422        }
423    }
424
425    /// How many gaps this loop has taken — for the sched task heartbeat, so a busy
426    /// image can say whether the guarantee is being exercised or is dead code.
427    #[must_use]
428    pub const fn gaps(&self) -> u64 {
429        self.gaps
430    }
431}
432
433/// The same decision for the C sched task runners, which keep the `u64` themselves.
434///
435/// Pass `0` on the first call. The sleep happens HERE, so the two languages
436/// share one implementation of both halves of the rule.
437///
438/// # Safety
439/// None beyond the platform ABI being linked, which is true in any image that
440/// has sched tasks to run.
441#[unsafe(no_mangle)]
442pub extern "C" fn nros_sched_task_spin_gap_step(
443    state: u64,
444    iter_start_ns: u64,
445    now_ns: u64,
446    spin_period_us: u64,
447) -> u64 {
448    let (next, sleep) = gap_step(
449        state,
450        now_ns.saturating_sub(iter_start_ns),
451        now_ns,
452        spin_period_us,
453    );
454    if sleep {
455        // SAFETY: no preconditions; blocks the calling task for >= 1 ms.
456        unsafe { nros_platform_sleep_ms(GAP_MS) };
457        // SAFETY: bare monotonic read.
458        return open_state(unsafe { nros_platform_clock_ns() }, false);
459    }
460    next
461}
462
463const fn clamp31(n: u8) -> u8 {
464    if n > 31 { 31 } else { n }
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470
471    #[test]
472    fn freertos_anchors_match_rfc0016() {
473        // RFC-0016 table column FreeRTOS(0–7).
474        assert_eq!(freertos_priority_for(0), 0); // idle
475        assert_eq!(freertos_priority_for(12), 3); // normal
476        assert_eq!(freertos_priority_for(20), 5); // high
477        assert_eq!(freertos_priority_for(31), 7); // critical
478        // Saturates above the scale.
479        assert_eq!(freertos_priority_for(200), 7);
480    }
481
482    #[test]
483    fn threadx_inverts_scale() {
484        assert_eq!(threadx_priority_for(0), 31); // idle → lowest
485        assert_eq!(threadx_priority_for(31), 0); // critical → highest
486        assert_eq!(threadx_priority_for(12), 19);
487    }
488
489    #[test]
490    fn posix_nice_anchors() {
491        assert_eq!(posix_nice_for(0), 19); // idle pinned to max nice
492        assert_eq!(posix_nice_for(12), 0); // normal
493        assert_eq!(posix_nice_for(31), -20); // critical (clamped)
494        assert!(posix_nice_for(20) < 0); // high → negative nice
495    }
496
497    #[test]
498    fn single_sched_task_is_wildcard() {
499        let t = SchedTaskSpec::single();
500        assert!(t.groups.is_empty());
501        assert_eq!(t.priority, 0);
502    }
503
504    fn spec(name: &'static str, priority: i64) -> SchedTaskSpec<'static> {
505        SchedTaskSpec {
506            name,
507            priority,
508            ..SchedTaskSpec::single()
509        }
510    }
511
512    /// issue 0636 — the owner must be the sched task that outranks nothing, and
513    /// "nothing" depends on which end of the kernel's scale is urgent.
514    #[test]
515    fn boot_sched_task_is_the_least_urgent_on_either_direction() {
516        // As `resolve_sched_tasks` hands them over: RAW number, descending.
517        let sched_tasks = [spec("high", 110), spec("mid", 105), spec("low", 100)];
518
519        // Bigger wins (NuttX, FreeRTOS, POSIX): 100 is least urgent. This is
520        // the case that starved — the board used to take index 0 (110) and
521        // spin there.
522        assert_eq!(
523            boot_sched_task_index(&sched_tasks, PriorityDirection::BiggerIsMoreUrgent),
524            2
525        );
526        // Smaller wins (Zephyr, ThreadX): 110 is least urgent, which is index
527        // 0 — the arrangement those boards already had, now stated rather than
528        // inherited from the sort direction.
529        assert_eq!(
530            boot_sched_task_index(&sched_tasks, PriorityDirection::SmallerIsMoreUrgent),
531            0
532        );
533    }
534
535    /// A sched task that declared nothing makes no claim, so it is the safest owner —
536    /// but only where 0 is out of the kernel's range.
537    #[test]
538    fn undeclared_is_least_urgent_only_where_zero_is_a_sentinel() {
539        let sched_tasks = [spec("declared", 12), spec("undeclared", 0)];
540        assert_eq!(
541            boot_sched_task_index(&sched_tasks, PriorityDirection::BiggerIsMoreUrgent),
542            1
543        );
544        // On ThreadX 0 is a REAL priority, and the most urgent one. Treating it
545        // as a sentinel would hand the session to the sched task that must never own
546        // it — the exact inversion this function exists to prevent.
547        assert_eq!(
548            boot_sched_task_index(&sched_tasks, PriorityDirection::SmallerIsMoreUrgent),
549            0
550        );
551    }
552
553    // ---- issue 0636 option 3 — the spin gap ----
554
555    /// What `SchedTaskSpinGap` does after sleeping: open a fresh window at `now`.
556    fn open_state_for_test(now_ns: u64) -> u64 {
557        super::open_state(now_ns, false)
558    }
559
560    /// The interval is the declared period, floored so the 1 ms gap can never
561    /// cost more than 10 %.
562    #[test]
563    fn gap_interval_floors_at_ten_ms() {
564        assert_eq!(gap_interval_us(200), 10_000); // 200 us sched task: floored
565        assert_eq!(gap_interval_us(10_000), 10_000); // exactly the floor
566        assert_eq!(gap_interval_us(100_000), 100_000); // 100 ms sched task: its own
567    }
568
569    /// "It blocked" is half the declared period — a waited spin lands near the
570    /// period, a free-running one is orders of magnitude below it.
571    #[test]
572    fn blocked_is_half_the_declared_period() {
573        // 10 ms sched task: 5 ms counts, 4.9 ms does not.
574        assert!(iteration_blocked(5_000_000, 10_000));
575        assert!(!iteration_blocked(4_900_000, 10_000));
576        // A free-running iteration (~2 us) never counts.
577        assert!(!iteration_blocked(2_000, 10_000));
578        // Degenerate sub-2 us period: any measurable time counts, so such a
579        // loop is not gapped every window.
580        assert!(iteration_blocked(1, 1));
581        assert!(!iteration_blocked(0, 1));
582    }
583
584    /// A loop whose spins BLOCK never sleeps here — the whole point of keeping
585    /// the cost off the healthy path.
586    #[test]
587    fn a_blocking_loop_never_gaps() {
588        let period_us = 10_000;
589        let mut state = 0u64;
590        let mut now = 1_000_000_000u64;
591        for _ in 0..500 {
592            // Each iteration takes its full declared period.
593            let iter_ns = period_us * 1_000;
594            now += iter_ns;
595            let (next, sleep) = gap_step(state, iter_ns, now, period_us);
596            assert!(!sleep, "a spin that waited its period must not be gapped");
597            state = next;
598        }
599    }
600
601    /// A free-running loop gaps once per interval, and not more.
602    #[test]
603    fn a_free_running_loop_gaps_once_per_interval() {
604        let period_us = 10_000; // interval = 10 ms
605        let mut state = 0u64;
606        let mut now = 42u64;
607        let mut sleeps = 0;
608        // 100 ms of 5 us iterations.
609        for _ in 0..20_000 {
610            let iter_ns = 5_000;
611            now += iter_ns;
612            let (next, sleep) = gap_step(state, iter_ns, now, period_us);
613            if sleep {
614                sleeps += 1;
615                // The caller re-stamps after sleeping; model that.
616                now += 1_000_000;
617                state = open_state_for_test(now);
618            } else {
619                state = next;
620            }
621        }
622        // 100 ms of spinning, 10 ms windows, 1 ms of sleep charged to none of
623        // them: 9 or 10 depending on where the first window opens.
624        assert!(
625            (9..=10).contains(&sleeps),
626            "expected ~one gap per 10 ms window, got {sleeps}"
627        );
628    }
629
630    /// ONE blocking iteration is enough to spare the whole window — the rule is
631    /// "the loop reached a scheduling point", not "every spin did".
632    #[test]
633    fn one_block_in_a_window_suppresses_its_gap() {
634        let period_us = 10_000;
635        let mut state = 0u64;
636        let mut now = 1_000u64;
637        let mut sleeps = 0;
638        for i in 0..4_000 {
639            // One blocking iteration every 1000 free-running ones, which is
640            // more than one per 10 ms window at 5 us per iteration.
641            let iter_ns = if i % 1_000 == 999 { 6_000_000 } else { 5_000 };
642            now += iter_ns;
643            let (next, sleep) = gap_step(state, iter_ns, now, period_us);
644            if sleep {
645                sleeps += 1;
646            }
647            state = next;
648        }
649        assert_eq!(sleeps, 0, "a window containing a real block must not gap");
650    }
651
652    /// The first call opens a window instead of deciding: a zero state cannot
653    /// be read as "window opened at time 0", because the clock epoch is the
654    /// platform's and a fresh image legitimately reads small values.
655    #[test]
656    fn first_call_opens_a_window_and_never_sleeps() {
657        for now in [0u64, 1, 5_000_000, u64::MAX / 2] {
658            let (state, sleep) = gap_step(0, 5_000, now, 10_000);
659            assert!(!sleep, "the first iteration must not be gapped");
660            assert_ne!(state, 0, "the window must be open after the first call");
661        }
662    }
663
664    /// A port whose clock epoch IS zero must still gap. With the timestamp
665    /// alone as the state, `now = 0` re-read as "not started yet" on every
666    /// iteration and the guarantee silently did not exist on that port.
667    #[test]
668    fn a_clock_that_starts_at_zero_still_gaps() {
669        let period_us = 10_000;
670        let mut state = 0u64;
671        let mut now = 0u64; // epoch, exactly
672        let mut sleeps = 0;
673        for _ in 0..10_000 {
674            now += 5_000; // 5 us of free-running spin
675            let (next, sleep) = gap_step(state, 5_000, now, period_us);
676            if sleep {
677                sleeps += 1;
678                now += 1_000_000;
679                state = open_state_for_test(now);
680            } else {
681                state = next;
682            }
683        }
684        assert!(sleeps > 0, "a zero-epoch clock must not disable the gap");
685    }
686
687    /// Ties keep the earliest index, so a table with one sched task — or with every
688    /// sched task equal — behaves exactly as `sched_tasks[0]` did before issue 0636.
689    #[test]
690    fn ties_and_single_sched_task_keep_index_zero() {
691        let same = [spec("a", 7), spec("b", 7), spec("c", 7)];
692        for dir in [
693            PriorityDirection::BiggerIsMoreUrgent,
694            PriorityDirection::SmallerIsMoreUrgent,
695        ] {
696            assert_eq!(boot_sched_task_index(&same, dir), 0);
697            assert_eq!(boot_sched_task_index(&same[..1], dir), 0);
698        }
699    }
700}