use std::{cell, mem};
use o3::{
alloc,
base::{
marker::ThreadBound,
num::{self, Step},
},
};
use crate::{
driver::{
route,
route::{indices, indices::SlotIndex, table},
},
io::fd::{domain::Index, handles, states},
};
pub(super) mod retire;
use retire::Retirement;
const STATE_BITS: u32 = 3;
const PHASE_BITS: u32 = 2;
const PHASE_VALUE_MASK: u64 = (1_u64 << PHASE_BITS) - 1;
const PHASE_MASK: u64 = PHASE_VALUE_MASK << route::AUX_SHIFT;
const LEASE_VALUE: u8 = 1 << PHASE_BITS;
const LEASE_MASK: u64 = (LEASE_VALUE as u64) << route::AUX_SHIFT;
const STATE_VALUE_MASK: u64 = (1_u64 << STATE_BITS) - 1;
const STATE_MASK: u64 = STATE_VALUE_MASK << route::AUX_SHIFT;
const LIFECYCLE_SHIFT: u32 = route::AUX_SHIFT + STATE_BITS;
const LIFECYCLE_MASK: u64 = (u16::MAX as u64) << LIFECYCLE_SHIFT;
const EXHAUSTED_SHIFT: u32 = LIFECYCLE_SHIFT + u16::BITS;
const EXHAUSTED_MASK: u64 = 1_u64 << EXHAUSTED_SHIFT;
pub(super) const INFLIGHT_MASK: u64 = EXHAUSTED_MASK << 1;
pub(super) const SIDE_MASK: u64 = INFLIGHT_MASK << 1;
pub(super) const BOUND_MASK: u64 = SIDE_MASK << 1;
pub(super) const RETIREMENT_MASK: u64 = INFLIGHT_MASK | SIDE_MASK | BOUND_MASK;
const TARGET_WORDS: usize = 2;
const LINK_BITS: u32 = route::SLOT_BITS + 1;
pub(super) const LINK_MASK: u64 = (1_u64 << LINK_BITS) - 1;
const EMPTY_LINK: u32 = 1_u32 << route::SLOT_BITS;
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(in crate::io::fd::domain) enum Phase {
Ready,
Pending,
InFlight,
Quiescent,
}
pub(in crate::io::fd) struct Store {
storage: Box<[cell::Cell<u64>]>,
pub(super) pending: Queue,
pub(super) inflight: cell::Cell<Inflight>,
thread: ThreadBound,
}
#[derive(Clone, Copy)]
#[repr(transparent)]
pub(super) struct Inflight(u32);
pub(super) struct Entry<'a> {
pub(super) words: Words<'a>,
pub(super) generation: Counter<'a>,
}
pub(in crate::io::fd) struct Lifecycle<'a> {
meta: &'a cell::Cell<u64>,
}
pub(super) struct Queue {
heads: [cell::Cell<Option<indices::SlotIndex>>; 2],
active: cell::Cell<Side>,
}
#[derive(Clone, Copy)]
pub(super) enum Side {
Zero,
One,
}
#[derive(Clone, Copy)]
pub(super) struct Counter<'a> {
word: &'a cell::Cell<u64>,
}
impl Phase {
pub(super) const QUARANTINED: Self = Self::Quiescent;
const fn can_claim(self, lease: bool, spent: bool) -> bool {
!lease && !spent && matches!(self, Self::Ready | Self::InFlight)
}
pub(super) const fn is_inflight(self) -> bool {
matches!(self, Self::InFlight)
}
fn from_bits(low: bool, high: bool) -> Self {
match (low, high) {
(false, false) => Self::Ready,
(true, false) => Self::Pending,
(false, true) => Self::InFlight,
(true, true) => Self::Quiescent,
}
}
}
impl Store {
pub(super) fn try_new(capacity: table::Capacity) -> Result<Self, alloc::Error> {
use alloc::BoxSliceExt;
let capacity = capacity.raw() as usize;
let words = capacity * (TARGET_WORDS + 1);
let storage = BoxSliceExt::try_default(words)?;
Ok(Self {
storage,
pending: Queue::new(),
inflight: cell::Cell::new(Inflight::EMPTY),
thread: ThreadBound::NEW,
})
}
pub(super) fn claim(&self, index: Index, state: states::SlotState) -> num::Generation {
let entry = self.at(Bound::mapped(index));
entry.claim();
Lifecycle {
meta: entry.words.meta(),
}
.set(state);
entry.generation.get()
}
pub(super) fn try_claim(&self, index: indices::SlotIndex) -> Option<num::Generation> {
let entry = self.entry(index)?;
if !entry
.phase()
.can_claim(entry.has_lease(), entry.is_exhausted())
{
return None;
}
entry.claim();
Some(entry.generation.get())
}
pub(super) fn set_target(
&self,
index: indices::SlotIndex,
version: num::Generation,
target: route::Token,
) {
if let Some(entry) = self.resolve(index, version) {
entry.set_target(target);
}
}
pub(super) fn target(
&self,
index: indices::SlotIndex,
version: num::Generation,
) -> Option<route::Token> {
let entry = self.entry(index)?;
if entry.generation.get() != version {
return None;
}
entry.dispatch()
}
pub(super) fn target_at(&self, index: indices::SlotIndex) -> Option<route::Token> {
let entry = self.entry(index)?;
entry.dispatch()
}
pub(in crate::io::fd) fn lifecycle(&self, slot: handles::PhysicalSlot) -> Lifecycle<'_> {
let entry = self.at(Bound::slot(slot));
Lifecycle {
meta: entry.words.meta(),
}
}
pub(super) fn mapped(&self, index: Index) -> Lifecycle<'_> {
let entry = self.at(Bound::mapped(index));
Lifecycle {
meta: entry.words.meta(),
}
}
pub(super) fn has_retiring(&self) -> bool {
let solo = u64::from(states::SlotState::STANDALONE.raw()) << LIFECYCLE_SHIFT;
self.storage
.as_chunks::<TARGET_WORDS>()
.0
.iter()
.take(self.capacity())
.any(|words| {
let state = words[1].get() & (STATE_MASK | LIFECYCLE_MASK | EXHAUSTED_MASK);
state == solo | ((Phase::Pending as u64) << route::AUX_SHIFT)
|| state == solo | ((Phase::InFlight as u64) << route::AUX_SHIFT)
})
}
fn resolve(&self, index: indices::SlotIndex, version: num::Generation) -> Option<Entry<'_>> {
let entry = self.entry(index)?;
(entry.generation.get() == version && entry.phase() == Phase::Ready && entry.has_lease())
.then_some(entry)
}
pub(super) fn entry(&self, index: indices::SlotIndex) -> Option<Entry<'_>> {
let bound = Bound::try_new(index, self.capacity())?;
Some(self.at(bound))
}
pub(super) fn at(&self, bound: Bound) -> Entry<'_> {
let capacity = self.capacity();
let [meta, data, word] = bound.cells(&self.storage, capacity);
Entry {
words: Words::new(meta, data, self.thread),
generation: Counter { word },
}
}
fn capacity(&self) -> usize {
self.storage.len() / (TARGET_WORDS + 1)
}
}
impl Entry<'_> {
pub(super) fn phase(&self) -> Phase {
let raw = ((self.words.meta().get() & PHASE_MASK) >> route::AUX_SHIFT) as u8;
Phase::from_bits(raw & 1 != 0, raw & 2 != 0)
}
pub(super) fn has_lease(&self) -> bool {
self.words.meta().get() & LEASE_MASK != 0
}
pub(super) fn set_phase(&self, phase: Phase) {
let meta = self.words.meta().get() & !PHASE_MASK;
self.words
.meta()
.set(meta | (u64::from(phase as u8) << route::AUX_SHIFT));
}
pub(super) fn set_status(&self, phase: Phase, lease: bool) {
let meta = self.words.meta().get() & !STATE_MASK;
let state = u64::from(phase as u8) | (u64::from(lease) << PHASE_BITS);
self.words.meta().set(meta | (state << route::AUX_SHIFT));
}
pub(super) fn is_exhausted(&self) -> bool {
self.words.meta().get() & EXHAUSTED_MASK != 0
}
pub(super) fn advance(&self) {
match self.generation.get().next() {
Some(next) => self.generation.set(next),
None => self
.words
.meta()
.set(self.words.meta().get() | EXHAUSTED_MASK),
}
}
pub(super) fn retired(&self) -> Option<num::Generation> {
if self.is_exhausted() {
Some(self.generation.get())
} else {
Some(num::Generation::from_raw(
self.generation.get().get().checked_sub(1)?,
))
}
}
pub(super) fn recycle(&self) {
self.set_status(Phase::Ready, false);
}
fn claim(&self) {
self.words.identity().set(0);
self.set_status(Phase::Ready, true);
}
fn set_target(&self, target: route::Token) {
self.words
.publish(target, STATE_VALUE_MASK as u8, LEASE_VALUE);
}
fn dispatch(&self) -> Option<route::Token> {
self.words.dispatch(STATE_VALUE_MASK as u8, LEASE_VALUE)
}
}
impl Inflight {
const EMPTY: Self = Self(0);
pub(super) fn submit(self) -> Self {
Self(self.0.wrapping_add(1))
}
fn finish(self) -> Self {
Self(self.0.wrapping_sub(1))
}
pub(super) const fn is_empty(self) -> bool {
self.0 == 0
}
}
impl Queue {
const fn new() -> Self {
Self {
heads: [const { cell::Cell::new(None) }; 2],
active: cell::Cell::new(Side::Zero),
}
}
fn push(&self, index: indices::SlotIndex, link: &cell::Cell<u64>) {
let head = &self.heads[self.active.get() as usize];
link.set(u64::from(
head.get().map_or(EMPTY_LINK, indices::SlotIndex::raw),
));
head.set(Some(index));
}
fn front(&self) -> Option<(indices::SlotIndex, Side)> {
let active = self.active.get();
let draining = active.other();
if let Some(head) = self.heads[draining as usize].get() {
return Some((head, draining));
}
let head = self.heads[active as usize].get()?;
self.active.set(draining);
Some((head, active))
}
pub(super) fn commit(&self, side: Side, next: u32) {
self.heads[side as usize].set(indices::SlotIndex::from_raw(u64::from(next)));
}
}
impl Side {
const fn other(self) -> Self {
match self {
Self::Zero => Self::One,
Self::One => Self::Zero,
}
}
}
impl Lifecycle<'_> {
pub(super) fn is_exhausted(&self) -> bool {
self.meta.get() & EXHAUSTED_MASK != 0
}
pub(in crate::io::fd) fn get(&self) -> states::SlotState {
let raw = (self.meta.get() & LIFECYCLE_MASK) >> LIFECYCLE_SHIFT;
states::SlotState::from_raw(raw as u16)
}
pub(in crate::io::fd) fn set(&self, state: states::SlotState) {
let meta = self.meta.get() & !LIFECYCLE_MASK;
self.meta
.set(meta | (u64::from(state.raw()) << LIFECYCLE_SHIFT));
}
}
impl Counter<'_> {
pub(super) fn get(self) -> num::Generation {
num::Generation::from_raw(self.word.get() as u32)
}
fn set(self, value: num::Generation) {
let word = self.word.get() & !u64::from(u32::MAX);
self.word.set(word | u64::from(value.get()));
}
pub(super) fn submitted(self) -> num::Generation {
num::Generation::from_raw((self.word.get() >> u32::BITS) as u32)
}
pub(super) fn submit(self, value: num::Generation) {
let word = self.word.get() & u64::from(u32::MAX);
self.word.set(word | (u64::from(value.get()) << u32::BITS));
}
}
const _: () = {
let phases = [
Phase::Ready,
Phase::Pending,
Phase::InFlight,
Phase::Quiescent,
];
let mut index = 0;
while index < phases.len() {
assert!(!phases[index].can_claim(false, true));
assert!(!phases[index].can_claim(true, false));
assert!(!phases[index].can_claim(true, true));
index += 1;
}
assert!(!Phase::QUARANTINED.can_claim(false, false));
assert!(!Phase::QUARANTINED.is_inflight());
assert!(Phase::Ready.can_claim(false, false));
assert!(Phase::InFlight.can_claim(false, false));
assert!(BOUND_MASK < 1_u64 << (route::AUX_SHIFT + route::AUX_BITS));
assert!(EMPTY_LINK as u64 == route::SLOT_MASK + 1);
assert!(mem::size_of::<Store>() == 4 * mem::size_of::<usize>());
assert!(mem::size_of::<Entry<'static>>() == 3 * mem::size_of::<usize>());
assert!(mem::size_of::<Lifecycle<'static>>() == mem::size_of::<usize>());
assert!(mem::size_of::<Counter<'static>>() == mem::size_of::<usize>());
};
mod words;
pub(super) use words::{Bound, Words};
impl Store {
pub(in crate::io::fd::domain) fn enqueue(&self, slot: handles::PhysicalSlot) {
let index = SlotIndex::from(slot);
let entry = self.at(Bound::slot(slot));
entry.set_phase(Phase::Pending);
entry.queue(self, index);
}
pub(in crate::io::fd::domain) fn pending(&self) -> Option<Retirement> {
let (index, side) = self.pending.front()?;
let entry = self.entry(index)?;
if entry.phase() != Phase::Pending {
return None;
}
let epoch = if entry.has_lease() {
entry.generation.get()
} else {
entry.retired()?
};
Some(Retirement::new(index, epoch, side))
}
pub(super) fn consume(&self, token: &Retirement) -> Entry<'_> {
let entry = self.at(Bound::retirement(token));
let meta = entry.words.meta().get() & !RETIREMENT_MASK;
entry.words.meta().set(meta);
self.inflight.set(self.inflight.get().finish());
entry
}
}
impl Entry<'_> {
pub(super) fn queue(&self, store: &Store, index: SlotIndex) {
if self.words.meta().get() & INFLIGHT_MASK == 0 {
store.pending.push(index, self.words.identity());
}
}
pub(super) fn promote(&self, store: &Store, index: SlotIndex) {
if self.phase() == Phase::Pending {
self.queue(store, index);
}
}
}
impl Entry<'_> {
pub(super) fn settle(&self) {
if self.has_lease() {
self.set_phase(Phase::Quiescent);
} else {
self.recycle();
}
}
pub(super) fn commit(&self, store: &Store, side: Side) {
let link = (self.words.identity().get() & LINK_MASK) as u32;
store.pending.commit(side, link);
self.settle();
}
}