use std::{marker, mem, time};
#[cfg(target_os = "macos")]
use std::pin;
use dope_sys::engine;
#[cfg(target_os = "macos")]
use dope_sys::memory::Context as _;
pub(in crate::driver) use epochs::Final;
use finish::Finish;
use o3::base::{
cell::{brand, region},
marker::ThreadBound,
};
#[cfg(target_os = "macos")]
use o3::{buffer, buffer::storage::provided::fixed};
#[cfg(target_os = "macos")]
use plans::Provided;
use schedule::state::Core;
use state::scope;
use crate::{
Engine, driver,
driver::{
result::poll,
retained::flight::cancel,
route::{self, kind},
},
driver::{
retained::flight,
route::lease::Registry,
schedule,
schedule::state,
storage,
storage::{resident, resident::Alloc},
},
io,
io::event::{
batch,
net::{accept, recv},
},
};
pub mod creation;
pub mod domain;
pub mod finish;
pub(crate) mod native;
mod plans;
pub mod recovery;
#[cfg(target_os = "linux")]
type Native<'d> = &'d mut Engine;
#[cfg(target_os = "macos")]
type Native<'d> = fixed::Loan<'d, Engine>;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Busy;
pub mod raw;
pub trait Operation<S: storage::Plan, Q: ?Sized, Report: io::Report>: Sized {
type Output;
fn rejected(&self, _source: &Q) {}
fn run<'a, 'p, 'd>(
self,
scope: Scope<'a, 'd, Report>,
storage: storage::Loan<'a, 'p, 'd, S>,
source: &'a Q,
) -> Self::Output
where
'd: 'p,
'p: 'a,
'd: 'a,
Self: 'd,
S: 'd,
Q: 'd;
}
pub struct Local<'d> {
pub(crate) driver: driver::Reference<'d>,
pub(crate) backend: Native<'d>,
pub(in crate::driver) 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 struct Lifecycle<'d, Report> {
pub(crate) local: Local<'d>,
pub(crate) source: Option<dope_sys::engine::register::Source<'d>>,
pub(crate) resuming: bool,
pub(crate) pending: bool,
pub(crate) report: &'d mut Report,
}
impl<'d, Report: io::Report> Lifecycle<'d, Report> {
pub fn context(&mut self) -> &mut driver::Local<'d> {
&mut self.local
}
pub fn driver_ref(&self) -> driver::Reference<'d> {
self.local.driver
}
pub(crate) fn shutdown(&mut self) {
let owned = self.source.take().is_some();
if self.resuming && owned {
self.pending = true;
return;
}
self.report.report(io::Reclaimed::Shutdown);
}
pub fn rejected(&mut self, failure: cancel::Failure) {
let report = io::Reclaimed::Cancellation(failure);
self.report.report(report);
}
pub fn accept_error(
&mut self,
target: route::Erased<'d, kind::Accept>,
cause: accept::Failure,
flow: batch::Flow,
) {
self.report.report(io::Reclaimed::AcceptRoute {
target: target.into_token(),
cause,
flow,
});
}
pub fn reclaim(&mut self, done: recv::Data<'d, impl route::Selection>) {
let (target, flow, buffer) = done.into_parts();
let result = Ok(buffer.len());
drop(buffer);
self.receive_result(target, flow, result);
}
pub fn receive_result(
&mut self,
target: route::Erased<'d, kind::Recv, impl route::Selection>,
flow: batch::Flow,
result: Result<io::transfer::Len, crate::Errno>,
) {
self.report.report(io::Reclaimed::RecvRoute {
target: target.into_token(),
result,
flow,
});
}
}
impl<'d, Report: io::Report> Lifecycle<'d, Report> {
pub fn commit(&mut self, work: scope::Reactor<'_, 'd>) -> Result<poll::Commit, poll::Error> {
work.reclaim(self);
let retry = self.local.retry;
let owner = self.driver_ref();
#[cfg(target_os = "linux")]
let pending = {
use dope_sys::{
engine::ring::Backend as _, io::reactor::submit::Queue as _,
ring::ready::Ready as _,
};
drop(work.quota);
let backend = &mut *self.local.backend;
let busy =
retry
|| owner.has_deferred()
|| <crate::ring::cqe::Tuning as dope_uring::Progress<
crate::ring::cqe::Token,
>>::has_pending(backend.tuning());
backend.ring().commit().map_err(poll::Error::from_backend)?;
busy || !backend.ring().submission().is_empty()
};
#[cfg(target_os = "macos")]
let pending = {
use dope_sys::io::reactor::ready::Backend as _;
let quota = work.quota;
let backend = &mut *self.local.backend;
if backend.has_changes() && quota.remaining() != 0 {
unsafe { backend.poll("a, Some(time::Duration::ZERO), quota.remaining(), 0) }
.map_err(poll::Error::from_backend)?;
}
backend.check().map_err(poll::Error::from_backend)?;
let changes = backend.has_changes();
drop(quota);
let pending = retry || owner.has_deferred();
changes || pending
};
self.local.retry = false;
Ok(if pending {
poll::Commit::Pending
} else {
poll::Commit::Drained
})
}
pub fn wait(
&mut self,
work: scope::Reactor<'_, 'd>,
timeout: Option<time::Duration>,
) -> Result<(), poll::Error> {
work.reclaim(self);
let owner = self.driver_ref();
let busy =
self.local.retry || self.pending || owner.has_deferred() || owner.ready().has_ready();
let mut native = native::Access::new(&mut self.local);
unsafe { engine::raw::Poll::wait(native.as_mut(), work.quota, timeout, busy) }
.map_err(poll::Error::from_backend)?;
self.local.retry = false;
Ok(())
}
}
pub(in crate::driver) struct State<'d, Report> {
lifecycle: Lifecycle<'d, Report>,
work: Core<'d>,
token: brand::Token<brand::Identity<'d>>,
}
impl<'d, Report> State<'d, Report> {
fn new(lifecycle: Lifecycle<'d, Report>, token: brand::Token<brand::Identity<'d>>) -> Self {
Self {
work: Core::new(lifecycle.local.driver),
lifecycle,
token,
}
}
}
mod epochs;
#[repr(transparent)]
pub struct Scope<'a, 'd, Report> {
state: &'a mut State<'d, Report>,
}
impl<'a, 'd, Report: io::Report> Scope<'a, 'd, Report> {
fn new(state: &'a mut State<'d, Report>) -> Self {
Self { state }
}
pub fn context(&mut self) -> &mut driver::Local<'d> {
let state = &mut *self.state;
&mut state.lifecycle.local
}
pub fn lifecycle(&mut self) -> &mut Lifecycle<'d, Report> {
&mut self.state.lifecycle
}
pub fn token(&mut self) -> &mut brand::Token<brand::Identity<'d>> {
&mut self.state.token
}
#[inline]
pub fn split(
&mut self,
) -> (
&mut brand::Token<brand::Identity<'d>>,
&mut Lifecycle<'d, Report>,
scope::Scope<'_, 'd>,
) {
let state = &mut *self.state;
(
&mut state.token,
&mut state.lifecycle,
scope::Scope::new(&mut state.work),
)
}
pub fn driver_ref(&self) -> driver::Reference<'d> {
self.state.lifecycle.local.driver
}
pub fn try_boot(&self) -> Result<(), Busy> {
if self.state.lifecycle.local.flights.is_pending() {
Err(Busy)
} else {
Ok(())
}
}
pub fn quiesce(&mut self) {
let state = &mut *self.state;
Final::suspend(&mut state.lifecycle).resume()
}
pub(crate) fn finish<'app, H, T>(
&mut self,
forced: bool,
owner: crate::executor::raw::Owner<'app, 'd, H::Joined<T>, crate::executor::raw::Draining>,
) -> (H::Retired, Option<dope_sys::Errno>)
where
'd: 'app,
H: crate::topology::lending::raw::Head<'d>,
T: crate::executor::raw::App<'d>,
{
let state = &mut *self.state;
let last = Final::suspend(&mut state.lifecycle);
let mut finish = Finish::new(last, forced);
let output = owner.finish_child::<H, T>(&mut state.token, &mut finish);
let disarm = finish.disarm_error();
finish.resume();
(output, disarm)
}
}
#[cfg(target_os = "macos")]
impl driver::Driver {
fn run_scope<A, Q: ?Sized, O, Report: io::Report>(
&mut self,
arenas: A,
source: &domain::Source<Q>,
op: O,
report: &mut Report,
) -> O::Output
where
A: buffer::raw::Arenas,
O: Operation<storage::Scope<A>, Q, Report>,
{
let runtime = &mut self.runtime;
let root = Root {
flights: &mut runtime.flights,
resident: &mut runtime.resident,
source,
report,
};
runtime.shared.run(
pin::pin!((root, arenas)),
runtime.shared.context().buffer().layout().0.accounts(),
&mut runtime.backend,
Provided(op),
)
}
fn scope<'b, Q: ?Sized, O, Report: io::Report>(
&'b mut self,
source: &'b domain::Source<Q>,
op: O,
report: &'b mut Report,
) -> O::Output
where
O: fixed::Operation<
Root<'b, Q, Report>,
crate::Buffer,
driver::Shared,
Terminal = crate::Engine,
>,
{
let runtime = &mut self.runtime;
let root = Root {
flights: &mut runtime.flights,
resident: &mut runtime.resident,
source,
report,
};
runtime.shared.run(
pin::pin!(root),
runtime.shared.context().buffer().layout().0.accounts(),
&mut runtime.backend,
op,
)
}
}
const _: () = {
assert!(mem::size_of::<Scope<'static, 'static, ()>>() == mem::size_of::<&mut ()>());
assert!(mem::align_of::<Scope<'static, 'static, ()>>() == mem::align_of::<&mut ()>());
};
struct Root<'a, Q: ?Sized, Report> {
flights: &'a mut flight::Arena,
resident: &'a mut resident::Arena,
source: &'a domain::Source<Q>,
report: &'a mut Report,
}
impl<Q: ?Sized, Report: io::Report> Root<'_, Q, Report> {
fn enter<'d>(
&'d mut self,
shared: driver::ReceiveRoot<'d>,
token: brand::Token<brand::Identity<'d>>,
regions: (
region::Token<region::Identity<'d>>,
region::Token<region::Identity<'d, 1>>,
),
backend: Native<'d>,
) -> (State<'d, Report>, &'d Q) {
let alloc = self.resident.enter(®ions.0);
let local = Local {
driver: driver::Reference::new(shared),
backend,
retry: false,
flights: &*self.flights,
resident: alloc,
routes: Registry::new(),
region: regions,
};
let lifecycle = Lifecycle {
local,
source: self.source.descriptor(),
resuming: false,
pending: false,
report: &mut *self.report,
};
let state = State::new(lifecycle, token);
(state, &self.source.value)
}
}
#[must_use]
pub struct Install<'a, 'd> {
owner: marker::PhantomData<(&'a mut raw::Anchor<'a>, ThreadBound)>,
_driver: driver::Invariant<'d>,
}
impl<'a, 'd> Install<'a, 'd> {
pub fn new<T: raw::Root<'a>>(root: T, driver: driver::Reference<'d>) -> Self {
Self {
owner: root.anchor().owner(),
_driver: driver.brand,
}
}
pub fn reborrow(&mut self) -> Install<'_, 'd> {
Install {
owner: marker::PhantomData,
_driver: self._driver,
}
}
}
const _: () = {
assert!(mem::size_of::<Install<'static, 'static>>() == 0);
assert!(mem::align_of::<Install<'static, 'static>>() == 1);
};