nros_node/executor/deferred.rs
1//! Deferred dispatch for a hand-written host (the **Defer** part of the
2//! lowest framework support tier).
3//!
4//! A host that schedules work by priority (RTIC, a work queue, an RTOS task
5//! per callback class) wants the executor to find out WHAT is ready, and to
6//! run it LATER, in a task the host picks. Until this module the only form of
7//! that was the per-node `__nros_node_<pkg>_on_callback` slot ABI that
8//! `nros::node!` emitted, so a caller that did not go through the macros could
9//! not use it. (Nothing ever filled or drained that registry, and it was
10//! retired.)
11//!
12//! The shape is three calls on [`Executor`], with no macro-private type:
13//!
14//! 1. [`Executor::set_deferred`] marks one registered callback (by the
15//! [`HandleId`] its registration returned) as deferred. The spin never runs
16//! it inline again.
17//! 2. [`Executor::set_defer_notifier`] installs a plain
18//! `fn(ctx, HandleId)`. When a deferred callback becomes ready, the spin
19//! ENQUEUES it and calls the notifier once, so the host can pend the task
20//! that will run it. The notifier runs on the spinning thread, inside the
21//! pass: it must not block and cannot reach the executor.
22//! 3. The host drains from its own task: [`Executor::run_deferred`] runs every
23//! queued callback, [`Executor::run_deferred_handle`] runs one (for a host
24//! that maps callbacks onto tasks of different priorities).
25//!
26//! The queue is one bit per callback slot (a `SlotMask`, which names every
27//! slot the callback table can hold, `MAX_CALLBACK_SLOTS`), so it allocates nothing
28//! and an enqueue of a callback that is already queued is a no-op: the
29//! callback runs once per drain, and takes what one dispatch takes. Data left
30//! behind is found by the next spin, which queues the callback again.
31//!
32//! Timers cannot be deferred. A timer's readiness is decided INSIDE its
33//! dispatch (it consumes the spin's elapsed time there), so there is nothing
34//! to enqueue ahead of running it; [`Executor::set_deferred`] refuses one.
35
36use super::{
37 arena::EntryKind,
38 slot_mask::SlotMask,
39 spin::Executor,
40 types::{DeferNotify, HandleId, SpinOnceResult},
41};
42
43impl<'s> Executor<'s> {
44 /// Defer (or stop deferring) one registered callback.
45 ///
46 /// A deferred callback is never run by `spin_once` / `spin_some`: when it
47 /// is ready the spin queues it and calls the notifier from
48 /// [`set_defer_notifier`](Self::set_defer_notifier), and it runs when the
49 /// host calls [`run_deferred`](Self::run_deferred) or
50 /// [`run_deferred_handle`](Self::run_deferred_handle).
51 ///
52 /// Returns `false`, changing nothing, when `id` names no live callback or
53 /// names a timer (see the module docs). Turning deferral OFF also drops
54 /// the callback from the queue; it stays ready, so the next spin runs it
55 /// inline.
56 ///
57 /// A deferred callback takes no part in the spin's trigger
58 /// ([`set_trigger`](Self::set_trigger)): it is neither "ready" for
59 /// `Trigger::Any` nor required by `Trigger::All`.
60 pub fn set_deferred(&mut self, id: HandleId, deferred: bool) -> bool {
61 let Some(slot) = self.resolve_handle(id) else {
62 return false;
63 };
64 let Some(meta) = self.entries.get(slot).and_then(|e| e.as_ref()) else {
65 return false;
66 };
67 if matches!(meta.kind, EntryKind::Timer) {
68 return false;
69 }
70 if deferred {
71 self.deferred_mask.set(slot);
72 } else {
73 self.deferred_mask.clear(slot);
74 self.deferred_pending.clear(slot);
75 }
76 true
77 }
78
79 /// Whether `id` names a deferred callback.
80 pub fn is_deferred(&self, id: HandleId) -> bool {
81 self.resolve_handle(id)
82 .is_some_and(|slot| self.deferred_mask.test(slot))
83 }
84
85 /// Install the notifier the spin calls when it queues a deferred
86 /// callback, with the context it is called with. Replaces any earlier
87 /// notifier.
88 ///
89 /// Called once per queueing: a callback that is already queued is not
90 /// queued (or notified) again until a drain has run it. With no notifier
91 /// the queue still fills, and the host can poll
92 /// [`has_deferred`](Self::has_deferred).
93 ///
94 /// `ctx` is handed back verbatim and never dereferenced by the executor;
95 /// whatever it points to must stay valid while the notifier is installed.
96 pub fn set_defer_notifier(&mut self, notify: DeferNotify, ctx: *mut core::ffi::c_void) {
97 self.defer_notify = Some((notify, ctx));
98 }
99
100 /// Remove the notifier. Deferred callbacks keep being queued.
101 pub fn clear_defer_notifier(&mut self) {
102 self.defer_notify = None;
103 }
104
105 /// Whether any deferred callback is queued and waiting for a drain.
106 pub fn has_deferred(&self) -> bool {
107 !self.deferred_pending.is_empty()
108 }
109
110 /// Whether the deferred callback `id` is queued.
111 pub fn is_deferred_pending(&self, id: HandleId) -> bool {
112 self.resolve_handle(id)
113 .is_some_and(|slot| self.deferred_pending.test(slot))
114 }
115
116 /// Run every queued deferred callback once, in slot (registration)
117 /// order, and empty the queue. The counts are `spin_once`'s.
118 ///
119 /// Call this from the host task that owns deferred work. It does no I/O
120 /// and never waits: a callback that finds no data (it was taken some
121 /// other way) is an `Ok(false)` dispatch, counted as nothing.
122 pub fn run_deferred(&mut self) -> SpinOnceResult {
123 let mut result = SpinOnceResult::new();
124 self.reap_deferred_releases();
125 for slot in self.deferred_pending.iter_ones() {
126 self.dispatch_deferred_slot(slot, &mut result);
127 }
128 result
129 }
130
131 /// Run the deferred callback `id` once if it is queued. Returns whether it
132 /// ran (`false` when it was not queued or `id` names no live callback).
133 ///
134 /// For a host that maps deferred callbacks onto tasks of different
135 /// priorities: the notifier says which one is ready, and the task that
136 /// owns it runs exactly that one.
137 pub fn run_deferred_handle(&mut self, id: HandleId) -> bool {
138 let Some(slot) = self.resolve_handle(id) else {
139 return false;
140 };
141 self.reap_deferred_releases();
142 let mut result = SpinOnceResult::new();
143 self.dispatch_deferred_slot(slot, &mut result)
144 }
145
146 /// The spin's half: move every deferred bit of `ready` into the queue,
147 /// notify the newly queued ones, and return what is left for the spin to
148 /// dispatch inline.
149 pub(crate) fn defer_ready(&mut self, ready: SlotMask) -> SlotMask {
150 let deferred = ready & self.deferred_mask;
151 if deferred.is_empty() {
152 return ready;
153 }
154 let fresh = deferred.and_not(self.deferred_pending);
155 self.deferred_pending |= deferred;
156 if let Some((notify, ctx)) = self.defer_notify {
157 for slot in fresh.iter_ones() {
158 notify(ctx, self.handle_for(slot));
159 }
160 }
161 ready.and_not(self.deferred_mask)
162 }
163
164 /// Forget a slot's deferral when its entry is released, so the slot's
165 /// next occupant starts inline and unqueued.
166 pub(crate) fn forget_deferred(&mut self, slot: usize) {
167 self.deferred_mask.clear(slot);
168 self.deferred_pending.clear(slot);
169 }
170
171 fn dispatch_deferred_slot(&mut self, slot: usize, result: &mut SpinOnceResult) -> bool {
172 if !self.deferred_pending.test(slot) {
173 return false;
174 }
175 // Held: its release is pending (it never runs again) or its callback
176 // is already running below us. Either way not now; a held slot that
177 // still has data is queued again by the next spin.
178 if Self::slot_held(self.slot_tags, slot) {
179 return false;
180 }
181 self.deferred_pending.clear(slot);
182 let Some(meta) = self.entries.get(slot).and_then(|e| e.as_ref()) else {
183 return false;
184 };
185 let kind = meta.kind;
186 let try_process = meta.try_process;
187 // SAFETY: `meta.offset` is this live entry's arena slot, written by its
188 // registration; `try_process` matches the entry's concrete type.
189 let data_ptr = unsafe { (self.arena.as_mut_ptr() as *mut u8).add(meta.offset) };
190 Self::begin_dispatch(self.slot_tags, slot);
191 // SAFETY: as the spin's own dispatch: `data_ptr` is the live entry
192 // `try_process` was registered for, and nothing else runs it (the slot
193 // is marked dispatching). `delta_us` is only read by a timer, which
194 // cannot be deferred, so 0 is never observed.
195 let processed = unsafe { try_process(data_ptr, 0, slot as u8) };
196 self.finish_dispatch(slot);
197 // One dispatch takes what one call takes; an attributed slot is asked
198 // `has_data` again next spin, exactly as the inline drain arranges.
199 #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
200 {
201 self.entity_recheck |= SlotMask::bit(slot) & self.entity_attributed;
202 }
203 match processed {
204 Ok(true) => match kind {
205 EntryKind::Subscription => result.subscriptions_processed += 1,
206 EntryKind::Service
207 | EntryKind::ServiceClient
208 | EntryKind::ActionServer
209 | EntryKind::ActionClient => result.services_handled += 1,
210 EntryKind::Timer => result.timers_fired += 1,
211 EntryKind::GuardCondition => {}
212 },
213 Ok(false) => {}
214 Err(_) => match kind {
215 EntryKind::Subscription => result.subscription_errors += 1,
216 EntryKind::Service
217 | EntryKind::ServiceClient
218 | EntryKind::ActionServer
219 | EntryKind::ActionClient => result.service_errors += 1,
220 EntryKind::Timer | EntryKind::GuardCondition => {}
221 },
222 }
223 true
224 }
225}