use std::{alloc::Layout, cell, marker, mem, num, ptr};
use o3::{
alloc::{self, raw::LayoutExt},
depot::arena::slab,
mem::slot,
};
use crate::driver::retained::flight::{
self, GENERATION_BITS, INDEX_BITS, Target,
storage::{Echo, Slots, generation_max, index_limit},
};
const ATTACHED: usize = 1;
const PENDING: usize = 2;
const BOUND: usize = 4;
const FLAGS: usize = ATTACHED | PENDING | BOUND;
const RETIRED: usize = ATTACHED | BOUND;
const LEASED: u64 = 1 << 63;
const EMPTY: u64 = 1 << 62;
#[repr(C, align(8))]
pub(in crate::driver::retained::flight) struct State<T: Copy, const I: u32, const G: u32> {
value: cell::Cell<mem::MaybeUninit<T>>,
word: cell::UnsafeCell<Word<T, I, G>>,
index: u32,
generation: cell::Cell<num::NonZero<u32>>,
}
union Word<T: Copy, const I: u32, const G: u32> {
free: mem::ManuallyDrop<Option<Link<T, I, G>>>,
occupied: *mut Header<T, I, G>,
}
#[repr(transparent)]
struct Link<T: Copy, const I: u32, const G: u32>(ptr::NonNull<State<T, I, G>>);
#[repr(align(8))]
pub(super) struct Header<T: Copy, const I: u32, const G: u32> {
free: cell::Cell<Option<Link<T, I, G>>>,
admission: cell::Cell<u64>,
}
#[repr(C)]
pub(in crate::driver::retained::flight) struct Cell<T: Copy, B, const I: u32, const G: u32> {
native: State<T, I, G>,
backing: cell::UnsafeCell<mem::MaybeUninit<B>>,
}
#[repr(C)]
pub(super) struct Group<T: Copy, const I: u32, const G: u32> {
header: Header<T, I, G>,
next: Option<Allocation<T, I, G>>,
layout: Layout,
extent: usize,
}
pub(super) struct Allocation<T: Copy, const I: u32, const G: u32>(
pub(super) ptr::NonNull<Group<T, I, G>>,
);
#[repr(C)]
struct Inline<T: Copy, B, const I: u32, const G: u32> {
group: Group<T, I, G>,
cells: [Cell<T, B, I, G>; 0],
}
#[repr(C)]
pub(super) struct Vacant<'a, T: Copy, const I: u32, const G: u32> {
entry: ptr::NonNull<State<T, I, G>>,
owner: &'a Header<T, I, G>,
}
pub(in crate::driver::retained::flight) struct Front<
'slot,
'owner,
T: Copy,
const I: u32,
const G: u32,
> {
vacancy: Vacant<'owner, T, I, G>,
slots: marker::PhantomData<&'slot Slots<'owner, T, I, G>>,
}
#[repr(transparent)]
pub(super) struct Live<'a, T: Copy, const I: u32, const G: u32> {
entry: ptr::NonNull<State<T, I, G>>,
invariant: marker::PhantomData<fn(&'a ()) -> &'a ()>,
}
#[repr(transparent)]
pub(super) struct Bound<'a, T: Copy, const I: u32, const G: u32> {
live: Live<'a, T, I, G>,
}
impl<T: Copy, const I: u32, const G: u32> State<T, I, G> {
const fn new(index: u32) -> Self {
Self {
value: cell::Cell::new(mem::MaybeUninit::uninit()),
word: cell::UnsafeCell::new(Word {
free: mem::ManuallyDrop::new(None),
}),
index,
generation: cell::Cell::new(num::NonZero::<u32>::MIN),
}
}
fn pointer(&self) -> *mut Header<T, I, G> {
unsafe { (*self.word.get()).occupied }
}
fn set(&self, pointer: *mut Header<T, I, G>) {
unsafe { (*self.word.get()).occupied = pointer };
}
pub(super) fn is_pending(&self) -> bool {
self.pointer().addr() & PENDING != 0
}
fn is_attached(&self) -> bool {
let address = self.pointer().addr();
address != RETIRED && address & ATTACHED != 0
}
pub(super) unsafe fn finish(entry: ptr::NonNull<Self>) {
let generation = unsafe { entry.as_ref() }.generation.get();
if let Some(bound) = unsafe { Self::bind(entry, generation) } {
bound.finish();
}
}
pub(super) unsafe fn bind<'a>(
entry: ptr::NonNull<Self>,
expected: num::NonZero<u32>,
) -> Option<Bound<'a, T, I, G>> {
let value = unsafe { entry.as_ref() };
let pointer = value.pointer();
let address = pointer.addr();
if address & (PENDING | BOUND) != PENDING || value.generation.get() != expected {
return None;
}
value.set(pointer.map_addr(|address| address | BOUND));
Some(Bound {
live: Live {
entry,
invariant: marker::PhantomData,
},
})
}
}
impl<T: Copy, const I: u32, const G: u32> Group<T, I, G> {
fn layout<B>(extent: usize) -> Result<Layout, alloc::Overflow> {
let cells = Layout::array::<Cell<T, B, I, G>>(extent).map_err(|_| alloc::Overflow)?;
let (layout, _) = Layout::new::<Self>()
.extend(cells)
.map_err(|_| alloc::Overflow)?;
Ok(layout.pad_to_align())
}
pub(super) fn try_new<B>(
start: usize,
extent: usize,
) -> Result<Allocation<T, I, G>, alloc::Error> {
let end = start.checked_add(extent).ok_or(alloc::Overflow)?;
if end > index_limit::<I>() {
return Err(alloc::Error::Overflow);
}
let layout = Self::layout::<B>(extent)?;
let pointer = layout.try_allocate::<Self>()?;
unsafe {
pointer.as_ptr().write(Self {
header: Header {
free: cell::Cell::new(None),
admission: cell::Cell::new(0),
},
next: None,
layout,
extent,
});
let cells = Self::cells::<B>(pointer);
for offset in 0..extent {
cells.add(offset).write(Cell {
native: State::new((start + offset) as u32),
backing: cell::UnsafeCell::new(mem::MaybeUninit::uninit()),
});
}
}
Ok(Allocation(pointer))
}
unsafe fn cells<B>(base: ptr::NonNull<Self>) -> *mut Cell<T, B, I, G> {
unsafe {
base.cast::<u8>()
.add(mem::offset_of!(Inline<T, B, I, G>, cells))
.cast()
.as_ptr()
}
}
pub(super) fn select<'a, B>(
groups: &'a cell::UnsafeCell<Option<Allocation<T, I, G>>>,
capacity: usize,
) -> Option<Slots<'a, T, I, G>> {
let mut next = unsafe { &*groups.get() }.as_ref().map(|group| group.0);
let mut selected = None;
let mut best = usize::MAX;
'groups: while let Some(pointer) = next {
let group = unsafe { pointer.as_ref() };
next = group.next.as_ref().map(|group| group.0);
if group.extent < capacity
|| group.header.admission.get() & LEASED != 0
|| Self::layout::<B>(group.extent).ok() != Some(group.layout)
{
continue;
}
let mut count = 0;
let cells = unsafe { Self::cells::<B>(pointer) };
for index in 0..group.extent {
let address = unsafe { &(*cells.add(index)).native }.pointer().addr();
if address & FLAGS == 0 {
count += 1;
} else if address != RETIRED {
continue 'groups;
}
}
if count >= capacity && count < best {
selected = Some(pointer);
best = count;
if count == capacity {
break;
}
}
}
Some(unsafe { Self::activate::<B>(selected?, capacity) })
}
unsafe fn activate<'a, B>(pointer: ptr::NonNull<Self>, capacity: usize) -> Slots<'a, T, I, G> {
let group = unsafe { pointer.as_ref() };
let header = &group.header;
let state = if capacity == 0 {
EMPTY
} else {
capacity as u64
};
header.admission.set(LEASED | state);
header.free.set(None);
let mut left = capacity;
let cells = unsafe { Self::cells::<B>(pointer) };
for index in (0..group.extent).rev() {
if left == 0 {
break;
}
let entry: ptr::NonNull<State<T, I, G>> =
unsafe { ptr::NonNull::new_unchecked(cells.add(index).cast()) };
if unsafe { entry.as_ref() }.pointer().addr() & FLAGS == 0 {
Vacant {
entry,
owner: header,
}
.release();
left -= 1;
}
}
Slots {
group: pointer,
owner: marker::PhantomData,
}
}
pub(super) fn publish<'a, B>(
groups: &'a cell::UnsafeCell<Option<Allocation<T, I, G>>>,
dir: &mut Vec<ptr::NonNull<State<T, I, G>>>,
allocation: Allocation<T, I, G>,
capacity: usize,
) -> Slots<'a, T, I, G> {
let pointer = allocation.0;
unsafe {
let group = pointer.as_ptr();
let extent = (*group).extent;
(*group).next = (*groups.get()).take();
*groups.get() = Some(allocation);
let cells = Self::cells::<B>(pointer);
let len = dir.len();
for index in 0..extent {
dir.as_mut_ptr()
.add(len + index)
.write(ptr::NonNull::new_unchecked(cells.add(index).cast()));
}
dir.set_len(len + extent);
Self::activate::<B>(pointer, capacity)
}
}
}
impl<T: Copy, const I: u32, const G: u32> Drop for Allocation<T, I, G> {
fn drop(&mut self) {
unsafe {
let layout = self.0.as_ref().layout;
self.0.as_ptr().drop_in_place();
layout.deallocate(self.0);
}
}
}
pub(super) fn drop_groups<T: Copy, const I: u32, const G: u32>(
groups: &mut Option<Allocation<T, I, G>>,
) {
while let Some(allocation) = groups.take() {
*groups = unsafe { &mut *allocation.0.as_ptr() }.next.take();
drop(allocation);
}
}
impl<T: Copy, const I: u32, const G: u32> Header<T, I, G> {
pub(super) fn release(&self) {
self.admission.set(self.admission.get() & !LEASED);
}
}
impl<'owner, T: Copy, const I: u32, const G: u32> Slots<'owner, T, I, G> {
pub(super) fn header(&self) -> &Header<T, I, G> {
unsafe { &self.group.as_ref().header }
}
pub(in crate::driver::retained::flight) fn header_pointer(&self) -> *const () {
self.group.as_ptr().cast()
}
pub(in crate::driver::retained::flight) unsafe fn front<'slot>(
&'slot self,
) -> Result<Front<'slot, 'owner, T, I, G>, slab::Vacancy> {
let owner = unsafe { &self.group.as_ref().header };
let head = unsafe { &*owner.free.as_ptr() };
let Some(Link(pointer)) = head.as_ref() else {
return Err(if owner.admission.get() & !LEASED == 0 {
slab::Vacancy::IdentityExhausted
} else {
slab::Vacancy::Full
});
};
Ok(Front {
vacancy: Vacant {
entry: *pointer,
owner,
},
slots: marker::PhantomData,
})
}
pub(in crate::driver::retained::flight) unsafe fn tail<B>(
&mut self,
) -> (*mut Cell<T, B, I, G>, usize) {
let extent = unsafe { self.group.as_ref() }.extent;
(unsafe { Group::cells::<B>(self.group) }, extent)
}
}
impl<'slot, 'owner, T: Copy, const I: u32, const G: u32> Front<'slot, 'owner, T, I, G> {
fn detach(self) -> Vacant<'owner, T, I, G> {
let vacancy = self.vacancy;
let next =
unsafe { mem::ManuallyDrop::take(&mut (*vacancy.entry.as_ref().word.get()).free) };
vacancy.owner.free.set(next);
vacancy
}
pub(in crate::driver::retained::flight) fn index(&self) -> u32 {
unsafe { self.vacancy.entry.as_ref() }.index
}
pub(in crate::driver::retained::flight) fn take(self) -> super::Vacant<'slot, 'owner, T, I, G> {
super::Vacant {
vacant: o3::mem::Lease::open(super::Release(self.detach(), marker::PhantomData), ()),
}
}
pub(in crate::driver::retained::flight) fn reserve(
self,
value: T,
) -> super::Reserved<'owner, T, I, G> {
super::Reserved {
live: o3::mem::Lease::open(super::Release(self.detach().occupy(value), ()), ()),
}
}
pub(in crate::driver::retained::flight) unsafe fn write<B>(
self,
value: T,
backing: B,
) -> ptr::NonNull<State<T, I, G>> {
let pointer = self.vacancy.entry;
unsafe {
(*pointer.cast::<Cell<T, B, I, G>>().as_ptr())
.backing
.get()
.write(mem::MaybeUninit::new(backing))
};
let _ = self.detach().occupy(value);
pointer
}
}
impl<'a, T: Copy, const I: u32, const G: u32> Vacant<'a, T, I, G> {
pub(super) fn occupy(self, value: T) -> Live<'a, T, I, G> {
let entry = unsafe { self.entry.as_ref() };
entry.value.set(mem::MaybeUninit::new(value));
entry.set(
ptr::from_ref(self.owner)
.cast_mut()
.map_addr(|address| address | ATTACHED | PENDING),
);
Live {
entry: self.entry,
invariant: marker::PhantomData,
}
}
pub(super) fn release(self) {
let head = self.owner.free.as_ptr();
unsafe {
self.entry.as_ref().word.get().write(Word {
free: mem::ManuallyDrop::new(head.read()),
});
head.write(Some(Link(self.entry)));
}
}
}
impl<'a, T: Copy, const I: u32, const G: u32> Live<'a, T, I, G> {
fn get(&self) -> &State<T, I, G> {
unsafe { self.entry.as_ref() }
}
pub(super) fn is_pending(&self) -> bool {
self.get().is_pending()
}
pub(super) fn value(&self) -> T {
unsafe { self.get().value.get().assume_init() }
}
pub(super) fn echo(&self) -> Echo<T, I, G> {
Echo::from_parts(self.get().index, self.get().generation.get())
}
pub(super) fn detach(self) {
let pointer = self.get().pointer();
if pointer.addr() & FLAGS == ATTACHED {
self.recycle();
} else {
self.get()
.set(pointer.map_addr(|address| address & !ATTACHED));
}
}
pub(super) fn release(self) {
let pointer = self.get().pointer();
if pointer.addr() & BOUND != 0 {
self.get()
.set(pointer.map_addr(|address| address & !(ATTACHED | PENDING)));
} else {
self.recycle();
}
}
fn recycle(self) {
let owner = self.get().pointer().map_addr(|address| address & !FLAGS);
let owner: &Header<T, I, G> = unsafe { &*owner };
let next = self.get().generation.get().checked_add(1);
let Some(next) = next.filter(|next| next.get() <= generation_max::<G>()) else {
self.get().set(ptr::without_provenance_mut(RETIRED));
owner.admission.set(owner.admission.get() - 1);
return;
};
self.get().generation.set(next);
Vacant {
entry: self.entry,
owner,
}
.release();
}
}
impl<T: Copy, const I: u32, const G: u32> Bound<'_, T, I, G> {
pub(super) fn echo(&self) -> Echo<T, I, G> {
self.live.echo()
}
pub(super) fn value(&self) -> T {
self.live.value()
}
pub(super) fn mark_terminal(&self) {
let pointer = self.live.get().pointer();
self.live
.get()
.set(pointer.map_addr(|address| address & !PENDING));
}
pub(super) fn header_matches(&self, header: *const ()) -> bool {
self.live
.get()
.pointer()
.map_addr(|address| address & !FLAGS)
.cast_const()
.cast::<()>()
== header
}
pub(super) fn is_attached(&self) -> bool {
self.live.get().is_attached()
}
pub(super) fn into_pointer(self) -> ptr::NonNull<State<T, I, G>> {
self.live.entry
}
pub(super) fn finish(self) {
let live = self.live;
let pointer = live.get().pointer();
if pointer.addr() & ATTACHED == 0 {
live.recycle();
} else {
live.get()
.set(pointer.map_addr(|address| address & !(PENDING | BOUND)));
}
}
pub(super) fn retain(self) {
let pointer = self.live.get().pointer();
if pointer.addr() & PENDING == 0 {
self.live.recycle();
} else {
self.live
.get()
.set(pointer.map_addr(|address| address & !BOUND));
}
}
}
#[repr(C)]
pub struct Retiring<B, const COMPLETE: bool> {
native: State<Target, INDEX_BITS, GENERATION_BITS>,
backing: mem::ManuallyDrop<B>,
}
impl<B, const COMPLETE: bool> Retiring<B, COMPLETE> {
pub(in crate::driver::retained::flight) unsafe fn occupy<'a>(
pointer: ptr::NonNull<State<Target, INDEX_BITS, GENERATION_BITS>>,
) -> slot::Occupied<'a, Self> {
const {
assert!(
mem::size_of::<Self>()
== mem::size_of::<Cell<Target, B, INDEX_BITS, GENERATION_BITS>>()
);
assert!(
mem::align_of::<Self>()
== mem::align_of::<Cell<Target, B, INDEX_BITS, GENERATION_BITS>>()
);
assert!(
mem::offset_of!(Self, backing)
== mem::offset_of!(Cell<Target, B, INDEX_BITS, GENERATION_BITS>, backing)
);
}
unsafe {
slot::Vacant::new(&mut *pointer.cast::<mem::MaybeUninit<Self>>().as_ptr()).assume_init()
}
}
fn release(pointer: ptr::NonNull<State<Target, INDEX_BITS, GENERATION_BITS>>) {
let live = Live {
entry: pointer,
invariant: marker::PhantomData,
};
if COMPLETE {
live.recycle();
} else {
live.detach();
}
}
pub fn take(mut owner: slot::Occupied<'_, Self>) -> B {
let value = owner.get_mut();
let pointer = ptr::NonNull::from(&mut *value).cast();
let backing = unsafe { mem::ManuallyDrop::take(&mut value.backing) };
let _ = owner.into_uninit();
Self::release(pointer);
backing
}
pub fn backing(&mut self) -> &mut B {
&mut self.backing
}
pub fn echo(&self) -> flight::raw::Echo {
flight::raw::Echo::from_inner(Echo::from_parts(
self.native.index,
self.native.generation.get(),
))
}
pub fn slot(&self) -> crate::driver::route::indices::SlotIndex {
unsafe { self.native.value.get().assume_init() }.slot
}
pub fn epoch(&self) -> crate::driver::route::Epoch {
unsafe { self.native.value.get().assume_init() }.epoch
}
}
impl<B, const COMPLETE: bool> Drop for Retiring<B, COMPLETE> {
fn drop(&mut self) {
let pointer = ptr::NonNull::from(&mut *self).cast();
unsafe { mem::ManuallyDrop::drop(&mut self.backing) };
Self::release(pointer);
}
}
pub struct RetainedDrain<'a, B> {
next: *mut Cell<Target, B, INDEX_BITS, GENERATION_BITS>,
end: *mut Cell<Target, B, INDEX_BITS, GENERATION_BITS>,
owner: marker::PhantomData<&'a mut B>,
}
impl<'a, B> RetainedDrain<'a, B> {
pub(in crate::driver::retained::flight) unsafe fn new(
slots: &'a mut Slots<'_, Target, INDEX_BITS, GENERATION_BITS>,
) -> Self {
let (next, extent) = unsafe { slots.tail::<B>() };
Self {
next,
end: unsafe { next.add(extent) },
owner: marker::PhantomData,
}
}
}
impl<'a, B> Iterator for RetainedDrain<'a, B> {
type Item = slot::Occupied<'a, Retiring<B, false>>;
fn next(&mut self) -> Option<Self::Item> {
while self.next != self.end {
let pointer = self.next;
self.next = unsafe { self.next.add(1) };
if unsafe { &(*pointer).native }.is_attached() {
return Some(unsafe {
Retiring::occupy(ptr::NonNull::new_unchecked(pointer.cast()))
});
}
}
None
}
}
const _: () = {
assert!(mem::size_of::<State<u64, 32, 32>>() == 3 * mem::size_of::<usize>());
assert!(mem::size_of::<Header<u64, 32, 32>>() == 2 * mem::size_of::<usize>());
assert!(mem::align_of::<State<u64, 32, 32>>() == 8);
assert!(mem::align_of::<Header<u64, 32, 32>>() == 8);
assert!(mem::size_of::<Vacant<'static, u64, 32, 32>>() == 2 * mem::size_of::<usize>());
assert!(mem::size_of::<Live<'static, u64, 32, 32>>() == mem::size_of::<usize>());
assert!(mem::size_of::<Option<Live<'static, u64, 32, 32>>>() == mem::size_of::<usize>());
assert!(mem::size_of::<Bound<'static, u64, 32, 32>>() == mem::size_of::<usize>());
};