feat(drivers): reserve actual workers under entered authority
This commit is contained in:
1 parent
03cb91e152
commit
0827801ffa
4 files changed
+819
-5
No files matched your search
@@ -36,8 +36,12 @@ pub mod scheduling;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub mod service;
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
mod general_reservation;
|
||||
mod reservation;
|
||||
mod stack_requirement;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub use general_reservation::{AssignedGeneral, EnteredProcess, GeneralReservation};
|
||||
pub use stack_requirement::{StackProfile, StackRequirement};
|
||||
#[cfg(all(test, unix, target_arch = "x86_64"))]
|
||||
pub(crate) mod test_support;
|
||||
@@ -183,6 +187,9 @@ struct Job {
|
||||
}
|
||||
struct State<const N: usize> {
|
||||
jobs: [Option<Job>; N],
|
||||
reservations: [u64; N],
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
next_reservation: u64,
|
||||
layout: Layout,
|
||||
stack_profile: Option<StackProfile>,
|
||||
stack_catalog: stack_requirement::Catalog,
|
||||
@@ -294,6 +301,9 @@ impl<const N: usize> Queue<N> {
|
||||
owner: ManuallyDrop::new(owner),
|
||||
state: ManuallyDrop::new(UnsafeCell::new(State {
|
||||
jobs: [None; N],
|
||||
reservations: [0; N],
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
next_reservation: 1,
|
||||
layout: Layout::Ordinary,
|
||||
stack_profile: None,
|
||||
stack_catalog: stack_requirement::Catalog::empty(),
|
||||
@@ -387,7 +397,7 @@ impl<const N: usize> Queue<N> {
|
||||
let slot = ranges
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|index| state.jobs[*index].is_none())
|
||||
.find(|index| state.jobs[*index].is_none() && state.reservations[*index] == 0)
|
||||
.ok_or(WorkError::Full)?;
|
||||
let sequence = state.next;
|
||||
state.next = sequence.checked_add(1).ok_or(WorkError::Exhausted)?;
|
||||
@@ -504,7 +514,8 @@ impl<const N: usize> Queue<N> {
|
||||
.enumerate()
|
||||
.filter_map(|(i, j)| {
|
||||
j.filter(|j| {
|
||||
j.lane == lane
|
||||
state.reservations[i] == 0
|
||||
&& j.lane == lane
|
||||
&& !j.running
|
||||
&& stack_requirement::compatible(j.requirement, geometry)
|
||||
})
|
||||
@@ -520,6 +531,9 @@ impl<const N: usize> Queue<N> {
|
||||
fn finish(&self, slot: usize, sequence: u64) -> Result<(), WorkError> {
|
||||
let mut g = self.lock()?;
|
||||
let state = g.state();
|
||||
if state.reservations.get(slot).is_none_or(|nonce| *nonce != 0) {
|
||||
return Err(WorkError::CorruptContext);
|
||||
}
|
||||
if !state
|
||||
.jobs
|
||||
.get(slot)
|
||||
@@ -544,7 +558,12 @@ impl<const N: usize> Queue<N> {
|
||||
if !state.scheduling.quiet() {
|
||||
return Err(WorkError::Pending);
|
||||
}
|
||||
if !state.closed || state.poisoned || state.jobs.iter().any(Option::is_some) {
|
||||
if !state.closed
|
||||
|| state.poisoned
|
||||
|| self.abandoned.load(Ordering::Acquire)
|
||||
|| state.jobs.iter().any(Option::is_some)
|
||||
|| state.reservations.iter().any(|nonce| *nonce != 0)
|
||||
{
|
||||
return Err(WorkError::Pending);
|
||||
}
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
@@ -768,6 +787,7 @@ impl<const N: usize> Drop for WakeHandle<N> {
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum TaskState {
|
||||
Idle,
|
||||
Reserved,
|
||||
Ready,
|
||||
Running,
|
||||
Runnable,
|
||||
@@ -801,6 +821,7 @@ pub struct Runtime<const N: usize> {
|
||||
current: Cell<usize>,
|
||||
cursor: Cell<usize>,
|
||||
retired: Cell<bool>,
|
||||
pending_reservations: Cell<usize>,
|
||||
service_started: Cell<bool>,
|
||||
firmware_started: Cell<bool>,
|
||||
firmware_turn: Cell<bool>,
|
||||
@@ -929,7 +950,8 @@ impl<const N: usize> Runtime<N> {
|
||||
// Native worker permits require an empty pre-admission queue: a
|
||||
// legacy Notify job in an ordinary slot otherwise bypasses the two
|
||||
// real-worker limit. Legacy constructors keep their prior contract.
|
||||
if (layout.firmware_roles() && state.jobs.iter().any(Option::is_some))
|
||||
if state.reservations.iter().any(|nonce| *nonce != 0)
|
||||
|| (layout.firmware_roles() && state.jobs.iter().any(Option::is_some))
|
||||
|| state.jobs[N - layout.slots()..].iter().any(Option::is_some)
|
||||
{
|
||||
return Err(WorkError::Busy);
|
||||
@@ -955,6 +977,7 @@ impl<const N: usize> Runtime<N> {
|
||||
current: Cell::new(NONE),
|
||||
cursor: Cell::new(0),
|
||||
retired: Cell::new(false),
|
||||
pending_reservations: Cell::new(0),
|
||||
service_started: Cell::new(false),
|
||||
firmware_started: Cell::new(false),
|
||||
firmware_turn: Cell::new(true),
|
||||
@@ -1311,6 +1334,9 @@ impl<const N: usize> Runtime<N> {
|
||||
}
|
||||
fn suspend(self: Pin<&Self>, reason: LeaveReason) -> Result<ParkOutcome, WorkError> {
|
||||
self.current_id()?;
|
||||
if self.pending_reservations.get() != 0 {
|
||||
return Err(WorkError::Busy);
|
||||
}
|
||||
let index = self.current.get();
|
||||
let flags = self.queue.cpu.save_disable()?;
|
||||
let view = self.context_view(index, true);
|
||||
@@ -1677,7 +1703,7 @@ impl<const N: usize> Runtime<N> {
|
||||
TaskState::Ready | TaskState::Runnable => true,
|
||||
TaskState::Blocked => task.signal.pending.load(Ordering::Acquire),
|
||||
TaskState::Idle => queued_lanes[lane_index(task.lane)],
|
||||
TaskState::Running => false,
|
||||
TaskState::Running | TaskState::Reserved => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1856,6 +1882,12 @@ impl<const N: usize> Runtime<N> {
|
||||
/// Timeout/failed drain is not retirement authority and retains every owner.
|
||||
pub unsafe fn retire(self: Pin<&Self>) -> Result<(), WorkError> {
|
||||
self.queue.process()?;
|
||||
if self.queue.abandoned.load(Ordering::Acquire) {
|
||||
return Err(WorkError::Closed);
|
||||
}
|
||||
if self.pending_reservations.get() != 0 {
|
||||
return Err(WorkError::Pending);
|
||||
}
|
||||
if self.domain().is_some_and(|domain| !domain.retired()) {
|
||||
return Err(WorkError::Pending);
|
||||
}
|
||||
@@ -1895,6 +1927,11 @@ unsafe extern "sysv64" fn entry<const N: usize>(pointer: usize, index: usize) ->
|
||||
// SAFETY: covered by this function's own safety contract.
|
||||
unsafe { (job.callback)(job.context as *mut c_void) };
|
||||
executor.valid();
|
||||
if executor.pending_reservations.get() != 0 {
|
||||
executor.queue.abandoned.store(true, Ordering::Release);
|
||||
quarantine();
|
||||
executor.queue.cpu.fatal(WorkError::Pending);
|
||||
}
|
||||
let _flags = match executor.queue.cpu.save_disable() {
|
||||
Ok(f) => f,
|
||||
Err(e) => executor.queue.cpu.fatal(e),
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Affine actual-worker/job reservation under a borrowed entered process guard.
|
||||
use super::*;
|
||||
/// Actual borrowed platform process-entry authority, independent of task IDs.
|
||||
///
|
||||
/// # Safety
|
||||
/// The view borrows a genuine entered process guard for its entire lifetime.
|
||||
/// check validates actual CPU/root/process generation before mutable service
|
||||
/// access; neither RootIdentity nor a caller integer substitutes for that guard.
|
||||
/// It is nonblocking/nonallocating and valid with local IRQs saved/disabled:
|
||||
/// no AML, queue callback, allocator, RestoreRoot reacquisition or wait. There
|
||||
/// is no permissive default. A borrowed authority must not escape across Guest.
|
||||
pub unsafe trait EnteredProcess {
|
||||
fn check(&self) -> Result<(), WorkError>;
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Creator {
|
||||
queue: u64,
|
||||
context: u64,
|
||||
sequence: u64,
|
||||
}
|
||||
impl Creator {
|
||||
fn of(view: TaskContext) -> Self {
|
||||
Self {
|
||||
queue: view.queue_id,
|
||||
context: view.context_id,
|
||||
sequence: view.sequence,
|
||||
}
|
||||
}
|
||||
fn matches(self, view: TaskContext) -> bool {
|
||||
self.queue == view.queue_id
|
||||
&& self.context == view.context_id
|
||||
&& self.sequence == view.sequence
|
||||
}
|
||||
}
|
||||
/// Receipt for actual assigned deferred work, not child startup or C current.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct AssignedGeneral {
|
||||
ticket: Ticket,
|
||||
context: ContextId,
|
||||
}
|
||||
impl AssignedGeneral {
|
||||
pub fn ticket(self) -> Ticket {
|
||||
self.ticket
|
||||
}
|
||||
pub fn context_id(self) -> ContextId {
|
||||
self.context
|
||||
}
|
||||
}
|
||||
/// Non-Send, non-Clone short-lived reservation. Drop rolls back only under its
|
||||
/// matching actual entered scope; uncertain ownership retains the whole owner.
|
||||
#[must_use = "drop/cancel rolls back; commit publishes only actual owned deferred work"]
|
||||
pub struct GeneralReservation<'runtime, 'entered, const N: usize> {
|
||||
runtime: Pin<&'runtime Runtime<N>>,
|
||||
queue: Arc<Queue<N>>,
|
||||
entered: &'entered dyn EnteredProcess,
|
||||
creator: Creator,
|
||||
worker: usize,
|
||||
context: ContextId,
|
||||
slot: usize,
|
||||
nonce: u64,
|
||||
requirement: StackRequirement,
|
||||
live: bool,
|
||||
_local: PhantomData<*mut ()>,
|
||||
}
|
||||
impl<const N: usize> Runtime<N> {
|
||||
/// Reserve one actually idle, unbound compatible General worker and one
|
||||
/// ordinary job slot. This publishes no callback, ticket, C task or current.
|
||||
/// All mutations follow real scope/current checks. Incoming IF is restored
|
||||
/// before returning for bounded nonblocking metadata setup; no permit parks.
|
||||
pub fn reserve_general<'runtime, 'entered>(
|
||||
self: Pin<&'runtime Self>,
|
||||
entered: &'entered dyn EnteredProcess,
|
||||
requirement: StackRequirement,
|
||||
) -> Result<GeneralReservation<'runtime, 'entered, N>, WorkError> {
|
||||
entered.check()?;
|
||||
self.current_context()?;
|
||||
let flags = self.queue.cpu.save_disable()?;
|
||||
let result = (|| {
|
||||
entered.check()?;
|
||||
let creator = Creator::of(self.current_context()?);
|
||||
let mut guard = self.queue.lock()?;
|
||||
let state = guard.state();
|
||||
if state.closed || state.poisoned || self.queue.abandoned.load(Ordering::Acquire) {
|
||||
return Err(WorkError::Closed);
|
||||
}
|
||||
if state.stack_profile.is_none()
|
||||
|| !state.stack_catalog.supports(Lane::General, requirement)
|
||||
{
|
||||
return Err(WorkError::Unavailable);
|
||||
}
|
||||
let slot = state
|
||||
.layout
|
||||
.admission(Lane::General, N)?
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|slot| state.jobs[*slot].is_none() && state.reservations[*slot] == 0)
|
||||
.ok_or(WorkError::Full)?;
|
||||
// SAFETY: actual current CPU and IF0 own this immutable retained Vec;
|
||||
// no foreign hook/callback, allocation or switch spans these reads.
|
||||
let count = unsafe { (*self.tasks.get()).len() };
|
||||
let worker = (0..count)
|
||||
.find(|index| {
|
||||
// SAFETY: bounded actual task entry, stopped while creator runs at IF0.
|
||||
let task = unsafe { &*self.task(*index) };
|
||||
task.lane == Lane::General
|
||||
&& task.state == TaskState::Idle
|
||||
&& task.job.is_none()
|
||||
&& task.binding.is_none()
|
||||
&& !task.draining
|
||||
&& task.signal.sequence.load(Ordering::Acquire) == 0
|
||||
&& stack_requirement::compatible(
|
||||
Some(requirement),
|
||||
stack_requirement::Geometry::of(&task.stack),
|
||||
)
|
||||
})
|
||||
.ok_or(WorkError::Full)?;
|
||||
let nonce = state.next_reservation;
|
||||
if nonce == 0 {
|
||||
return Err(WorkError::CorruptContext);
|
||||
}
|
||||
let next = nonce.checked_add(1).ok_or(WorkError::Exhausted)?;
|
||||
let pending = self
|
||||
.pending_reservations
|
||||
.get()
|
||||
.checked_add(1)
|
||||
.ok_or(WorkError::Exhausted)?;
|
||||
// SAFETY: exact idle unbound worker selected above, exclusively stopped at IF0.
|
||||
let task = unsafe { &mut *self.task(worker) };
|
||||
state.next_reservation = next;
|
||||
state.reservations[slot] = nonce;
|
||||
task.state = TaskState::Reserved;
|
||||
self.pending_reservations.set(pending);
|
||||
Ok(GeneralReservation {
|
||||
runtime: self,
|
||||
queue: self.queue.clone(),
|
||||
entered,
|
||||
creator,
|
||||
worker,
|
||||
context: task.id,
|
||||
slot,
|
||||
nonce,
|
||||
requirement,
|
||||
live: true,
|
||||
_local: PhantomData,
|
||||
})
|
||||
})();
|
||||
// SAFETY: exact enclosing save_disable flags; all queue/task borrows ended.
|
||||
unsafe { self.queue.cpu.restore(flags) };
|
||||
result
|
||||
}
|
||||
}
|
||||
impl<const N: usize> GeneralReservation<'_, '_, N> {
|
||||
fn current(&self) -> Result<(), WorkError> {
|
||||
self.entered.check()?;
|
||||
if !self.creator.matches(self.runtime.current_context()?) {
|
||||
return Err(WorkError::CorruptContext);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// # Safety
|
||||
/// The provider already retains callback/code/context and every reachable
|
||||
/// resource through completion or quarantine, as for Queue::execute. The
|
||||
/// body fits the requested actual extent and must not unwind. Metadata
|
||||
/// setup was nonblocking; no borrowed process authority enters the job.
|
||||
/// Error admits no callback and grants no wrong-scope cleanup authority.
|
||||
pub unsafe fn commit(
|
||||
mut self,
|
||||
callback: Callback,
|
||||
context: *mut c_void,
|
||||
) -> Result<AssignedGeneral, WorkError> {
|
||||
self.current()?;
|
||||
let flags = self.runtime.queue.cpu.save_disable()?;
|
||||
let result = (|| {
|
||||
self.current()?;
|
||||
let mut guard = self.runtime.queue.lock()?;
|
||||
let state = guard.state();
|
||||
if state.closed
|
||||
|| state.poisoned
|
||||
|| self.runtime.queue.abandoned.load(Ordering::Acquire)
|
||||
{
|
||||
return Err(WorkError::Closed);
|
||||
}
|
||||
self.validate(state)?;
|
||||
let sequence = state.next;
|
||||
let next = sequence.checked_add(1).ok_or(WorkError::Exhausted)?;
|
||||
state.scheduling.insert(self.context, sequence, false)?;
|
||||
let job = Job {
|
||||
callback,
|
||||
context: context as usize,
|
||||
lane: Lane::General,
|
||||
sequence,
|
||||
running: true,
|
||||
requirement: Some(self.requirement),
|
||||
};
|
||||
// No fallible operation follows this actual ownership publication.
|
||||
state.next = next;
|
||||
state.jobs[self.slot] = Some(job);
|
||||
state.reservations[self.slot] = 0;
|
||||
// SAFETY: exact matching private reservation was checked at IF0 above;
|
||||
// no alias/hook/switch crosses the assignment of this owned child frame.
|
||||
let task = unsafe { &mut *self.runtime.task(self.worker) };
|
||||
task.job = Some((self.slot, job));
|
||||
task.flags = flags;
|
||||
task.state = TaskState::Ready;
|
||||
task.signal.pending.store(false, Ordering::Relaxed);
|
||||
task.signal.sequence.store(sequence, Ordering::Release);
|
||||
self.runtime
|
||||
.pending_reservations
|
||||
.set(self.runtime.pending_reservations.get() - 1);
|
||||
self.live = false;
|
||||
Ok(AssignedGeneral {
|
||||
ticket: Ticket {
|
||||
queue: self.runtime.queue.id,
|
||||
sequence,
|
||||
},
|
||||
context: self.context,
|
||||
})
|
||||
})();
|
||||
// SAFETY: all queue/task borrows ended; restore exact commit entry flags.
|
||||
unsafe { self.runtime.queue.cpu.restore(flags) };
|
||||
result
|
||||
}
|
||||
fn validate(&self, state: &State<N>) -> Result<(), WorkError> {
|
||||
if self.slot >= N
|
||||
|| state.reservations[self.slot] != self.nonce
|
||||
|| state.jobs[self.slot].is_some()
|
||||
|| self.runtime.pending_reservations.get() == 0
|
||||
{
|
||||
return Err(WorkError::CorruptContext);
|
||||
}
|
||||
// SAFETY: caller checked real current authority at IF0 and retained the
|
||||
// unchanged actual task vector; worker is private constructor-captured.
|
||||
let task = unsafe { &*self.runtime.task(self.worker) };
|
||||
if task.id != self.context
|
||||
|| task.lane != Lane::General
|
||||
|| task.state != TaskState::Reserved
|
||||
|| task.job.is_some()
|
||||
|| task.binding.is_some()
|
||||
|| task.draining
|
||||
|| task.signal.sequence.load(Ordering::Acquire) != 0
|
||||
|| !stack_requirement::compatible(
|
||||
Some(self.requirement),
|
||||
stack_requirement::Geometry::of(&task.stack),
|
||||
)
|
||||
{
|
||||
return Err(WorkError::CorruptContext);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn rollback(&mut self) -> Result<(), WorkError> {
|
||||
self.current()?;
|
||||
let flags = self.runtime.queue.cpu.save_disable()?;
|
||||
let result = (|| {
|
||||
self.current()?;
|
||||
let mut guard = self.runtime.queue.lock()?;
|
||||
let state = guard.state();
|
||||
self.validate(state)?;
|
||||
state.reservations[self.slot] = 0;
|
||||
// SAFETY: exact reserved worker ownership validated above. No callback
|
||||
// or task metadata was published, and no binding/producer owns it.
|
||||
unsafe { (*self.runtime.task(self.worker)).state = TaskState::Idle };
|
||||
self.runtime
|
||||
.pending_reservations
|
||||
.set(self.runtime.pending_reservations.get() - 1);
|
||||
self.live = false;
|
||||
Ok(())
|
||||
})();
|
||||
// SAFETY: no metadata borrow survives restoration of exact entry flags.
|
||||
unsafe { self.runtime.queue.cpu.restore(flags) };
|
||||
result
|
||||
}
|
||||
fn abandon(&mut self) {
|
||||
// No affine Runtime/Task/queue state is read or freed under a stale
|
||||
// authority. The atomic view closes admission; reserved state and every
|
||||
// real owner remain retained, including this whole pinned executor.
|
||||
self.queue.abandoned.store(true, Ordering::Release);
|
||||
quarantine();
|
||||
self.live = false;
|
||||
}
|
||||
pub fn cancel(mut self) -> Result<(), WorkError> {
|
||||
let result = self.rollback();
|
||||
if result.is_err() {
|
||||
self.abandon();
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
impl<const N: usize> Drop for GeneralReservation<'_, '_, N> {
|
||||
fn drop(&mut self) {
|
||||
if self.live && self.rollback().is_err() {
|
||||
self.abandon();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -301,3 +301,5 @@ fn nonempty_queue_refuses_profile_without_reinterpreting_its_original_callback()
|
||||
drop(executor);
|
||||
assert_eq!(dropped.load(Ordering::Relaxed), 48);
|
||||
}
|
||||
|
||||
mod general_reservation;
|
||||
+481
@@ -0,0 +1,481 @@
|
||||
//! Actual compatible reservations, bounded setup and fail-closed ownership tests.
|
||||
use super::*;
|
||||
use core::cell::Cell;
|
||||
use std::{println, process::Command, string::String};
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum Mode {
|
||||
Drop,
|
||||
MetadataFailure,
|
||||
Commit,
|
||||
Exhaust,
|
||||
Closed,
|
||||
Pressure,
|
||||
StaleScope,
|
||||
StaleCurrent,
|
||||
BadNonce,
|
||||
Forgotten,
|
||||
Denied,
|
||||
NoProfile,
|
||||
CommitExhaust,
|
||||
BoundWorker,
|
||||
}
|
||||
struct HarnessCpu {
|
||||
model: Arc<test_support::CpuModel>,
|
||||
dropped: Arc<AtomicUsize>,
|
||||
mode: Mode,
|
||||
}
|
||||
// SAFETY: delegates the same actual hosted-thread/flag model, with no native
|
||||
// CPU/root grant. Negative fixtures stop the subprocess at the mandatory fatal
|
||||
// boundary while asserting no real mapping owner was reclaimed.
|
||||
unsafe impl Cpu for HarnessCpu {
|
||||
fn check_cpu(&self) -> Result<(), WorkError> {
|
||||
self.model.check_cpu()
|
||||
}
|
||||
fn in_interrupt(&self) -> bool {
|
||||
self.model.in_interrupt()
|
||||
}
|
||||
fn save_disable(&self) -> Result<u64, WorkError> {
|
||||
self.model.save_disable()
|
||||
}
|
||||
unsafe fn restore(&self, flags: u64) {
|
||||
// SAFETY: caller supplies this exact model's enclosing save_disable flags.
|
||||
unsafe { self.model.restore(flags) }
|
||||
}
|
||||
fn ticks(&self) -> u64 {
|
||||
self.model.ticks()
|
||||
}
|
||||
fn fatal(&self, error: WorkError) -> ! {
|
||||
if matches!(
|
||||
self.mode,
|
||||
Mode::StaleScope | Mode::StaleCurrent | Mode::BadNonce | Mode::Forgotten
|
||||
) {
|
||||
assert_eq!(
|
||||
error,
|
||||
if self.mode == Mode::Forgotten {
|
||||
WorkError::Pending
|
||||
} else {
|
||||
WorkError::Closed
|
||||
}
|
||||
);
|
||||
assert_eq!(self.dropped.load(Ordering::Relaxed), 0);
|
||||
println!("STELA_RESERVATION_FATAL_RETAINED {:?}", self.mode);
|
||||
std::process::exit(91);
|
||||
}
|
||||
panic!("unexpected reservation fixture fatal: {error:?}")
|
||||
}
|
||||
}
|
||||
struct Authority {
|
||||
cpu: Arc<HarnessCpu>,
|
||||
active: Cell<bool>,
|
||||
}
|
||||
// SAFETY: explicit hosted model only. It borrows this actual callback's model
|
||||
// scope, checks its constructing OS thread and active state without allocation,
|
||||
// waits or callbacks, including IF0. Production must use real DriverExecution.
|
||||
unsafe impl EnteredProcess for Authority {
|
||||
fn check(&self) -> Result<(), WorkError> {
|
||||
self.cpu.check_cpu()?;
|
||||
if self.active.get() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(WorkError::Unavailable)
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Scene {
|
||||
runtime: AtomicU64,
|
||||
cpu: Arc<HarnessCpu>,
|
||||
dropped: Arc<AtomicUsize>,
|
||||
mode: Mode,
|
||||
child: AtomicUsize,
|
||||
ordinary: AtomicUsize,
|
||||
assigned: Mutex<Option<AssignedGeneral>>,
|
||||
actual: Mutex<Option<TaskContext>>,
|
||||
occupied: Mutex<Option<(Arc<Binding>, WakeHandle<64>)>>,
|
||||
}
|
||||
impl Scene {
|
||||
fn runtime(&self) -> Pin<&Runtime<64>> {
|
||||
// SAFETY: constructor publishes this exact pinned allocation before
|
||||
// admission; queue retains Scene through join or full quarantine.
|
||||
unsafe {
|
||||
Pin::new_unchecked(&*(self.runtime.load(Ordering::Acquire) as *const Runtime<64>))
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe extern "C" fn child(pointer: *mut c_void) {
|
||||
// SAFETY: Scene and code remain retained by this queue until real completion.
|
||||
let f = unsafe { &*pointer.cast::<Scene>() };
|
||||
let r = f.runtime();
|
||||
let view = r.current_context().unwrap();
|
||||
assert_eq!(view.stack_end - view.stack_start, 16 * 1024);
|
||||
assert!(view.stack_start.is_multiple_of(16 * 1024));
|
||||
assert!((view.stack_start..view.stack_end).contains(&context::stack_pointer()));
|
||||
*f.actual.lock().unwrap() = Some(view);
|
||||
f.child.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
unsafe extern "C" fn bind_retained_worker(pointer: *mut c_void) {
|
||||
// SAFETY: queue retains Scene until the actual binding is joined/detached.
|
||||
let f = unsafe { &*pointer.cast::<Scene>() };
|
||||
let r = f.runtime();
|
||||
let binding = Arc::new(Binding {
|
||||
id: AtomicU64::new(0),
|
||||
blocked: AtomicBool::new(false),
|
||||
});
|
||||
let wake = r.bind_current(binding.clone()).unwrap();
|
||||
*f.occupied.lock().unwrap() = Some((binding, wake));
|
||||
}
|
||||
unsafe extern "C" fn ordinary_marker(pointer: *mut c_void) {
|
||||
// SAFETY: the same queue retains Scene through each ordinary marker completion.
|
||||
let f = unsafe { &*pointer.cast::<Scene>() };
|
||||
assert!(
|
||||
f.runtime().current_context().unwrap().stack_end
|
||||
- f.runtime().current_context().unwrap().stack_start
|
||||
>= 128 * 1024
|
||||
);
|
||||
f.ordinary.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
fn failed_metadata(r: Pin<&Runtime<64>>, authority: &dyn EnteredProcess) -> Result<(), WorkError> {
|
||||
let _permit = r.reserve_general(authority, kernel())?;
|
||||
// Actual fallible capacity rejection exercises caller-setup error rollback.
|
||||
// This does not claim physical allocator exhaustion or a Linux OOM service.
|
||||
let mut metadata = Vec::<u8>::new();
|
||||
metadata
|
||||
.try_reserve_exact(usize::MAX)
|
||||
.map_err(|_| WorkError::Full)?;
|
||||
unreachable!()
|
||||
}
|
||||
unsafe extern "C" fn creator(pointer: *mut c_void) {
|
||||
// SAFETY: accepted Foreground owns Scene and its live actual runtime view.
|
||||
let f = unsafe { &*pointer.cast::<Scene>() };
|
||||
let r = f.runtime();
|
||||
let authority = Authority {
|
||||
cpu: f.cpu.clone(),
|
||||
active: Cell::new(true),
|
||||
};
|
||||
let before = r.current_context().unwrap();
|
||||
let next = r.queue.lock().unwrap().state().next;
|
||||
match f.mode {
|
||||
Mode::BoundWorker => {
|
||||
let mut permits = Vec::new();
|
||||
for _ in 0..19 {
|
||||
permits.push(r.reserve_general(&authority, kernel()).unwrap());
|
||||
}
|
||||
assert!(matches!(
|
||||
r.reserve_general(&authority, kernel()),
|
||||
Err(WorkError::Full)
|
||||
));
|
||||
drop(permits);
|
||||
}
|
||||
Mode::Denied => {
|
||||
authority.active.set(false);
|
||||
assert!(matches!(
|
||||
r.reserve_general(&authority, kernel()),
|
||||
Err(WorkError::Unavailable)
|
||||
));
|
||||
authority.active.set(true);
|
||||
}
|
||||
Mode::NoProfile => {
|
||||
assert!(matches!(
|
||||
r.reserve_general(&authority, kernel()),
|
||||
Err(WorkError::Unavailable)
|
||||
));
|
||||
}
|
||||
Mode::CommitExhaust => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
r.queue.lock().unwrap().state().next = u64::MAX;
|
||||
assert_eq!(
|
||||
// SAFETY: provider-owned Scene stays retained; counter exhaustion must transfer nothing.
|
||||
unsafe { permit.commit(child, pointer) },
|
||||
Err(WorkError::Exhausted)
|
||||
);
|
||||
assert_eq!(r.queue.lock().unwrap().state().next, u64::MAX);
|
||||
r.queue.lock().unwrap().state().next = next;
|
||||
}
|
||||
Mode::Drop => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
assert_eq!(r.pending_reservations.get(), 1);
|
||||
assert_eq!(r.yield_now(), Err(WorkError::Busy));
|
||||
assert_eq!(r.reschedule(), Err(WorkError::Busy));
|
||||
assert_eq!(r.park_if_blocked(), Err(WorkError::Busy));
|
||||
assert_eq!(f.cpu.model.flags(), 0x202);
|
||||
assert_eq!(f.child.load(Ordering::Relaxed), 0);
|
||||
drop(permit);
|
||||
}
|
||||
Mode::MetadataFailure => assert_eq!(failed_metadata(r, &authority), Err(WorkError::Full)),
|
||||
Mode::Commit => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
// SAFETY: queue-retained Scene/code fit exact actual kernel geometry;
|
||||
// no borrowed authority is stored in the child callback/context.
|
||||
let assigned = unsafe { permit.commit(child, pointer) }.unwrap();
|
||||
assert_eq!(f.child.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(r.queue.completed(assigned.ticket()), Ok(false));
|
||||
assert_ne!(assigned.context_id().get(), before.context_id);
|
||||
*f.assigned.lock().unwrap() = Some(assigned);
|
||||
assert_eq!(r.pending_reservations.get(), 0);
|
||||
drop(authority); // Commit consumed its short borrow before any child wait.
|
||||
r.yield_now().unwrap();
|
||||
return;
|
||||
}
|
||||
Mode::Exhaust => {
|
||||
let mut permits = Vec::new();
|
||||
for _ in 0..4 {
|
||||
permits.push(r.reserve_general(&authority, ordinary()).unwrap());
|
||||
}
|
||||
assert!(matches!(
|
||||
r.reserve_general(&authority, ordinary()),
|
||||
Err(WorkError::Full)
|
||||
));
|
||||
for permit in permits {
|
||||
permit.cancel().unwrap();
|
||||
}
|
||||
assert_eq!(r.pending_reservations.get(), 0);
|
||||
r.queue.lock().unwrap().state().next_reservation = u64::MAX;
|
||||
assert!(matches!(
|
||||
r.reserve_general(&authority, kernel()),
|
||||
Err(WorkError::Exhausted)
|
||||
));
|
||||
assert!(
|
||||
r.queue
|
||||
.lock()
|
||||
.unwrap()
|
||||
.state()
|
||||
.reservations
|
||||
.iter()
|
||||
.all(|nonce| *nonce == 0)
|
||||
);
|
||||
}
|
||||
Mode::Closed => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
r.queue.close().unwrap();
|
||||
assert_eq!(
|
||||
// SAFETY: error retains provider-owned Scene and admits no callback.
|
||||
unsafe { permit.commit(child, pointer) },
|
||||
Err(WorkError::Closed)
|
||||
);
|
||||
assert_eq!(r.pending_reservations.get(), 0);
|
||||
}
|
||||
Mode::Pressure => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
for _ in 0..54 {
|
||||
// SAFETY: all retained ordinary markers fit actual128KiB workers.
|
||||
unsafe { r.queue.execute(Kind::General, ordinary_marker, pointer) }.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
// SAFETY: the private reserved slot must not accept ordinary work.
|
||||
unsafe { r.queue.execute(Kind::General, ordinary_marker, pointer) },
|
||||
Err(WorkError::Full)
|
||||
);
|
||||
permit.cancel().unwrap();
|
||||
// SAFETY: exact released slot becomes ordinary admission again; no child was published.
|
||||
unsafe { r.queue.execute(Kind::General, ordinary_marker, pointer) }.unwrap();
|
||||
assert!(matches!(
|
||||
r.reserve_general(&authority, kernel()),
|
||||
Err(WorkError::Full)
|
||||
));
|
||||
return;
|
||||
}
|
||||
Mode::StaleScope => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
let old = quarantined_owners();
|
||||
authority.active.set(false);
|
||||
assert_eq!(permit.cancel(), Err(WorkError::Unavailable));
|
||||
assert!(r.queue.abandoned.load(Ordering::Acquire));
|
||||
assert!(quarantined_owners() > old);
|
||||
assert_eq!(f.dropped.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(f.child.load(Ordering::Relaxed), 0);
|
||||
println!("STELA_RESERVATION_UNCERTAIN_RETAINED");
|
||||
return;
|
||||
}
|
||||
Mode::StaleCurrent => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
let flags = f.cpu.save_disable().unwrap();
|
||||
// SAFETY: deliberate isolated corruption of this actual current test
|
||||
// job's sequence, with IF0 and no foreign task. Fatal must retain it.
|
||||
unsafe {
|
||||
(*r.task(r.current.get())).job.as_mut().unwrap().1.sequence += 1;
|
||||
}
|
||||
// SAFETY: exact local save_disable flags above, no borrow survives.
|
||||
unsafe { f.cpu.restore(flags) };
|
||||
assert_eq!(permit.cancel(), Err(WorkError::CorruptContext));
|
||||
println!("STELA_RESERVATION_UNCERTAIN_RETAINED");
|
||||
return;
|
||||
}
|
||||
Mode::BadNonce => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
let mut guard = r.queue.lock().unwrap();
|
||||
let slot = guard
|
||||
.state()
|
||||
.reservations
|
||||
.iter()
|
||||
.position(|nonce| *nonce != 0)
|
||||
.unwrap();
|
||||
guard.state().reservations[slot] += 1;
|
||||
drop(guard);
|
||||
assert_eq!(permit.cancel(), Err(WorkError::CorruptContext));
|
||||
println!("STELA_RESERVATION_UNCERTAIN_RETAINED");
|
||||
return;
|
||||
}
|
||||
Mode::Forgotten => {
|
||||
let permit = r.reserve_general(&authority, kernel()).unwrap();
|
||||
core::mem::forget(permit);
|
||||
assert_eq!(f.dropped.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(f.child.load(Ordering::Relaxed), 0);
|
||||
println!("STELA_RESERVATION_FORGOTTEN_RETAINED");
|
||||
return;
|
||||
}
|
||||
}
|
||||
assert_eq!(r.queue.lock().unwrap().state().next, next);
|
||||
assert_eq!(r.pending_reservations.get(), 0);
|
||||
assert_eq!(r.current_context().unwrap().context_id, before.context_id);
|
||||
assert_eq!(r.current_context().unwrap().sequence, before.sequence);
|
||||
assert_eq!(f.child.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
fn run(mode: Mode) {
|
||||
let model = test_support::CpuModel::new();
|
||||
let dropped = Arc::new(AtomicUsize::new(0));
|
||||
let cpu = Arc::new(HarnessCpu {
|
||||
model,
|
||||
dropped: dropped.clone(),
|
||||
mode,
|
||||
});
|
||||
let f = Arc::new(Scene {
|
||||
runtime: AtomicU64::new(0),
|
||||
cpu: cpu.clone(),
|
||||
dropped: dropped.clone(),
|
||||
mode,
|
||||
child: AtomicUsize::new(0),
|
||||
ordinary: AtomicUsize::new(0),
|
||||
assigned: Mutex::new(None),
|
||||
actual: Mutex::new(None),
|
||||
occupied: Mutex::new(None),
|
||||
});
|
||||
// SAFETY: same-thread hosted CPU and retained exact Scene; no native grant.
|
||||
let q = unsafe { Queue::<64>::new(cpu.clone(), f.clone()) }.unwrap();
|
||||
let executor = if mode == Mode::NoProfile {
|
||||
Executor::new_hosted_for_test(q, test_support::stacks(&dropped)).unwrap()
|
||||
} else {
|
||||
Executor::new_hosted_profile_for_test(q, support::stacks(&dropped, 20), policy(), profile())
|
||||
.unwrap()
|
||||
};
|
||||
let r = executor.runtime();
|
||||
f.runtime
|
||||
.store(r.get_ref() as *const Runtime<64> as u64, Ordering::Release);
|
||||
if mode == Mode::BoundWorker {
|
||||
// SAFETY: queue-retained Scene binds an actual compatible worker; its real binding intentionally remains attached.
|
||||
unsafe {
|
||||
r.queue.execute_general_with_requirement(
|
||||
kernel(),
|
||||
bind_retained_worker,
|
||||
Arc::as_ptr(&f) as *mut c_void,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
r.drain(cpu.ticks() + 1_000_000_000).unwrap();
|
||||
assert!(f.occupied.lock().unwrap().is_some());
|
||||
}
|
||||
// SAFETY: actual Foreground stack and Scene remain retained through genuine join or fatal.
|
||||
unsafe {
|
||||
r.call_foreground(
|
||||
creator,
|
||||
Arc::as_ptr(&f) as *mut c_void,
|
||||
cpu.ticks() + 1_000_000_000,
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
r.drain(cpu.ticks() + 1_000_000_000).unwrap();
|
||||
if mode == Mode::Commit {
|
||||
let assigned = f.assigned.lock().unwrap().unwrap();
|
||||
assert_eq!(r.queue.completed(assigned.ticket()), Ok(true));
|
||||
assert_eq!(
|
||||
f.actual.lock().unwrap().unwrap().context_id,
|
||||
assigned.context_id().get()
|
||||
);
|
||||
assert_eq!(f.child.load(Ordering::Relaxed), 1);
|
||||
} else {
|
||||
assert_eq!(f.child.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
assert_eq!(
|
||||
f.ordinary.load(Ordering::Relaxed),
|
||||
if mode == Mode::Pressure { 55 } else { 0 }
|
||||
);
|
||||
if let Some((binding, wake)) = f.occupied.lock().unwrap().take() {
|
||||
// SAFETY: actual bound callback returned; fixture stopped every producer before detaching this idle owner.
|
||||
drop(unsafe { r.detach_binding(wake.context_id()) }.unwrap());
|
||||
drop(binding);
|
||||
drop(wake);
|
||||
}
|
||||
r.queue.close().unwrap();
|
||||
// SAFETY: no producer exists; every accepted callback returned and all bindings were detached.
|
||||
unsafe { r.retire() }.unwrap();
|
||||
drop(executor);
|
||||
assert_eq!(
|
||||
dropped.load(Ordering::Relaxed),
|
||||
if mode == Mode::NoProfile { 16 } else { 32 }
|
||||
);
|
||||
assert_eq!(cpu.model.flags(), 0x202);
|
||||
}
|
||||
#[test]
|
||||
fn dropped_and_failed_metadata_setup_restore_actual_worker_without_ticket() {
|
||||
run(Mode::Drop);
|
||||
run(Mode::MetadataFailure);
|
||||
}
|
||||
#[test]
|
||||
fn committed_actual_child_runs_after_borrow_release_on_its_reserved_geometry() {
|
||||
run(Mode::Commit);
|
||||
}
|
||||
#[test]
|
||||
fn real_worker_slot_nonce_exhaustion_and_closed_commit_transfer_nothing() {
|
||||
run(Mode::Exhaust);
|
||||
run(Mode::Closed);
|
||||
run(Mode::Pressure);
|
||||
}
|
||||
fn isolated(name: &str, mode: &str) {
|
||||
let test = format!("{}::{name}", module_path!().split_once("::").unwrap().1);
|
||||
let output = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &test, "--nocapture", "--test-threads=1"])
|
||||
.env("STELA_RESERVATION_TEST_MODE", mode)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(output.status.code(), Some(91));
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("STELA_RESERVATION_FATAL_RETAINED"));
|
||||
}
|
||||
#[test]
|
||||
fn stale_scope_current_and_nonce_keep_real_owners_before_mandatory_stop() {
|
||||
if let Ok(mode) = std::env::var("STELA_RESERVATION_TEST_MODE") {
|
||||
run(match mode.as_str() {
|
||||
"scope" => Mode::StaleScope,
|
||||
"current" => Mode::StaleCurrent,
|
||||
"nonce" => Mode::BadNonce,
|
||||
_ => panic!("wrong fixture mode"),
|
||||
});
|
||||
unreachable!();
|
||||
}
|
||||
for mode in ["scope", "current", "nonce"] {
|
||||
isolated(
|
||||
"stale_scope_current_and_nonce_keep_real_owners_before_mandatory_stop",
|
||||
mode,
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn forgotten_permit_stops_before_return_or_owner_release() {
|
||||
if std::env::var("STELA_RESERVATION_TEST_MODE").as_deref() == Ok("forgotten") {
|
||||
run(Mode::Forgotten);
|
||||
unreachable!();
|
||||
}
|
||||
isolated(
|
||||
"forgotten_permit_stops_before_return_or_owner_release",
|
||||
"forgotten",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_authority_profile_and_ticket_exhaustion_refuse_before_publication() {
|
||||
run(Mode::Denied);
|
||||
run(Mode::NoProfile);
|
||||
run(Mode::CommitExhaust);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physically_idle_but_retained_binding_is_not_an_unowned_spawn_stack() {
|
||||
run(Mode::BoundWorker);
|
||||
}
|
||||
Reference in new issue
Block a user