use core::{cell, mem, mem::MaybeUninit, pin, task::Poll};
use o3::{
depot::{array, array::bits},
mem::slot,
};
use crate::{
driver::schedule::{
app,
ready::task::{self, Index, pool, topology},
},
executor::task::Fiber,
executor::task::context,
executor::task::context::wake,
executor::task::storage::slots,
};
type Bindings<'d, const N: usize> = task::raw::Bindings<'d, task::raw::Scheduler<'d, N>, N>;
pub(in crate::executor::task) struct Live<'a, F>(pin::Pin<&'a mut MaybeUninit<F>>);
impl<'a, F> Live<'a, F> {
pub(in crate::executor::task) fn into_slot(self) -> pin::Pin<&'a mut MaybeUninit<F>> {
self.0
}
}
enum Member<'d, const N: usize> {
Fresh(Index<N>),
Woken(topology::Wake<'d, Index<N>>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct Error(task::Error);
#[must_use = "a group drive failure must be handled"]
pub struct Drive<const N: usize> {
completed: bits::Set<Index<N>, N>,
pub error: Option<Error>,
}
impl<const N: usize> Drive<N> {
pub fn completed(&self) -> array::Len<N> {
self.completed.len()
}
}
#[pin_project::pin_project(PinnedDrop)]
pub struct Group<'d, F, const N: usize> {
#[pin]
slots: [MaybeUninit<F>; N],
bindings: Bindings<'d, N>,
ready: Ready<N>,
root: pool::Root<'d>,
}
#[must_use = "a vacancy must be filled before the fiber can run"]
#[repr(C)]
pub struct Vacant<'group, 'd, F, const N: usize> {
group: pin::Pin<&'group mut Group<'d, F, N>>,
slot: Vacancy<N>,
}
impl Error {
pub const fn domain(&self) -> &task::Error {
&self.0
}
}
impl<'d, F, const N: usize> Group<'d, F, N> {
pub fn try_new<'a>(
target: slot::raw::Vacant<'a, Self>,
parent: wake::RootWaker<'d>,
) -> Result<slot::Occupied<'a, Self>, Error> {
let (bindings, root) = Self::admit(parent)?;
Ok(target.insert(Self {
slots: [const { MaybeUninit::uninit() }; N],
bindings,
ready: Ready::new(bits::Set::EMPTY),
root,
}))
}
pub fn try_with<'a>(
target: slot::raw::Vacant<'a, Self>,
parent: wake::RootWaker<'d>,
fibers: [F; N],
) -> Result<slot::Occupied<'a, Self>, Error> {
let (bindings, root) = Self::admit(parent)?;
bindings.owner().wake(root);
Ok(target.insert(Self {
slots: fibers.map(MaybeUninit::new),
bindings,
ready: Ready::new(bits::Set::EMPTY.complement()),
root,
}))
}
fn admit(parent: wake::RootWaker<'d>) -> Result<(Bindings<'d, N>, pool::Root<'d>), Error> {
const { assert!(N > 0 && N <= 16) };
let parent: wake::Waker<'d> = parent.into();
let ready = topology::Endpoint::try_new(parent.0).map_err(Error)?;
let (pool, root) = pool::Pool::try_rooted(parent.0).map_err(Error)?;
Ok((task::raw::Scheduler::new(pool, ready).into_slots(), root))
}
pub fn len(&self) -> array::Len<N> {
self.ready.len()
}
pub fn is_ready(&self) -> bool {
self.ready.is_ready() || !self.bindings.owner().ready.is_empty()
}
pub fn vacant(self: pin::Pin<&mut Self>) -> Option<Vacant<'_, 'd, F, N>> {
let slot = self.ready.vacant()?;
Some(Vacant { group: self, slot })
}
}
impl<'d, F, const N: usize> Group<'d, F, N>
where
F: Fiber<'d>,
{
pub fn drive_ready<'group, 'out, 'call, 'turn>(
self: pin::Pin<&'group mut Self>,
context: &'call mut context::Context<'turn, 'd>,
output: slot::raw::Vacant<'out, Drive<N>>,
) -> Drain<'group, 'out, 'call, 'turn, 'd, F, N>
where
'd: 'turn,
{
Drain::new(self, context, output, false)
}
pub fn drive_admit<'group, 'out, 'call, 'turn>(
self: pin::Pin<&'group mut Self>,
admit: context::raw::Admission<'call, 'turn, 'd>,
output: slot::raw::Vacant<'out, Drive<N>>,
) -> Drain<'group, 'out, 'call, 'turn, 'd, F, N>
where
'd: 'turn,
{
Drain::new(self, admit.into_context(), output, true)
}
}
impl<F, const N: usize> Vacant<'_, '_, F, N> {
pub fn insert(self, fiber: F) {
let this = self.group.project();
let mut slot = task::raw::project(self.slot.index(), this.slots);
slot.set(MaybeUninit::new(fiber));
this.ready.fill(self.slot);
this.bindings.owner().wake(*this.root);
}
}
#[pin_project::pinned_drop]
impl<F, const N: usize> PinnedDrop for Group<'_, F, N> {
fn drop(self: pin::Pin<&mut Self>) {
let mut this = self.project();
let mut live = this.ready.live();
let (_, mut bindings) = this.bindings.split();
while let Some(index) = live.first() {
live.remove(index);
let _reclaim = bindings.cancel(index);
slots::raw::discard(Live(task::raw::project(index, this.slots.as_mut())));
}
}
}
const _: () = assert!(mem::size_of::<Drive<16>>() == 4 * mem::size_of::<usize>());
#[derive(Clone, Copy)]
#[repr(C, align(8))]
struct State<const N: usize> {
current: bits::Set<Index<N>, N>,
next: bits::Set<Index<N>, N>,
live: bits::Set<Index<N>, N>,
}
struct Ready<const N: usize> {
members: cell::Cell<State<N>>,
}
#[repr(transparent)]
struct Vacancy<const N: usize>(Index<N>);
impl<const N: usize> Vacancy<N> {
const fn index(&self) -> Index<N> {
self.0
}
}
pub struct Drain<'group, 'out, 'call, 'turn, 'd: 'turn, F, const N: usize> {
slots: pin::Pin<&'group mut [MaybeUninit<F>; N]>,
bindings: task::raw::Slots<'group, 'd, N>,
ready: &'group Ready<N>,
root: pool::Root<'d>,
endpoint: Option<topology::Drain<'group, 'd, Index<N>>>,
context: &'call mut context::Context<'turn, 'd>,
output: slot::Occupied<'out, Drive<N>>,
initial: bool,
}
impl<'group, 'out, 'call, 'turn, 'd, F, const N: usize>
Drain<'group, 'out, 'call, 'turn, 'd, F, N>
{
fn new(
group: pin::Pin<&'group mut Group<'d, F, N>>,
context: &'call mut context::Context<'turn, 'd>,
output: slot::raw::Vacant<'out, Drive<N>>,
initial: bool,
) -> Self {
let this = group.project();
let ready = this.ready;
let (sched, bindings) = this.bindings.split();
let mut state = ready.members.get();
if state.current.is_empty() {
let next = state.next.intersect(state.live);
if !next.is_empty() {
state.current = next;
state.next = state.next.without(state.live);
ready.members.set(state);
}
}
Self {
slots: this.slots,
bindings,
ready,
root: *this.root,
endpoint: sched.ready.drain(),
context,
output: output.insert(Drive {
completed: bits::Set::EMPTY,
error: None,
}),
initial,
}
}
pub fn finish(
self,
) -> (
slot::Occupied<'out, Drive<N>>,
&'call mut context::Context<'turn, 'd>,
) {
let Self {
endpoint,
context,
output,
..
} = self;
drop(endpoint);
(output, context)
}
}
impl<'d, F: Fiber<'d>, const N: usize> Iterator for Drain<'_, '_, '_, '_, 'd, F, N> {
type Item = F::Output;
fn next(&mut self) -> Option<Self::Item> {
loop {
let mut state = self.ready.members.get();
let member = if let Some(index) = state.current.first() {
if !self.initial && self.context.work().permit().is_none() {
self.context.requeue();
return None;
}
state.current.remove(index);
self.ready.members.set(state);
Member::Fresh(index)
} else {
let Some(endpoint) = self.endpoint.as_mut() else {
break;
};
if self.initial {
let Some(index) = endpoint.pop() else {
break;
};
Member::Woken(index)
} else {
match endpoint.next(self.context.work()) {
app::Next::Item(wake, _permit) => Member::Woken(wake),
app::Next::Empty => break,
app::Next::Exhausted(_) => {
self.context.requeue();
return None;
}
}
}
};
self.initial = false;
let done = match member {
Member::Fresh(index) => {
let binding = match self.bindings.start(self.root, index) {
Ok(binding) => binding,
Err(error) => {
let mut state = self.ready.members.get();
state.next.insert(index);
self.ready.members.set(state);
self.output.get_mut().error.get_or_insert(Error(error));
return None;
}
};
self.ready
.poll_member(index, self.slots.as_mut(), self.context, binding)
}
Member::Woken(wake) => {
let index = wake.local();
let Some(binding) = self.bindings.resume(wake) else {
continue;
};
self.ready
.poll_member(index, self.slots.as_mut(), self.context, binding)
}
};
if let Some((index, output)) = done {
self.output.get_mut().completed.insert(index);
return Some(output);
}
}
if self.ready.is_ready() || self.bindings.has_ready() {
self.context.requeue();
}
None
}
}
impl<const N: usize> Ready<N> {
fn poll_member<'d, F: Fiber<'d>>(
&self,
index: Index<N>,
slots: pin::Pin<&mut [MaybeUninit<F>; N]>,
context: &mut context::Context<'_, 'd>,
binding: impl task::raw::Binding<'d>,
) -> Option<(Index<N>, F::Output)> {
let mut slot = Live(task::raw::project(index, slots));
let fiber = slots::raw::member(Live(slot.0.as_mut()));
let Poll::Ready((output, claim)) = slots::poll(fiber, context, binding) else {
return None;
};
let mut state = self.members.get();
match claim {
task::Reclaim::Reusable => state.next.remove(index),
task::Reclaim::Retired => state.next.insert(index),
}
state.live.remove(index);
self.members.set(state);
slots::raw::discard(slot);
Some((index, output))
}
fn new(live: bits::Set<Index<N>, N>) -> Self {
Self {
members: cell::Cell::new(State {
current: bits::Set::EMPTY,
next: live,
live,
}),
}
}
fn vacant(&self) -> Option<Vacancy<N>> {
let state = self.members.get();
let index = state.live.union(state.next).complement().first()?;
Some(Vacancy(index))
}
fn fill(&self, slot: Vacancy<N>) {
let mut state = self.members.get();
state.live.insert(slot.0);
state.next.insert(slot.0);
self.members.set(state);
}
fn is_ready(&self) -> bool {
let state = self.members.get();
let ready = state.current.union(state.next).intersect(state.live);
!ready.is_empty()
}
fn len(&self) -> array::Len<N> {
self.live().len()
}
fn live(&self) -> bits::Set<Index<N>, N> {
self.members.get().live
}
}
const _: () = {
assert!(core::mem::size_of::<State<16>>() == core::mem::size_of::<u64>());
assert!(core::mem::align_of::<State<16>>() == core::mem::align_of::<u64>());
assert!(core::mem::size_of::<cell::Cell<State<16>>>() == core::mem::size_of::<u64>());
assert!(core::mem::size_of::<Ready<16>>() == core::mem::size_of::<u64>());
};