embassy_sync/waitqueue/atomic_waker.rs
1use core::cell::Cell;
2#[cfg(target_has_atomic = "32")]
3use core::cell::UnsafeCell;
4#[cfg(target_has_atomic = "32")]
5use core::sync::atomic::AtomicUsize;
6#[cfg(target_has_atomic = "32")]
7use core::sync::atomic::Ordering::{AcqRel, Acquire, Release};
8use core::task::Waker;
9
10use crate::blocking_mutex::Mutex;
11use crate::blocking_mutex::raw::RawMutex;
12
13/// Utility struct to register and wake a waker.
14/// If a waker is registered, registering another waker will replace the previous one without waking it.
15/// Intended to wake a task from an interrupt. Therefore, it is generally not expected,
16/// that multiple tasks register try to register a waker simultaneously.
17///
18/// Most users should prefer [`AtomicWaker`], which uses a small atomic state machine and
19/// does **not** enter a critical section on the wake path. See also
20/// [`CriticalSectionWaker`](super::CriticalSectionWaker), a non-generic convenience wrapper
21/// that hard-codes [`CriticalSectionRawMutex`](crate::blocking_mutex::raw::CriticalSectionRawMutex).
22pub struct GenericAtomicWaker<M: RawMutex> {
23 waker: Mutex<M, Cell<Option<Waker>>>,
24}
25
26impl<M: RawMutex> GenericAtomicWaker<M> {
27 /// Create a new `GenericAtomicWaker`.
28 pub const fn new(mutex: M) -> Self {
29 Self {
30 waker: Mutex::const_new(mutex, Cell::new(None)),
31 }
32 }
33
34 /// Register a waker. Overwrites the previous waker, if any.
35 pub fn register(&self, w: &Waker) {
36 self.waker.lock(|cell| {
37 cell.set(match cell.replace(None) {
38 Some(w2) if (w2.will_wake(w)) => Some(w2),
39 _ => Some(w.clone()),
40 })
41 })
42 }
43
44 /// Wake the registered waker, if any.
45 pub fn wake(&self) {
46 self.waker.lock(|cell| {
47 if let Some(w) = cell.replace(None) {
48 w.wake_by_ref();
49 cell.set(Some(w));
50 }
51 })
52 }
53}
54
55// Lockless single-slot waker, ported from `futures::task::AtomicWaker` and
56// adapted for `no_std`. Coordinates access to a single waker slot via a small
57// atomic state machine, so neither `register()` nor `wake()` enters a critical
58// section.
59//
60// Reference: <https://docs.rs/futures/latest/futures/task/struct.AtomicWaker.html>
61
62// The state machine is encoded as a pair of independent bitflags packed into a
63// single `AtomicUsize`. They are *not* mutually exclusive: `wake()` uses
64// `fetch_or` to set the `WAKING` bit unconditionally, so a `wake()` that races
65// an in-flight `register()` legitimately produces the combined state
66// `REGISTERING | WAKING` (0b11). All four encodings are valid:
67//
68// - `WAITING` (0b00): no operation in flight, waker cell is idle.
69// - `REGISTERING` (0b01): a `register()` call owns the waker cell.
70// - `WAKING` (0b10): a `wake()` call owns the waker cell.
71// - `REGISTERING | WAKING` (0b11): a `register()` owns the cell and a
72// concurrent `wake()` has flagged that a wake is pending; the in-flight
73// `register()` is responsible for honoring it before releasing the cell
74// (see `register()` and `wake()` below).
75//
76// Only the holder of `REGISTERING` *or* `WAKING` (but never both at the same
77// time, by virtue of the protocol) may dereference the waker cell.
78
79/// No flags set: waker cell is idle and may be claimed by `register()` or
80/// `wake()`.
81#[cfg(target_has_atomic = "32")]
82const WAITING: usize = 0;
83/// Bit set while a `register()` call owns the waker cell.
84#[cfg(target_has_atomic = "32")]
85const REGISTERING: usize = 0b01;
86/// Bit set while a `wake()` call owns the waker cell, or — when combined with
87/// `REGISTERING` — to signal an in-flight `register()` that a wake is pending
88/// and must be driven before the cell is released.
89#[cfg(target_has_atomic = "32")]
90const WAKING: usize = 0b10;
91
92/// Utility struct to register and wake a waker.
93///
94/// Single-slot waker coordinated by an atomic state machine. Unlike
95/// [`CriticalSectionWaker`](super::CriticalSectionWaker), `wake()` does **not**
96/// enter a critical section, which avoids unnecessary jitter on higher-priority
97/// interrupts and improves wake latency for time-critical async drivers.
98///
99/// If a waker is registered, registering a different waker replaces the
100/// previous one and wakes it, giving the displaced task a chance to
101/// re-register itself. This matches the semantics of
102/// [`WakerRegistration`](super::WakerRegistration); note that
103/// [`GenericAtomicWaker`] and
104/// [`CriticalSectionWaker`](super::CriticalSectionWaker) instead replace the
105/// previous waker *without* waking it.
106///
107/// Intended to wake a single task from an interrupt handler.
108///
109/// On targets without 32-bit atomic CAS support (e.g. Xtensa S2, AVR, RV32I),
110/// `AtomicWaker` is a type alias for
111/// [`CriticalSectionWaker`](super::CriticalSectionWaker), since the lockless
112/// state machine relies on `compare_exchange`/`swap`/`fetch_or`.
113#[cfg(target_has_atomic = "32")]
114pub struct AtomicWaker {
115 state: AtomicUsize,
116 waker: UnsafeCell<Option<Waker>>,
117}
118
119// SAFETY: All access to the `waker` cell is serialized through the `state`
120// machine: only the holder of the REGISTERING or WAKING flag may dereference
121// the cell.
122#[cfg(target_has_atomic = "32")]
123unsafe impl Send for AtomicWaker {}
124#[cfg(target_has_atomic = "32")]
125unsafe impl Sync for AtomicWaker {}
126
127#[cfg(target_has_atomic = "32")]
128impl AtomicWaker {
129 /// Create a new `AtomicWaker`.
130 pub const fn new() -> Self {
131 Self {
132 state: AtomicUsize::new(WAITING),
133 waker: UnsafeCell::new(None),
134 }
135 }
136
137 /// Register a waker.
138 ///
139 /// If a different waker was previously registered, it is replaced and
140 /// woken so the displaced task can re-register itself if it is still
141 /// interested. This matches
142 /// [`WakerRegistration::register`](super::WakerRegistration::register).
143 ///
144 /// If a [`wake`](Self::wake) call is in flight when this is called, the
145 /// supplied waker is woken directly to schedule a re-poll.
146 pub fn register(&self, waker: &Waker) {
147 match self
148 .state
149 .compare_exchange(WAITING, REGISTERING, Acquire, Acquire)
150 .unwrap_or_else(|x| x)
151 {
152 WAITING => {
153 // The waker evicted from the cell (if any), to be woken
154 // *after* we release REGISTERING so the wake cannot re-enter
155 // while we still own the cell.
156 let evicted: Option<Waker>;
157 // The newly-registered waker, taken back out in the handoff
158 // path because a racing `wake()` transferred wake duty to us.
159 let pending_wake: Option<Waker>;
160
161 // SAFETY: We hold the REGISTERING flag; no other call can
162 // touch the waker cell while we own it.
163 unsafe {
164 evicted = match &*self.waker.get() {
165 Some(old) if old.will_wake(waker) => None,
166 _ => (*self.waker.get()).replace(waker.clone()),
167 };
168
169 // Try to release the cell by clearing REGISTERING. This
170 // CAS only succeeds if no `wake()` raced us; otherwise the
171 // observed state is REGISTERING | WAKING (0b11) and the
172 // CAS fails — that failure is precisely the handoff
173 // signal from `wake()`.
174 let res = self.state.compare_exchange(REGISTERING, WAITING, AcqRel, Acquire);
175 pending_wake = match res {
176 Ok(_) => None,
177 Err(_) => {
178 // A concurrent `wake()` observed our REGISTERING
179 // bit and intentionally left the WAKING bit set
180 // instead of touching the waker cell (which we
181 // own). The wake duty has been transferred to us:
182 // take the waker out and clear both bits in a
183 // single `swap` so a new `register()` / `wake()`
184 // cycle can begin. We drive the wake outside the
185 // unsafe block, below.
186 //
187 // This is what makes the "missed wake" race
188 // impossible: the wake is delivered exactly once,
189 // either by `wake()` itself (no race) or by
190 // `register()` here (race), but never dropped.
191 let w = (*self.waker.get()).take().unwrap();
192 self.state.swap(WAITING, AcqRel);
193 Some(w)
194 }
195 };
196 }
197
198 // Cell ownership has been released. It is now safe to invoke
199 // user wakers, which may re-enter `register()` / `wake()` on
200 // this same `AtomicWaker`.
201 if let Some(w) = pending_wake {
202 w.wake();
203 }
204 if let Some(w) = evicted {
205 w.wake();
206 }
207 }
208 WAKING => {
209 // A wake is currently in flight. Schedule the supplied waker
210 // directly so the task does not miss the wakeup.
211 waker.wake_by_ref();
212 }
213 state => {
214 // A concurrent `register` is in flight. The single-waiter
215 // contract is being violated; drop our call (memory-safe).
216 debug_assert!(state == REGISTERING || state == REGISTERING | WAKING);
217 }
218 }
219 }
220
221 /// Wake the registered waker, if any.
222 ///
223 /// A clone of the stored waker is woken after the state is released, so
224 /// the stored waker remains registered, matching the semantics of
225 /// [`CriticalSectionWaker`](super::CriticalSectionWaker).
226 pub fn wake(&self) {
227 // `fetch_or` (rather than `compare_exchange`) is load-bearing here.
228 // It unconditionally publishes the WAKING bit, even if a `register()`
229 // is mid-flight (state == REGISTERING). This is what enables the
230 // handoff: the in-flight `register()` will observe the combined
231 // REGISTERING | WAKING state on its release-CAS, take ownership of
232 // the wake, and drive it.
233 //
234 // A `compare_exchange(WAITING, WAKING, ...)` here would silently drop
235 // the wake whenever it lost the race against `register()`, leaving
236 // the task hung — the waker cell holds a stale waker that nothing is
237 // about to invoke.
238 match self.state.fetch_or(WAKING, AcqRel) {
239 WAITING => {
240 // No `register()` was in flight, so we now solely own the
241 // waker cell via the WAKING bit.
242 //
243 // SAFETY: We hold the WAKING bit; the protocol guarantees
244 // no other call can touch the waker cell while we own it.
245 let waker = unsafe { (*self.waker.get()).clone() };
246 self.state.swap(WAITING, Release);
247 // Wake only after releasing the WAKING bit. Waking can hand
248 // control to the woken task before this function returns: an
249 // interrupt-mode executor at a higher priority than the
250 // interrupt calling `wake()` preempts it right here. If the
251 // task then registers again while WAKING is still set,
252 // `register()` wakes it at once, the executor polls it again,
253 // and the preempted `wake()` never gets to clear the bit: a
254 // livelock that starves everything at or below the waking
255 // interrupt's priority. `futures`' `AtomicWaker`, which this
256 // is ported from, also releases the state before waking.
257 if let Some(w) = waker {
258 w.wake();
259 }
260 }
261 _ => {
262 // Previous state was REGISTERING (now REGISTERING | WAKING due
263 // to `fetch_or` above), WAKING (another wake is in flight), or
264 // REGISTERING | WAKING (both). In every case, *somebody else*
265 // owns the waker cell and is responsible for delivering the
266 // wake:
267 //
268 // - REGISTERING: the in-flight `register()` will see WAKING
269 // on its release-CAS and wake the registered waker itself.
270 // - WAKING / REGISTERING | WAKING: another `wake()` /
271 // `register()` is already going to deliver the wake.
272 //
273 // So we deliberately do nothing here — including not touching
274 // the waker cell, which we do not own.
275 }
276 }
277 }
278}
279
280#[cfg(target_has_atomic = "32")]
281impl Default for AtomicWaker {
282 fn default() -> Self {
283 Self::new()
284 }
285}
286
287/// On targets without 32-bit atomic CAS, fall back to the critical-section
288/// based waker. The lockless state machine requires
289/// `AtomicUsize::{compare_exchange, swap, fetch_or}`, which are unavailable on
290/// such targets (e.g. Xtensa S2, AVR, RV32I).
291#[cfg(not(target_has_atomic = "32"))]
292pub type AtomicWaker = super::CriticalSectionWaker;
293
294#[cfg(all(test, target_has_atomic = "32"))]
295mod tests {
296 extern crate std;
297
298 use std::sync::Arc;
299 use std::sync::atomic::{AtomicUsize, Ordering};
300 use std::task::{Wake, Waker};
301
302 use super::AtomicWaker;
303
304 /// Test waker that counts how many times it was woken (via either
305 /// `wake` or `wake_by_ref`).
306 struct CountingWaker {
307 count: AtomicUsize,
308 }
309
310 impl CountingWaker {
311 fn new() -> Arc<Self> {
312 Arc::new(Self {
313 count: AtomicUsize::new(0),
314 })
315 }
316
317 fn count(&self) -> usize {
318 self.count.load(Ordering::SeqCst)
319 }
320
321 fn waker(self: &Arc<Self>) -> Waker {
322 Waker::from(self.clone())
323 }
324 }
325
326 impl Wake for CountingWaker {
327 fn wake(self: Arc<Self>) {
328 self.count.fetch_add(1, Ordering::SeqCst);
329 }
330 fn wake_by_ref(self: &Arc<Self>) {
331 self.count.fetch_add(1, Ordering::SeqCst);
332 }
333 }
334
335 #[test]
336 fn register_with_distinct_waker_wakes_evicted() {
337 let aw = AtomicWaker::new();
338 let a = CountingWaker::new();
339 let b = CountingWaker::new();
340
341 aw.register(&a.waker());
342 assert_eq!(a.count(), 0);
343 assert_eq!(b.count(), 0);
344
345 aw.register(&b.waker());
346
347 // The evicted (a) is woken exactly once; the newly-registered (b) is
348 // not woken by `register` alone.
349 assert_eq!(a.count(), 1, "evicted waker should be woken on eviction");
350 assert_eq!(b.count(), 0, "newly-registered waker must not be woken by register");
351 }
352
353 #[test]
354 fn register_same_waker_no_spurious_wakes() {
355 let aw = AtomicWaker::new();
356 let a = CountingWaker::new();
357 let w = a.waker();
358
359 aw.register(&w);
360 aw.register(&w);
361
362 // `Waker::will_wake` is best-effort: it may return `false` even
363 // when both wakers wake the same task (the result depends on
364 // toolchain-specific const-promotion of the internal vtable).
365 // Either branch is correct:
366 // - fast path taken → 0 wakes
367 // - eviction + re-register → 1 wake (the evicted clone)
368 // What we guard against is *spurious extra* wakes.
369 assert!(a.count() <= 1);
370 }
371
372 #[test]
373 fn wake_after_register_wakes_registered() {
374 let aw = AtomicWaker::new();
375 let a = CountingWaker::new();
376
377 aw.register(&a.waker());
378 aw.wake();
379
380 assert_eq!(a.count(), 1);
381 }
382
383 /// A waker whose wake registers it again on the same `AtomicWaker`, as a
384 /// task does when an executor that preempts the waking interrupt polls
385 /// it before `wake()` has returned. Built by hand on a `static` vtable
386 /// and a `static` context, so `will_wake` holds between all its copies
387 /// (it does not for `Waker::from(Arc)` under Miri, whose vtables have no
388 /// stable address).
389 mod reregistering {
390 use core::sync::atomic::{AtomicUsize, Ordering};
391 use core::task::{RawWaker, RawWakerVTable, Waker};
392
393 use super::AtomicWaker;
394
395 pub static AW: AtomicWaker = AtomicWaker::new();
396 pub static WAKES: AtomicUsize = AtomicUsize::new(0);
397 static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop);
398
399 pub fn waker() -> Waker {
400 // SAFETY: the vtable functions touch nothing but the statics.
401 unsafe { Waker::from_raw(RawWaker::new(&WAKES as *const AtomicUsize as *const (), &VTABLE)) }
402 }
403
404 fn clone(_: *const ()) -> RawWaker {
405 RawWaker::new(&WAKES as *const AtomicUsize as *const (), &VTABLE)
406 }
407
408 fn wake(_: *const ()) {
409 // Bounded, so a regression fails the assertion instead of
410 // recursing without end.
411 if WAKES.fetch_add(1, Ordering::SeqCst) < 10 {
412 AW.register(&waker());
413 }
414 }
415
416 fn drop(_: *const ()) {}
417 }
418
419 #[test]
420 fn register_from_within_wake_is_not_woken_again() {
421 use reregistering::{AW, WAKES, waker};
422
423 AW.register(&waker());
424 AW.wake();
425
426 // One wake. Registering from inside the wake must not see the wake
427 // still in flight and wake the task again (and again).
428 assert_eq!(WAKES.load(Ordering::SeqCst), 1);
429 }
430
431 #[test]
432 fn wake_with_no_registered_waker_is_noop() {
433 let aw = AtomicWaker::new();
434 aw.wake();
435 // Just checking we don't panic / UB.
436 }
437}