Skip to main content

nros_node/executor/
backing.rs

1//! The executor's storage as a NAMED STATIC.
2//!
3//! # What this fixes, and what it does not
4//!
5//! The static-RAM campaign prices an image's static RAM by reading its symbol table
6//! (`just mem-report`). Every later wave of that campaign is defined as a saving
7//! against those numbers, so a consumer the symbol table cannot see is a
8//! consumer the campaign cannot price — and the executor's storage was exactly
9//! that on every Rust image.
10//!
11//! **Not because the arena is inline.** It stopped being an inline
12//! `[MaybeUninit<u8>; ARENA_SIZE]` field long ago, and
13//! [`Executor`](super::spin::Executor) has held `arena: &'s mut
14//! [MaybeUninit<u8>]` — a slice carved out of caller-supplied backing — ever
15//! since. Four documents, a build-script comment and a runtime advisory string
16//! went on asserting the inline shape for a long time, until a later
17//! review caught the claim and the sites were corrected.
18//!
19//! **Where that backing lives is the caller's choice**, and before this module
20//! the tree answered it three different ways:
21//!
22//! * **C** — all 34 in-tree `rclc_executor_t` objects are file-scope `static`,
23//!   so the backing is carved from `_opaque` in `.bss`. Visible.
24//! * **C++** — `nros::Node::GlobalStorageHolder<0>::storage`, a template static
25//!   member, so also `.bss`. Visible.
26//! * **Rust** — every board entry (`linux`, `zephyr`, `freertos`, `nuttx`,
27//!   `threadx`, `esp32-qemu`, `mps2-an385`) reaches an `alloc` convenience
28//!   constructor, which leaked a `Box`. **Invisible**: a heap allocation has no
29//!   symbol. Measured on the native zenoh talker before this module: the largest
30//!   `nros_node` RAM symbol in the whole image was **1 byte**.
31//!
32//! This module closes the Rust arm — one change, every Rust board.
33//!
34//! # It is a MOVE, not a saving, and the second half is the caller's
35//!
36//! The same bytes are reserved either way; what changes is *which budget pays*.
37//! A leaked `Box` is drawn from the image's allocator arena. On a hosted target
38//! that arena is the OS heap and has no fixed reservation, so the static costs
39//! nothing that was not already spent. **On an RTOS it is itself a fixed
40//! static** — `CONFIG_COMMON_LIBC_MALLOC_ARENA_SIZE` on Zephyr,
41//! `configTOTAL_HEAP_SIZE` on FreeRTOS — already sized to hold this backing, so
42//! turning the reservation on there without lowering that knob reserves the same
43//! bytes twice.
44//!
45//! That pairing is per-image and only the image's author can measure it, so the
46//! opt-out is a knob rather than a guess: `NROS_EXECUTOR_BACKING_BYTES=0` emits
47//! no static at all and restores the leak. A non-zero value overrides the
48//! reservation's SIZE, which is also how a fat entry — one declaring
49//! `max_callbacks` above `NROS_EXECUTOR_MAX_CBS` — keeps a static instead of
50//! falling back to the heap.
51//!
52//! **The Zephyr `CONFIG_` spelling IS wired** (this paragraph said
53//! the opposite until it was). `zephyr/Kconfig` declares
54//! `NROS_EXECUTOR_BACKING_BYTES` with the tree's `-1` DERIVE sentinel as its
55//! default, and `nros-node`'s build script reaches it through the same env →
56//! `$DOTCONFIG` reader every other executor knob uses. `-1` does
57//! not parse as a `usize`, which is exactly how every other `-1 = derive` knob
58//! in this tree falls through to its crate default, so the shipped default is
59//! still the derived size and no Zephyr image moved the day it landed — a
60//! plain `default 0` would have meant "no static" on all of them, which is the
61//! opposite of the default this chose.
62//!
63//! # Why an image would STATE the size rather than derive it
64//!
65//! Because the derivation cannot be paired with anything. A fix once lowered
66//! one leaf's `CONFIG_COMMON_LIBC_MALLOC_ARENA_SIZE` by a size copied out of
67//! `nm` output, and that subtrahend is a function of the executor knobs: move
68//! `MAX_CBS`, the arena or the rx buffer and it is silently stale in whichever
69//! direction, with nothing to say so. It was also wrong on the
70//! second board the same conf builds for — the derived size is **87,256 B on
71//! `mps2_an385` and 88,328 B on `native_sim/native/64`**, because the carved
72//! tables hold pointers, so one number cannot pair both.
73//!
74//! Stating it inverts the dependency: the reservation is `8 * words` bytes on
75//! every target, the arena's lowering is arithmetic a gate can check
76//! (`check-executor-backing-arena-pairing`), and a stated size BELOW what the
77//! executor needs is the `const` assertion below — a compile error naming this
78//! knob, which is the direction that would otherwise re-create the double
79//! reservation in silence.
80//!
81//! **Zephyr no longer pairs it**. Every Zephyr
82//! Rust allocation moved onto the nros heap, so picolibc's arena holds no Rust bytes
83//! and the six example confs that lowered it now state neither number. The
84//! pairing above survives on ThreadX's rung.
85//!
86//! # Why there is no `// nros-pool:` annotation
87//!
88//! `scripts/gen-pool-inventory.py` evaluates a pool as a PRODUCT of knobs at
89//! their literal defaults. This one is a SUM — the executor's carved tables plus
90//! the arena, laid out with alignment padding between them — and its largest
91//! term, `ARENA_SIZE`, is itself derived
92//! (`env_usize("NROS_EXECUTOR_ARENA_BYTES", derived_arena)` in
93//! `nros-node/build.rs`), so the inventory would record it as a computed default
94//! even if the sum were expressible. A formula that is right for one build and
95//! wrong for the rest is the drift class this tree gates against, so this
96//! follows the two documented deliberate non-annotations
97//! (`nros_rmw_zenoh::shim::publisher`, `nros_rmw_cffi`): **the size is known to
98//! the compiler, so read it from the compiler's output.** `mem-report` prices
99//! the symbol from the ELF, exactly, with no formula to drift.
100//!
101//! # Placement
102//!
103//! `NROS_EXECUTOR_BACKING_SECTION` (build-time env, read by `nros-node`'s build
104//! script) puts the static in a named section, for the amendment-A case where a
105//! part has tightly-coupled memory the linker script can target —
106//! `nros_thread_stacks` does the same with `DTCM`. Two constraints, both
107//! load-bearing: **the section must be `NOLOAD`**, because this static is
108//! uninitialised and a loadable section would add its whole size to the image's
109//! flash footprint; and it must be reachable by every bus master that touches
110//! the executor's buffers, which on Cortex-M7 the TCMs typically are not.
111
112use core::mem::MaybeUninit;
113
114#[cfg(nros_executor_backing_static)]
115use portable_atomic::{AtomicBool, Ordering};
116
117use super::storage::ExecutorSizing;
118
119/// The reservation's size when nothing overrides it: one default-sized
120/// executor's worth.
121///
122/// One executor, not a multiple, because an entry opens ONE through this road:
123/// a sched-task boot's SPAWNED sched tasks take their slots from the entry's own
124/// [`SchedTaskExecutorBacking`] instead, each slot this many words.
125///
126/// Named by the GENERATED file when nothing overrides the size, so it is unused
127/// under `NROS_EXECUTOR_BACKING_BYTES=0` (no static) and under an explicit
128/// override (a literal). Kept rather than `cfg`'d: it is what the override is
129/// judged against, and a constant that disappears with its consumer cannot be
130/// compared to anything.
131#[allow(dead_code)]
132pub const EXECUTOR_BACKING_DEFAULT_U64S: usize = ExecutorSizing::DEFAULT.u64_len();
133
134/// The words the DEFAULT backing spends on the carved
135/// parameter store: zero unless the build implies a store
136/// (`nros_params::IMPLIED_STORE_SLOTS`). A STATED reservation
137/// (`NROS_EXECUTOR_BACKING_BYTES`, a board's `backing_bytes`) covers the
138/// executor's tables and gets this added on top -- see `nros-node/build.rs`'s
139/// `emit_executor_backing` for why the statement does not absorb it.
140#[allow(dead_code)]
141pub const PARAMETER_STORE_U64S: usize = ExecutorSizing::DEFAULT.u64_len()
142    - ExecutorSizing {
143        params: 0,
144        ..ExecutorSizing::DEFAULT
145    }
146    .u64_len();
147
148// `EXECUTOR_BACKING`, its size const, and the optional
149// `#[unsafe(link_section = …)]` on it are emitted by `build.rs`: `link_section`
150// takes a string LITERAL and the section name is a build-time input, and the
151// size may be overridden or the whole item suppressed. The file is EMPTY when
152// `NROS_EXECUTOR_BACKING_BYTES=0`, which is why the include is unconditional
153// while everything that reads it is `cfg`-gated.
154include!(concat!(env!("OUT_DIR"), "/nros_executor_backing.rs"));
155
156/// The reservation must cover the sizing every `alloc` convenience constructor
157/// passes, or it is dead weight every image carries and no executor ever uses.
158///
159/// A `const` assertion rather than a test, deliberately: the only way to make it
160/// false is to set `NROS_EXECUTOR_BACKING_BYTES` too low, and the person doing
161/// that wants to hear about it from the build they just ran, not from a test
162/// suite they may not run at all. `0` is the documented opt-out and is not
163/// reached here — it emits no static, so this whole arm is `cfg`'d away.
164///
165/// **It also goes false the OTHER way, and a const assertion alone cannot see
166/// that** (issue 1284): a conf that STATES the knob stays put while the executor
167/// grows under it. That fails only in the image's own build, which no
168/// merge-gating lane runs, so twelve Zephyr leaves drifted twice in a week. `just
169/// check node-std-tests` now runs this assertion per stated claim at each
170/// claimed board's pointer width, and `tests/executor_backing_claims.rs` checks
171/// the host-width claims against [`EXECUTOR_BACKING_DEFAULT_U64S`] by number;
172/// `check-executor-backing-arena-pairing --claims` says which confs claim what.
173#[cfg(nros_executor_backing_static)]
174const _: () = assert!(
175    EXECUTOR_BACKING_U64S >= EXECUTOR_BACKING_DEFAULT_U64S,
176    "NROS_EXECUTOR_BACKING_BYTES is below the default executor sizing, so the \
177     reservation can never be taken and is pure dead weight; use 0 to decline \
178     the static entirely"
179);
180
181/// Has [`EXECUTOR_BACKING`] been handed out?
182///
183/// A latch, not a free list: the backing is handed out as `&'static mut` and
184/// never returned, exactly like the `Box::leak` it replaces. An executor that
185/// drops does not give it back — reclaiming it would need the executor's own
186/// tables to be provably dead first, which `Drop` cannot show for a slice it has
187/// already lent out.
188#[cfg(nros_executor_backing_static)]
189static TAKEN: AtomicBool = AtomicBool::new(false);
190
191/// Hand out [`EXECUTOR_BACKING`], once, if it can hold `words`.
192///
193/// `None` means "use the heap", and every path to it is legitimate rather than
194/// degraded — it is the caller's behaviour from before this module existed:
195///
196/// * the reservation is switched off (`NROS_EXECUTOR_BACKING_BYTES=0`);
197/// * another executor already took it (a second `Executor::open` in one
198///   process — a sched-task boot's spawned sched tasks no longer come here, they take
199///   the entry's [`SchedTaskExecutorBacking`], issue 1571);
200/// * this executor is sized past the reservation (a fat entry).
201///
202/// The `swap` is what makes the returned `&'static mut` sound: exactly one
203/// caller observes `false`, so exactly one reference to the static ever exists.
204#[cfg(nros_executor_backing_static)]
205pub(crate) fn take(words: usize) -> Option<&'static mut [MaybeUninit<u64>]> {
206    if words > EXECUTOR_BACKING_U64S {
207        return None;
208    }
209    if TAKEN.swap(true, Ordering::AcqRel) {
210        return None;
211    }
212    // SAFETY: the swap above succeeds exactly once for the life of the process,
213    // so this is the only reference ever created to `EXECUTOR_BACKING`, and it
214    // is `'static` because the static is. `words <= EXECUTOR_BACKING_U64S` was
215    // checked, so the slice is in bounds.
216    // The raw ref is bound first rather than dereferenced in place: `&mut
217    // *(&raw mut X)` reads as `deref_addrof` to clippy, and the obvious
218    // rewrite it suggests (`&mut X`) is the `static_mut_refs` hazard this
219    // spelling exists to avoid.
220    let ptr = &raw mut EXECUTOR_BACKING;
221    let all: &'static mut [MaybeUninit<u64>; EXECUTOR_BACKING_U64S] = unsafe { &mut *ptr };
222    Some(&mut all[..words])
223}
224
225/// Issue 2579 — hand back a backing [`take`] gave out, so the next taker gets it.
226///
227/// Only for an executor open that FAILED: the caller has no executor over the
228/// slice, and the open dropped whatever it had built over it (see
229/// `spin.rs`'s `with_default_backing`). Returns `false` when `backing` is not
230/// the static, i.e. it came from the heap, and the caller frees it instead.
231///
232/// # Safety
233/// `backing` must be the slice [`take`] returned (or a heap block), and no
234/// reference into it may be live: the latch is what made the one `&'static
235/// mut` unique, and re-arming it lets the next `take` create another.
236#[cfg(all(nros_executor_backing_static, feature = "alloc", feature = "rmw-cffi"))]
237pub(crate) unsafe fn give_back(backing: *mut [MaybeUninit<u64>]) -> bool {
238    let base = (&raw mut EXECUTOR_BACKING) as *mut MaybeUninit<u64>;
239    if backing as *mut MaybeUninit<u64> != base {
240        return false;
241    }
242    TAKEN.store(false, Ordering::Release);
243    true
244}
245
246/// The reservation is switched off, so nothing [`take`] gave out can come back.
247#[cfg(all(
248    not(nros_executor_backing_static),
249    feature = "alloc",
250    feature = "rmw-cffi"
251))]
252pub(crate) unsafe fn give_back(_backing: *mut [MaybeUninit<u64>]) -> bool {
253    false
254}
255
256/// Issue 2576 — the default backing an `alloc` open (`Executor::open` and its
257/// siblings) took, handed back when the executor is DROPPED.
258///
259/// A board that loses its XRCE session drops the executor and opens a new one.
260/// Without this, the dropped executor kept the static reservation latched (and
261/// a heap backing leaked), so the re-open fell to a fresh ~87 KB heap block:
262/// the panic issue 2579 removed from a failed open, back on the re-open path.
263///
264/// It is the executor's LAST field, so it drops after every other field, and
265/// `Executor`'s own `Drop` has already torn down every arena entry by then:
266/// nothing references the slice when it is given back. Entity handles do not
267/// borrow the arena (they own backend handles), and `SessionHandle` is valid
268/// only while its executor lives, so none outlives the executor into memory
269/// the next open reuses.
270///
271/// It carries its RELEASE as a function pointer rather than naming
272/// [`give_back`] in `Drop`. Every image that can drop an `Executor` links
273/// `Drop`, including a C or C++ image that only ever opens over its own storage
274/// (`open_in`); a `Drop` that named `give_back` named `EXECUTOR_BACKING`, so
275/// those images linked the ~360 KB static beside their own executor storage and
276/// overflowed RAM (mps2-an385 FreeRTOS by 89,672 B). The pointer is taken only
277/// in [`OwnedBacking::owned`], which only `default_backing` reaches, so an
278/// `open_in`-only image keeps the static out of its link, as it did before.
279#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
280pub(crate) struct OwnedBacking(Option<(core::ptr::NonNull<[MaybeUninit<u64>]>, ReleaseBacking)>);
281
282/// How an [`OwnedBacking`] gives its block back.
283#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
284type ReleaseBacking = unsafe fn(*mut [MaybeUninit<u64>]);
285
286/// The release `default_backing` arms, and the one a failed default open
287/// runs (`spin.rs`'s `with_default_backing`): re-arm the static's latch, or free the
288/// heap block.
289///
290/// # Safety
291/// As [`OwnedBacking`]'s doc: `backing` is the block `default_backing` handed
292/// out, and nothing references it any more.
293#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
294pub(crate) unsafe fn release_default_backing(backing: *mut [MaybeUninit<u64>]) {
295    // SAFETY: the caller's contract. A static handout re-arms the latch;
296    // otherwise it is the `Box::new_uninit_slice` `default_backing` leaked,
297    // and this is that exact fat pointer.
298    unsafe {
299        if !give_back(backing) {
300            drop(alloc::boxed::Box::from_raw(backing));
301        }
302    }
303}
304
305// SAFETY: the pointer is a unique owner of its block (the static's latch, or a
306// leaked `Box`), moved with the executor and touched only by `drop`.
307#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
308unsafe impl Send for OwnedBacking {}
309// SAFETY: `&OwnedBacking` exposes nothing.
310#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
311unsafe impl Sync for OwnedBacking {}
312
313#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
314impl OwnedBacking {
315    /// A backing the caller supplied (`open_in` and friends): theirs to reuse.
316    pub(crate) const NONE: Self = Self(None);
317
318    /// # Safety
319    /// `backing` must come from `default_backing`, and be the one the executor
320    /// this is stored in was opened over.
321    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
322    pub(crate) unsafe fn owned(backing: *mut [MaybeUninit<u64>]) -> Self {
323        Self(
324            core::ptr::NonNull::new(backing)
325                .map(|b| (b, release_default_backing as ReleaseBacking)),
326        )
327    }
328}
329
330#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
331impl Drop for OwnedBacking {
332    fn drop(&mut self) {
333        if let Some((backing, release)) = self.0.take() {
334            // SAFETY: see the type's doc — nothing references the slice any
335            // more, and `release` is the one `owned` armed for it.
336            unsafe { release(backing.as_ptr()) }
337        }
338    }
339}
340
341/// The reservation is switched off, so there is nothing to hand out.
342///
343/// A stub rather than a `cfg` at the call site: `default_backing` reads the same
344/// either way, which is the paired-stub idiom `trace_register` uses one file
345/// over, and it keeps the `#[cfg]` in exactly one place.
346#[cfg(not(nros_executor_backing_static))]
347pub(crate) fn take(_words: usize) -> Option<&'static mut [MaybeUninit<u64>]> {
348    None
349}
350
351/// Has the static been claimed? Tests only.
352#[cfg(all(test, nros_executor_backing_static))]
353pub(crate) fn is_taken() -> bool {
354    TAKEN.load(Ordering::Acquire)
355}
356
357// ============================================================================
358// issue 1571 — the SPAWNED sched tasks' executor backing, as the entry's own static
359// ============================================================================
360//
361// A sched-task boot opens one executor per sched task. The boot sched task takes
362// `EXECUTOR_BACKING` through `Executor::open` like any single-executor entry;
363// every OTHER sched task used to reach `default_backing` too, find the latch already
364// taken, and `Box::leak` a default-sized block — correctly sized, but invisible
365// to `mem-report` and drawn from the allocator arena, where issue 1568 had just
366// moved every C and C++ RTOS executor (sched task and single) OUT of it.
367//
368// The fix is the C/C++ METHOD, not a second one: the sched task count is known when
369// the entry is generated, so the entry (`nros::main!`) emits ONE named static of
370// `N - 1` slots — the C pack's `__nros_sched_task_executor_storage` — and the board's
371// `run_sched_tasks` hands each spawned sched task its slot. The slot is typed, so its size is
372// the executor's exact need by construction: the sched task opens with
373// `ExecutorSizing::DEFAULT` (see `Executor::open_with_session_slot`) and the slot
374// is `ExecutorSizing::DEFAULT.u64_len()` words — the same const the boot
375// reservation above is judged against, so there is ONE spelling of "a default
376// executor's worth" for both.
377//
378// It is a MOVE, exactly like the boot reservation: on an RTOS the same bytes
379// leave the allocator arena (`CONFIG_COMMON_LIBC_MALLOC_ARENA_SIZE`,
380// `configTOTAL_HEAP_SIZE`, the NuttX kernel heap, the ThreadX byte pool) and
381// become linker-visible `.bss`.
382
383/// One spawned sched task executor's backing: exactly the words an
384/// executor opened with [`ExecutorSizing::DEFAULT`] carves.
385pub type SchedTaskExecutorBackingSlot = [MaybeUninit<u64>; EXECUTOR_BACKING_DEFAULT_U64S];
386
387/// The spawned sched tasks' executor backing, `N` slots in ONE named
388/// static that the ENTRY owns.
389///
390/// `nros::main!` emits one per sched-task entry, with `N` = the sched task count minus the
391/// boot sched task (which takes the `EXECUTOR_BACKING` road), and passes
392/// [`take`](Self::take) to the board's `run_sched_tasks`. The board then refuses a
393/// short block with [`check_sched_task_executor_backing`] — the Rust twin of the C
394/// library's `nros_cpp_executor_storage_check`.
395///
396/// Placement is the caller's: the static lives in the entry's
397/// `.bss`, so `mem-report` prices it by name.
398pub struct SchedTaskExecutorBacking<const N: usize> {
399    /// The same once-only latch as the boot reservation's, per static: the
400    /// slots go out as `&'static mut`, so exactly one caller may observe them.
401    taken: portable_atomic::AtomicBool,
402    slots: core::cell::UnsafeCell<[SchedTaskExecutorBackingSlot; N]>,
403}
404
405// SAFETY: the slots are only reachable through `take`, whose latch hands them
406// out at most once, so no two threads can ever hold a reference to them.
407unsafe impl<const N: usize> Sync for SchedTaskExecutorBacking<N> {}
408
409impl<const N: usize> SchedTaskExecutorBacking<N> {
410    /// An untouched reservation. `const` so it can initialise a `static`, and
411    /// uninitialised (plus a `false` latch), so the static is all-zero `.bss`
412    /// and costs no flash.
413    ///
414    /// `large_stack_arrays` is allowed because this is only ever evaluated in
415    /// CONST context (a `static` initialiser): the array is built by the
416    /// compiler into `.bss`, never on a stack.
417    #[allow(clippy::new_without_default, clippy::large_stack_arrays)]
418    pub const fn new() -> Self {
419        Self {
420            taken: portable_atomic::AtomicBool::new(false),
421            slots: core::cell::UnsafeCell::new(
422                [[MaybeUninit::uninit(); EXECUTOR_BACKING_DEFAULT_U64S]; N],
423            ),
424        }
425    }
426
427    /// Hand out every slot, once. A second call returns an EMPTY slice, which
428    /// the board's [`check_sched_task_executor_backing`] then refuses by name rather
429    /// than aliasing a slot another executor is using.
430    ///
431    /// `mut_from_ref` is the point, not an accident: `&'static self` is how a
432    /// `static` is reached, and the latch is what makes the one `&mut` sound —
433    /// the same shape as the boot reservation's `take`.
434    #[allow(clippy::mut_from_ref)]
435    pub fn take(&'static self) -> &'static mut [SchedTaskExecutorBackingSlot] {
436        if self.taken.swap(true, portable_atomic::Ordering::AcqRel) {
437            return &mut [];
438        }
439        // SAFETY: the swap above succeeds exactly once per static, so this is
440        // the only reference ever created to `slots`; `'static` because `self`
441        // is.
442        unsafe { &mut *self.slots.get() }
443    }
444}
445
446/// The sched task backing a board was handed does not cover the sched tasks it
447/// must spawn. Carries both counts so the refusal names them.
448#[derive(Debug, Clone, Copy, PartialEq, Eq)]
449pub struct SchedTaskBackingShort {
450    /// Sched tasks the board spawns (every sched task but the boot one).
451    pub spawned: usize,
452    /// Slots it was handed.
453    pub slots: usize,
454}
455
456impl core::fmt::Display for SchedTaskBackingShort {
457    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
458        write!(
459            f,
460            // issue 1571
461            "sched task executor backing holds {} slot(s) but {} spawned sched task(s) need one each \
462             — the entry's `SchedTaskExecutorBacking` was sized for a different sched task table, \
463             or taken twice",
464            self.slots, self.spawned
465        )
466    }
467}
468
469/// The ONE refusal every board's `run_sched_tasks` makes before it opens
470/// anything: `n_sched_tasks` sched tasks run, one on the boot executor, so `n_sched_tasks - 1`
471/// must each find a slot. Checked up front rather than at each spawn, so a
472/// short block never leaves a half-spawned sched task chain.
473pub fn check_sched_task_executor_backing(
474    n_sched_tasks: usize,
475    backing: &[SchedTaskExecutorBackingSlot],
476) -> Result<(), SchedTaskBackingShort> {
477    let spawned = n_sched_tasks.saturating_sub(1);
478    if backing.len() < spawned {
479        return Err(SchedTaskBackingShort {
480            spawned,
481            slots: backing.len(),
482        });
483    }
484    Ok(())
485}
486
487/// The ONE gate a tier runner holds across each tier's
488/// open-and-`setup` so no two sched tasks declare entities on the shared session at
489/// once.
490///
491/// Every sched task executor borrows the boot executor's ONE RMW session, and a
492/// sched task's `setup` declares its nodes and entities on it. The backend's
493/// entity-creation path is not reentrant across threads: zenoh's
494/// `ZenohSession::create_*` takes `&mut self` and mutates the per-node
495/// liveliness table, and the topic-binding scramble that
496/// concurrent declares cause was measured. The RTOS runners serialize by CHAINING the
497/// spawns (sched task N+1 starts only after sched task N's setup returned);
498/// a runner that spawns every sched task at once holds this instead. Setup runs once
499/// per boot and off the hot path, so a sleeping spin costs nothing that
500/// matters, and the spin loops that follow stay fully concurrent.
501///
502/// `no_std` and allocation-free (one atomic flag), so the same gate serves the
503/// native C++ runner (`nros-cpp`), the Linux Rust runner and the NuttX Rust
504/// runner. The backoff sleeps through the platform ABI, never spins hot: a
505/// waiter that outranks the holder under `SCHED_FIFO` would otherwise starve
506/// it on one CPU.
507#[derive(Debug, Default)]
508pub struct SchedTaskSetupGate {
509    held: portable_atomic::AtomicBool,
510}
511
512impl SchedTaskSetupGate {
513    /// An open gate.
514    #[must_use]
515    pub const fn new() -> Self {
516        Self {
517            held: portable_atomic::AtomicBool::new(false),
518        }
519    }
520
521    /// Block until this caller holds the gate; it is released when the
522    /// returned guard drops (on every return path, including a failed setup).
523    pub fn enter(&self) -> SchedTaskSetupGuard<'_> {
524        while self
525            .held
526            .compare_exchange_weak(
527                false,
528                true,
529                portable_atomic::Ordering::Acquire,
530                portable_atomic::Ordering::Relaxed,
531            )
532            .is_err()
533        {
534            super::spin::platform_sleep(core::time::Duration::from_micros(200));
535        }
536        SchedTaskSetupGuard { gate: self }
537    }
538}
539
540/// Proof of holding a [`SchedTaskSetupGate`]; dropping it opens the
541/// gate.
542#[derive(Debug)]
543#[must_use = "the gate is released as soon as the guard drops"]
544pub struct SchedTaskSetupGuard<'a> {
545    gate: &'a SchedTaskSetupGate,
546}
547
548impl Drop for SchedTaskSetupGuard<'_> {
549    fn drop(&mut self) {
550        self.gate
551            .held
552            .store(false, portable_atomic::Ordering::Release);
553    }
554}
555
556// ---------------------------------------------------------------------------
557// issue 1598 — each spawned sched task's TASK memory (stack + control block), the
558// same "entry declares, board uses" method one step further: the executor
559// backing above is in `.bss`, and so now is the task that runs it.
560// ---------------------------------------------------------------------------
561
562/// The control-block region every [`SchedTaskMemory`] carries,
563/// in 8-byte words. An UPPER BOUND over the kernels that take it (a FreeRTOS
564/// `StaticTask_t` on Cortex-M is about a hundred bytes); the port REFUSES a
565/// region smaller than its own control block at spawn, by name, so a kernel
566/// whose block outgrows this fails loudly rather than overrunning the stack
567/// that follows. Rust cannot name a C type's size at macro time, which is why
568/// this one number is a bound and the stack beside it is exact.
569pub const SCHED_TASK_TCB_U64S: usize = 64;
570
571/// One spawned sched task's RTOS task memory as a board receives it: raw,
572/// `Copy`, no lifetime. The ENTRY owns the bytes ([`SchedTaskMemory`]); the
573/// handout is once-only ([`SchedTaskMemorySet::take`]), which is what makes the
574/// raw pointers exclusive.
575#[derive(Clone, Copy, Debug)]
576pub struct SchedTaskMemoryRaw {
577    /// The stack: `stack_bytes` bytes, 64-byte aligned.
578    pub stack: *mut u8,
579    /// The stack's size in bytes — the sched task's declared `stack_bytes` (or the
580    /// family default), rounded up to whole words.
581    pub stack_bytes: usize,
582    /// The control-block region: `tcb_bytes` bytes, 64-byte aligned.
583    pub tcb: *mut u8,
584    /// [`SCHED_TASK_TCB_U64S`] words.
585    pub tcb_bytes: usize,
586}
587
588impl SchedTaskMemoryRaw {
589    /// "This sched task has no task memory from the entry": the port keeps its own
590    /// default (Zephyr's pool slot for a sched task that declared no `stack_bytes`).
591    pub const NONE: Self = Self {
592        stack: core::ptr::null_mut(),
593        stack_bytes: 0,
594        tcb: core::ptr::null_mut(),
595        tcb_bytes: 0,
596    };
597}
598
599// SAFETY: the pointers name `'static` storage handed out once (see the set's
600// latch), so moving the row to the task that uses it is the whole point.
601unsafe impl Send for SchedTaskMemoryRaw {}
602unsafe impl Sync for SchedTaskMemoryRaw {}
603
604/// One spawned sched task's stack and control block, as ONE named static
605/// the entry owns. `STACK_U64S` is the sched task's stack in 8-byte words;
606/// `TCB_U64S` the control-block region, [`SCHED_TASK_TCB_U64S`] by default and
607/// `0` for a kernel whose control block the port keeps itself (Zephyr's
608/// `struct k_thread` — a Rust entry cannot size it).
609///
610/// The control block comes first and the struct is 64-byte aligned, so the
611/// stack starts on a boundary every in-tree kernel accepts for a thread stack
612/// (the TCB region is a whole number of 64-byte lines).
613#[repr(C, align(64))]
614pub struct SchedTaskMemory<const STACK_U64S: usize, const TCB_U64S: usize = SCHED_TASK_TCB_U64S> {
615    tcb: core::cell::UnsafeCell<[MaybeUninit<u64>; TCB_U64S]>,
616    stack: core::cell::UnsafeCell<[MaybeUninit<u64>; STACK_U64S]>,
617}
618
619// SAFETY: the bytes are reached only through `raw`, collected into a
620// `SchedTaskMemorySet` whose latch hands them out at most once.
621unsafe impl<const STACK_U64S: usize, const TCB_U64S: usize> Sync
622    for SchedTaskMemory<STACK_U64S, TCB_U64S>
623{
624}
625
626impl<const STACK_U64S: usize, const TCB_U64S: usize> SchedTaskMemory<STACK_U64S, TCB_U64S> {
627    /// An untouched reservation, `const` so it initialises a `static`
628    /// (all-zero `.bss`, no flash).
629    #[allow(clippy::new_without_default, clippy::large_stack_arrays)]
630    pub const fn new() -> Self {
631        Self {
632            tcb: core::cell::UnsafeCell::new([MaybeUninit::uninit(); TCB_U64S]),
633            stack: core::cell::UnsafeCell::new([MaybeUninit::uninit(); STACK_U64S]),
634        }
635    }
636
637    /// The raw row for this static — `const`, so the entry builds its
638    /// [`SchedTaskMemorySet`] in a `static` initialiser.
639    pub const fn raw(&'static self) -> SchedTaskMemoryRaw {
640        SchedTaskMemoryRaw {
641            stack: self.stack.get() as *mut u8,
642            stack_bytes: STACK_U64S * core::mem::size_of::<u64>(),
643            tcb: self.tcb.get() as *mut u8,
644            tcb_bytes: TCB_U64S * core::mem::size_of::<u64>(),
645        }
646    }
647}
648
649/// The spawned sched tasks' task memory, `N` rows in spawn (chain)
650/// order, behind a once-only latch.
651pub struct SchedTaskMemorySet<const N: usize> {
652    taken: portable_atomic::AtomicBool,
653    rows: [SchedTaskMemoryRaw; N],
654}
655
656impl<const N: usize> SchedTaskMemorySet<N> {
657    /// `const`, for a `static` initialiser over the per-sched-task statics.
658    pub const fn new(rows: [SchedTaskMemoryRaw; N]) -> Self {
659        Self {
660            taken: portable_atomic::AtomicBool::new(false),
661            rows,
662        }
663    }
664
665    /// Hand out every row, once. A second call returns an EMPTY slice, which a
666    /// board refuses by count rather than giving two tasks one stack.
667    pub fn take(&'static self) -> &'static [SchedTaskMemoryRaw] {
668        if self.taken.swap(true, portable_atomic::Ordering::AcqRel) {
669            return &[];
670        }
671        &self.rows
672    }
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678
679    /// Issue 1733 — the gate admits ONE holder at a time, across threads, and
680    /// lets every waiter through once the holder drops its guard. Eight
681    /// threads released together each count themselves in and out of the
682    /// critical section; any overlap (a second holder) is recorded. A
683    /// `SchedTaskSetupGate::enter` that admitted concurrently is exactly the native
684    /// C++ runner before the issue: four sched task setups declaring at once.
685    #[test]
686    fn sched_task_setup_gate_admits_one_holder_at_a_time() {
687        use std::sync::{
688            Arc, Barrier,
689            atomic::{AtomicUsize, Ordering},
690        };
691        const THREADS: usize = 8;
692        let gate = Arc::new(SchedTaskSetupGate::new());
693        let inside = Arc::new(AtomicUsize::new(0));
694        let overlaps = Arc::new(AtomicUsize::new(0));
695        let entered = Arc::new(AtomicUsize::new(0));
696        let start = Arc::new(Barrier::new(THREADS));
697        let handles: std::vec::Vec<_> = (0..THREADS)
698            .map(|_| {
699                let (gate, inside, overlaps, entered, start) = (
700                    gate.clone(),
701                    inside.clone(),
702                    overlaps.clone(),
703                    entered.clone(),
704                    start.clone(),
705                );
706                std::thread::spawn(move || {
707                    start.wait();
708                    let _g = gate.enter();
709                    if inside.fetch_add(1, Ordering::SeqCst) != 0 {
710                        overlaps.fetch_add(1, Ordering::SeqCst);
711                    }
712                    entered.fetch_add(1, Ordering::SeqCst);
713                    std::thread::sleep(core::time::Duration::from_millis(2));
714                    inside.fetch_sub(1, Ordering::SeqCst);
715                })
716            })
717            .collect();
718        for h in handles {
719            h.join().expect("a gate holder panicked");
720        }
721        assert_eq!(
722            entered.load(Ordering::SeqCst),
723            THREADS,
724            "every waiter got through"
725        );
726        assert_eq!(overlaps.load(Ordering::SeqCst), 0, "two holders at once");
727    }
728
729    /// The POSITIVE CONTROL, and the reason it and the two `None` cases share
730    /// one test: `TAKEN` is process-scoped by design, so a second test would
731    /// observe an already-consumed latch and assert nothing — the vacuous shape
732    /// `check-no-vacuous-tests` exists to catch.
733    ///
734    /// A test that only ever saw `take` return `None` would pass against a `take`
735    /// that can never succeed, which is exactly the bug that would make this
736    /// whole module inert while reading as if it worked.
737    ///
738    /// `#[ignore]` because it needs a VIRGIN PROCESS, and that is a property of
739    /// the subject rather than a wish: `TAKEN` is process-global, and
740    /// `spin.rs`'s `default_backing` — reached by every `Executor::open` under
741    /// the `alloc` feature — claims it. Any of this binary's other 365 tests
742    /// that opens an executor therefore consumes the one handout first, and
743    /// this test's own positive control (`take` returning `Some`) becomes
744    /// impossible. Measured: passes alone, fails in the full lane at the
745    /// `!is_taken()` assertion below.
746    ///
747    /// `just check node-std-tests` runs it in its own cargo invocation, which
748    /// is a second process. Same shape and same answer as `boot_report::tests`
749    /// one recipe over, and for the same underlying reason.
750    #[cfg(nros_executor_backing_static)]
751    #[test]
752    #[ignore = "needs a virgin process: TAKEN is a process-global latch that \
753                Executor::open consumes — run via `just check node-std-tests`"]
754    fn the_static_is_handed_out_once_and_only_once() {
755        // Too large for the reservation: refused BEFORE the latch is touched, so
756        // this case cannot consume the one handout.
757        assert!(
758            take(EXECUTOR_BACKING_U64S + 1).is_none(),
759            "a request past the reservation must fall back to the heap"
760        );
761        assert!(
762            !is_taken(),
763            "an over-large request must not claim the latch"
764        );
765
766        let first = take(EXECUTOR_BACKING_U64S).expect("the first taker gets the static");
767        assert_eq!(
768            first.len(),
769            EXECUTOR_BACKING_U64S,
770            "the handout is the requested length, not the whole reservation"
771        );
772        assert!(is_taken());
773
774        assert!(
775            take(1).is_none(),
776            "a second taker must fall back to the heap — two `&'static mut` to \
777             one static is UB, which is the whole reason for the latch"
778        );
779    }
780
781    /// Issue 2579 — a FAILED `Executor::open` hands the static back, so a
782    /// retry gets it instead of the heap.
783    ///
784    /// A bare-metal board that boots before its XRCE Agent retries
785    /// `Executor::open` in a loop. Each failed open used to keep the
786    /// reservation it had just claimed, so every retry `Box::leak`ed a
787    /// default executor's worth (~87 KB on Cortex-M) from the heap, and on a
788    /// small heap the second retry panicked in the allocator. No backend is
789    /// registered in this binary, so `open` fails at backend selection,
790    /// before it touches the backing: the same "nothing came of it" shape as
791    /// an Agent that is not up yet.
792    ///
793    /// `#[ignore]` for the same virgin-process reason as the test above, and
794    /// run beside it by `just check node-std-tests`.
795    #[cfg(all(nros_executor_backing_static, feature = "rmw-cffi"))]
796    #[test]
797    #[ignore = "needs a virgin process: TAKEN is a process-global latch that \
798                Executor::open consumes — run via `just check node-std-tests`"]
799    fn the_static_comes_back_after_a_failed_open_or_a_drop() {
800        let config = crate::executor::ExecutorConfig::new("serial:///dev/null");
801        for attempt in 0..3 {
802            assert!(
803                crate::executor::Executor::open(&config).is_err(),
804                "attempt {attempt}: no backend is registered, so the open must fail"
805            );
806            assert!(
807                !is_taken(),
808                "attempt {attempt}: a failed open kept the static, so the next \
809                 retry allocates a default executor from the heap"
810            );
811        }
812        let held = take(EXECUTOR_BACKING_DEFAULT_U64S);
813        assert!(
814            held.is_some(),
815            "after the failed opens the reservation is still there to take"
816        );
817        // Issue 2576 — the drop path: an executor `open` built over the static
818        // owns it through `OwnedBacking`, and dropping that hands it back, so
819        // a re-open after a lost session gets the static again rather than a
820        // fresh heap block.
821        let owned = unsafe { OwnedBacking::owned(held.unwrap() as *mut _) };
822        assert!(is_taken());
823        drop(owned);
824        assert!(
825            !is_taken(),
826            "dropping the executor's owned backing must re-arm the static, or a \
827             re-open after a lost session allocates a default executor from the heap"
828        );
829        // A heap backing is freed, and leaves the latch alone.
830        let heap: *mut [MaybeUninit<u64>] =
831            alloc::boxed::Box::leak(alloc::boxed::Box::new_uninit_slice(4));
832        drop(unsafe { OwnedBacking::owned(heap) });
833        assert!(!is_taken());
834        let held = take(EXECUTOR_BACKING_DEFAULT_U64S);
835        assert!(
836            held.is_some(),
837            "the re-armed reservation can be taken again"
838        );
839        // The heap arm: with the static held, a failed open's backing is a
840        // `Box::new_uninit_slice`, which the give-back must FREE rather than
841        // re-arm a latch it never took. It must leave the static taken.
842        assert!(crate::executor::Executor::open(&config).is_err());
843        assert!(
844            is_taken(),
845            "a failed open over a HEAP backing must not re-arm the static's latch"
846        );
847    }
848
849    /// With the reservation off there is no static, so `take` is inert and no
850    /// image carries the bytes.
851    #[cfg(not(nros_executor_backing_static))]
852    #[test]
853    fn the_opt_out_removes_the_reservation_entirely() {
854        assert!(
855            take(1).is_none(),
856            "NROS_EXECUTOR_BACKING_BYTES=0 must hand out nothing"
857        );
858    }
859
860    /// issue 1571 — the entry's sched task backing goes out ONCE, whole, and each
861    /// slot is exactly one default executor's worth. Its own static, so unlike
862    /// the boot reservation's test it needs no virgin process.
863    #[test]
864    fn sched_task_backing_is_handed_out_once_and_each_slot_is_one_default_executor() {
865        static SCHED_TASKS: SchedTaskExecutorBacking<3> = SchedTaskExecutorBacking::new();
866        let slots = SCHED_TASKS.take();
867        assert_eq!(slots.len(), 3, "the first taker gets every slot");
868        assert_eq!(
869            core::mem::size_of::<SchedTaskExecutorBackingSlot>(),
870            8 * ExecutorSizing::DEFAULT.u64_len(),
871            "a slot is exactly what a DEFAULT-sized executor carves"
872        );
873        assert!(
874            SCHED_TASKS.take().is_empty(),
875            "a second taker must get nothing — two `&'static mut` to one slot is UB"
876        );
877    }
878
879    /// issue 1598 — a sched task's RTOS task memory is exactly the declared stack plus the
880    /// stated control-block bound, aligned for a thread stack, and handed out
881    /// ONCE: a second take is empty, never a second task on the same stack.
882    #[test]
883    fn sched_task_memory_is_the_declared_size_and_handed_out_once() {
884        static A: SchedTaskMemory<128> = SchedTaskMemory::new();
885        static B: SchedTaskMemory<32> = SchedTaskMemory::new();
886        static SET: SchedTaskMemorySet<2> = SchedTaskMemorySet::new([A.raw(), B.raw()]);
887        let rows = SET.take();
888        assert_eq!(rows.len(), 2);
889        assert_eq!(rows[0].stack_bytes, 128 * 8);
890        assert_eq!(rows[1].stack_bytes, 32 * 8);
891        assert_eq!(rows[0].tcb_bytes, SCHED_TASK_TCB_U64S * 8);
892        assert_eq!(rows[0].stack as usize % 64, 0, "stack is 64-byte aligned");
893        assert_ne!(rows[0].stack, rows[1].stack);
894        assert_eq!(
895            core::mem::size_of::<SchedTaskMemory<128>>(),
896            (SCHED_TASK_TCB_U64S + 128) * 8,
897            "nothing but the TCB bound and the stack"
898        );
899        assert!(
900            SET.take().is_empty(),
901            "a second take must not alias the rows"
902        );
903    }
904
905    /// issue 1571 — the one refusal: every sched task but the boot one needs a slot.
906    #[test]
907    fn sched_task_backing_refuses_a_block_short_of_the_spawned_sched_tasks() {
908        static TWO: SchedTaskExecutorBacking<2> = SchedTaskExecutorBacking::new();
909        let two = TWO.take();
910        assert_eq!(check_sched_task_executor_backing(3, two), Ok(()));
911        assert_eq!(
912            check_sched_task_executor_backing(1, &[]),
913            Ok(()),
914            "boot sched task only"
915        );
916        assert_eq!(
917            check_sched_task_executor_backing(4, two),
918            Err(SchedTaskBackingShort {
919                spawned: 3,
920                slots: 2
921            })
922        );
923        assert_eq!(
924            check_sched_task_executor_backing(2, &[]),
925            Err(SchedTaskBackingShort {
926                spawned: 1,
927                slots: 0
928            }),
929            "a taken-twice (empty) block is refused, not aliased"
930        );
931    }
932}