feat(linux): run original fork children on reserved hosted stacks
This commit is contained in:
1 parent
eb3960a741
commit
37e4e9f569
11 files changed
+926
-51
No files matched your search
@@ -352,7 +352,20 @@ impl<const N: usize> HostedChild<'_, N> {
|
||||
/// Observe the exact child on its physical dispatcher successor.
|
||||
pub fn returned(&self) -> Result<bool, WorkError> {
|
||||
self.runtime.dispatcher_successor()?;
|
||||
// SAFETY: actual original dispatcher, with every hosted task stopped.
|
||||
self.returned_stopped()
|
||||
}
|
||||
|
||||
/// Observe a physical return from another live process on the same runtime.
|
||||
pub fn returned_to_peer(&self) -> Result<bool, WorkError> {
|
||||
self.runtime.current_context()?;
|
||||
if self.worker == self.runtime.current.get() {
|
||||
return Err(WorkError::InvalidTicket);
|
||||
}
|
||||
self.returned_stopped()
|
||||
}
|
||||
|
||||
fn returned_stopped(&self) -> Result<bool, WorkError> {
|
||||
// SAFETY: the dispatcher or a different live task owns this runtime.
|
||||
let task = unsafe { &*self.runtime.task(self.worker) };
|
||||
if task.stack_pin_nonce != self.nonce {
|
||||
return Err(WorkError::InvalidTicket);
|
||||
@@ -487,6 +500,7 @@ mod tests {
|
||||
// SAFETY: exact source preparation ended and the fixture stays kept.
|
||||
let child = unsafe { reserved.publish(child_body, raw) }
|
||||
.unwrap_or_else(|(_, error)| panic!("{error:?}"));
|
||||
assert_eq!(child.returned_to_peer(), Ok(false));
|
||||
*call.child.borrow_mut() = Some(child);
|
||||
runtime.yield_now().unwrap();
|
||||
assert_eq!(call.visits.get(), 0);
|
||||
@@ -495,6 +509,13 @@ mod tests {
|
||||
unsafe { call.child.borrow_mut().as_mut().unwrap().activate() }.unwrap();
|
||||
}
|
||||
|
||||
unsafe extern "C" fn observe_return(raw: *mut c_void) {
|
||||
// SAFETY: the fixture keeps the same context while this peer runs.
|
||||
let call = unsafe { &*raw.cast::<Call<'_>>() };
|
||||
let child = call.child.borrow();
|
||||
assert_eq!(child.as_ref().unwrap().returned_to_peer(), Ok(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_child_stack_is_dormant_until_activation_and_kept_until_source_release() {
|
||||
let queue = HostedQueue::new(HostedExecution::new(), Arc::new(())).unwrap();
|
||||
@@ -532,6 +553,17 @@ mod tests {
|
||||
assert_eq!(runtime.step(), Ok(true));
|
||||
assert_eq!(call.visits.get(), 1);
|
||||
assert_eq!(queue.completed(ticket), Ok(true));
|
||||
// SAFETY: the same context survives this separate hosted assignment.
|
||||
let peer = unsafe {
|
||||
queue.execute(
|
||||
Kind::General,
|
||||
observe_return,
|
||||
ptr::from_ref(&call).cast_mut().cast(),
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
assert_eq!(runtime.step(), Ok(true));
|
||||
assert_eq!(queue.completed(peer), Ok(true));
|
||||
let child = call.child.take().unwrap();
|
||||
assert_eq!(child.returned(), Ok(true));
|
||||
queue.close().unwrap();
|
||||
|
||||
@@ -77,6 +77,10 @@ unsafe extern "C" fn finish<const N: usize>(context: *mut c_void) {
|
||||
// SAFETY: original callbacks returned and this is their real next deadline.
|
||||
unsafe { runtime.finish_service_batch(ManuallyDrop::into_inner(batch), deadline) }
|
||||
.unwrap_or_else(|error| timer::fatal(error));
|
||||
// SAFETY: still on this mounted Initial, after the timer capture returned.
|
||||
if unsafe { crate::task::hosted_service_progress(owner, runtime) }.is_err() {
|
||||
timer::fatal(WorkError::CorruptContext);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn no_native_irq(_: *mut c_void) -> c_int {
|
||||
|
||||
@@ -18,9 +18,15 @@ mod inactive;
|
||||
target_os = "linux",
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
pub(crate) use hosted::service_progress as hosted_service_progress;
|
||||
#[cfg(all(
|
||||
feature = "hosted-runtime",
|
||||
target_os = "linux",
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
pub use hosted::{
|
||||
HostedStackReservation, HostedTaskBinding, initialize_hosted_resources,
|
||||
reserve_hosted_child_stack,
|
||||
reserve_hosted_child_stack, start_hosted_threads, step_hosted,
|
||||
};
|
||||
mod native;
|
||||
pub mod runtime;
|
||||
|
||||
@@ -17,30 +17,30 @@ const ACTIVE: u8 = 2;
|
||||
const SOURCE_RELEASED: u8 = 3;
|
||||
const FINISHED: u8 = 4;
|
||||
#[repr(C)]
|
||||
struct CData {
|
||||
pub(super) struct CData {
|
||||
_opaque: [u8; 0],
|
||||
}
|
||||
#[repr(C)]
|
||||
struct DataIdentity {
|
||||
queue_id: u64,
|
||||
context_id: u64,
|
||||
sequence: u64,
|
||||
pub(super) struct DataIdentity {
|
||||
pub(super) queue_id: u64,
|
||||
pub(super) context_id: u64,
|
||||
pub(super) sequence: u64,
|
||||
}
|
||||
const _: () = assert!(core::mem::size_of::<DataIdentity>() == 24);
|
||||
#[repr(C)]
|
||||
struct DataView {
|
||||
lease: *mut CData,
|
||||
total: *mut u64,
|
||||
system: *mut u64,
|
||||
pub(super) struct DataView {
|
||||
pub(super) lease: *mut CData,
|
||||
pub(super) total: *mut u64,
|
||||
pub(super) system: *mut u64,
|
||||
}
|
||||
const _: () = assert!(core::mem::size_of::<DataView>() == 24);
|
||||
unsafe extern "C" {
|
||||
fn stela_linux_task_data_prepare(
|
||||
pub(super) fn stela_linux_task_data_prepare(
|
||||
task: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
view: *mut DataView,
|
||||
) -> i32;
|
||||
fn stela_linux_task_data_release(
|
||||
pub(super) fn stela_linux_task_data_release(
|
||||
lease: *mut CData,
|
||||
owner: *const RawOwner,
|
||||
view: *const DataIdentity,
|
||||
|
||||
@@ -13,7 +13,25 @@ pub(super) const SOURCE_FREED: u8 = 2;
|
||||
pub(super) const TERMINAL_RETURNED: u8 = 4;
|
||||
pub(super) const SOURCE_TAIL: u8 = 16;
|
||||
|
||||
#[cfg(all(
|
||||
feature = "hosted-runtime",
|
||||
target_os = "linux",
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
pub(super) struct HostedHooks {
|
||||
pub(super) runtime: *const c_void,
|
||||
pub(super) start: unsafe fn(*const c_void) -> i32,
|
||||
pub(super) service: unsafe fn(*const c_void) -> i32,
|
||||
pub(super) dispatcher: unsafe fn(*const c_void) -> i32,
|
||||
}
|
||||
|
||||
pub(super) struct Dispatch {
|
||||
#[cfg(all(
|
||||
feature = "hosted-runtime",
|
||||
target_os = "linux",
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
pub(super) hosted: Option<HostedHooks>,
|
||||
pub(super) pending: unsafe fn(*const c_void) -> bool,
|
||||
pub(super) process: unsafe fn(*const c_void) -> i32,
|
||||
pub(super) context: *const c_void,
|
||||
@@ -40,6 +58,19 @@ impl Dispatch {
|
||||
!DISPATCH.load(Ordering::Acquire).is_null()
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
feature = "hosted-runtime",
|
||||
target_os = "linux",
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
pub(super) fn hosted(runtime: *const c_void) -> Option<(&'static Self, &'static HostedHooks)> {
|
||||
let pointer = DISPATCH.load(Ordering::Acquire);
|
||||
// SAFETY: successful publication keeps this immutable table permanently.
|
||||
let table = unsafe { pointer.as_ref() }?;
|
||||
let hooks = table.hosted.as_ref()?;
|
||||
(hooks.runtime == runtime).then_some((table, hooks))
|
||||
}
|
||||
|
||||
/// Publish the sole source callback owner.
|
||||
///
|
||||
/// # Safety
|
||||
|
||||
@@ -5,8 +5,11 @@ use core::cell::{Cell, RefCell};
|
||||
use stela_driver_base::platform::work::kernel_domain::{
|
||||
DomainRef, HostedRuntime, HostedSwitchBinding, HostedWake,
|
||||
};
|
||||
mod fork;
|
||||
pub(crate) use fork::service_progress;
|
||||
pub use fork::step_hosted;
|
||||
mod initial;
|
||||
pub use initial::initialize_hosted_resources;
|
||||
pub use initial::{initialize_hosted_resources, start_hosted_threads};
|
||||
mod stack;
|
||||
pub use stack::{HostedStackReservation, reserve_hosted_child_stack};
|
||||
|
||||
@@ -17,7 +20,15 @@ pub struct HostedTaskBinding<const N: usize> {
|
||||
wake: RefCell<Option<HostedWake>>,
|
||||
detached: Cell<bool>,
|
||||
released: bool,
|
||||
initial: bool,
|
||||
kind: Kind,
|
||||
identity: Cell<Option<TaskContext>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
Bare,
|
||||
Initial,
|
||||
Child,
|
||||
}
|
||||
|
||||
impl<const N: usize> HostedTaskBinding<N> {
|
||||
@@ -47,21 +58,18 @@ impl<const N: usize> HostedTaskBinding<N> {
|
||||
DomainRef::borrow_hosted(runtime)?.dispatcher_successor()?;
|
||||
// SAFETY: caller supplies the original heap and serialized dispatcher.
|
||||
let task = NonNull::new(unsafe { stela_linux_task_allocate() }).ok_or(WorkError::Full)?;
|
||||
Ok(Self::new_record(task, runtime, false))
|
||||
Ok(Self::new_record(task, runtime, Kind::Bare))
|
||||
}
|
||||
|
||||
fn new_record(
|
||||
task: NonNull<CTask>,
|
||||
runtime: Pin<&HostedRuntime<N>>,
|
||||
initial: bool,
|
||||
) -> Rc<Self> {
|
||||
fn new_record(task: NonNull<CTask>, runtime: Pin<&HostedRuntime<N>>, kind: Kind) -> Rc<Self> {
|
||||
Rc::new(Self {
|
||||
task,
|
||||
runtime: NonNull::from(runtime.get_ref()),
|
||||
wake: RefCell::new(None),
|
||||
detached: Cell::new(false),
|
||||
released: false,
|
||||
initial,
|
||||
kind,
|
||||
identity: Cell::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -109,7 +117,7 @@ impl<const N: usize> HostedTaskBinding<N> {
|
||||
/// Original producer/waiter/lease users have actually joined. This must
|
||||
/// run on the sole dispatcher, after successful detach if ever attached.
|
||||
pub unsafe fn release_quiescent(self: Rc<Self>) -> Result<(), Rc<Self>> {
|
||||
if self.initial
|
||||
if self.kind != Kind::Bare
|
||||
|| DomainRef::borrow_hosted(self.runtime())
|
||||
.and_then(|domain| domain.dispatcher_successor())
|
||||
.is_err()
|
||||
@@ -159,7 +167,7 @@ impl<const N: usize> HostedTaskBinding<N> {
|
||||
|
||||
unsafe extern "C" fn service_reserved(binding: *mut c_void) -> bool {
|
||||
// SAFETY: C retains the same binding and checks its assignment.
|
||||
unsafe { &*binding.cast::<Self>() }.initial
|
||||
unsafe { &*binding.cast::<Self>() }.kind == Kind::Initial
|
||||
}
|
||||
|
||||
unsafe extern "C" fn rank(
|
||||
@@ -246,10 +254,12 @@ impl<const N: usize> HostedTaskBinding<N> {
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn terminate(_: *mut c_void) -> ! {
|
||||
// SAFETY: bare source may not retire an original child. Preserve the
|
||||
// current stack and owners if it reaches this impossible boundary.
|
||||
unsafe { core::arch::asm!("ud2", options(noreturn)) }
|
||||
unsafe extern "C" fn terminate(scope: *mut c_void) -> ! {
|
||||
// SAFETY: C entered from original do_task_dead and keeps the exact
|
||||
// child scope. The runtime independently checks the live child stack.
|
||||
let runtime = unsafe { *scope.cast::<Pin<&HostedRuntime<N>>>() };
|
||||
// SAFETY: the nonreturning C body owns no returning Rust guards.
|
||||
unsafe { runtime.terminate_child() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,7 +279,7 @@ unsafe impl<const N: usize> HostedSwitchBinding for HostedTaskBinding<N> {
|
||||
return Err(WorkError::Busy);
|
||||
}
|
||||
let runtime = self.runtime();
|
||||
if runtime.service_current()? != self.initial {
|
||||
if runtime.service_current()? != (self.kind == Kind::Initial) {
|
||||
return Err(WorkError::Unavailable);
|
||||
}
|
||||
let wake = runtime.current_wake()?;
|
||||
@@ -285,6 +295,7 @@ unsafe impl<const N: usize> HostedSwitchBinding for HostedTaskBinding<N> {
|
||||
core::ptr::from_ref(self).cast_mut().cast(),
|
||||
)
|
||||
})?;
|
||||
self.identity.set(Some(*context));
|
||||
*self.wake.borrow_mut() = Some(wake);
|
||||
Ok(())
|
||||
}
|
||||
@@ -306,7 +317,7 @@ unsafe impl<const N: usize> HostedSwitchBinding for HostedTaskBinding<N> {
|
||||
|
||||
unsafe fn arrive(&self, context: &TaskContext, new_job: bool) -> Result<(), WorkError> {
|
||||
if new_job {
|
||||
if self.initial {
|
||||
if self.kind != Kind::Bare {
|
||||
return Err(WorkError::CorruptContext);
|
||||
}
|
||||
// Old signal/OS execution owners remain kept by the same runtime.
|
||||
@@ -321,6 +332,22 @@ unsafe impl<const N: usize> HostedSwitchBinding for HostedTaskBinding<N> {
|
||||
status(unsafe { stela_linux_task_complete(self.task.as_ptr(), context) })
|
||||
}
|
||||
|
||||
unsafe fn terminal_prepare(&self, context: &TaskContext) -> Result<(), WorkError> {
|
||||
if self.kind != Kind::Child {
|
||||
return Err(WorkError::InvalidTicket);
|
||||
}
|
||||
// SAFETY: actual current, source terminal path and kept child record.
|
||||
status(unsafe { stela_linux_task_terminal_prepare(self.task.as_ptr(), context) })
|
||||
}
|
||||
|
||||
unsafe fn terminal_successor(&self, context: &TaskContext) -> Result<(), WorkError> {
|
||||
if self.kind != Kind::Child {
|
||||
return Err(WorkError::InvalidTicket);
|
||||
}
|
||||
// SAFETY: runtime returned to its dispatcher from this exact child.
|
||||
status(unsafe { stela_linux_task_terminal_successor(self.task.as_ptr(), context) })
|
||||
}
|
||||
|
||||
unsafe fn detach(&self, context: &TaskContext) -> Result<(), WorkError> {
|
||||
// SAFETY: the actual dispatcher and independently joined users.
|
||||
status(unsafe { stela_linux_task_detach(self.task.as_ptr(), context) })?;
|
||||
|
||||
@@ -0,0 +1,631 @@
|
||||
//! Original fork, publication, and reaping on the hosted execution owner.
|
||||
use super::{initial::fatal, stack::ModelStackTicket, *};
|
||||
use crate::{
|
||||
owner::RawOwner,
|
||||
task::{
|
||||
data::{
|
||||
CData, DataIdentity, DataView, stela_linux_task_data_prepare,
|
||||
stela_linux_task_data_release,
|
||||
},
|
||||
dispatch::{
|
||||
Dispatch, HostedHooks, SOURCE_FREED, SOURCE_TAIL, SourceEntry, TERMINAL_RETURNED,
|
||||
},
|
||||
},
|
||||
};
|
||||
use alloc::{boxed::Box, vec::Vec};
|
||||
use core::ptr;
|
||||
use stela_driver_base::platform::work::kernel_domain::{DomainRaised, HostedChild, HostedDomain};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn stela_linux_task_child_identity(
|
||||
task: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
original: *mut *mut c_void,
|
||||
generation: *mut u64,
|
||||
) -> i32;
|
||||
fn stela_linux_task_child_install_stack(
|
||||
task: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
base: *mut c_void,
|
||||
bytes: usize,
|
||||
);
|
||||
fn stela_linux_task_child_source_unwound(
|
||||
task: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
generation: u64,
|
||||
) -> i32;
|
||||
fn stela_linux_task_child_tails_joined(
|
||||
task: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
generation: u64,
|
||||
) -> i32;
|
||||
fn stela_linux_task_source_broker_wake(owner: *const RawOwner) -> i32;
|
||||
fn stela_linux_task_run_original(context: *mut c_void);
|
||||
fn stela_linux_page_stack_lend(
|
||||
ticket: *const ModelStackTicket,
|
||||
original: *const c_void,
|
||||
base: *mut *mut c_void,
|
||||
) -> i32;
|
||||
fn stela_linux_page_stack_prepare_publish(
|
||||
ticket: *const ModelStackTicket,
|
||||
original: *const c_void,
|
||||
) -> i32;
|
||||
fn stela_linux_page_stack_publish(ticket: *const ModelStackTicket, original: *const c_void);
|
||||
fn stela_linux_page_stack_retire(
|
||||
ticket: *const ModelStackTicket,
|
||||
original: *const c_void,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
const DISPATCH_JOINED: u8 = 32;
|
||||
|
||||
pub(super) struct Broker<const N: usize> {
|
||||
runtime: NonNull<HostedRuntime<N>>,
|
||||
owner: *const RawOwner,
|
||||
initial: Option<NonNull<CTask>>,
|
||||
raised: DomainRaised<HostedDomain>,
|
||||
slots: Box<[Slot<N>]>,
|
||||
}
|
||||
|
||||
struct Slot<const N: usize> {
|
||||
child: RefCell<Option<Child<N>>>,
|
||||
events: Cell<u8>,
|
||||
source_tail: Cell<bool>,
|
||||
}
|
||||
|
||||
struct Child<const N: usize> {
|
||||
binding: Rc<HostedTaskBinding<N>>,
|
||||
original: NonNull<c_void>,
|
||||
generation: u64,
|
||||
data: NonNull<CData>,
|
||||
stage: Stage<N>,
|
||||
}
|
||||
|
||||
enum Stage<const N: usize> {
|
||||
Reserved(HostedStackReservation<'static, N>, bool),
|
||||
Dormant(Published<N>),
|
||||
Running(Published<N>),
|
||||
Joining(Published<N>),
|
||||
Detach(HostedChild<'static, N>),
|
||||
Final,
|
||||
Transition,
|
||||
}
|
||||
|
||||
struct Published<const N: usize> {
|
||||
worker: HostedChild<'static, N>,
|
||||
descriptors: ModelStackTicket,
|
||||
}
|
||||
|
||||
impl<const N: usize> Broker<N> {
|
||||
pub(super) fn new(
|
||||
runtime: Pin<&HostedRuntime<N>>,
|
||||
owner: *const RawOwner,
|
||||
capacity: usize,
|
||||
) -> Result<Self, WorkError> {
|
||||
let mut slots = Vec::new();
|
||||
slots
|
||||
.try_reserve_exact(capacity)
|
||||
.map_err(|_| WorkError::Full)?;
|
||||
for _ in 0..capacity {
|
||||
slots.push(Slot {
|
||||
child: RefCell::new(None),
|
||||
events: Cell::new(0),
|
||||
source_tail: Cell::new(false),
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
runtime: NonNull::from(runtime.get_ref()),
|
||||
owner,
|
||||
initial: None,
|
||||
raised: runtime.service_raised_work()?,
|
||||
slots: slots.into_boxed_slice(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) unsafe fn install(mut self, initial: NonNull<CTask>) -> Result<(), WorkError> {
|
||||
self.initial = Some(initial);
|
||||
let broker = Box::leak(Box::new(self));
|
||||
let dispatch = Dispatch {
|
||||
hosted: Some(HostedHooks {
|
||||
runtime: broker.runtime.as_ptr().cast(),
|
||||
start: start::<N>,
|
||||
service: service::<N>,
|
||||
dispatcher: dispatcher::<N>,
|
||||
}),
|
||||
owner: broker.owner,
|
||||
context: ptr::from_ref(broker).cast(),
|
||||
allocate: allocate::<N>,
|
||||
thread: thread::<N>,
|
||||
reserve_rank: reserve_rank::<N>,
|
||||
publish: publish::<N>,
|
||||
activate: activate::<N>,
|
||||
event: event::<N>,
|
||||
abort: abort::<N>,
|
||||
pending: pending::<N>,
|
||||
process: process::<N>,
|
||||
};
|
||||
// SAFETY: mounted source, broker and original host runtime stay kept.
|
||||
unsafe { dispatch.install() }.map_err(|()| WorkError::Busy)
|
||||
}
|
||||
|
||||
fn runtime(&'static self) -> Pin<&'static HostedRuntime<N>> {
|
||||
// SAFETY: installation keeps the exact original pinned host runtime.
|
||||
unsafe { Pin::new_unchecked(self.runtime.as_ref()) }
|
||||
}
|
||||
|
||||
fn slot(
|
||||
&self,
|
||||
record: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
generation: Option<u64>,
|
||||
) -> &Slot<N> {
|
||||
if owner != self.owner {
|
||||
fatal();
|
||||
}
|
||||
self.slots
|
||||
.iter()
|
||||
.find(|slot| {
|
||||
slot.child.borrow().as_ref().is_some_and(|child| {
|
||||
child.binding.task.as_ptr() == record
|
||||
&& generation.is_none_or(|v| child.generation == v)
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| fatal())
|
||||
}
|
||||
|
||||
fn raise(&self) {
|
||||
self.raised.raise().unwrap_or_else(|_| fatal());
|
||||
}
|
||||
|
||||
fn pending(&self) -> bool {
|
||||
self.slots.iter().any(|slot| slot.events.get() != 0)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn broker<const N: usize>(context: *const c_void) -> &'static Broker<N> {
|
||||
// SAFETY: the installed table supplies the exact permanently kept broker.
|
||||
unsafe { &*context.cast() }
|
||||
}
|
||||
|
||||
fn result(status: i32) -> Result<(), ResourceBootstrapError> {
|
||||
if status == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ResourceBootstrapError::Native(status))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) unsafe fn start_threads<const N: usize>(
|
||||
owner: *const RawOwner,
|
||||
runtime: Pin<&HostedRuntime<N>>,
|
||||
) -> Result<(), ResourceBootstrapError> {
|
||||
use ResourceBootstrapError::Work;
|
||||
DomainRef::borrow_hosted(runtime)
|
||||
.and_then(|domain| domain.current_context())
|
||||
.map_err(Work)?;
|
||||
let (table, hooks) = Dispatch::hosted(ptr::from_ref(runtime.get_ref()).cast())
|
||||
.filter(|(table, _)| table.owner == owner)
|
||||
.ok_or(Work(WorkError::InvalidTicket))?;
|
||||
// SAFETY: caller owns the source scope. C checks the exact Initial record.
|
||||
result(unsafe { (hooks.start)(table.context) })
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn service_progress<const N: usize>(
|
||||
owner: &RawOwner,
|
||||
runtime: Pin<&HostedRuntime<N>>,
|
||||
) -> Result<(), ResourceBootstrapError> {
|
||||
use ResourceBootstrapError::Work;
|
||||
let (table, hooks) = Dispatch::hosted(ptr::from_ref(runtime.get_ref()).cast())
|
||||
.filter(|(table, _)| ptr::eq(table.owner, owner))
|
||||
.ok_or(Work(WorkError::InvalidTicket))?;
|
||||
// SAFETY: the owned timer batch's exact Initial is current and entered.
|
||||
result(unsafe { (hooks.service)(table.context) })
|
||||
}
|
||||
|
||||
/// Drive the mounted hosted Linux runtime and consume any completed source
|
||||
/// child releases on the actual taskless dispatcher.
|
||||
pub fn step_hosted<const N: usize>(
|
||||
runtime: Pin<&HostedRuntime<N>>,
|
||||
idle: bool,
|
||||
) -> Result<bool, ResourceBootstrapError> {
|
||||
use ResourceBootstrapError::Work;
|
||||
DomainRef::borrow_hosted(runtime)
|
||||
.and_then(|domain| domain.dispatcher_successor())
|
||||
.map_err(Work)?;
|
||||
let (table, hooks) = Dispatch::hosted(ptr::from_ref(runtime.get_ref()).cast())
|
||||
.ok_or(Work(WorkError::InvalidTicket))?;
|
||||
// SAFETY: actual taskless dispatcher and the installed exact runtime.
|
||||
result(unsafe { (hooks.dispatcher)(table.context) })?;
|
||||
if idle {
|
||||
runtime.step_or_idle()
|
||||
} else {
|
||||
runtime.step()
|
||||
}
|
||||
.map_err(Work)
|
||||
}
|
||||
|
||||
unsafe fn start<const N: usize>(context: *const c_void) -> i32 {
|
||||
// SAFETY: the installed context and exact Initial remain kept.
|
||||
let this = unsafe { broker::<N>(context) };
|
||||
let initial = this.initial.unwrap_or_else(|| fatal());
|
||||
// SAFETY: C authenticates the genuine current and entered source owner.
|
||||
unsafe { stela_linux_task_start_threads(initial.as_ptr(), this.owner) }
|
||||
}
|
||||
|
||||
unsafe fn service<const N: usize>(context: *const c_void) -> i32 {
|
||||
// SAFETY: exact installed hosted Initial service context.
|
||||
let this = unsafe { broker::<N>(context) };
|
||||
if !this.pending() {
|
||||
return 0;
|
||||
}
|
||||
// SAFETY: only the genuine current Initial delivers the recorded reason.
|
||||
unsafe { stela_linux_task_source_broker_wake(this.owner) }
|
||||
}
|
||||
|
||||
unsafe fn allocate<const N: usize>(
|
||||
context: *const c_void,
|
||||
birth: *mut OriginalBirth,
|
||||
node: i32,
|
||||
unexposed: *mut bool,
|
||||
) -> i32 {
|
||||
// SAFETY: original dup_task_struct lends its birth and writable result.
|
||||
let this = unsafe { broker::<N>(context) };
|
||||
let Some(slot) = this.slots.iter().find(|slot| slot.child.borrow().is_none()) else {
|
||||
// SAFETY: no birth or stack was accepted.
|
||||
unsafe { *unexposed = true };
|
||||
return -12;
|
||||
};
|
||||
if !matches!(node, -1 | 0) {
|
||||
// SAFETY: no birth or stack was accepted.
|
||||
unsafe { *unexposed = true };
|
||||
return -95;
|
||||
}
|
||||
// SAFETY: exact mounted creator, before consuming the original birth.
|
||||
let stack = match unsafe { reserve_hosted_child_stack(this.runtime(), this.owner) } {
|
||||
Ok(stack) => stack,
|
||||
Err(ResourceBootstrapError::Work(WorkError::Full)) => {
|
||||
// SAFETY: worker exhaustion accepted neither stack nor birth.
|
||||
unsafe { *unexposed = true };
|
||||
return -12;
|
||||
}
|
||||
Err(_) => fatal(),
|
||||
};
|
||||
let mut record = ptr::null_mut();
|
||||
// SAFETY: the original allocator lends this one-shot birth to the same creator.
|
||||
let error = unsafe { stela_linux_task_child_allocate(this.owner, birth, &mut record) };
|
||||
if error != 0 {
|
||||
// SAFETY: C refused before consuming birth. No source borrowed the stack.
|
||||
unsafe { stack.cancel() }.unwrap_or_else(|_| fatal());
|
||||
// SAFETY: actual rollback joined both reservations.
|
||||
unsafe { *unexposed = true };
|
||||
return error;
|
||||
}
|
||||
let task = NonNull::new(record).unwrap_or_else(|| fatal());
|
||||
let mut original = ptr::null_mut();
|
||||
let mut generation = 0;
|
||||
let mut data = DataView {
|
||||
lease: ptr::null_mut(),
|
||||
total: ptr::null_mut(),
|
||||
system: ptr::null_mut(),
|
||||
};
|
||||
// SAFETY: the sole actual creator owns this new source-born record.
|
||||
if unsafe { stela_linux_task_child_identity(record, this.owner, &mut original, &mut generation) } != 0
|
||||
|| generation == 0
|
||||
// SAFETY: these projections are prepared before either attachment or publication.
|
||||
|| unsafe { stela_linux_task_data_prepare(record, this.owner, &mut data) } != 0
|
||||
{
|
||||
fatal();
|
||||
}
|
||||
let original = NonNull::new(original).unwrap_or_else(|| fatal());
|
||||
let data = NonNull::new(data.lease).unwrap_or_else(|| fatal());
|
||||
let binding = HostedTaskBinding::new_record(task, this.runtime(), Kind::Child);
|
||||
let mapping = stack.stack();
|
||||
let expected = mapping
|
||||
.cpu_address(0, mapping.bytes())
|
||||
.unwrap_or_else(|_| fatal());
|
||||
let ticket = stack.descriptors.as_ref().unwrap_or_else(|| fatal());
|
||||
let mut base = ptr::null_mut();
|
||||
// SAFETY: actual original birth and its exact reserved page descriptors.
|
||||
if unsafe { stela_linux_page_stack_lend(ticket, original.as_ptr(), &mut base) } != 0
|
||||
|| base != expected.as_ptr().cast()
|
||||
{
|
||||
fatal();
|
||||
}
|
||||
*slot.child.borrow_mut() = Some(Child {
|
||||
binding,
|
||||
original,
|
||||
generation,
|
||||
data,
|
||||
stage: Stage::Reserved(stack, false),
|
||||
});
|
||||
// SAFETY: the registry keeps the precise stopped worker before exposure.
|
||||
unsafe { stela_linux_task_child_install_stack(record, this.owner, base, mapping.bytes()) };
|
||||
0
|
||||
}
|
||||
|
||||
unsafe fn thread<const N: usize>(
|
||||
context: *const c_void,
|
||||
record: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
entry: Option<SourceEntry>,
|
||||
_: *mut c_void,
|
||||
) -> i32 {
|
||||
// SAFETY: C authenticates this prepared record and retains the function and argument.
|
||||
let slot = unsafe { broker::<N>(context) }.slot(record, owner, None);
|
||||
let mut child = slot.child.borrow_mut();
|
||||
let Stage::Reserved(_, prepared) = &mut child.as_mut().unwrap_or_else(|| fatal()).stage else {
|
||||
fatal();
|
||||
};
|
||||
if *prepared || entry.is_none() {
|
||||
return -22;
|
||||
}
|
||||
*prepared = true;
|
||||
0
|
||||
}
|
||||
|
||||
unsafe fn reserve_rank<const N: usize>(
|
||||
context: *const c_void,
|
||||
record: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
rank: *const Rank,
|
||||
) -> i32 {
|
||||
// SAFETY: C lends the exact source rank in original sched_fork.
|
||||
let slot = unsafe { broker::<N>(context) }.slot(record, owner, None);
|
||||
// SAFETY: the bounded original fork hook lends the initialized rank.
|
||||
let Some(rank) = (unsafe { rank.as_ref() }) else {
|
||||
return -22;
|
||||
};
|
||||
let Ok(rank) = rank.snapshot() else {
|
||||
return -95;
|
||||
};
|
||||
let mut child = slot.child.borrow_mut();
|
||||
let Stage::Reserved(stack, _) = &mut child.as_mut().unwrap_or_else(|| fatal()).stage else {
|
||||
fatal();
|
||||
};
|
||||
match stack.worker.reserve_rank(rank) {
|
||||
Ok(()) => 0,
|
||||
Err(WorkError::Full) => -12,
|
||||
Err(WorkError::Unavailable) => -95,
|
||||
Err(_) => -5,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn publish<const N: usize>(
|
||||
context: *const c_void,
|
||||
record: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
rank: *const Rank,
|
||||
) {
|
||||
// SAFETY: original C validates the accepted fork rank and permanent source graph.
|
||||
if unsafe { reserve_rank::<N>(context, record, owner, rank) } != 0 {
|
||||
fatal();
|
||||
}
|
||||
// SAFETY: installed context retains the slot through source and dispatcher joins.
|
||||
let slot = unsafe { broker::<N>(context) }.slot(record, owner, None);
|
||||
let mut kept = slot.child.borrow_mut();
|
||||
let child = kept.as_mut().unwrap_or_else(|| fatal());
|
||||
let Stage::Reserved(mut stack, true) = core::mem::replace(&mut child.stage, Stage::Transition)
|
||||
else {
|
||||
fatal();
|
||||
};
|
||||
let descriptors = stack.descriptors.take().unwrap_or_else(|| fatal());
|
||||
// SAFETY: exact lent descriptor graph, still before Dormant publication.
|
||||
if unsafe { stela_linux_page_stack_prepare_publish(&descriptors, child.original.as_ptr()) } != 0
|
||||
{
|
||||
fatal();
|
||||
}
|
||||
// SAFETY: immutable slot and original C callback are kept through every join.
|
||||
let worker = unsafe {
|
||||
stack
|
||||
.worker
|
||||
.publish(run::<N>, ptr::from_ref(slot).cast_mut().cast())
|
||||
}
|
||||
.unwrap_or_else(|_| fatal());
|
||||
// SAFETY: same accepted Dormant worker and validated exact original child.
|
||||
unsafe { stela_linux_page_stack_publish(&descriptors, child.original.as_ptr()) };
|
||||
child.stage = Stage::Dormant(Published {
|
||||
worker,
|
||||
descriptors,
|
||||
});
|
||||
}
|
||||
|
||||
unsafe fn activate<const N: usize>(
|
||||
context: *const c_void,
|
||||
record: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
) {
|
||||
// SAFETY: C has published this exact child and reached wake_up_new_task.
|
||||
let slot = unsafe { broker::<N>(context) }.slot(record, owner, None);
|
||||
let mut kept = slot.child.borrow_mut();
|
||||
let child = kept.as_mut().unwrap_or_else(|| fatal());
|
||||
let Stage::Dormant(mut published) = core::mem::replace(&mut child.stage, Stage::Transition)
|
||||
else {
|
||||
fatal();
|
||||
};
|
||||
// SAFETY: exact source publication plus the first original runnable wake.
|
||||
unsafe { published.worker.activate() }.unwrap_or_else(|_| fatal());
|
||||
child.stage = Stage::Running(published);
|
||||
}
|
||||
|
||||
unsafe extern "C" fn run<const N: usize>(context: *mut c_void) {
|
||||
// SAFETY: this slot is retained through terminal, source and dispatcher joins.
|
||||
let slot = unsafe { &*context.cast::<Slot<N>>() };
|
||||
let binding = {
|
||||
let kept = slot.child.borrow();
|
||||
let binding = &kept.as_ref().unwrap_or_else(|| fatal()).binding;
|
||||
binding.bind_current().unwrap_or_else(|_| fatal());
|
||||
ptr::from_ref(binding.as_ref())
|
||||
};
|
||||
// SAFETY: the permanent slot independently retains the binding. No owning
|
||||
// Rust value or borrow guard is abandoned by the original do_exit path.
|
||||
let binding = unsafe { &*binding };
|
||||
// SAFETY: actual active child on the exact source stack and original callback.
|
||||
let _ =
|
||||
unsafe { binding.run_scoped(stela_linux_task_run_original, binding.task.as_ptr().cast()) };
|
||||
fatal();
|
||||
}
|
||||
|
||||
unsafe fn event<const N: usize>(
|
||||
context: *const c_void,
|
||||
record: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
generation: u64,
|
||||
event: u8,
|
||||
) {
|
||||
// SAFETY: original callback tail lends the exact kept record and generation.
|
||||
let this = unsafe { broker::<N>(context) };
|
||||
let slot = this.slot(record, owner, Some(generation));
|
||||
if event == SOURCE_TAIL {
|
||||
slot.source_tail.set(true);
|
||||
}
|
||||
slot.events.set(slot.events.get() | event);
|
||||
this.raise();
|
||||
}
|
||||
|
||||
unsafe fn abort<const N: usize>(
|
||||
context: *const c_void,
|
||||
record: *mut CTask,
|
||||
owner: *const RawOwner,
|
||||
generation: u64,
|
||||
) {
|
||||
// SAFETY: original unwind supplies the exact kept unpublished record.
|
||||
let this = unsafe { broker::<N>(context) };
|
||||
let slot = this.slot(record, owner, Some(generation));
|
||||
let mut kept = slot.child.borrow_mut();
|
||||
let child = kept.as_mut().unwrap_or_else(|| fatal());
|
||||
let Stage::Reserved(stack, _) = core::mem::replace(&mut child.stage, Stage::Transition) else {
|
||||
fatal();
|
||||
};
|
||||
// SAFETY: C authenticates its actual reverse unwind and original object free.
|
||||
if unsafe { stela_linux_task_child_source_unwound(record, owner, generation) } != 0 {
|
||||
fatal();
|
||||
}
|
||||
// SAFETY: same creator and joined unpublished source stack references.
|
||||
unsafe { stack.cancel() }.unwrap_or_else(|_| fatal());
|
||||
// SAFETY: the source data reference was never claimed and unwind has joined.
|
||||
if unsafe { stela_linux_task_data_release(child.data.as_ptr(), owner, ptr::null()) } != 0 {
|
||||
fatal();
|
||||
}
|
||||
child.stage = Stage::Final;
|
||||
}
|
||||
|
||||
unsafe fn pending<const N: usize>(context: *const c_void) -> bool {
|
||||
// SAFETY: the genuine C supervisor calls its exact mounted broker.
|
||||
unsafe { broker::<N>(context) }.pending()
|
||||
}
|
||||
|
||||
unsafe fn process<const N: usize>(context: *const c_void) -> i32 {
|
||||
// SAFETY: the genuine original supervisor supplies its installed context.
|
||||
let this = unsafe { broker::<N>(context) };
|
||||
let Some(slot) = this.slots.iter().find(|slot| slot.events.get() != 0) else {
|
||||
return 0;
|
||||
};
|
||||
let events = slot.events.replace(0);
|
||||
let (record, generation, data, identity, reap, join, finalize) = {
|
||||
let mut kept = slot.child.borrow_mut();
|
||||
let child = kept.as_mut().unwrap_or_else(|| fatal());
|
||||
let mut reap = false;
|
||||
if events & TERMINAL_RETURNED != 0 {
|
||||
let Stage::Running(published) = core::mem::replace(&mut child.stage, Stage::Transition)
|
||||
else {
|
||||
fatal();
|
||||
};
|
||||
if published.worker.returned_to_peer() != Ok(true) {
|
||||
fatal();
|
||||
}
|
||||
child.stage = Stage::Joining(published);
|
||||
reap = true;
|
||||
}
|
||||
(
|
||||
child.binding.task.as_ptr(),
|
||||
child.generation,
|
||||
child.data,
|
||||
child.binding.identity.get(),
|
||||
reap,
|
||||
matches!(child.stage, Stage::Joining(_)) && (reap || events & SOURCE_FREED != 0),
|
||||
matches!(child.stage, Stage::Final) && slot.source_tail.get(),
|
||||
)
|
||||
};
|
||||
if reap {
|
||||
// SAFETY: the same held stack physically returned before this process ran.
|
||||
// No slot borrow crosses original reaping or any source callback.
|
||||
if unsafe { stela_linux_task_reap_source(record, this.owner, generation) } != 0 {
|
||||
fatal();
|
||||
}
|
||||
let view = identity.unwrap_or_else(|| fatal());
|
||||
let identity = DataIdentity {
|
||||
queue_id: view.queue_id,
|
||||
context_id: view.context_id,
|
||||
sequence: view.sequence,
|
||||
};
|
||||
// SAFETY: the hosted CPU stopped the sole writer and joined the scheduler refs.
|
||||
if unsafe { stela_linux_task_data_release(data.as_ptr(), this.owner, &identity) } != 0 {
|
||||
fatal();
|
||||
}
|
||||
}
|
||||
if join {
|
||||
// SAFETY: the genuine supervisor owns source reap and data release.
|
||||
// The original RCU barrier may park, so hold no slot/runtime borrow.
|
||||
match unsafe { stela_linux_task_join_source(record, this.owner, generation) } {
|
||||
0 => {}
|
||||
-11 => return 1, // kernel_wait4 and later actual source-free delivery
|
||||
_ => fatal(),
|
||||
}
|
||||
let mut kept = slot.child.borrow_mut();
|
||||
let child = kept.as_mut().unwrap_or_else(|| fatal());
|
||||
let Stage::Joining(published) = core::mem::replace(&mut child.stage, Stage::Transition)
|
||||
else {
|
||||
fatal();
|
||||
};
|
||||
// SAFETY: exact actual source and physical return joined. The
|
||||
// descriptor owner independently checks page references are zero.
|
||||
if unsafe { stela_linux_page_stack_retire(&published.descriptors, child.original.as_ptr()) }
|
||||
!= 0
|
||||
{
|
||||
fatal();
|
||||
}
|
||||
child.stage = Stage::Detach(published.worker);
|
||||
}
|
||||
if finalize {
|
||||
// SAFETY: exact source callback tails and the runtime detach have joined.
|
||||
if unsafe { stela_linux_task_child_tails_joined(record, this.owner, generation) } != 0 {
|
||||
fatal();
|
||||
}
|
||||
// SAFETY: all actual source and hosted owners returned; this is final source release.
|
||||
if unsafe { stela_linux_task_release_original(record, this.owner, generation) } != 0 {
|
||||
fatal();
|
||||
}
|
||||
let mut child = slot.child.borrow_mut().take().unwrap_or_else(|| fatal());
|
||||
slot.source_tail.set(false);
|
||||
Rc::get_mut(&mut child.binding)
|
||||
.unwrap_or_else(|| fatal())
|
||||
.released = true;
|
||||
}
|
||||
1
|
||||
}
|
||||
|
||||
unsafe fn dispatcher<const N: usize>(context: *const c_void) -> i32 {
|
||||
// SAFETY: exact taskless hosted dispatcher, checked by step_hosted.
|
||||
let this = unsafe { broker::<N>(context) };
|
||||
for slot in &this.slots {
|
||||
let mut kept = slot.child.borrow_mut();
|
||||
let Some(child) = kept.as_mut() else { continue };
|
||||
if !matches!(child.stage, Stage::Detach(_)) {
|
||||
continue;
|
||||
}
|
||||
let Stage::Detach(worker) = core::mem::replace(&mut child.stage, Stage::Transition) else {
|
||||
fatal();
|
||||
};
|
||||
let wake = child.binding.wake.borrow();
|
||||
let wake = wake.as_ref().unwrap_or_else(|| fatal());
|
||||
// SAFETY: source C tails, page references and exact physical return joined.
|
||||
let binding = unsafe { this.runtime().detach_binding(wake) }.unwrap_or_else(|_| fatal());
|
||||
drop(binding);
|
||||
// SAFETY: exact source joins and runtime binding detach completed.
|
||||
unsafe { worker.release() }.unwrap_or_else(|_| fatal());
|
||||
child.stage = Stage::Final;
|
||||
slot.events.set(slot.events.get() | DISPATCH_JOINED);
|
||||
this.raise();
|
||||
}
|
||||
0
|
||||
}
|
||||
@@ -52,6 +52,21 @@ pub unsafe fn initialize_hosted_resources(
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish original PID1 and kthreadd from the mounted hosted Initial.
|
||||
/// Continue running Initial's hosted service and drive the dispatcher with
|
||||
/// `step_hosted` to run the children and process their source joins.
|
||||
///
|
||||
/// # Safety
|
||||
/// The exact Initial is entered and has completed original resources.
|
||||
/// Keep the mounted source and callback graph for the life of this process.
|
||||
pub unsafe fn start_hosted_threads<const N: usize>(
|
||||
owner: *const RawOwner,
|
||||
runtime: Pin<&HostedRuntime<N>>,
|
||||
) -> Result<(), ResourceBootstrapError> {
|
||||
// SAFETY: forwarded exact original Initial and its retained runtime.
|
||||
unsafe { fork::start_threads(owner, runtime) }
|
||||
}
|
||||
|
||||
const PAGE: usize = 4096;
|
||||
const MAX_MODEL_PAGES: usize = 16 * 1024;
|
||||
|
||||
@@ -113,8 +128,10 @@ impl<const N: usize> HostedTaskBinding<N> {
|
||||
let pgd = root
|
||||
.cpu_address(0, PAGE)
|
||||
.map_err(|_| Work(WorkError::CorruptContext))?;
|
||||
let owner = Owner::new(platform);
|
||||
let fork = fork::Broker::new(runtime, owner.raw(), stacks.len()).map_err(Work)?;
|
||||
let mount = Box::new(Initial {
|
||||
owner: Owner::new(platform),
|
||||
owner,
|
||||
_root: root,
|
||||
pages,
|
||||
_stacks: stacks,
|
||||
@@ -147,7 +164,9 @@ impl<const N: usize> HostedTaskBinding<N> {
|
||||
return Err(Native(status));
|
||||
}
|
||||
let task = NonNull::new(raw).ok_or(Work(WorkError::CorruptContext))?;
|
||||
mount.binding = Some(Self::new_record(task, runtime, true));
|
||||
// SAFETY: the irreversible original mount and same runtime stay kept.
|
||||
unsafe { fork.install(task) }.map_err(Work)?;
|
||||
mount.binding = Some(Self::new_record(task, runtime, Kind::Initial));
|
||||
let context = core::ptr::from_mut(mount).cast();
|
||||
// SAFETY: the published mount, binding, body and image remain kept
|
||||
// on every path after the irreversible original source claim.
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::owner::RawOwner;
|
||||
use stela_driver_base::platform::work::kernel_domain::{HostedChildReservation, HostedPages};
|
||||
|
||||
#[repr(C)]
|
||||
struct ModelStackTicket {
|
||||
pub(super) struct ModelStackTicket {
|
||||
version: u32,
|
||||
bytes: u32,
|
||||
generation: u64,
|
||||
@@ -27,8 +27,8 @@ unsafe extern "C" {
|
||||
#[must_use = "explicitly cancel this unpublished hosted stack"]
|
||||
pub struct HostedStackReservation<'runtime, const N: usize> {
|
||||
owner: *const RawOwner,
|
||||
worker: HostedChildReservation<'runtime, N>,
|
||||
descriptors: Option<ModelStackTicket>,
|
||||
pub(super) worker: HostedChildReservation<'runtime, N>,
|
||||
pub(super) descriptors: Option<ModelStackTicket>,
|
||||
}
|
||||
|
||||
/// Reserve the actual stopped worker and its model stack descriptors.
|
||||
|
||||
@@ -9,6 +9,12 @@ pub(super) unsafe fn publish<
|
||||
broker: &'static Broker<K, P, N>,
|
||||
) -> Result<(), Error> {
|
||||
let dispatch = Dispatch {
|
||||
#[cfg(all(
|
||||
feature = "hosted-runtime",
|
||||
target_os = "linux",
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
hosted: None,
|
||||
pending: pending::<K, P, N>,
|
||||
process: process::<K, P, N>,
|
||||
context: broker as *const _ as *const c_void,
|
||||
|
||||
@@ -16,7 +16,6 @@ use std::{
|
||||
sync::Arc,
|
||||
time::{Duration, Instant, SystemTime},
|
||||
};
|
||||
use stela_driver_base::platform::image::NativeReadOnlyImage;
|
||||
use stela_driver_base::platform::work::{
|
||||
WorkError,
|
||||
kernel_domain::{
|
||||
@@ -24,6 +23,10 @@ use stela_driver_base::platform::work::{
|
||||
HostedIdle, HostedQueue, HostedRuntime,
|
||||
},
|
||||
};
|
||||
use stela_driver_base::{
|
||||
entropy::{Entropy, EntropyError},
|
||||
platform::image::NativeReadOnlyImage,
|
||||
};
|
||||
use stela_linux::{
|
||||
owner::{
|
||||
Entered, Errno, IrqEnableError, MinimumDeadline, Platform, RawOwner, RealtimeOrigin,
|
||||
@@ -31,16 +34,27 @@ use stela_linux::{
|
||||
},
|
||||
task::{
|
||||
HostedTaskBinding, ResourceBootstrapError, initialize_hosted_resources,
|
||||
reserve_hosted_child_stack,
|
||||
reserve_hosted_child_stack, start_hosted_threads, step_hosted,
|
||||
},
|
||||
};
|
||||
|
||||
struct Host {
|
||||
clock: Arc<HostedClock>,
|
||||
boot_origin_ns: u64,
|
||||
timer: DomainRaised<HostedDomain>,
|
||||
tsc_hz: NonZeroU64,
|
||||
realtime: RealtimeOrigin,
|
||||
random: RefCell<stela_crypto::random::Generator>,
|
||||
random: RefCell<stela_linux::random::Seeded>,
|
||||
}
|
||||
|
||||
struct HostEntropy;
|
||||
|
||||
impl Entropy for HostEntropy {
|
||||
fn fill(&self, output: &mut [u8]) -> Result<(), EntropyError> {
|
||||
std::fs::File::open("/dev/urandom")
|
||||
.and_then(|mut source| source.read_exact(output))
|
||||
.map_err(|_| EntropyError::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
struct ProcessImage {
|
||||
@@ -81,10 +95,31 @@ unsafe impl NativeReadOnlyImage for ProcessImage {
|
||||
}
|
||||
}
|
||||
|
||||
fn host_boottime() -> Result<u64, WorkError> {
|
||||
let mut sample = std::mem::MaybeUninit::<libc::timespec>::uninit();
|
||||
// SAFETY: CLOCK_BOOTTIME initializes the exact output on success.
|
||||
if unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, sample.as_mut_ptr()) } != 0 {
|
||||
return Err(WorkError::Unavailable);
|
||||
}
|
||||
// SAFETY: the successful host call wrote both fields.
|
||||
let sample = unsafe { sample.assume_init() };
|
||||
let seconds = u64::try_from(sample.tv_sec).map_err(|_| WorkError::CorruptContext)?;
|
||||
let nanos = u64::try_from(sample.tv_nsec).map_err(|_| WorkError::CorruptContext)?;
|
||||
seconds
|
||||
.checked_mul(1_000_000_000)
|
||||
.and_then(|base| base.checked_add(nanos))
|
||||
.ok_or(WorkError::Exhausted)
|
||||
}
|
||||
|
||||
impl Platform for Host {
|
||||
fn now_ns(&self) -> i64 {
|
||||
self.clock.now_ns().unwrap().try_into().unwrap()
|
||||
}
|
||||
fn boottime_ns(&self) -> Result<u64, WorkError> {
|
||||
host_boottime()?
|
||||
.checked_sub(self.boot_origin_ns)
|
||||
.ok_or(WorkError::CorruptContext)
|
||||
}
|
||||
fn calibrated_tsc_hz(&self) -> Option<NonZeroU64> {
|
||||
Some(self.tsc_hz)
|
||||
}
|
||||
@@ -112,6 +147,13 @@ impl Platform for Host {
|
||||
fn random_bytes(&self, bytes: &mut [u8]) {
|
||||
self.random.borrow_mut().fill(bytes);
|
||||
}
|
||||
fn mix_random(&self, bytes: &[u8]) -> bool {
|
||||
let Ok(ticks) = self.clock.now_ns() else {
|
||||
return false;
|
||||
};
|
||||
self.random.borrow_mut().mix(ticks, bytes);
|
||||
true
|
||||
}
|
||||
fn shutdown(&self, _: bool) {
|
||||
process::abort()
|
||||
}
|
||||
@@ -154,6 +196,7 @@ unsafe extern "C" {
|
||||
static init_task: u8;
|
||||
static jiffies_64: u64;
|
||||
static system_wq: *const c_void;
|
||||
static kthreadd_task: *const c_void;
|
||||
static sighand_cachep: *const c_void;
|
||||
fn stela_linux_current() -> *const u8;
|
||||
fn task_sched_runtime(task: *const u8) -> u64;
|
||||
@@ -218,7 +261,7 @@ unsafe extern "C" fn check_initial(owner: *const RawOwner, context: *mut c_void)
|
||||
Err(WorkError::Unavailable)
|
||||
);
|
||||
// SAFETY: the stopped dispatcher keeps the exact pinned runtime handle.
|
||||
let runtime = unsafe { *context.cast::<Pin<&HostedRuntime<4>>>() };
|
||||
let runtime = unsafe { *context.cast::<Pin<&HostedRuntime<8>>>() };
|
||||
// SAFETY: C checks the owner before using it. A refusal must release the worker.
|
||||
let refused = unsafe { reserve_hosted_child_stack(runtime, ptr::null()) };
|
||||
assert!(matches!(refused, Err(ResourceBootstrapError::Native(-1))));
|
||||
@@ -304,6 +347,7 @@ fn hosted_initial_enters_the_original_task_without_native_admission() {
|
||||
"hosted_initial_enters_the_original_task_without_native_admission",
|
||||
"original hosted Initial attached",
|
||||
MODEL_PAGES,
|
||||
1,
|
||||
check_initial,
|
||||
run_once,
|
||||
);
|
||||
@@ -315,6 +359,7 @@ fn hosted_initial_bootstraps_original_resource_roots() {
|
||||
"hosted_initial_bootstraps_original_resource_roots",
|
||||
"original hosted resource bootstrap returned",
|
||||
16 * 1024,
|
||||
1,
|
||||
check_resources,
|
||||
run_once,
|
||||
);
|
||||
@@ -326,14 +371,86 @@ fn hosted_initial_services_original_timers_after_a_park() {
|
||||
"hosted_initial_services_original_timers_after_a_park",
|
||||
"original hosted timer service resumed",
|
||||
16 * 1024,
|
||||
1,
|
||||
start_timer_service,
|
||||
drive_timer_service,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_initial_publishes_original_pid1_and_kthreadd() {
|
||||
in_fresh_process(
|
||||
"hosted_initial_publishes_original_pid1_and_kthreadd",
|
||||
"original hosted kernel children dispatched",
|
||||
16 * 1024,
|
||||
2,
|
||||
check_threads_published,
|
||||
drive_first_children,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_original_fork_returns_enomem_without_an_unowned_stack() {
|
||||
in_fresh_process(
|
||||
"hosted_original_fork_returns_enomem_without_an_unowned_stack",
|
||||
"original hosted fork exhausted its worker inventory",
|
||||
16 * 1024,
|
||||
1,
|
||||
check_threads_exhausted,
|
||||
run_once,
|
||||
);
|
||||
}
|
||||
|
||||
unsafe extern "C" fn check_threads_exhausted(owner: *const RawOwner, context: *mut c_void) -> ! {
|
||||
// SAFETY: the stopped dispatcher keeps the exact pinned runtime handle.
|
||||
let runtime = unsafe { *context.cast::<Pin<&HostedRuntime<8>>>() };
|
||||
// SAFETY: the mounted Initial is the real entered source creator.
|
||||
let _entered = unsafe { Entered::new(owner) };
|
||||
// SAFETY: the permanent model inventory and clock are retained.
|
||||
unsafe { initialize_hosted_resources(owner) }.unwrap();
|
||||
// SAFETY: exact entered Initial after original resource initialization.
|
||||
let result = unsafe { start_hosted_threads(owner, runtime) };
|
||||
assert_eq!(result, Err(ResourceBootstrapError::Native(-12)));
|
||||
// SAFETY: the failed startup never published a kthreadd task.
|
||||
assert!(unsafe { kthreadd_task }.is_null());
|
||||
println!("original hosted fork exhausted its worker inventory");
|
||||
process::exit(0);
|
||||
}
|
||||
|
||||
unsafe extern "C" fn check_threads_published(owner: *const RawOwner, context: *mut c_void) -> ! {
|
||||
// SAFETY: exact retained original owner/current and dispatcher runtime handle.
|
||||
let (owner, runtime) = unsafe { (&*owner, *context.cast::<Pin<&HostedRuntime<8>>>()) };
|
||||
{
|
||||
// SAFETY: the mounted Initial is the real entered source creator.
|
||||
let _entered = unsafe { Entered::new(owner) };
|
||||
// SAFETY: the permanent model inventory and clock are retained.
|
||||
unsafe { initialize_hosted_resources(owner) }.unwrap();
|
||||
// SAFETY: exact entered Initial after original resource initialization.
|
||||
unsafe { start_hosted_threads(owner, runtime) }.unwrap();
|
||||
// SAFETY: original publication retains this genuine kthreadd task.
|
||||
assert!(!unsafe { kthreadd_task }.is_null());
|
||||
// SAFETY: both real children still own the reserved stacks.
|
||||
let extra = unsafe { reserve_hosted_child_stack(runtime, owner) };
|
||||
assert!(matches!(
|
||||
extra,
|
||||
Err(ResourceBootstrapError::Work(WorkError::Full))
|
||||
));
|
||||
}
|
||||
// SAFETY: mounted Initial's exact scope with the original resources kept.
|
||||
unsafe { stela_linux::service::run_hosted_service(owner, runtime) }
|
||||
}
|
||||
|
||||
fn drive_first_children(runtime: Pin<&HostedRuntime<8>>, _: &HostedClock) {
|
||||
assert!(step_hosted(runtime, false).unwrap()); // Initial parks
|
||||
assert!(step_hosted(runtime, false).unwrap()); // PID1 waits for kthreadd
|
||||
assert!(step_hosted(runtime, false).unwrap()); // kthreadd enters and parks
|
||||
println!("original hosted kernel children dispatched");
|
||||
process::exit(0);
|
||||
}
|
||||
|
||||
unsafe extern "C" fn start_timer_service(owner: *const RawOwner, context: *mut c_void) -> ! {
|
||||
// SAFETY: exact retained original owner/current and dispatcher runtime handle.
|
||||
let (owner, runtime) = unsafe { (&*owner, *context.cast::<Pin<&HostedRuntime<4>>>()) };
|
||||
let (owner, runtime) = unsafe { (&*owner, *context.cast::<Pin<&HostedRuntime<8>>>()) };
|
||||
{
|
||||
// SAFETY: this is the exact original Initial, before the C loop enters it.
|
||||
let _entered = unsafe { Entered::new(owner) };
|
||||
@@ -344,11 +461,11 @@ unsafe extern "C" fn start_timer_service(owner: *const RawOwner, context: *mut c
|
||||
unsafe { stela_linux::service::run_hosted_service(owner, runtime) }
|
||||
}
|
||||
|
||||
fn run_once(runtime: Pin<&HostedRuntime<4>>, _: &HostedClock) {
|
||||
fn run_once(runtime: Pin<&HostedRuntime<8>>, _: &HostedClock) {
|
||||
runtime.step().unwrap();
|
||||
}
|
||||
|
||||
fn drive_timer_service(runtime: Pin<&HostedRuntime<4>>, clock: &HostedClock) {
|
||||
fn drive_timer_service(runtime: Pin<&HostedRuntime<8>>, clock: &HostedClock) {
|
||||
let raised = runtime.service_raised_work().unwrap();
|
||||
raised.raise().unwrap();
|
||||
assert!(runtime.step().unwrap());
|
||||
@@ -377,8 +494,9 @@ fn in_fresh_process(
|
||||
test: &str,
|
||||
witness: &str,
|
||||
page_count: usize,
|
||||
general_stacks: usize,
|
||||
body: unsafe extern "C" fn(*const RawOwner, *mut c_void) -> !,
|
||||
drive: fn(Pin<&HostedRuntime<4>>, &HostedClock),
|
||||
drive: fn(Pin<&HostedRuntime<8>>, &HostedClock),
|
||||
) {
|
||||
const CHILD: &str = "STELA_HOSTED_INITIAL_CHILD";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
@@ -402,11 +520,16 @@ fn in_fresh_process(
|
||||
let clock = HostedClock::new(&execution).unwrap();
|
||||
let idle = HostedIdle::new(&clock).unwrap();
|
||||
let deadlines = HostedDeadlines::new(&clock, &idle).unwrap();
|
||||
let queue = HostedQueue::<4>::new(execution, Arc::new(())).unwrap();
|
||||
let queue = HostedQueue::<8>::new(execution, Arc::new(())).unwrap();
|
||||
let stack = stela_linux::task::stack_requirement().unwrap();
|
||||
// SAFETY: this fresh process retains its only executor through exit.
|
||||
let executor = unsafe {
|
||||
HostedExecutor::new_with_persistent_service_stacks(queue.clone(), stack, 1, deadlines)
|
||||
HostedExecutor::new_with_persistent_service_stacks(
|
||||
queue.clone(),
|
||||
stack,
|
||||
general_stacks,
|
||||
deadlines,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
let runtime = executor.runtime();
|
||||
@@ -429,17 +552,13 @@ fn in_fresh_process(
|
||||
utc.subsec_nanos(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut seed = [0; 32];
|
||||
std::fs::File::open("/dev/urandom")
|
||||
.unwrap()
|
||||
.read_exact(&mut seed)
|
||||
.unwrap();
|
||||
let platform = Host {
|
||||
clock: clock.clone(),
|
||||
boot_origin_ns: host_boottime().unwrap(),
|
||||
timer: runtime.service_raised_work().unwrap(),
|
||||
tsc_hz: NonZeroU64::new(hz.try_into().unwrap()).unwrap(),
|
||||
realtime,
|
||||
random: RefCell::new(stela_crypto::random::Generator::from_seed(seed)),
|
||||
random: RefCell::new(stela_linux::random::Seeded::from_entropy(&HostEntropy).unwrap()),
|
||||
};
|
||||
let context = ptr::from_ref(&runtime).cast_mut().cast();
|
||||
// SAFETY: the exact static archive, dispatcher and local runtime handle
|
||||
|
||||
Reference in new issue
Block a user