nros_node/executor/node_wake.rs
1//! `NodeWake`: heap-backed wake primitive
2//! used by `Executor::spin_once` on builds where the
3//! `nros_platform_wake_*` ABI is wired.
4//!
5//! Originally added for Zephyr+std because Zephyr's libc
6//! `pthread_cond_timedwait` hangs past its deadline. Now also
7//! active on FreeRTOS, NuttX, and ThreadX
8//! when those platforms are linked — each owns a kernel-native
9//! binary semaphore (`k_sem` / `xSemaphoreBinary` / `sem_t` /
10//! `tx_semaphore`) that honors its timeout. POSIX-only hosts
11//! still use the existing `std::sync::Condvar` path.
12//!
13//! Construction is fallible — if the platform provider hasn't
14//! linked a wake primitive (`wake_storage_size() == 0`) or
15//! `wake_init` returns non-zero, the caller falls back to
16//! driving the transport for the full timeout (matches the
17//! old expedient gate behaviour but without skipping
18//! reliable RTOS stream retransmission).
19//!
20//! Cfg relaxed from `std` to `alloc` so the same
21//! `NodeWake` type works for the embedded no_std FreeRTOS wake-cb
22//! path (target for the Cortex-M3 P99 acceptance). The
23//! `Box`/`Vec`/`Arc` types switch to the `alloc` crate; the
24//! kernel-side semantics are unchanged.
25
26// Phase 248 (C2) — platform-agnostic: no `platform-*` feature gate.
27// `NodeWake` calls the `nros_platform_wake_*` C ABI (the platform
28// vtable) generically; availability is decided at runtime by the
29// `wake_storage_size() == 0` probe in [`NodeWake::new`], not by a
30// compile-time per-RTOS cfg. Compiled for any `alloc + rmw-cffi` build;
31// platforms without a wake primitive simply report size 0 and the
32// caller falls back to driving the transport for the full timeout.
33#![cfg(all(feature = "alloc", feature = "rmw-cffi"))]
34// Phase 141.A.2 — `NodeWake` is callable from the std-gated
35// `install_wake_signal_on_*` path today; the matching no_std
36// caller for the FreeRTOS-embedded wake-cb path is the
37// follow-on 141.A.3 work. Until that lands, the no_std build of
38// this module has no consumer — `#[allow(dead_code)]` keeps the
39// type compilable so 141.A.3 only has to add the caller, not
40// re-introduce the type.
41#![cfg_attr(not(feature = "alloc"), allow(dead_code))]
42
43use core::ffi::c_void;
44
45unsafe extern "C" {
46 fn nros_platform_wake_init(w: *mut c_void) -> i8;
47 fn nros_platform_wake_drop(w: *mut c_void) -> i8;
48 fn nros_platform_wake_wait_ms(w: *mut c_void, timeout_ms: u32) -> i8;
49 fn nros_platform_wake_signal(w: *mut c_void) -> i8;
50 fn nros_platform_wake_signal_from_isr(w: *mut c_void) -> i8;
51 fn nros_platform_wake_park_handles_us(
52 w: *mut c_void,
53 handles: *const i32,
54 n: usize,
55 deadline_us: u64,
56 ) -> i8;
57 fn nros_platform_wake_park_until_us(w: *mut c_void, deadline_us: u64) -> i8;
58 fn nros_platform_wake_park_granularity_us() -> u64;
59 fn nros_platform_wake_storage_size() -> usize;
60 fn nros_platform_wake_storage_align() -> usize;
61}
62
63/// Heap-backed wake primitive. Sized at runtime from the platform
64/// probe (`nros_platform_wake_storage_size`).
65pub(crate) struct NodeWake {
66 storage: alloc::boxed::Box<[u8]>,
67 /// Issue 2225 (RFC-0113 D9) -- a framework scheduler's wake, called after
68 /// every [`signal`](Self::signal). The other half of the yielding park
69 /// slot: a PX4 sched task is a work item that never waits on this object, so an
70 /// arrival that only signals it would be dispatched at the tier's next
71 /// deadline. `hook_fn` is the `WakeHookFn` as a `usize`, 0 when unset;
72 /// `hook_ctx` is stored before it and cleared after it.
73 hook_fn: portable_atomic::AtomicUsize,
74 hook_ctx: portable_atomic::AtomicPtr<c_void>,
75}
76
77/// Issue 2225 -- the hook [`NodeWake::set_hook`] installs. Called from the
78/// signalling context (a transport thread, a publisher's context, an ISR
79/// forward), so it must be thread-safe, non-blocking and O(1).
80pub(crate) type WakeHookFn = unsafe extern "C" fn(ctx: *mut c_void);
81
82// SAFETY: per `<nros/platform.h>`'s wake contract, signal/wait are
83// callable from any thread (k_sem on Zephyr is kernel-managed).
84unsafe impl Send for NodeWake {}
85unsafe impl Sync for NodeWake {}
86
87impl NodeWake {
88 /// Allocate + init. Returns `None` if the platform provider
89 /// reports the primitive unavailable (`nros_platform_wake_storage_size() == 0`)
90 /// or if `wake_init` returns non-zero.
91 pub(crate) fn new() -> Option<Self> {
92 // SAFETY: probe functions are documented pure (no global
93 // state, may be called before init).
94 let size = unsafe { nros_platform_wake_storage_size() };
95 let align = unsafe { nros_platform_wake_storage_align() };
96 if size == 0 {
97 return None;
98 }
99 // Round capacity up so the boxed slice's data ptr is
100 // aligned to the requested boundary. `Box::<[u8]>` only
101 // guarantees byte alignment; layout-allocate via Vec
102 // capacity + a manual alignment check, or fall back to
103 // `vec![0; size + align]` and offset. Simplest: use a
104 // `Vec<u64>` for >=8B alignment (covers every platform we
105 // ship today; `k_sem` and `sem_t` are <= 8B-aligned).
106 if align > core::mem::align_of::<u64>() {
107 return None;
108 }
109 let u64s = size.div_ceil(8);
110 let boxed: alloc::boxed::Box<[u64]> = alloc::vec![0u64; u64s].into_boxed_slice();
111 // Reinterpret the boxed [u64] as a boxed [u8]. The
112 // capacity in bytes is `u64s * 8 >= size`; the data
113 // pointer inherits 8-byte alignment from `Vec<u64>`'s
114 // allocator request.
115 // Take the data pointer as a THIN `*mut u8` (not `as *mut [u8]`, which
116 // would keep the `u64s` element count for a u8 slice — wrong length, and
117 // trips `clippy::cast_slice_different_sizes`). The fat slice is rebuilt
118 // below with the correct byte length.
119 let raw = alloc::boxed::Box::into_raw(boxed) as *mut u8;
120 // SAFETY: `raw` came from `Box::<[u64]>::into_raw`; we
121 // re-box as `Box<[u8]>` with the same total byte length.
122 // The allocator only cares about the total size + the
123 // pointer originally returned, both preserved.
124 let storage: alloc::boxed::Box<[u8]> = unsafe {
125 alloc::boxed::Box::from_raw(core::ptr::slice_from_raw_parts_mut(raw, u64s * 8))
126 };
127 let ptr = storage.as_ptr() as *mut c_void;
128 // SAFETY: `ptr` references at least `size` bytes aligned
129 // to 8 (verified above). `wake_init` initialises in place
130 // or returns non-zero — in which case we drop `storage`
131 // without calling `wake_drop`, matching the "init failed,
132 // no teardown" contract.
133 let rc = unsafe { nros_platform_wake_init(ptr) };
134 if rc != 0 {
135 return None;
136 }
137 Some(Self {
138 storage,
139 hook_fn: portable_atomic::AtomicUsize::new(0),
140 hook_ctx: portable_atomic::AtomicPtr::new(core::ptr::null_mut()),
141 })
142 }
143
144 /// Block until signaled or `timeout_ms` elapses. Returns
145 /// `true` on signal, `false` on timeout or error.
146 /// The raw primitive a PORT must wait on if it installs its own park.
147 ///
148 /// phase-436 W7 — a park primitive that waits on its own fresh object
149 /// cannot be broken by the backend's listener, because the listener
150 /// signals THIS one. Installing such a park makes latency worse, not
151 /// better: `spin_once` drops the transport drain to non-blocking once a
152 /// port has parked, so an unbreakable park sleeps out its whole deadline
153 /// with data already waiting.
154 ///
155 /// A port's `ParkUntilFn` therefore takes this pointer as its `ctx`.
156 pub(crate) fn raw_ptr(&self) -> *mut c_void {
157 self.storage.as_ptr() as *mut c_void
158 }
159
160 pub(crate) fn wait_ms(&self, timeout_ms: u32) -> bool {
161 let ptr = self.storage.as_ptr() as *mut c_void;
162 // SAFETY: ptr was init'd in `new`; the underlying
163 // primitive supports concurrent calls per platform spec.
164 unsafe { nros_platform_wake_wait_ms(ptr, timeout_ms) == 0 }
165 }
166
167 /// Issue 2965 -- wait at most `us` microseconds, or until signalled, at
168 /// the finest park the port offers. `true` when signalled.
169 ///
170 /// A band worker's park is the time to its band's next timer, and that is
171 /// rarely a whole number of milliseconds. Rounded up to `wait_ms`'s
172 /// millisecond, a 1 kHz level whose callback takes 300 us parked 1000 us
173 /// for a deadline 700 us away, so every release came 1.3 ms after the last
174 /// and the `Skip` policy dropped one period in four. The port's
175 /// microsecond park (`nros_platform_wake_park_until_us`) takes the bound
176 /// as it is, rounded up only to the port's own granularity; a port that
177 /// offers none (granularity 0) or cannot park (-1) keeps the millisecond
178 /// wait, which still never wakes before the timer.
179 pub(crate) fn wait_us(&self, us: u64) -> bool {
180 let ptr = self.storage.as_ptr() as *mut c_void;
181 // SAFETY: a pure query of the port.
182 let granularity = unsafe { nros_platform_wake_park_granularity_us() };
183 match band_park(us, granularity) {
184 BandPark::Us(us) => {
185 // SAFETY: as `wait_ms`.
186 match unsafe { nros_platform_wake_park_until_us(ptr, us) } {
187 0 => return true,
188 1 => return false,
189 _ => {}
190 }
191 }
192 BandPark::Ms(ms) => return self.wait_ms(ms),
193 }
194 self.wait_ms(band_park_ms(us))
195 }
196
197 /// phase-521 W3 (RFC-0113 D3) — park on this object AND on the OS
198 /// `handles` (the sessions' `ReadinessSource::Waitable` descriptors) for
199 /// at most `deadline_us`.
200 ///
201 /// `Some(true)` when signalled or a handle became readable, `Some(false)`
202 /// when the deadline expired, `None` when the port cannot wait on handles —
203 /// the caller then keeps the wait it had.
204 pub(crate) fn park_handles_us(&self, handles: &[i32], deadline_us: u64) -> Option<bool> {
205 let ptr = self.storage.as_ptr() as *mut c_void;
206 // SAFETY: ptr was init'd in `new`; `handles` is a live slice for the
207 // call, and the port reads it only during the call.
208 match unsafe {
209 nros_platform_wake_park_handles_us(ptr, handles.as_ptr(), handles.len(), deadline_us)
210 } {
211 0 => Some(true),
212 1 => Some(false),
213 _ => None,
214 }
215 }
216
217 /// Call the hook if one is installed, then wake one waiter. Safe from
218 /// any thread.
219 ///
220 /// The hook goes FIRST: a framework that installs one (a PX4 work item)
221 /// has nothing waiting on this object, so its reschedule must not queue
222 /// behind the platform signal's syscall.
223 pub(crate) fn signal(&self) {
224 let f = self.hook_fn.load(portable_atomic::Ordering::Acquire);
225 if f != 0 {
226 let ctx = self.hook_ctx.load(portable_atomic::Ordering::Acquire);
227 // SAFETY: `f` was stored from a `WakeHookFn` by `set_hook`, and
228 // its caller keeps `ctx` alive until it clears the hook.
229 let hook: WakeHookFn = unsafe { core::mem::transmute::<usize, WakeHookFn>(f) };
230 unsafe { hook(ctx) };
231 }
232 let ptr = self.storage.as_ptr() as *mut c_void;
233 // SAFETY: see wait_ms.
234 let _ = unsafe { nros_platform_wake_signal(ptr) };
235 }
236
237 /// [`signal`](Self::signal) from an interrupt handler (on POSIX, a
238 /// signal handler): the hook, then the port's
239 /// `nros_platform_wake_signal_from_isr` (`xSemaphoreGiveFromISR` and a
240 /// yield on FreeRTOS). Issue 2696. The hook's own contract already
241 /// covers an ISR forward ([`WakeHookFn`]).
242 ///
243 /// `false` when the port has no interrupt-safe signal (it returns -1, as
244 /// the ports no test reaches do, issue 2706): the waiter then sees the
245 /// flag at its own deadline.
246 pub(crate) fn signal_from_isr(&self) -> bool {
247 let f = self.hook_fn.load(portable_atomic::Ordering::Acquire);
248 if f != 0 {
249 let ctx = self.hook_ctx.load(portable_atomic::Ordering::Acquire);
250 // SAFETY: as `signal`.
251 let hook: WakeHookFn = unsafe { core::mem::transmute::<usize, WakeHookFn>(f) };
252 unsafe { hook(ctx) };
253 }
254 let ptr = self.storage.as_ptr() as *mut c_void;
255 // SAFETY: see wait_ms.
256 unsafe { nros_platform_wake_signal_from_isr(ptr) == 0 }
257 }
258
259 /// Issue 2225 -- install (`Some`) or clear (`None`) the hook
260 /// [`signal`](Self::signal) calls. `ctx` must outlive the hook: clear it
261 /// before `ctx` goes away.
262 pub(crate) fn set_hook(&self, hook: Option<WakeHookFn>, ctx: *mut c_void) {
263 match hook {
264 Some(f) => {
265 self.hook_ctx.store(ctx, portable_atomic::Ordering::Release);
266 self.hook_fn
267 .store(f as usize, portable_atomic::Ordering::Release);
268 }
269 None => {
270 self.hook_fn.store(0, portable_atomic::Ordering::Release);
271 self.hook_ctx
272 .store(core::ptr::null_mut(), portable_atomic::Ordering::Release);
273 }
274 }
275 }
276}
277
278impl Drop for NodeWake {
279 fn drop(&mut self) {
280 let ptr = self.storage.as_ptr() as *mut c_void;
281 // SAFETY: ptr was init'd in `new`; this is the matching
282 // teardown call. NodeWake is owned exclusively by the
283 // Executor (held inside Arc), so no in-flight wait can
284 // overlap Drop.
285 let _ = unsafe { nros_platform_wake_drop(ptr) };
286 }
287}
288
289/// phase-509 P9b item 4 (RFC-0108 "As built in P9b") -- a band worker's wake
290/// object over the platform's (`nros_platform_wake_*`): what a level runner
291/// gives each spawned level.
292impl super::scheduler::BandWaiter {
293 /// A waiter over a new platform wake object, leaked with it: one per
294 /// level, for the image's life. `None` when the platform links no wake
295 /// primitive; the level then polls.
296 pub fn platform() -> Option<&'static Self> {
297 unsafe extern "C" fn wake(ctx: *mut c_void) {
298 // SAFETY: `ctx` is the leaked `NodeWake` below.
299 unsafe { &*(ctx as *const NodeWake) }.signal();
300 }
301 unsafe extern "C" fn wake_from_isr(ctx: *mut c_void) {
302 // SAFETY: as `wake`.
303 let _ = unsafe { &*(ctx as *const NodeWake) }.signal_from_isr();
304 }
305 unsafe extern "C" fn wait(ctx: *mut c_void, us: u64) -> i32 {
306 // Issue 2965 -- at the port's finest park, never the millisecond
307 // when the port can do better ([`NodeWake::wait_us`]).
308 // SAFETY: as `wake`.
309 if unsafe { &*(ctx as *const NodeWake) }.wait_us(us) {
310 0
311 } else {
312 -1
313 }
314 }
315 let w: &'static NodeWake =
316 alloc::boxed::Box::leak(alloc::boxed::Box::new(NodeWake::new()?));
317 let ctx = w as *const NodeWake as *mut c_void;
318 // SAFETY: the wake object is leaked, so it outlives every executor;
319 // its signal and wait are callable from any thread (the platform's
320 // wake contract).
321 let waiter = unsafe { Self::new(wake, wake_from_isr, wait, ctx) };
322 Some(alloc::boxed::Box::leak(alloc::boxed::Box::new(waiter)))
323 }
324}
325
326/// Issue 2965 -- how a band worker parks for `us` microseconds on a port whose
327/// microsecond park has `granularity_us` resolution.
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
329pub(crate) enum BandPark {
330 /// The port's microsecond park, for this many microseconds: `us` rounded
331 /// UP to the granularity, so the park never ends before the timer is due.
332 Us(u64),
333 /// The millisecond wait, for this many milliseconds: the port offers no
334 /// finer park (granularity 0, `PlatformThreading`'s default).
335 Ms(u32),
336}
337
338/// Issue 2965 -- the park a band worker takes for a bound of `us`.
339pub(crate) fn band_park(us: u64, granularity_us: u64) -> BandPark {
340 if granularity_us == 0 {
341 return BandPark::Ms(band_park_ms(us));
342 }
343 BandPark::Us(us.div_ceil(granularity_us).saturating_mul(granularity_us))
344}
345
346/// `us` rounded UP to whole milliseconds, for the millisecond wait.
347pub(crate) fn band_park_ms(us: u64) -> u32 {
348 us.div_ceil(1000).min(u64::from(u32::MAX)) as u32
349}
350
351#[cfg(test)]
352mod band_park_tests {
353 use super::{BandPark, band_park, band_park_ms};
354
355 /// The measured case: a 1 kHz level whose 300 us callback leaves its next
356 /// release 700 us away. A 1 us park waits 700 us; the millisecond wait it
357 /// replaced waited 1000, which put every release 1.3 ms after the last.
358 #[test]
359 fn a_microsecond_port_parks_for_the_bound_itself() {
360 assert_eq!(band_park(700, 1), BandPark::Us(700));
361 assert_eq!(band_park(1, 1), BandPark::Us(1));
362 assert_eq!(band_park(0, 1), BandPark::Us(0));
363 }
364
365 /// A coarser port (an RTOS tick) rounds UP to its tick, so the park never
366 /// ends before the timer is due.
367 #[test]
368 fn a_tick_port_rounds_up_to_its_tick() {
369 assert_eq!(band_park(700, 10_000), BandPark::Us(10_000));
370 assert_eq!(band_park(10_001, 10_000), BandPark::Us(20_000));
371 assert_eq!(band_park(10_000, 10_000), BandPark::Us(10_000));
372 }
373
374 /// The negative control: a port with no microsecond park keeps the
375 /// millisecond wait, rounded up as before.
376 #[test]
377 fn a_port_with_no_microsecond_park_keeps_the_millisecond() {
378 assert_eq!(band_park(700, 0), BandPark::Ms(1));
379 assert_eq!(band_park(1_001, 0), BandPark::Ms(2));
380 assert_eq!(band_park_ms(u64::MAX), u32::MAX);
381 }
382}