use std::{cell::Cell, marker, mem, num, ptr, time};
use dope_sys::table::permit::Queue as _;
use dope_sys::{
engine, kernel, memory::Context as _, memory::buffer::Access, table::Slots as _,
thread::Thread as _,
};
use o3::{
base::{cell::region, marker::ThreadBound, num::Epoch},
buffer::{self, storage::provided::native},
};
use route::table;
use crate::{
Engine,
driver::{
life::native::Loan,
retained::flight,
route::{lease::Registry, queues},
schedule::{
clock,
clock::{timer, timer::heap},
ready,
ready::{task::owner, wake::resident::slot},
sequence,
},
},
io::{fd::access, transfer},
};
#[repr(transparent)]
pub struct Seed([u64; 2]);
impl Seed {
pub fn acquire() -> Result<Self, crate::Errno> {
let mut bytes = mem::MaybeUninit::uninit();
let [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] =
*crate::Backend::entropy::<16>(&mut bytes)?;
Ok(Self([
u64::from_ne_bytes([a, b, c, d, e, f, g, h]),
u64::from_ne_bytes([i, j, k, l, m, n, o, p]),
]))
}
pub fn map(&self, derive: impl FnOnce([u64; 2]) -> [u64; 2]) -> Self {
Self(derive(self.0))
}
}
impl AsRef<[u64; 2]> for Seed {
fn as_ref(&self) -> &[u64; 2] {
&self.0
}
}
pub mod life;
pub mod receive;
pub mod result;
pub mod retained;
pub mod route;
pub mod schedule;
pub mod settings;
pub mod storage;
use result::{IoOperation, Opcode, SubmitError};
use storage::resident::Alloc;
type ReceiveArena = <Engine as engine::Buffer>::Arena<Shared>;
type ReceiveRoot<'d> = <Engine as engine::Buffer>::Root<'d, Shared>;
type Native<'d> = &'d mut Engine;
pub struct Local<'d> {
pub(crate) driver: Reference<'d>,
pub(crate) backend: Native<'d>,
pub(crate) retry: bool,
pub(crate) flights: &'d flight::Arena,
pub(in crate::driver) resident: Alloc<'d>,
pub(in crate::driver) routes: Registry,
pub(crate) region: (
region::Token<region::Identity<'d>>,
region::Token<region::Identity<'d, 1>>,
),
}
pub(crate) type LocalMarker<T> = marker::PhantomData<(fn(T) -> T, ThreadBound)>;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub(crate) struct Invariant<'d>(LocalMarker<&'d ()>);
#[must_use = "application binding must be consumed during startup"]
pub struct Binding<'d> {
timer: timer::Timer<'d>,
owners: owner::Capacity,
}
impl<'d> Binding<'d> {
#[doc(hidden)]
pub const fn new(timer: timer::Timer<'d>, owners: owner::Capacity) -> Self {
Self { timer, owners }
}
pub const fn timer(&self) -> timer::Timer<'d> {
self.timer
}
pub const fn owners(&self) -> owner::Capacity {
self.owners
}
pub fn sequence(&self) -> sequence::Block<'d> {
sequence::Block::new(self.timer.driver)
}
}
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Reference<'d> {
shared: ReceiveRoot<'d>,
pub(crate) brand: Invariant<'d>,
}
impl<'d> Reference<'d> {
pub fn outbound_cap(self) -> table::Capacity {
let arena = self.ready().arena();
arena.descriptors().outbound_cap()
}
pub fn accept_cap(self) -> table::Capacity {
let arena = self.ready().arena();
arena.descriptors().accept_cap()
}
fn new(shared: ReceiveRoot<'d>, _: region::Identity<'d>) -> Self {
Self {
shared,
brand: Invariant(marker::PhantomData),
}
}
pub const fn ready(self) -> ready::Context<'d> {
ready::Context::new(self)
}
pub const fn targets<Tag: route::Tag>(self) -> route::Space<'d, Tag> {
route::Space {
driver: route::Brand::new(self.brand),
}
}
pub const fn scheduler(self) -> schedule::Context<'d> {
schedule::Context::new(self)
}
pub fn try_next_id(self) -> Result<sequence::Id<'d>, sequence::Exhausted> {
let raw = self
.shared
.context()
.sequence
.next()
.ok_or(sequence::Exhausted)?;
Ok(sequence::Id::new(self, raw))
}
pub fn clock(self) -> clock::Clock<'d, 'd> {
self.scheduler().clock()
}
pub const fn timer(self) -> timer::Timer<'d> {
timer::Timer::new(self)
}
pub(crate) fn exhausted(self) -> &'d crate::Permits {
&self.shared.context().receive
}
pub(crate) fn layout(self) -> settings::Receive {
self.shared.context().buffer().layout().0
}
pub(crate) const fn descriptors(self) -> access::Access<'d> {
access::Access::new(self)
}
#[doc(hidden)]
pub fn is_same(self, other: Reference<'_>) -> bool {
ptr::from_ref(self.shared.context()).addr() == ptr::from_ref(other.shared.context()).addr()
}
#[doc(hidden)]
pub fn random_seed(self) -> &'d Seed {
self.shared.context().random_seed()
}
}
impl<'d, Root: Copy> Access<Root, receive::Exhausted<'d>> for Reference<'d>
where
Engine: engine::Buffer<Root<'d, Shared> = Root>,
{
type Capacity = transfer::NonZero;
fn owners(&self) -> Root {
self.shared
}
fn buffer_len(&self) -> Self::Capacity {
self.layout().buffer_len()
}
fn release(&self) {
if let Ok(permit) = crate::Permits::try_acquire() {
receive::Proof::release(&permit, self.exhausted(), *self);
}
}
fn try_exhaust(&self) -> Option<receive::Exhausted<'d>> {
if crate::Permits::try_acquire().is_ok() {
Some(receive::Exhausted::from_driver(*self))
} else {
None
}
}
}
impl engine::Pending for Reference<'_> {
fn has_deferred(&self) -> bool {
self.shared.has_returned()
|| self.descriptors().retirement().has_pending()
|| self.shared.context().retire.has_pending()
}
}
const _: () = {
assert!(mem::size_of::<IoOperation>() == 1);
assert!(mem::align_of::<IoOperation>() == 1);
assert!(mem::size_of::<Opcode>() == mem::size_of::<<crate::Backend as kernel::Source>::Code>());
assert!(
mem::align_of::<Opcode>() == mem::align_of::<<crate::Backend as kernel::Source>::Code>()
);
assert!(mem::size_of::<Reference<'_>>() == mem::size_of::<usize>());
assert!(mem::align_of::<Reference<'_>>() == mem::align_of::<usize>());
assert!(mem::size_of::<Invariant<'_>>() == 0);
assert!(mem::align_of::<Invariant<'_>>() == 1);
assert!(mem::size_of::<SubmitError>() == 1 && mem::align_of::<SubmitError>() == 1);
assert!(
mem::size_of::<Result<flight::Flight<'static>, SubmitError>>()
== mem::size_of::<(flight::Flight<'static>, SubmitError)>()
);
assert!(
mem::align_of::<Result<flight::Flight<'static>, SubmitError>>()
== mem::align_of::<flight::Flight<'static>>()
);
};
impl<'d> Local<'d> {
pub fn storage(&mut self) -> storage::Context<'_, 'd> {
storage::Context::new(self)
}
pub(crate) fn native(&mut self) -> Loan<'_, 'd> {
Loan::new(self)
}
pub fn region_token(&mut self) -> &mut region::Token<region::Identity<'d>> {
&mut self.region.0
}
pub fn state_token(&mut self) -> &mut region::Token<region::Identity<'d, 1>> {
&mut self.region.1
}
pub fn regions_mut(
&mut self,
) -> &mut (
region::Token<region::Identity<'d>>,
region::Token<region::Identity<'d, 1>>,
) {
&mut self.region
}
pub fn regions(
&self,
) -> &(
region::Token<region::Identity<'d>>,
region::Token<region::Identity<'d, 1>>,
) {
&self.region
}
pub fn receive(&self) -> settings::Receive {
self.driver.layout()
}
pub fn driver_ref(&self) -> Reference<'d> {
self.driver
}
}
pub(crate) struct Shared<B = <Engine as engine::Buffer>::Context> {
random_seed: Seed,
pub(in crate::driver) schedule: schedule::State,
pub(in crate::driver) receive: crate::Permits,
buffer: B,
pub(in crate::driver) retire: queues::Pending,
pub(in crate::driver) generations: [Cell<Option<Epoch>>; route::CAPACITY],
pub(in crate::driver) sequence: sequence::Owner,
timer: heap::raw::Store<time::Instant, slot::Slot, timer::Tag>,
}
impl<B> Shared<B> {
pub(in crate::driver) const fn random_seed(&self) -> &Seed {
&self.random_seed
}
pub(crate) fn buffer(&self) -> &B {
&self.buffer
}
pub(in crate::driver) fn timer(
&self,
) -> &heap::raw::Store<time::Instant, slot::Slot, timer::Tag> {
&self.timer
}
}
impl<T, B: buffer::raw::Fixed<T>> buffer::raw::Fixed<T> for Shared<B> {
fn resident(&self) -> num::NonZero<u32> {
buffer::raw::Fixed::resident(&self.buffer)
}
unsafe fn project<'a, 'id>(
&'a self,
item: &'a mut T,
limit: buffer::raw::Limit<'id>,
) -> buffer::raw::Projection<'a, 'id> {
unsafe { buffer::raw::Fixed::project(&self.buffer, item, limit) }
}
}
unsafe impl<B: native::raw::Context> native::raw::Context for Shared<B> {
fn resident(&self) -> num::NonZero<u32> {
self.buffer.resident()
}
fn buffer_ptr(&self, bid: u16) -> *mut u8 {
self.buffer.buffer_ptr(bid)
}
}