//! Retained, boot-owned process identity metadata for the native product. //! //! This owner does not hold ELF images, exception frames, address spaces, ASIDs, //! physical pages, or scheduler tasks. A metadata transition never proves EL0 //! execution and never authorizes releasing any of those resources. The D3 //! execution owner must retain and retire them independently. use turkos_kernel::process::{Error, PROCESS_CAPACITY, ProcessTable}; pub(super) use turkos_kernel::process::{ProcessId as Id, State}; use core::sync::atomic::{Ordering, compiler_fence}; pub(super) const CAPACITY: usize = PROCESS_CAPACITY; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct Snapshot { pub init: Id, pub boot_id: u64, /// Occupied identities which have not exited. Exited identities are kept /// separately until their actual parent waits and reaps their metadata. pub live: u64, pub exited: u64, pub current: Option, pub execs: u64, pub spawns: u64, pub waits: u64, pub exits: u64, pub reaps: u64, pub stale_rejections: u64, } #[derive(Clone, Copy)] struct Record { id: Option, parent: Option, image_generation: u64, waiting_for: Option, } impl Record { const EMPTY: Self = Self { id: None, parent: None, image_generation: 0, waiting_for: None, }; } struct Owner { table: ProcessTable, records: [Record; CAPACITY], boot_id: u64, init: Option, current: Option, execs: u64, spawns: u64, waits: u64, exits: u64, reaps: u64, stale_rejections: u64, } impl Owner { const fn new() -> Self { Self { table: ProcessTable::new(), records: [Record::EMPTY; CAPACITY], boot_id: 0, init: None, current: None, execs: 0, spawns: 0, waits: 0, exits: 0, reaps: 0, stale_rejections: 0, } } fn checked_state(&mut self, id: Id) -> Result { match self.table.state(id) { Ok(state) if self.records[id.slot as usize].id == Some(id) => Ok(state), Ok(_) => Err("process-owner-record-mismatch"), Err(Error::StaleId) => { self.stale_rejections = self.stale_rejections.saturating_add(1); Err("process-owner-stale-id") } Err(error) => Err(tag(error)), } } fn require_current(&mut self, id: Id) -> Result<(), &'static str> { if self.checked_state(id)? != State::Running || self.current != Some(id) { return Err("process-owner-current-mismatch"); } Ok(()) } fn initialize(&mut self, boot_id: u64) -> Result { if boot_id == 0 { return Err("process-owner-zero-boot-id"); } if self.boot_id != 0 { if self.boot_id != boot_id { return Err("process-owner-boot-mismatch"); } // Idempotent access never recreates PID1 or clears retained state. return self.snapshot(); } let init = self.table.create().map_err(tag)?; if init.slot != 0 { return Err("process-owner-init-slot"); } self.records[0] = Record { id: Some(init), ..Record::EMPTY }; self.init = Some(init); self.boot_id = boot_id; self.snapshot() } fn snapshot(&mut self) -> Result { let init = self.init.ok_or("process-owner-uninitialized")?; if self.boot_id == 0 || self.records[init.slot as usize].parent.is_some() { return Err("process-owner-init-owner"); } if matches!(self.checked_state(init)?, State::Exited(_)) { return Err("process-owner-init-exited"); } let mut live = 0; let mut exited = 0; let mut running = None; for index in 0..CAPACITY { let Some(id) = self.records[index].id else { continue; }; match self.checked_state(id)? { State::Exited(_) => exited += 1, State::Running => { if running.replace(id).is_some() { return Err("process-owner-multiple-current"); } live += 1; } _ => live += 1, } } if self.current != running { return Err("process-owner-current-mismatch"); } Ok(Snapshot { init, boot_id: self.boot_id, live, exited, current: self.current, execs: self.execs, spawns: self.spawns, waits: self.waits, exits: self.exits, reaps: self.reaps, stale_rejections: self.stale_rejections, }) } fn start(&mut self, id: Id) -> Result<(), &'static str> { if self.checked_state(id)? != State::Ready || self.current.is_some() { return Err("process-owner-not-ready"); } self.table.run(id).map_err(tag)?; self.current = Some(id); Ok(()) } fn yield_ready(&mut self, id: Id) -> Result<(), &'static str> { self.require_current(id)?; self.table.yield_ready(id).map_err(tag)?; self.current = None; Ok(()) } fn spawn(&mut self, parent: Id) -> Result { self.require_current(parent)?; let spawns = next(self.spawns)?; let child = self.table.create().map_err(tag)?; self.records[child.slot as usize] = Record { id: Some(child), parent: Some(parent), ..Record::EMPTY }; self.spawns = spawns; Ok(child) } fn exec(&mut self, id: Id) -> Result { self.require_current(id)?; let generation = next(self.records[id.slot as usize].image_generation)?; let execs = next(self.execs)?; self.records[id.slot as usize].image_generation = generation; self.execs = execs; Ok(generation) } fn child_id(&mut self, parent: Id, token: u64) -> Result, &'static str> { self.require_current(parent)?; let child = self.records.iter().find_map(|record| { let id = record.id?; (pid(id) == token && record.parent == Some(parent)).then_some(id) }); if let Some(id) = child { // Exited children remain valid wait targets until their parent // reaps them. Never resolve a token using the slot number alone. self.checked_state(id)?; Ok(Some(id)) } else { // Count an actual rejected public child lookup, including a token // for another parent's process. No caller can increment this // evidence without performing the bounded ownership lookup. self.stale_rejections = self.stale_rejections.saturating_add(1); Ok(None) } } fn wait(&mut self, parent: Id, child: Id) -> Result, &'static str> { self.require_current(parent)?; let child_state = self.checked_state(child)?; if self.records[child.slot as usize].parent != Some(parent) { return Err("process-owner-not-child"); } let waits = next(self.waits)?; if let State::Exited(code) = child_state { let reaps = next(self.reaps)?; if self.table.reap(child).map_err(tag)? != code { return Err("process-owner-reap-code"); } self.records[child.slot as usize] = Record::EMPTY; self.waits = waits; self.reaps = reaps; return Ok(Some(code)); } if child_state == State::Running { return Err("process-owner-child-already-current"); } self.table.wait(parent).map_err(tag)?; self.records[parent.slot as usize].waiting_for = Some(child); self.current = None; self.waits = waits; Ok(None) } fn exit(&mut self, id: Id, code: i32) -> Result<(), &'static str> { self.require_current(id)?; if self.init == Some(id) { return Err("process-owner-init-must-survive"); } // The bounded product path has no orphan adoption service. Refuse to // lose any descendant's parent identity, including unreaped zombies. if self.records.iter().any(|entry| entry.parent == Some(id)) { return Err("process-owner-unreaped-children"); } let parent = self.records[id.slot as usize] .parent .ok_or("process-owner-parent-missing")?; let parent_state = self.checked_state(parent)?; if matches!(parent_state, State::Exited(_)) { return Err("process-owner-parent-exited"); } let wake = parent_state == State::Waiting && self.records[parent.slot as usize].waiting_for == Some(id); let exits = next(self.exits)?; self.table.exit(id, code).map_err(tag)?; self.current = None; if wake { self.table.wake(parent).map_err(tag)?; self.records[parent.slot as usize].waiting_for = None; } self.exits = exits; Ok(()) } fn interrupt_wait(&mut self, parent: Id, child: Id) -> Result<(), &'static str> { // A supervisor service event may interrupt a blocked wait. It never // reports an exit, reaps an identity, or changes the child's state. if self.current.is_some() || self.checked_state(parent)? != State::Waiting || self.records[parent.slot as usize].waiting_for != Some(child) || self.checked_state(child)? != State::Ready || self.records[child.slot as usize].parent != Some(parent) { return Err("process-owner-wait-interrupt-target"); } self.table.wake(parent).map_err(tag)?; self.records[parent.slot as usize].waiting_for = None; Ok(()) } } fn next(value: u64) -> Result { value .checked_add(1) .ok_or("process-owner-counter-exhausted") } fn tag(error: Error) -> &'static str { match error { Error::Capacity => "process-owner-capacity", Error::GenerationExhausted => "process-owner-generation-exhausted", Error::StaleId => "process-owner-stale-id", Error::Transition => "process-owner-transition", Error::AlreadyRunning => "process-owner-already-running", } } // This is a boot-CPU reentry guard, never an inter-CPU lock. In particular it // must not issue exclusive accesses: native guest mappings need not support // exclusive byte loads. All other CPUs are rejected before touching this flag. static mut BUSY: bool = false; static mut OWNER: Owner = Owner::new(); struct Access; impl Drop for Access { fn drop(&mut self) { // Finish all metadata accesses before permitting synchronous reentry. // This fence is compiler-only and emits no exclusive/atomic accesses. compiler_fence(Ordering::SeqCst); // SAFETY: Access exists only while the boot CPU owns the flag with // every asynchronous exception class masked. No reference is retained. unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(BUSY), false) }; } } fn require_boot_cpu() -> Result<(), &'static str> { #[cfg(target_arch = "aarch64")] { let cpu: u64; let el: u64; let daif: u64; // SAFETY: this runtime is an EL1-only native product module. These // observations neither change masks nor grant any hardware ownership. unsafe { core::arch::asm!( "mrs {cpu}, MPIDR_EL1", "mrs {el}, CurrentEL", "mrs {daif}, DAIF", cpu = out(reg) cpu, el = out(reg) el, daif = out(reg) daif, options(nomem, nostack, preserves_flags) ); } if cpu & 0x0000_00ff_00ff_ffff != 0 || el != 4 || daif & 0x3c0 != 0x3c0 { return Err("process-owner-masked-boot-cpu-required"); } Ok(()) } #[cfg(not(target_arch = "aarch64"))] Err("process-owner-native-el1-required") } fn access(f: impl FnOnce(&mut Owner) -> Result) -> Result { require_boot_cpu()?; // SAFETY: the CPU/mask check precedes every access to this single-CPU // flag. Masking D/A/I/F prevents asynchronous entry between the check and // store; a synchronous exception here occurs before OWNER is borrowed. unsafe { if core::ptr::read_volatile(core::ptr::addr_of!(BUSY)) { return Err("process-owner-reentrant-access"); } core::ptr::write_volatile(core::ptr::addr_of_mut!(BUSY), true); } // Do not let the compiler move metadata access before publishing reentry // protection. The fence has no hardware atomic instruction requirement. compiler_fence(Ordering::SeqCst); let _access = Access; // SAFETY: only the fully masked boot CPU may enter. BUSY rejects synchronous // reentry before another mutable reference can be created. No reference // escapes this private function; the closure cannot unmask exceptions or // switch CPUs, and secondary CPUs always fail before reading BUSY. let owner = unsafe { &mut *core::ptr::addr_of_mut!(OWNER) }; f(owner) } /// Public process tokens use the table-wide monotonic generation, so a reaped /// process and its replacement never share a userspace wait token. The bounded /// slot remains an internal index; execution owners must retain the complete Id. pub(super) const fn pid(id: Id) -> u64 { id.generation } /// Creates a retained Ready PID1 without allocating frames or executing ELF. pub(super) fn initialize(boot_id: u64) -> Result { access(|owner| owner.initialize(boot_id)) } pub(super) fn snapshot() -> Result { access(Owner::snapshot) } pub(super) fn state(id: Id) -> Result { access(|owner| owner.checked_state(id)) } pub(super) fn parent(id: Id) -> Result, &'static str> { access(|owner| { owner.checked_state(id)?; Ok(owner.records[id.slot as usize].parent) }) } pub(super) fn image_generation(id: Id) -> Result { access(|owner| { owner.checked_state(id)?; Ok(owner.records[id.slot as usize].image_generation) }) } pub(super) fn start(id: Id) -> Result<(), &'static str> { access(|owner| owner.start(id)) } pub(super) fn yield_ready(id: Id) -> Result<(), &'static str> { access(|owner| owner.yield_ready(id)) } pub(super) fn spawn(parent: Id) -> Result { access(|owner| owner.spawn(parent)) } /// Advances an image's metadata generation without changing its process Id. /// The caller must separately prove the ELF image was validated and installed. pub(super) fn exec(id: Id) -> Result { access(|owner| owner.exec(id)) } /// Resolves a public wait token only for the current process's retained child. /// Unknown, reaped, and foreign tokens return None and record their rejection. pub(super) fn child_id(parent: Id, token: u64) -> Result, &'static str> { access(|owner| owner.child_id(parent, token)) } /// Waits for an actual child, or reaps only its exited identity metadata. /// This function never releases an ELF space, ASID, frame, or task resource. pub(super) fn wait(parent: Id, child: Id) -> Result, &'static str> { access(|owner| owner.wait(parent, child)) } /// Records a child exit and makes its waiting parent Ready. The parent's /// execution owner must separately resume its saved frame/address space. pub(super) fn exit(id: Id, code: i32) -> Result<(), &'static str> { access(|owner| owner.exit(id, code)) } /// Makes a blocked parent Ready for an actual interrupted-wait return. The /// execution owner must supply EINTR in the parent's saved syscall result. /// Both the child and the wait/exit/reap counters retain their actual history. pub(super) fn interrupt_wait(parent: Id, child: Id) -> Result<(), &'static str> { access(|owner| owner.interrupt_wait(parent, child)) } #[cfg(test)] mod tests { use super::*; #[test] fn init_survives_child_fault_wait_reap_and_recycled_generation() { let mut owner = Owner::new(); let init = owner.initialize(77).unwrap().init; assert_eq!(pid(init), 1); owner.start(init).unwrap(); assert_eq!(owner.exec(init), Ok(1)); let shell = owner.spawn(init).unwrap(); assert_eq!(owner.wait(init, shell), Ok(None)); owner.start(shell).unwrap(); owner.exec(shell).unwrap(); let child = owner.spawn(shell).unwrap(); assert_eq!(owner.wait(shell, child), Ok(None)); owner.start(child).unwrap(); assert_eq!(owner.exec(child), Ok(1)); assert_eq!(owner.exec(child), Ok(2)); assert_eq!(owner.current, Some(child)); owner.exit(child, -11).unwrap(); assert_eq!(owner.checked_state(init), Ok(State::Waiting)); assert_eq!(owner.checked_state(shell), Ok(State::Ready)); owner.start(shell).unwrap(); assert_eq!(owner.wait(shell, child), Ok(Some(-11))); let replacement = owner.spawn(shell).unwrap(); assert_eq!(replacement.slot, child.slot); assert!(replacement.generation > child.generation); assert_ne!(pid(replacement), pid(child)); assert_eq!( owner.child_id(shell, pid(replacement)), Ok(Some(replacement)) ); assert_eq!(owner.child_id(shell, pid(child)), Ok(None)); assert_eq!(owner.checked_state(child), Err("process-owner-stale-id")); assert_eq!(owner.exit(child, 0), Err("process-owner-stale-id")); owner.yield_ready(shell).unwrap(); let snapshot = owner.snapshot().unwrap(); assert_eq!(snapshot.init, init); assert_eq!(snapshot.current, None); assert_eq!(snapshot.live, 3); assert_eq!(snapshot.exited, 0); assert_eq!(snapshot.reaps, 1); assert_eq!(snapshot.stale_rejections, 3); } #[test] fn wrong_parent_wait_and_pid1_exit_do_not_mutate_lifecycle() { let mut owner = Owner::new(); let init = owner.initialize(88).unwrap().init; owner.start(init).unwrap(); let shell = owner.spawn(init).unwrap(); let sibling = owner.spawn(init).unwrap(); assert_eq!(owner.exit(init, 0), Err("process-owner-init-must-survive")); owner.wait(init, shell).unwrap(); owner.start(shell).unwrap(); let before = owner.snapshot().unwrap(); assert_eq!(owner.wait(shell, sibling), Err("process-owner-not-child")); assert_eq!(owner.snapshot(), Ok(before)); assert_eq!(owner.child_id(shell, pid(sibling)), Ok(None)); assert_eq!(owner.stale_rejections, before.stale_rejections + 1); let child = owner.spawn(shell).unwrap(); assert_eq!(owner.exit(shell, 0), Err("process-owner-unreaped-children")); assert_eq!(owner.checked_state(shell), Ok(State::Running)); assert_eq!(owner.checked_state(child), Ok(State::Ready)); } #[test] fn repeated_initialization_preserves_owner_and_rejects_boot_replacement() { let mut owner = Owner::new(); assert_eq!(owner.initialize(0), Err("process-owner-zero-boot-id")); let before = owner.initialize(99).unwrap(); assert_eq!(owner.initialize(99), Ok(before)); assert_eq!(owner.initialize(100), Err("process-owner-boot-mismatch")); assert_eq!(owner.snapshot(), Ok(before)); owner.start(before.init).unwrap(); let child = owner.spawn(before.init).unwrap(); let running = owner.snapshot().unwrap(); assert_eq!(owner.initialize(99), Ok(running)); assert_eq!(owner.records[child.slot as usize].parent, Some(before.init)); } #[test] fn interrupted_live_child_wait_retains_both_identities_and_exit_history() { let mut owner = Owner::new(); let init = owner.initialize(123).unwrap().init; owner.start(init).unwrap(); let shell = owner.spawn(init).unwrap(); owner.wait(init, shell).unwrap(); let before = owner.snapshot().unwrap(); owner.interrupt_wait(init, shell).unwrap(); let after = owner.snapshot().unwrap(); assert_eq!(owner.checked_state(init), Ok(State::Ready)); assert_eq!(owner.checked_state(shell), Ok(State::Ready)); assert_eq!(after.live, 2); assert_eq!(after.exited, 0); assert_eq!(after.waits, before.waits); assert_eq!(after.exits, before.exits); assert_eq!(after.reaps, before.reaps); assert_eq!(owner.records[init.slot as usize].waiting_for, None); assert_eq!(owner.records[shell.slot as usize].parent, Some(init)); assert_eq!( owner.interrupt_wait(init, shell), Err("process-owner-wait-interrupt-target") ); owner.start(init).unwrap(); assert_eq!(owner.wait(init, shell), Ok(None)); } }