Skip to main content

dope_core/executor/task/
group.rs

1use core::{cell, mem, mem::MaybeUninit, pin, task::Poll};
2
3use o3::{
4    depot::{array, array::bits},
5    mem::slot,
6};
7
8use crate::{
9    driver::schedule::{
10        app,
11        ready::task::{self, Index, pool, topology},
12    },
13    executor::task::Fiber,
14    executor::task::context,
15    executor::task::context::wake,
16    executor::task::storage::slots,
17};
18
19type Bindings<'d, const N: usize> = task::raw::Bindings<'d, task::raw::Scheduler<'d, N>, N>;
20
21pub(in crate::executor::task) struct Live<'a, F>(pin::Pin<&'a mut MaybeUninit<F>>);
22
23impl<'a, F> Live<'a, F> {
24    pub(in crate::executor::task) fn into_slot(self) -> pin::Pin<&'a mut MaybeUninit<F>> {
25        self.0
26    }
27}
28
29enum Member<'d, const N: usize> {
30    Fresh(Index<N>),
31    Woken(topology::Wake<'d, Index<N>>),
32}
33
34/// Failure to reserve the exact driver task domain for a group.
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36#[repr(transparent)]
37pub struct Error(task::Error);
38
39#[must_use = "a group drive failure must be handled"]
40pub struct Drive<const N: usize> {
41    completed: bits::Set<Index<N>, N>,
42    pub error: Option<Error>,
43}
44
45impl<const N: usize> Drive<N> {
46    pub fn completed(&self) -> array::Len<N> {
47        self.completed.len()
48    }
49}
50
51/// Inline streaming group for 1 through 16 homogeneous fibers.
52/// Slots, bindings, readiness, and membership stay resident; wakes produced
53/// while polling enter the next stable batch.
54#[pin_project::pin_project(PinnedDrop)]
55pub struct Group<'d, F, const N: usize> {
56    #[pin]
57    slots: [MaybeUninit<F>; N],
58    bindings: Bindings<'d, N>,
59    ready: Ready<N>,
60    root: pool::Root<'d>,
61}
62
63/// Exclusive proof that one group slot remains vacant.
64#[must_use = "a vacancy must be filled before the fiber can run"]
65#[repr(C)]
66pub struct Vacant<'group, 'd, F, const N: usize> {
67    group: pin::Pin<&'group mut Group<'d, F, N>>,
68    slot: Vacancy<N>,
69}
70
71impl Error {
72    /// Returns the exact driver-domain failure without conversion or erasure.
73    pub const fn domain(&self) -> &task::Error {
74        &self.0
75    }
76}
77
78impl<'d, F, const N: usize> Group<'d, F, N> {
79    /// Reserves the exact driver task domain without allocating group storage.
80    pub fn try_new<'a>(
81        target: slot::raw::Vacant<'a, Self>,
82        parent: wake::RootWaker<'d>,
83    ) -> Result<slot::Occupied<'a, Self>, Error> {
84        let (bindings, root) = Self::admit(parent)?;
85        Ok(target.insert(Self {
86            slots: [const { MaybeUninit::uninit() }; N],
87            bindings,
88            ready: Ready::new(bits::Set::EMPTY),
89            root,
90        }))
91    }
92
93    /// Reserves the task domain and schedules every input in array order.
94    pub fn try_with<'a>(
95        target: slot::raw::Vacant<'a, Self>,
96        parent: wake::RootWaker<'d>,
97        fibers: [F; N],
98    ) -> Result<slot::Occupied<'a, Self>, Error> {
99        let (bindings, root) = Self::admit(parent)?;
100        bindings.owner().wake(root);
101        Ok(target.insert(Self {
102            slots: fibers.map(MaybeUninit::new),
103            bindings,
104            ready: Ready::new(bits::Set::EMPTY.complement()),
105            root,
106        }))
107    }
108
109    fn admit(parent: wake::RootWaker<'d>) -> Result<(Bindings<'d, N>, pool::Root<'d>), Error> {
110        const { assert!(N > 0 && N <= 16) };
111        let parent: wake::Waker<'d> = parent.into();
112        let ready = topology::Endpoint::try_new(parent.0).map_err(Error)?;
113        let (pool, root) = pool::Pool::try_rooted(parent.0).map_err(Error)?;
114        Ok((task::raw::Scheduler::new(pool, ready).into_slots(), root))
115    }
116
117    pub fn len(&self) -> array::Len<N> {
118        self.ready.len()
119    }
120
121    /// Whether an inserted or woken member is ready for a stable batch.
122    pub fn is_ready(&self) -> bool {
123        self.ready.is_ready() || !self.bindings.owner().ready.is_empty()
124    }
125
126    /// Borrows the group exclusively only when one inline slot is available.
127    pub fn vacant(self: pin::Pin<&mut Self>) -> Option<Vacant<'_, 'd, F, N>> {
128        let slot = self.ready.vacant()?;
129        Some(Vacant { group: self, slot })
130    }
131}
132
133impl<'d, F, const N: usize> Group<'d, F, N>
134where
135    F: Fiber<'d>,
136{
137    pub fn drive_ready<'group, 'out, 'call, 'turn>(
138        self: pin::Pin<&'group mut Self>,
139        context: &'call mut context::Context<'turn, 'd>,
140        output: slot::raw::Vacant<'out, Drive<N>>,
141    ) -> Drain<'group, 'out, 'call, 'turn, 'd, F, N>
142    where
143        'd: 'turn,
144    {
145        Drain::new(self, context, output, false)
146    }
147
148    pub fn drive_admit<'group, 'out, 'call, 'turn>(
149        self: pin::Pin<&'group mut Self>,
150        admit: context::raw::Admission<'call, 'turn, 'd>,
151        output: slot::raw::Vacant<'out, Drive<N>>,
152    ) -> Drain<'group, 'out, 'call, 'turn, 'd, F, N>
153    where
154        'd: 'turn,
155    {
156        Drain::new(self, admit.into_context(), output, true)
157    }
158}
159
160impl<F, const N: usize> Vacant<'_, '_, F, N> {
161    /// Fills the proven task-domain vacancy and schedules its initial poll.
162    pub fn insert(self, fiber: F) {
163        let this = self.group.project();
164        let mut slot = task::raw::project(self.slot.index(), this.slots);
165        slot.set(MaybeUninit::new(fiber));
166        this.ready.fill(self.slot);
167        this.bindings.owner().wake(*this.root);
168    }
169}
170
171#[pin_project::pinned_drop]
172impl<F, const N: usize> PinnedDrop for Group<'_, F, N> {
173    fn drop(self: pin::Pin<&mut Self>) {
174        let mut this = self.project();
175        let mut live = this.ready.live();
176        let (_, mut bindings) = this.bindings.split();
177        while let Some(index) = live.first() {
178            live.remove(index);
179            let _reclaim = bindings.cancel(index);
180            slots::raw::discard(Live(task::raw::project(index, this.slots.as_mut())));
181        }
182    }
183}
184
185const _: () = assert!(mem::size_of::<Drive<16>>() == 4 * mem::size_of::<usize>());
186
187#[derive(Clone, Copy)]
188#[repr(C, align(8))]
189struct State<const N: usize> {
190    current: bits::Set<Index<N>, N>,
191    next: bits::Set<Index<N>, N>,
192    live: bits::Set<Index<N>, N>,
193}
194
195struct Ready<const N: usize> {
196    members: cell::Cell<State<N>>,
197}
198
199#[repr(transparent)]
200struct Vacancy<const N: usize>(Index<N>);
201
202impl<const N: usize> Vacancy<N> {
203    const fn index(&self) -> Index<N> {
204        self.0
205    }
206}
207
208pub struct Drain<'group, 'out, 'call, 'turn, 'd: 'turn, F, const N: usize> {
209    slots: pin::Pin<&'group mut [MaybeUninit<F>; N]>,
210    bindings: task::raw::Slots<'group, 'd, N>,
211    ready: &'group Ready<N>,
212    root: pool::Root<'d>,
213    endpoint: Option<topology::Drain<'group, 'd, Index<N>>>,
214    context: &'call mut context::Context<'turn, 'd>,
215    output: slot::Occupied<'out, Drive<N>>,
216    initial: bool,
217}
218
219impl<'group, 'out, 'call, 'turn, 'd, F, const N: usize>
220    Drain<'group, 'out, 'call, 'turn, 'd, F, N>
221{
222    fn new(
223        group: pin::Pin<&'group mut Group<'d, F, N>>,
224        context: &'call mut context::Context<'turn, 'd>,
225        output: slot::raw::Vacant<'out, Drive<N>>,
226        initial: bool,
227    ) -> Self {
228        let this = group.project();
229        let ready = this.ready;
230        let (sched, bindings) = this.bindings.split();
231        let mut state = ready.members.get();
232        if state.current.is_empty() {
233            let next = state.next.intersect(state.live);
234            if !next.is_empty() {
235                state.current = next;
236                state.next = state.next.without(state.live);
237                ready.members.set(state);
238            }
239        }
240        Self {
241            slots: this.slots,
242            bindings,
243            ready,
244            root: *this.root,
245            endpoint: sched.ready.drain(),
246            context,
247            output: output.insert(Drive {
248                completed: bits::Set::EMPTY,
249                error: None,
250            }),
251            initial,
252        }
253    }
254
255    pub fn finish(
256        self,
257    ) -> (
258        slot::Occupied<'out, Drive<N>>,
259        &'call mut context::Context<'turn, 'd>,
260    ) {
261        let Self {
262            endpoint,
263            context,
264            output,
265            ..
266        } = self;
267        drop(endpoint);
268        (output, context)
269    }
270}
271
272impl<'d, F: Fiber<'d>, const N: usize> Iterator for Drain<'_, '_, '_, '_, 'd, F, N> {
273    type Item = F::Output;
274
275    fn next(&mut self) -> Option<Self::Item> {
276        loop {
277            let mut state = self.ready.members.get();
278            let member = if let Some(index) = state.current.first() {
279                if !self.initial && self.context.work().permit().is_none() {
280                    self.context.requeue();
281                    return None;
282                }
283                state.current.remove(index);
284                self.ready.members.set(state);
285                Member::Fresh(index)
286            } else {
287                let Some(endpoint) = self.endpoint.as_mut() else {
288                    break;
289                };
290                if self.initial {
291                    let Some(index) = endpoint.pop() else {
292                        break;
293                    };
294                    Member::Woken(index)
295                } else {
296                    match endpoint.next(self.context.work()) {
297                        app::Next::Item(wake, _permit) => Member::Woken(wake),
298                        app::Next::Empty => break,
299                        app::Next::Exhausted(_) => {
300                            self.context.requeue();
301                            return None;
302                        }
303                    }
304                }
305            };
306            self.initial = false;
307
308            let done = match member {
309                Member::Fresh(index) => {
310                    let binding = match self.bindings.start(self.root, index) {
311                        Ok(binding) => binding,
312                        Err(error) => {
313                            let mut state = self.ready.members.get();
314                            state.next.insert(index);
315                            self.ready.members.set(state);
316                            self.output.get_mut().error.get_or_insert(Error(error));
317                            return None;
318                        }
319                    };
320                    self.ready
321                        .poll_member(index, self.slots.as_mut(), self.context, binding)
322                }
323                Member::Woken(wake) => {
324                    let index = wake.local();
325                    let Some(binding) = self.bindings.resume(wake) else {
326                        continue;
327                    };
328                    self.ready
329                        .poll_member(index, self.slots.as_mut(), self.context, binding)
330                }
331            };
332            if let Some((index, output)) = done {
333                self.output.get_mut().completed.insert(index);
334                return Some(output);
335            }
336        }
337        if self.ready.is_ready() || self.bindings.has_ready() {
338            self.context.requeue();
339        }
340        None
341    }
342}
343
344impl<const N: usize> Ready<N> {
345    fn poll_member<'d, F: Fiber<'d>>(
346        &self,
347        index: Index<N>,
348        slots: pin::Pin<&mut [MaybeUninit<F>; N]>,
349        context: &mut context::Context<'_, 'd>,
350        binding: impl task::raw::Binding<'d>,
351    ) -> Option<(Index<N>, F::Output)> {
352        let mut slot = Live(task::raw::project(index, slots));
353        let fiber = slots::raw::member(Live(slot.0.as_mut()));
354        let Poll::Ready((output, claim)) = slots::poll(fiber, context, binding) else {
355            return None;
356        };
357        let mut state = self.members.get();
358        match claim {
359            task::Reclaim::Reusable => state.next.remove(index),
360            task::Reclaim::Retired => state.next.insert(index),
361        }
362        state.live.remove(index);
363        self.members.set(state);
364        slots::raw::discard(slot);
365        Some((index, output))
366    }
367
368    fn new(live: bits::Set<Index<N>, N>) -> Self {
369        Self {
370            members: cell::Cell::new(State {
371                current: bits::Set::EMPTY,
372                next: live,
373                live,
374            }),
375        }
376    }
377
378    fn vacant(&self) -> Option<Vacancy<N>> {
379        let state = self.members.get();
380        let index = state.live.union(state.next).complement().first()?;
381        Some(Vacancy(index))
382    }
383
384    fn fill(&self, slot: Vacancy<N>) {
385        let mut state = self.members.get();
386        state.live.insert(slot.0);
387        state.next.insert(slot.0);
388        self.members.set(state);
389    }
390
391    fn is_ready(&self) -> bool {
392        let state = self.members.get();
393        let ready = state.current.union(state.next).intersect(state.live);
394        !ready.is_empty()
395    }
396
397    fn len(&self) -> array::Len<N> {
398        self.live().len()
399    }
400
401    fn live(&self) -> bits::Set<Index<N>, N> {
402        self.members.get().live
403    }
404}
405
406const _: () = {
407    assert!(core::mem::size_of::<State<16>>() == core::mem::size_of::<u64>());
408    assert!(core::mem::align_of::<State<16>>() == core::mem::align_of::<u64>());
409    assert!(core::mem::size_of::<cell::Cell<State<16>>>() == core::mem::size_of::<u64>());
410    assert!(core::mem::size_of::<Ready<16>>() == core::mem::size_of::<u64>());
411};