use std::{marker, mem, num, ops::ControlFlow, pin};
use dope_sys::{
io::{
reactor::{Full, submit::Queue as _},
socket::option::tuning,
},
table::token::Codec,
};
use o3::alloc;
use crate::{
driver::{
Key,
tuning::{Progress, token},
},
reactor::{cq, op::sockets, sq},
};
#[derive(Debug)]
pub struct State<E, const N: usize> {
target: Option<E>,
values: [libc::c_int; N],
status: Status,
connect: mem::MaybeUninit<crate::raw::Deferred>,
next: Option<sq::Fixed>,
_pin: marker::PhantomPinned,
}
#[derive(Debug)]
struct Status {
retiring: bool,
stopped: bool,
phase: Phase,
count: num::NonZero<u32>,
error: Option<cq::Outcome>,
}
impl<E, const N: usize> Default for State<E, N> {
fn default() -> Self {
Self {
target: None,
values: [0; N],
status: Status {
retiring: false,
stopped: false,
phase: Phase::Idle,
count: num::NonZero::<u32>::MIN,
error: None,
},
connect: mem::MaybeUninit::uninit(),
next: None,
_pin: marker::PhantomPinned,
}
}
}
#[derive(Debug)]
pub struct Table<E, const N: usize> {
states: Box<[State<E, N>]>,
ready: Option<sq::Fixed>,
tail: Option<sq::Fixed>,
}
#[derive(Clone, Copy, Debug)]
enum Phase {
Idle,
Options,
OptionsConnect,
Peer,
}
pub struct Occupied<'a, E, const N: usize> {
state: &'a mut State<E, N>,
target: E,
}
pub(crate) enum Retirement<'a> {
Ready,
Pending,
Cancel(Cancelling<'a>),
}
pub(crate) struct Cancelling<'a> {
status: &'a mut Status,
slot: sq::Fixed,
}
impl<E, const N: usize> Table<E, N> {
pub(crate) fn retirement(&mut self, slot: sq::Fixed) -> Retirement<'_> {
let Some(state) = self.states.get_mut(slot.index() as usize) else {
return Retirement::Ready;
};
if state.target.is_none() {
return Retirement::Ready;
}
if state.status.retiring {
return Retirement::Pending;
}
Retirement::Cancel(Cancelling {
status: &mut state.status,
slot,
})
}
}
impl Cancelling<'_> {
pub(crate) fn try_submit<T: Codec>(self, queue: sq::raw::Queue<'_, T>) -> Result<(), Full> {
let vacancy = queue.try_one()?;
let target = token::<T>(self.slot);
vacancy.cancel::<true>(T::tuning(target), T::cancel_tune(target));
self.status.retiring = true;
self.status.stopped = true;
Ok(())
}
}
impl<E, const N: usize> Table<E, N> {
pub(crate) unsafe fn admitted(&mut self, slot: sq::Fixed) -> pin::Pin<&mut State<E, N>> {
unsafe { pin::Pin::new_unchecked(self.states.get_unchecked_mut(slot.index() as usize)) }
}
}
impl<E, const N: usize> tuning::Create for Table<E, N> {
fn try_new(capacity: num::NonZero<u32>) -> Result<Self, alloc::Error> {
use alloc::BoxSliceExt as _;
const {
assert!(mem::align_of::<Self>() == mem::align_of::<Box<[State<E, N>]>>());
};
let states = Box::<[State<E, N>]>::try_default(capacity.get() as usize)?;
Ok(Self {
states,
ready: None,
tail: None,
})
}
}
impl<E: Copy, const N: usize> tuning::Table<E, N> for Table<E, N> {
type State = State<E, N>;
type Occupied<'a>
= Occupied<'a, E, N>
where
Self: 'a;
fn bind(&mut self, index: u32) -> Result<Self::Occupied<'_>, tuning::Missing> {
let state = self
.states
.get_mut(index as usize)
.ok_or(tuning::Missing::Slot)?;
state.occupied().ok_or(tuning::Missing::Vacant)
}
fn get(&mut self, index: u32) -> Option<pin::Pin<&mut Self::State>> {
let state = self.states.get_mut(index as usize)?;
Some(unsafe { pin::Pin::new_unchecked(state) })
}
fn retry_cancel(&mut self, index: u32) {
if let Some(state) = self.states.get_mut(index as usize) {
state.status.retiring = false;
}
}
}
unsafe impl<E, const N: usize> tuning::raw::Quiesce for Table<E, N> {
type Storage = Box<[State<E, N>]>;
fn is_quiescent(&self) -> bool {
self.states.iter().all(|state| state.target.is_none())
}
fn into_storage(self) -> Self::Storage {
self.states
}
}
impl<E: Copy, const N: usize> tuning::Occupied<E> for Occupied<'_, E, N> {
fn target(&self) -> E {
self.target
}
fn is_failed(&self) -> bool {
self.state.status.error.is_some()
}
fn output(&self) -> (usize, u32) {
let state = &*self.state;
match state.status.phase {
Phase::Peer => (mem::size_of::<libc::ucred>(), state.values[1] as u32),
_ => (0, 0),
}
}
fn clear(self) {
let state = self.state;
state.target = None;
state.status.retiring = false;
state.status.stopped = false;
state.status.phase = Phase::Idle;
}
}
const _: () = {
assert!(std::mem::size_of::<Table<u64, 7>>() == 3 * std::mem::size_of::<usize>());
assert!(mem::size_of::<Status>() == 16);
assert!(mem::size_of::<State<num::NonZero<u64>, 7>>() == 72);
};
impl<E, const N: usize> State<E, N> {
fn start(&mut self, target: E, count: num::NonZero<u32>, phase: Phase) {
self.target = Some(target);
self.status = Status {
count,
phase,
retiring: false,
stopped: false,
error: None,
};
self.next = None;
}
pub(crate) unsafe fn begin(
self: pin::Pin<&mut Self>,
target: E,
count: num::NonZero<u32>,
terminal: Option<crate::raw::Deferred>,
) -> &mut [libc::c_int; N] {
let state = unsafe { self.get_unchecked_mut() };
let phase = match terminal {
Some(entry) => {
state.connect.write(entry);
Phase::OptionsConnect
}
None => Phase::Options,
};
state.start(target, count, phase);
&mut state.values
}
}
impl<E: Copy, const N: usize> Table<E, N> {
pub fn complete(
&mut self,
index: u32,
outcome: &mut cq::Outcome,
) -> Result<Option<Occupied<'_, E, N>>, tuning::Missing> {
use dope_sys::io::reactor::complete::Outcome as _;
let index = index as usize;
if index >= self.states.len() {
return Err(tuning::Missing::Slot);
}
let states = Box::as_mut_ptr(&mut self.states).cast::<State<E, N>>();
let state = unsafe { &mut *states.add(index) };
if matches!(state.status.phase, Phase::Options | Phase::OptionsConnect)
&& outcome.unit().is_ok()
{
if !outcome.is_zero()
&& (state.status.error.is_none()
|| state.status.error
== Some(cq::Outcome::from_error(dope_sys::Errno::CANCELED)))
{
state.status.error = Some(*outcome);
}
if let Some(count) = num::NonZero::new(state.status.count.get() - 1) {
state.status.count = count;
return Ok(None);
}
if let Some(failure) = state.status.error {
*outcome = failure;
} else if state.status.stopped {
*outcome = cq::Outcome::from_error(dope_sys::Errno::CANCELED);
} else if matches!(state.status.phase, Phase::OptionsConnect) {
state.status.phase = Phase::Idle;
let bytes = (index as u32).to_le_bytes();
let slot = sq::Fixed::new([bytes[0], bytes[1], bytes[2]]);
if let Some(tail) = self.tail {
unsafe { (*states.add(tail.index() as usize)).next = Some(slot) };
} else {
self.ready = Some(slot);
}
self.tail = Some(slot);
return Ok(None);
}
state.status.phase = Phase::Idle;
}
state.occupied().map(Some).ok_or(tuning::Missing::Vacant)
}
}
impl<E: Copy, const N: usize> State<E, N> {
fn occupied(&mut self) -> Option<Occupied<'_, E, N>> {
Some(Occupied {
target: self.target?,
state: self,
})
}
pub(crate) unsafe fn peer<T: Codec>(
self: pin::Pin<&mut Self>,
ready: sq::raw::Vacancy<'_, T>,
slot: sq::Fixed,
target: E,
token: T,
) {
use dope_sys::io::reactor::submit::{Ready as _, raw::Vacancy as _};
let state = unsafe { self.get_unchecked_mut() };
state.start(target, num::NonZero::<u32>::MIN, Phase::Peer);
let request = sockets::peer_uid(slot, &mut state.values).user_data(token);
unsafe { ready.borrow(&request) }.push();
}
}
unsafe impl<E: Copy, const N: usize> tuning::raw::State<E, N> for State<E, N> {
type Occupied<'a>
= Occupied<'a, E, N>
where
Self: 'a;
fn bind(self: pin::Pin<&mut Self>) -> Option<Self::Occupied<'_>> {
const {
assert!(
mem::size_of::<Occupied<'_, E, N>>() == mem::size_of::<(pin::Pin<&mut Self>, E)>()
);
assert!(
mem::align_of::<Occupied<'_, E, N>>()
== mem::align_of::<(pin::Pin<&mut Self>, E)>()
);
};
unsafe { self.get_unchecked_mut() }.occupied()
}
unsafe fn values(
self: pin::Pin<&mut Self>,
target: E,
count: num::NonZero<u32>,
) -> &mut [libc::c_int; N] {
unsafe { self.begin(target, count, None) }
}
}
impl<T: Codec, const N: usize> Progress<T> for Table<Key<T>, N> {
fn next(&mut self, queue: sq::raw::Queue<'_, T>) -> Option<Option<T::Tuning>> {
let slot = self.ready?;
let state = unsafe { self.states.get_unchecked_mut(slot.index() as usize) };
let stopped = state.status.stopped;
if !stopped {
let vacancy = queue.try_acquire().ok()?;
let entry = unsafe { state.connect.assume_init_read() };
entry.submit(vacancy, T::tuning(token::<T>(slot)));
}
self.ready = state.next.take();
if self.ready.is_none() {
self.tail = None;
}
Some(if stopped {
Some(token::<T>(slot))
} else {
None
})
}
fn has_pending(&self) -> bool {
self.ready.is_some()
}
fn cancel_all(&mut self) {
for state in &mut self.states {
if state.target.is_some() {
state.status.stopped = true;
}
}
}
fn cancel_at(&mut self, slot: sq::Fixed, target: Option<Key<T>>) -> ControlFlow<()> {
match self.states.get_mut(slot.index() as usize) {
Some(State {
target: Some(current),
status,
..
}) if target.is_none() || target == Some(*current) => {
status.stopped = true;
ControlFlow::Break(())
}
_ => ControlFlow::Continue(()),
}
}
}