Skip to main content

dope_core/executor/task/wait/
mod.rs

1use std::{cell, marker, mem, num, pin::Pin, ptr};
2
3use o3::{base::marker::ThreadBound, depot};
4
5use crate::{
6    driver,
7    driver::{
8        route::table::conn,
9        schedule::{app, ready::wake},
10    },
11    executor::task::context,
12};
13
14mod capacity;
15mod length;
16mod target;
17
18pub use capacity::Capacity;
19pub use length::Length;
20use target::{Active, Target};
21
22/// Exact registration state of a caller-owned waiter.
23#[must_use = "registration state must be consumed"]
24#[derive(Clone, Copy, Eq, PartialEq)]
25#[repr(u8)]
26pub enum Registration {
27    Vacant,
28    Active,
29}
30
31const _: () = assert!(core::mem::size_of::<Registration>() == core::mem::size_of::<u8>());
32
33/// Exact reason a caller-owned waiter could not be registered.
34pub enum Error<'d> {
35    Foreign,
36    QueueFull {
37        capacity: Capacity,
38        wake: wake::Waker<'d>,
39    },
40    SlotFull(wake::Waker<'d>),
41}
42
43/// Exact registration failure without moving the caller's retained wake capability.
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45pub enum Cause {
46    Foreign,
47    QueueFull { capacity: Capacity },
48    SlotFull,
49}
50
51impl Error<'_> {
52    pub const fn cause(&self) -> Cause {
53        match self {
54            Self::Foreign => Cause::Foreign,
55            Self::QueueFull { capacity, .. } => Cause::QueueFull {
56                capacity: *capacity,
57            },
58            Self::SlotFull(_) => Cause::SlotFull,
59        }
60    }
61}
62
63#[must_use = "Pending means the wake did not fit in this application turn"]
64#[derive(Clone, Copy, PartialEq, Eq)]
65#[repr(u8)]
66pub enum WakeStatus {
67    Complete,
68    Pending,
69}
70
71/// An inline bounded FIFO of caller-owned waiters with O(1) operations.
72#[repr(align(2))]
73pub struct Queue<'d> {
74    links: depot::raw::Links<cell::Cell<Option<Active<'d>>>>,
75    len: cell::Cell<usize>,
76    capacity: Capacity,
77}
78
79impl<'d> Queue<'d> {
80    pub const fn new(_: driver::Reference<'d>, capacity: Capacity) -> Self {
81        Self {
82            links: depot::raw::Links::new(),
83            len: cell::Cell::new(0),
84            capacity,
85        }
86    }
87
88    pub const fn for_conns(driver: driver::Reference<'d>, capacity: conn::Capacity) -> Self {
89        Self::new(driver, Capacity::new(capacity.count().get() as usize))
90    }
91
92    pub fn try_register<'target, 'poll>(
93        &'target self,
94        waiter: Pin<&Waiter<'target, 'd>>,
95        context: &context::Context<'poll, 'd>,
96    ) -> Result<(), Error<'d>> {
97        let target = Target::queue(self);
98        let Some(wake) = waiter.replace(target, context.completion()) else {
99            return Ok(());
100        };
101        if self.len.get() >= self.capacity.get() {
102            return Err(Error::QueueFull {
103                capacity: self.capacity,
104                wake,
105            });
106        }
107        let (previous, vacant) = waiter.vacate();
108        vacant.enqueue(self, wake);
109        if let Some(previous) = previous {
110            previous.wake();
111        }
112        Ok(())
113    }
114
115    pub fn wake(&self, work: app::Work<'_, 'd>) -> WakeStatus {
116        while let Some(lease) = work.lease() {
117            let Some(wake) = self.pop() else {
118                return WakeStatus::Complete;
119            };
120            let _permit = lease.commit();
121            wake.wake();
122        }
123        if self.len.get() != 0 {
124            WakeStatus::Pending
125        } else {
126            WakeStatus::Complete
127        }
128    }
129
130    /// Releases every registered waiter when its owner becomes terminal.
131    pub fn wake_all(&self) {
132        while let Some(wake) = self.pop() {
133            wake.wake();
134        }
135    }
136
137    pub fn wake_one(&self, work: app::Work<'_, 'd>) -> WakeStatus {
138        let Some(lease) = work.lease() else {
139            return if self.len.get() != 0 {
140                WakeStatus::Pending
141            } else {
142                WakeStatus::Complete
143            };
144        };
145        if let Some(wake) = self.pop() {
146            let _permit = lease.commit();
147            wake.wake();
148        }
149        WakeStatus::Complete
150    }
151
152    pub fn len(&self) -> Length {
153        Length::new(self.len.get())
154    }
155
156    fn detach(&self, entry: Pin<&depot::raw::Entry<cell::Cell<Option<Active<'d>>>>>) {
157        // SAFETY: the active registration identifies this exact linked queue.
158        unsafe { self.links.remove(entry) };
159        self.len.set(self.len.get() - 1);
160    }
161
162    fn pop(&self) -> Option<wake::Waker<'d>> {
163        let entry = self.links.front()?;
164        let active = entry.value().take();
165        self.detach(entry);
166        active.map(|active| active.wake)
167    }
168}
169
170/// A notification snapshots the waiter count; re-registration cannot extend it.
171pub struct Notifier<'d> {
172    queue: Queue<'d>,
173    remaining: cell::Cell<usize>,
174}
175
176impl<'d> Notifier<'d> {
177    pub const fn new(driver: driver::Reference<'d>, capacity: Capacity) -> Self {
178        Self {
179            queue: Queue::new(driver, capacity),
180            remaining: cell::Cell::new(0),
181        }
182    }
183
184    pub fn try_register<'target, 'poll>(
185        &'target self,
186        waiter: Pin<&Waiter<'target, 'd>>,
187        context: &context::Context<'poll, 'd>,
188    ) -> Result<(), Error<'d>> {
189        self.queue.try_register(waiter, context)
190    }
191
192    /// Starts a new round with the current waiter count.
193    pub fn notify(&self) {
194        self.remaining.set(self.queue.len().get());
195    }
196
197    /// Wakes at most one waiter within the application's work budget.
198    pub fn flush(&self, work: app::Work<'_, 'd>) {
199        let left = self.remaining.get();
200        if left != 0 && self.queue.wake_one(work) == WakeStatus::Complete {
201            self.remaining.set((left - 1).min(self.queue.len().get()));
202        }
203    }
204
205    pub fn is_pending(&self) -> bool {
206        self.remaining.get() != 0
207    }
208}
209
210/// A one-word endpoint containing at most one caller-owned waiter.
211#[repr(align(2))]
212pub struct Slot<'d> {
213    waiter: cell::Cell<Option<Link<'d>>>,
214    thread: marker::PhantomData<ThreadBound>,
215}
216
217#[derive(Clone, Copy)]
218#[repr(transparent)]
219struct Link<'d>(ptr::NonNull<depot::raw::Entry<cell::Cell<Option<Active<'d>>>>>);
220
221impl<'d> Link<'d> {
222    fn entry(&self) -> Pin<&depot::raw::Entry<cell::Cell<Option<Active<'d>>>>> {
223        // SAFETY: an occupied slot retains its pinned waiter until it unlinks itself.
224        unsafe { Pin::new_unchecked(self.0.as_ref()) }
225    }
226}
227
228impl<'d> Slot<'d> {
229    pub const fn new() -> Self {
230        Self {
231            waiter: cell::Cell::new(None),
232            thread: marker::PhantomData,
233        }
234    }
235
236    pub fn try_register<'target, 'poll>(
237        &'target self,
238        waiter: Pin<&Waiter<'target, 'd>>,
239        context: &context::Context<'poll, 'd>,
240    ) -> Result<(), Error<'d>> {
241        let target = Target::slot(self);
242        let Some(wake) = waiter.replace(target, context.completion()) else {
243            return Ok(());
244        };
245        if self.waiter.get().is_some() {
246            return Err(Error::SlotFull(wake));
247        }
248        let (previous, vacant) = waiter.vacate();
249        vacant.bind(self, wake);
250        if let Some(previous) = previous {
251            previous.wake();
252        }
253        Ok(())
254    }
255
256    fn take(&self) -> Option<wake::Waker<'d>> {
257        let link = self.waiter.take()?;
258        let active = link.entry().value().take();
259        active.map(|active| active.wake)
260    }
261
262    pub fn wake_one(&self, work: app::Work<'_, 'd>) -> WakeStatus {
263        let Some(lease) = work.lease() else {
264            return if self.waiter.get().is_some() {
265                WakeStatus::Pending
266            } else {
267                WakeStatus::Complete
268            };
269        };
270        if let Some(wake) = self.take() {
271            let _permit = lease.commit();
272            wake.wake();
273        }
274        WakeStatus::Complete
275    }
276
277    pub fn wake(&self) {
278        if let Some(wake) = self.take() {
279            wake.wake();
280        }
281    }
282}
283
284impl Default for Slot<'_> {
285    fn default() -> Self {
286        Self::new()
287    }
288}
289
290/// A caller-owned pinned registration; its invariant target borrow outlives unlinking.
291#[pin_project::pin_project(PinnedDrop)]
292#[repr(C)]
293pub struct Waiter<'target, 'd> {
294    #[pin]
295    entry: depot::raw::Entry<cell::Cell<Option<Active<'d>>>>,
296    thread: ThreadBound,
297    target: marker::PhantomData<cell::Cell<&'target ()>>,
298}
299
300struct Vacant<'a, 'target, 'd> {
301    waiter: Pin<&'a Waiter<'target, 'd>>,
302}
303
304impl<'target, 'd> Vacant<'_, 'target, 'd> {
305    fn enqueue(self, queue: &'target Queue<'d>, wake: wake::Waker<'d>) {
306        self.waiter.entry.value().set(Some(Active {
307            target: Target::queue(queue),
308            wake,
309        }));
310        // SAFETY: vacating detached this pinned entry; the invariant target borrow
311        // and Waiter::drop keep it live until it removes itself from this queue.
312        unsafe { queue.links.push_back(self.waiter.entry()) };
313        queue.len.set(queue.len.get() + 1);
314    }
315
316    fn bind(self, slot: &'target Slot<'d>, wake: wake::Waker<'d>) {
317        self.waiter.entry.value().set(Some(Active {
318            target: Target::slot(slot),
319            wake,
320        }));
321        slot.waiter.set(Some(Link(ptr::NonNull::from(
322            self.waiter.entry().get_ref(),
323        ))));
324    }
325}
326
327impl Default for Waiter<'_, '_> {
328    fn default() -> Self {
329        Self::new()
330    }
331}
332
333impl<'target, 'd> Waiter<'target, 'd> {
334    pub const fn new() -> Self {
335        Self {
336            entry: depot::raw::Entry::new(cell::Cell::new(None)),
337            thread: ThreadBound::NEW,
338            target: marker::PhantomData,
339        }
340    }
341
342    fn entry(self: Pin<&Self>) -> Pin<&depot::raw::Entry<cell::Cell<Option<Active<'d>>>>> {
343        self.project_ref().entry
344    }
345
346    fn replace(&self, target: Target<'d>, wake: wake::Waker<'d>) -> Option<wake::Waker<'d>> {
347        match self.entry.value().take() {
348            Some(previous) if previous.target == target => {
349                let changed = previous.wake != wake;
350                self.entry.value().set(Some(Active { target, wake }));
351                if changed {
352                    previous.wake.wake();
353                }
354                None
355            }
356            previous => {
357                self.entry.value().set(previous);
358                Some(wake)
359            }
360        }
361    }
362
363    fn vacate<'a>(self: Pin<&'a Self>) -> (Option<wake::Waker<'d>>, Vacant<'a, 'target, 'd>) {
364        let Some(active) = self.entry.value().take() else {
365            return (None, Vacant { waiter: self });
366        };
367        self.unlink(&active);
368        (Some(active.wake), Vacant { waiter: self })
369    }
370
371    fn unlink<'a>(self: Pin<&'a Self>, active: &Active<'d>) {
372        let tagged = active.target.pointer;
373        let pointer = tagged.map_addr(|addr| {
374            // SAFETY: removing the tag from a live aligned endpoint cannot produce zero.
375            unsafe { num::NonZero::<usize>::new_unchecked(addr.get() & !1) }
376        });
377        if tagged.addr().get() & 1 == 0 {
378            // SAFETY: this pinned waiter retains its queue's invariant target borrow.
379            let queue: &'a Queue<'d> = unsafe { pointer.cast::<Queue<'d>>().as_ref() };
380            queue.detach(self.entry());
381        } else {
382            // SAFETY: the same target borrow keeps this exact slot live and unmoved.
383            let slot: &'a Slot<'d> = unsafe { pointer.cast::<Slot<'d>>().as_ref() };
384            slot.waiter.set(None);
385        }
386    }
387
388    pub fn unregister(self: Pin<&Self>) {
389        let _ = self.vacate();
390    }
391
392    pub fn registration(&self) -> Registration {
393        // SAFETY: this shared observation neither mutates the cell nor calls user code.
394        match unsafe { &*self.entry.value().as_ptr() } {
395            Some(_) => Registration::Active,
396            None => Registration::Vacant,
397        }
398    }
399}
400
401#[pin_project::pinned_drop]
402impl PinnedDrop for Waiter<'_, '_> {
403    fn drop(self: Pin<&mut Self>) {
404        self.as_ref().unregister();
405    }
406}
407
408const _: () = {
409    assert!(mem::align_of::<Queue<'static>>() >= 2);
410    assert!(mem::align_of::<Slot<'static>>() >= 2);
411    assert!(mem::size_of::<Option<Active<'static>>>() == 3 * mem::size_of::<usize>());
412    assert!(
413        mem::size_of::<Option<wake::Waker<'static>>>() == mem::size_of::<wake::Waker<'static>>()
414    );
415    assert!(mem::size_of::<Option<Link<'static>>>() == mem::size_of::<usize>());
416    assert!(mem::size_of::<Queue<'static>>() == 4 * mem::size_of::<usize>());
417    assert!(
418        mem::size_of::<Notifier<'static>>()
419            == mem::size_of::<Queue<'static>>() + mem::size_of::<usize>()
420    );
421    assert!(mem::size_of::<Slot<'static>>() == mem::size_of::<usize>());
422    assert!(mem::size_of::<Waiter<'static, 'static>>() == 5 * mem::size_of::<usize>());
423};