use std::{cell::Cell, marker, mem, num, ptr, time};
use dope_sys::{engine, kernel, memory::Context as _};
#[cfg(target_os = "macos")]
use o3::buffer;
use o3::{
base::{cell::region, marker::ThreadBound},
buffer::storage::provided,
};
use route::table;
use crate::{
Backend, Engine,
driver::{
life::{domain::runtime::Runtime, native, native::host::Host},
retained::flight,
route::queues,
schedule::{
clock,
clock::{timer, timer::heap},
ready,
ready::{task::owner, wake::resident::slot},
sequence,
},
},
io::fd::access::Access,
random,
};
pub mod life;
pub use life::Local;
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};
#[cfg(target_os = "linux")]
type ReceiveArena = provided::native::Arena<Shared>;
#[cfg(target_os = "macos")]
type ReceiveArena = provided::Arena<crate::Buffer, Shared, ()>;
#[cfg(target_os = "linux")]
type ReceiveRoot<'d> = provided::native::Root<'d, Shared>;
#[cfg(target_os = "macos")]
type ReceiveRoot<'d> = provided::Root<'d, crate::Buffer, Shared, ()>;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub(crate) struct Invariant<'d>(marker::PhantomData<(fn(&'d ()) -> &'d (), ThreadBound)>);
#[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)
}
}
#[repr(transparent)]
pub struct Driver {
runtime: Runtime,
}
#[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>) -> 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 owners(self) -> ReceiveRoot<'d> {
self.shared
}
pub(crate) fn exhausted(self) -> &'d crate::Permits {
&self.shared.context().receive
}
pub(crate) fn layout(self) -> settings::Receive {
self.owners().context().buffer().layout().0
}
pub fn has_deferred(self) -> bool {
self.owners().has_returned()
|| self.descriptors().retirement().has_pending()
|| self.shared.context().retire.has_pending()
}
pub(crate) const fn descriptors(self) -> Access<'d> {
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 random::Seed {
self.shared.context().random_seed()
}
}
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::<Driver>() == mem::size_of::<Runtime>());
assert!(mem::align_of::<Driver>() == mem::align_of::<Runtime>());
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) -> native::Access<'_, 'd> {
native::Access::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 {
random_seed: random::Seed,
pub(in crate::driver) schedule: schedule::State,
pub(in crate::driver) receive: crate::Permits,
buffer: <Engine as engine::Buffer>::Context,
pub(in crate::driver) retire: queues::Pending,
pub(in crate::driver) generations: [Cell<Option<route::Epoch>>; route::CAPACITY],
pub(in crate::driver) sequence: sequence::Owner,
timer: heap::raw::Store<time::Instant, slot::Slot, timer::Tag>,
}
impl Shared {
pub(in crate::driver) fn try_new<'f>(
seed: random::Seed,
plan: settings::Plan<'_>,
failure: &'f mut Option<result::CreateError>,
) -> Result<(ReceiveArena, Engine), &'f mut result::CreateError> {
let config = plan.config();
#[cfg(target_os = "linux")]
let initialize = match ReceiveArena::try_allocate(config.receive().count()) {
Ok(initialize) => initialize,
Err(error) => return Err(failure.insert(error.into())),
};
#[cfg(target_os = "macos")]
let initialize = match provided::Arena::<crate::Buffer, Self, ()>::try_allocate(
config.receive().count().into(),
) {
Ok(initialize) => initialize,
Err(error) => return Err(failure.insert(error.into())),
};
let schedule = match schedule::State::try_new(plan) {
Ok(schedule) => schedule,
Err(error) => return Err(failure.insert(error.into())),
};
let timer = match heap::raw::Store::try_new(config.schedule().timers().count().get()) {
Ok(timer) => timer,
Err(error) => return Err(failure.insert(error.into())),
};
let (backend, buffer, receive) =
match unsafe { <Backend as engine::raw::Create<Host<Backend>, _>>::try_new(config) } {
Ok(created) => created,
Err(error) => return Err(failure.insert(error.into())),
};
let shared = Self {
random_seed: seed,
schedule,
receive,
buffer,
retire: queues::Pending::new(),
generations: [const { Cell::new(Some(route::Epoch::INITIAL)) }; route::CAPACITY],
sequence: sequence::Owner::new(),
timer,
};
#[cfg(target_os = "linux")]
let shared = initialize.initialize(shared);
#[cfg(target_os = "macos")]
let shared = initialize(shared);
Ok((shared, backend))
}
pub(in crate::driver) const fn random_seed(&self) -> &random::Seed {
&self.random_seed
}
pub(crate) fn buffer(&self) -> &<Engine as engine::Buffer>::Context {
&self.buffer
}
pub(crate) fn into_buffer(self) -> <Engine as engine::Buffer>::Context {
self.buffer
}
pub(in crate::driver) fn timer(
&self,
) -> &heap::raw::Store<time::Instant, slot::Slot, timer::Tag> {
&self.timer
}
}
#[cfg(target_os = "macos")]
impl buffer::raw::Fixed<crate::Buffer> for Shared {
fn resident(&self) -> num::NonZero<u32> {
buffer::raw::Fixed::resident(&self.buffer)
}
unsafe fn project<'a, 'id>(
&'a self,
item: &'a mut crate::Buffer,
limit: buffer::raw::Limit<'id>,
) -> buffer::raw::Projection<'a, 'id> {
unsafe { buffer::raw::Fixed::project(&self.buffer, item, limit) }
}
}
#[cfg(target_os = "linux")]
unsafe impl provided::native::Context for Shared {
fn resident(&self) -> num::NonZero<u32> {
self.buffer.layout().0.buffer_len().into_nonzero()
}
unsafe fn project(&self, bid: u16, len: usize) -> &mut [u8] {
unsafe { self.buffer.project(bid, len) }
}
}