//! Native ownership observations. Missing owners are an error, never zero use. //! //! This module deliberately cannot infer product heap/DMA/handle ownership from //! K2500 evidence words. The product coordinator must lend its *live* owners to //! `Snapshot::observe_*` on both sides of the same workload before reconciliation. use super::super::*; use core::sync::atomic::{AtomicBool, Ordering}; use turkos_kernel::runtime::{ dma, frame_authority as frame, frame_metadata, handles, kernel_heap, platform_ram::Region, }; pub const UNKNOWN: u64 = u64::MAX; const OWNER_CAPACITY: usize = 32; static RECONCILED: AtomicBool = AtomicBool::new(false); /// Inert audit rows copied from the actual D4 owner's retained noncopy leases. /// `pins` means the number of owner-held published descriptor references. This /// does not manufacture a frame_metadata::Pin or authorize releasing a frame. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct NativeDmaRecord { pub address: u64, /// Device owner's actual initialization epoch; DmaLease exposes no frame /// generation. This is never presented as a frame::Lease generation. pub owner_epoch: u64, pub owner: u64, pub queue: u64, pub kind: u64, pub pins: u64, pub active: bool, pub quarantined: bool, } #[derive(Clone, Debug, PartialEq, Eq)] pub(super) struct NativeDmaInventory { records: [Option; 16], pub device: u64, pub epoch: u64, pub reset_seen: bool, } impl NativeDmaInventory { /// The privileged device owner must enumerate every ring and packet page. /// Empty is meaningful only for its real never-started or destroyed state. pub(super) fn from_records( device: u64, epoch: u64, records: &[NativeDmaRecord], reset_seen: bool, ) -> Result { if records.len() > 16 || (!records.is_empty() && (device == 0 || epoch == 0)) { return Err("d6-native-dma-owner-binding"); } let mut value = Self { records: [None; 16], device, epoch, reset_seen, }; for (index, record) in records.iter().copied().enumerate() { if record.address == 0 || record.address & 4095 != 0 || record.owner_epoch == 0 || record.owner_epoch != epoch || record.owner == 0 || record.queue > 1 || !(1..=2).contains(&record.kind) || (record.active && record.pins == 0) || records[..index].iter().any(|r| r.address == record.address) { return Err("d6-native-dma-owner-inventory"); } value.records[index] = Some(record); } value .records .sort_unstable_by_key(|r| r.map_or(u64::MAX, |r| r.address)); Ok(value) } pub(super) fn len(&self) -> usize { self.records.iter().flatten().count() } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct FrameSnapshot { pub audit: frame::Audit, free: [Region; frame::MAX_REGIONS], free_len: usize, live: [u64; frame::MAX_LIVE], live_len: usize, reserved: [Region; frame::MAX_RESERVATIONS], reserved_len: usize, } impl FrameSnapshot { const fn empty() -> Self { Self { audit: frame::Audit { ram_full_pages: 0, firmware_withheld_pages: 0, boot_reserved_pages: 0, authorized_pages: 0, free_pages: 0, reserved_pages: 0, live_pages: 0, }, free: [Region::EMPTY; frame::MAX_REGIONS], free_len: 0, live: [0; frame::MAX_LIVE], live_len: 0, reserved: [Region::EMPTY; frame::MAX_RESERVATIONS], reserved_len: 0, } } pub fn capture(allocator: &memory::FrameAllocator) -> Result { let mut snapshot = Self::empty(); snapshot.capture_into(allocator)?; Ok(snapshot) } /// Product accounting uses retained storage directly. D2's established /// return-by-value API above remains available for its smaller call graph. #[inline(never)] fn capture_into(&mut self, allocator: &memory::FrameAllocator) -> Result<(), &'static str> { let owner = allocator.os_authority(); self.audit = owner.audit().map_err(|_| "d6-frame-owner-audit")?; self.free.fill(Region::EMPTY); self.free_len = 0; self.live.fill(0); self.live_len = 0; self.reserved.fill(Region::EMPTY); self.reserved_len = 0; let snapshot = self; let free = allocator.free_regions().map_err(|_| "d6-free-map-audit")?; if free.len() > snapshot.free.len() { return Err("d6-free-map-capacity"); } snapshot.free[..free.len()].copy_from_slice(free); snapshot.free_len = free.len(); for address in owner.live_addresses() { if snapshot.live_len == snapshot.live.len() { return Err("d6-live-owner-capacity"); } snapshot.live[snapshot.live_len] = address; snapshot.live_len += 1; } // Membership is compared independently of allocator metadata slot reuse. snapshot.live[..snapshot.live_len].sort_unstable(); for region in owner.reserved_regions() { if snapshot.reserved_len == snapshot.reserved.len() { return Err("d6-reservation-capacity"); } snapshot.reserved[snapshot.reserved_len] = region; snapshot.reserved_len += 1; } snapshot.reserved[..snapshot.reserved_len].sort_unstable_by_key(|r| (r.start, r.end)); owner .audit_observed( &snapshot.free[..snapshot.free_len], &snapshot.live[..snapshot.live_len], &snapshot.reserved[..snapshot.reserved_len], ) .map_err(|_| "d6-exact-frame-inventory")?; if allocator.remaining_pages() != snapshot.audit.free_pages { return Err("d6-frame-adapter-disagrees"); } Ok(()) } pub fn live_addresses(&self) -> &[u64] { &self.live[..self.live_len] } pub fn require_restored(&self, after: &Self) -> Result<(), &'static str> { if self != after { return Err("d6-frame-inventory-not-restored"); } Ok(()) } } #[derive(Clone, Debug, PartialEq, Eq)] struct HeapObservation { audit: kernel_heap::Snapshot, objects: [Option; OWNER_CAPACITY], backing: [Option; OWNER_CAPACITY], } #[derive(Clone, Debug, PartialEq, Eq)] struct DmaObservation { audit: dma::Snapshot, owned: [Option; OWNER_CAPACITY], } #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct HandleRecord { handle: u64, owner: (u64, u64), object: handles::Object, rights: handles::Rights, } /// All optional fields start unobserved. Only methods borrowing real kernel /// owners can mark them observed. Capacity overflow fails instead of truncating. pub struct Snapshot { pub frames: FrameSnapshot, heap: Option, dma: Option, handles: Option<[Option; OWNER_CAPACITY]>, native_dma: Option, native_valid: bool, } impl Snapshot { const fn retained_storage() -> Self { Self { frames: FrameSnapshot::empty(), heap: Some(HeapObservation { audit: kernel_heap::Snapshot { objects: 0, requested_bytes: 0, capacity_bytes: 0, backing_pages: 0, slab_pages: 0, large_pages: 0, quarantined_pages: 0, retired_slots: 0, }, objects: [None; OWNER_CAPACITY], backing: [None; OWNER_CAPACITY], }), dma: None, handles: Some([None; OWNER_CAPACITY]), native_dma: Some(NativeDmaInventory { records: [None; 16], device: 0, epoch: 0, reset_seen: false, }), native_valid: false, } } pub fn capture_frames(allocator: &memory::FrameAllocator) -> Result { Ok(Self { frames: FrameSnapshot::capture(allocator)?, heap: None, dma: None, handles: None, native_dma: None, native_valid: false, }) } pub fn observe_heap( &mut self, heap: &kernel_heap::Heap, ) -> Result<(), &'static str> { if self.heap.is_some() { return Err("d6-heap-owner-already-observed"); } let mut observation = HeapObservation { audit: heap.audit().map_err(|_| "d6-heap-owner-audit")?, objects: [None; OWNER_CAPACITY], backing: [None; OWNER_CAPACITY], }; for (index, record) in heap.object_records().enumerate() { if index == OWNER_CAPACITY { return Err("d6-heap-object-capacity"); } observation.objects[index] = Some(record); } for (index, record) in heap.backing_records().enumerate() { if index == OWNER_CAPACITY { return Err("d6-heap-backing-capacity"); } observation.backing[index] = Some(record); } self.heap = Some(observation); Ok(()) } pub fn observe_dma( &mut self, owner: &dma::Dma<'_, B, N>, ) -> Result<(), &'static str> { if self.dma.is_some() { return Err("d6-dma-owner-already-observed"); } let mut observation = DmaObservation { audit: owner.audit().map_err(|_| "d6-dma-owner-audit")?, owned: [None; OWNER_CAPACITY], }; owner.observe_registry(|registry| { for (index, record) in registry.owned_records().enumerate() { if index == OWNER_CAPACITY { return Err("d6-dma-registry-capacity"); } observation.owned[index] = Some(record); } Ok(()) })?; self.dma = Some(observation); Ok(()) } /// `identity` must preserve both slot and generation of the product PID. /// A process slot alone is not sufficient to prove capability ownership. pub fn observe_handles( &mut self, table: &handles::Table, identity: impl Fn(P) -> (u64, u64), ) -> Result<(), &'static str> { if self.handles.is_some() { return Err("d6-handle-owner-already-observed"); } if N > OWNER_CAPACITY { return Err("d6-handle-table-capacity"); } let state = table.snapshot(); let mut records = [None; OWNER_CAPACITY]; for (index, entry) in state.entries.into_iter().enumerate() { if let Some((handle, owner, object, rights)) = entry { let raw = handles::Handle::from_raw(handle); if raw.slot() as usize != index + 1 || raw.generation() == 0 || raw.generation() != state.generations[index] { return Err("d6-handle-generation-inventory"); } let owner = identity(owner); if owner.1 == 0 { return Err("d6-handle-owner-generation"); } records[index] = Some(HandleRecord { handle, owner, object, rights, }); } } self.handles = Some(records); Ok(()) } fn complete(&self) -> bool { self.heap.is_some() && (self.dma.is_some() || (self.native_dma.is_some() && self.native_valid)) && self.handles.is_some() } } /// Differences are computed from observations. No persistence allowance is /// hardcoded: a retained owner or changed physical free map remains a failure. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Delta { pub newly_live_frames: u64, pub missing_live_frames: u64, pub frame_inventory_changed: bool, pub heap_inventory_changed: bool, pub dma_inventory_changed: bool, pub handle_inventory_changed: bool, pub final_heap_quarantined_pages: u64, pub final_dma_active: u64, pub final_dma_quarantined: u64, } impl Delta { pub fn between(before: &Snapshot, after: &Snapshot) -> Result { if !before.complete() || !after.complete() { return Err("d6-accounting-missing-product-owner-registry"); } Ok(Self { newly_live_frames: after .frames .live_addresses() .iter() .filter(|address| !before.frames.live_addresses().contains(address)) .count() as u64, missing_live_frames: before .frames .live_addresses() .iter() .filter(|address| !after.frames.live_addresses().contains(address)) .count() as u64, frame_inventory_changed: before.frames != after.frames, heap_inventory_changed: before.heap != after.heap, // A successful device reset legitimately changes its witness. // Compare resource ownership, not monotonic reset history. dma_inventory_changed: match (&before.dma, &after.dma) { (Some(a), Some(b)) => { a.owned != b.owned || a.audit.pins != b.audit.pins || a.audit.registry_pins != b.audit.registry_pins || a.audit.active != b.audit.active || a.audit.quarantined != b.audit.quarantined } (None, None) => { before.native_dma.as_ref().map(|a| &a.records) != after.native_dma.as_ref().map(|a| &a.records) } _ => true, }, handle_inventory_changed: before.handles != after.handles, final_heap_quarantined_pages: after .heap .as_ref() .ok_or("d6-heap-owner-missing")? .audit .quarantined_pages as u64, final_dma_active: match (&after.dma, &after.native_dma) { (Some(owner), None) => owner.audit.active as u64, (None, Some(owner)) => { owner.records.iter().flatten().filter(|r| r.active).count() as u64 } _ => return Err("d6-dma-owner-missing-or-ambiguous"), }, final_dma_quarantined: match (&after.dma, &after.native_dma) { (Some(owner), None) => owner.audit.quarantined as u64, (None, Some(owner)) => owner .records .iter() .flatten() .filter(|r| r.quarantined) .count() as u64, _ => return Err("d6-dma-owner-missing-or-ambiguous"), }, }) } pub fn require_reconciled(&self) -> Result<(), &'static str> { if self.newly_live_frames != 0 || self.missing_live_frames != 0 || self.frame_inventory_changed || self.heap_inventory_changed || self.dma_inventory_changed || self.handle_inventory_changed || self.final_heap_quarantined_pages != 0 || self.final_dma_active != 0 || self.final_dma_quarantined != 0 { return Err("d6-resource-inventory-not-restored"); } Ok(()) } } /// The coordinator must call this only on snapshots bracketing the *same* /// integrated workload. A failed or incomplete observation revokes any receipt. pub fn reconcile(before: &Snapshot, after: &Snapshot) -> Result { RECONCILED.store(false, Ordering::Release); let delta = Delta::between(before, after)?; delta.require_reconciled()?; RECONCILED.store(true, Ordering::Release); Ok(delta) } /// D7 must call this before interpreting D6 as a completed product teardown. pub fn require_reconciled() -> Result<(), &'static str> { if !RECONCILED.load(Ordering::Acquire) { return Err("d6-accounting-incomplete"); } product_access(None, |owner| { if !owner.baseline_present || owner.finalized_epoch == UNKNOWN || owner.finalized_epoch != owner.epoch { return Err("d6-accounting-receipt-stale"); } if super::d5_smp::lifecycle_initialized() { super::d5_smp::require_scheduler_retired()?; } Ok(()) }) } // The heap backend never retains an allocator reference across an API call. // Its pointer is bound only while an authorized fully masked service CPU // borrows runtime under D5's global exclusive dispatcher lease. static mut BOUND_ALLOCATOR: *mut memory::FrameAllocator = core::ptr::null_mut(); static mut PRODUCT_BUSY: bool = false; struct ProductBacking; impl kernel_heap::Backend for ProductBacking { type Lease = frame::Lease; fn acquire( &mut self, order: u8, ) -> Result, kernel_heap::Error> { // Channel messages are bounded to one slab page. Larger allocations // fail before touching the physical allocator, never use fake runs. if order != 0 { return Err(kernel_heap::Error::NoMemory); } let pointer = unsafe { core::ptr::read_volatile(core::ptr::addr_of!(BOUND_ALLOCATOR)) }; if pointer.is_null() { return Err(kernel_heap::Error::Backing); } let lease = unsafe { &mut *pointer } .os_authority_mut() .allocate() .map_err(|_| kernel_heap::Error::NoMemory)?; let address = lease.address() as usize; for offset in 0..4096 { unsafe { core::ptr::write_volatile((address + offset) as *mut u8, 0); } } Ok(kernel_heap::Block { address, pages: 1, lease, }) } fn relinquish(&mut self, lease: Self::Lease) -> Result<(), (kernel_heap::Error, Self::Lease)> { let pointer = unsafe { core::ptr::read_volatile(core::ptr::addr_of!(BOUND_ALLOCATOR)) }; if pointer.is_null() { return Err((kernel_heap::Error::Backing, lease)); } let allocator = unsafe { &mut *pointer }.os_authority_mut(); if allocator.validate_lease(&lease).is_err() { return Err((kernel_heap::Error::Backing, lease)); } for offset in 0..4096 { unsafe { core::ptr::write_volatile((lease.address() + offset) as *mut u8, 0); } } match allocator.release(&lease) { Ok(()) => Ok(()), Err(_) => Err((kernel_heap::Error::Backing, lease)), } } } type ProductHeap = kernel_heap::Heap; type ProductHandles = handles::Table; struct ProductOwners { heap: Option, handles: ProductHandles, baseline_present: bool, epoch: u64, finalized_epoch: u64, allocated: u64, released: u64, bytes_written: u64, bytes_read: u64, heap_events: usize, heap_event_overflow: u64, } static mut PRODUCT_OWNERS: ProductOwners = ProductOwners { heap: None, handles: ProductHandles::new(), baseline_present: false, epoch: 0, finalized_epoch: UNKNOWN, allocated: 0, released: 0, bytes_written: 0, bytes_read: 0, heap_events: 0, heap_event_overflow: 0, }; // Only product_access may borrow these independent storage regions. A capture // begins invalid and is committed only after all live owner audits pass. No // Snapshot value, Option, clone, or large return object crosses the // primary stack on the integrated path. static mut PRODUCT_BASELINE: Snapshot = Snapshot::retained_storage(); static mut PRODUCT_SCRATCH: Snapshot = Snapshot::retained_storage(); #[used] #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D6_ACCOUNTING: [u64; 128] = [UNKNOWN; 128]; #[used] #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D6_INVENTORY: [u64; 4608] = [UNKNOWN; 4608]; /// First 32 real heap operations are preserved as copied witnesses, not host /// reads of freed pages. Sixteen u64 per event: kind(1 allocated/2 read/3 /// released), counter, owner epoch, physical address, heap generation, process /// slot, process generation, length, first32 actual physical bytes (4 LE words), /// allocator free before/after (UNKNOWN for read without allocator borrow), /// operation number, live heap objects after. Released event bytes are read /// BEFORE release. Unused records zero; overflow never overwrites first events. #[used] #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D6_HEAP_HISTORY: [u64; 512] = [0; 512]; /// Twelve one-shot probe classes, independently decodable before/after owners. /// Each 4096-word slot is before(resource1536 + execution512), then after. /// Resource layout matches OS_PRODUCT_D6_INVENTORY, with PROBE-ONLY words /// 1104..1135 holding all32 actual capability slot generations, including /// empty slots. Remaining reserved tail is zero. Execution words are copies /// supplied by a caller observing an actual, valid D3 execution owner. #[used] #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D6_PROBE_INVENTORY: [u64; 49152] = [0; 49152]; /// 12 x64 words:0magic,1version,2boot,3slot,4scope(1resource/2executiontoo), /// 5state(1beforepending,2captured,3exact,4mismatch,5capturefailed),6sequence, /// 7/8before/aftercounter,9resourcesExact,10executionExact(UNKNOWNforscope1), /// 11capturemask(before1/after2),12..15beforehash,16..19afterhash, /// 20/21observedD6epochs(notowneridentity),22resourcewords1536, /// 23executionwords512or0,24capabilityGenerationWords32. Unused metadata zero. /// Slots0..3rankCPU, /// 4stall,5timeout,6..9staleCPU,10..11reserved; never overwritten on retry. #[used] #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D6_PROBE_OWNERSHIP: [u64; 768] = [0; 768]; static mut PROBE_SEQUENCE: u64 = 0; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct OwnershipFingerprint { pub slot: usize, pub sequence: u64, pub scope: u64, pub words: [u64; 4], } struct ProductAccess; impl Drop for ProductAccess { fn drop(&mut self) { unsafe { core::ptr::write_volatile( core::ptr::addr_of_mut!(BOUND_ALLOCATOR), core::ptr::null_mut(), ); } core::sync::atomic::compiler_fence(Ordering::SeqCst); unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(PRODUCT_BUSY), false); } } } fn product_access( runtime: Option<&mut OsK660Runtime>, f: impl FnOnce(&mut ProductOwners) -> Result, ) -> Result { #[cfg(target_arch = "aarch64")] { let el: u64; let daif: u64; unsafe { core::arch::asm!("mrs {el}, CurrentEL", "mrs {daif}, DAIF", el=out(reg) el, daif=out(reg) daif, options(nomem, nostack, preserves_flags)); } if el != 4 || daif & 0x3c0 != 0x3c0 { return Err("d6-owner-masked-el1-required"); } // This guard does not emulate synchronization. D5 authorizes CPU0 // alone when inactive, or the hardware-observed sole lease holder // during dispatch. Every other CPU fails before touching PRODUCT_BUSY, // the heap, capabilities, or the temporary allocator binding. super::d5_smp::authorize_service_cpu()?; } #[cfg(not(target_arch = "aarch64"))] if !cfg!(test) { return Err("d6-native-el1-required"); } // The actual heap/capability/frame observation owner occupies MEM40. // Process20 must be observed before entering; device inventory60 can be // borrowed separately by callers, never by creating an alias to its owner. #[cfg(target_arch = "aarch64")] let _rank = super::d5_smp::enter_rank(40)?; unsafe { if core::ptr::read_volatile(core::ptr::addr_of!(PRODUCT_BUSY)) { return Err("d6-owner-reentrant"); } core::ptr::write_volatile(core::ptr::addr_of_mut!(PRODUCT_BUSY), true); } core::sync::atomic::compiler_fence(Ordering::SeqCst); let _guard = ProductAccess; if let Some(runtime) = runtime { let memory = runtime.memory_mut().map_err(os_k660_policy::Error::tag)?; unsafe { core::ptr::write_volatile( core::ptr::addr_of_mut!(BOUND_ALLOCATOR), &mut memory.allocator as *mut memory::FrameAllocator, ); } } f(unsafe { &mut *core::ptr::addr_of_mut!(PRODUCT_OWNERS) }) } fn changed(owner: &mut ProductOwners) -> Result<(), &'static str> { RECONCILED.store(false, Ordering::Release); owner.finalized_epoch = UNKNOWN; owner.epoch = owner .epoch .checked_add(1) .ok_or("d6-owner-epoch-exhausted")?; Ok(()) } pub(super) fn invalidate() -> Result<(), &'static str> { product_access(None, changed) } pub(super) fn initialized() -> Result { product_access(None, |owner| Ok(owner.heap.is_some())) } fn require_process(id: super::process_owner::Id) -> Result { if matches!( super::process_owner::state(id)?, super::process_owner::State::Exited(_) ) { return Err("d6-owner-process-exited"); } u32::try_from(id.generation) .ok() .filter(|id| *id != 0) .ok_or("d6-owner-process-generation-range") } /// Noncopy message ownership retained by the actual IPC queue until receive. pub(super) struct Payload { handle: kernel_heap::Handle, owner: super::process_owner::Id, length: usize, } fn bound_free_pages() -> u64 { let pointer = unsafe { core::ptr::read_volatile(core::ptr::addr_of!(BOUND_ALLOCATOR)) }; if pointer.is_null() { UNKNOWN } else { unsafe { &*pointer }.remaining_pages() } } fn physical_prefix(payload: &Payload) -> [u64; 4] { let mut words = [0u64; 4]; for offset in 0..payload.length.min(32) { let byte = unsafe { core::ptr::read_volatile((payload.handle.address() + offset) as *const u8) }; words[offset / 8] |= u64::from(byte) << ((offset % 8) * 8); } words } fn heap_event( owner: &mut ProductOwners, kind: u64, payload: &Payload, prefix: [u64; 4], before: u64, after: u64, ) -> Result<(), &'static str> { raw_put(42, core::ptr::addr_of!(OS_PRODUCT_D6_HEAP_HISTORY) as u64); raw_put(43, 512); if owner.heap_events == 32 { owner.heap_event_overflow = owner .heap_event_overflow .checked_add(1) .ok_or("d6-heap-event-counter")?; raw_put(41, owner.heap_event_overflow); return Ok(()); } let count = owner .heap .as_ref() .ok_or("d6-heap-not-initialized")? .audit() .map_err(|_| "d6-heap-event-audit")? .objects; let words = [ kind, super::counter(), owner.epoch, payload.handle.address() as u64, payload.handle.generation(), payload.owner.slot as u64, payload.owner.generation, payload.length as u64, prefix[0], prefix[1], prefix[2], prefix[3], before, after, owner.heap_events as u64 + owner.heap_event_overflow + 1, count as u64, ]; for (index, value) in words.iter().copied().enumerate() { unsafe { core::ptr::write_volatile( core::ptr::addr_of_mut!(OS_PRODUCT_D6_HEAP_HISTORY) .cast::() .add(owner.heap_events * 16 + index), value, ); } } owner.heap_events += 1; raw_put(40, owner.heap_events as u64); raw_put(41, owner.heap_event_overflow); Ok(()) } pub(super) fn heap_allocate( runtime: &mut OsK660Runtime, id: super::process_owner::Id, bytes: &[u8], ) -> Result { let token = require_process(id)?; if bytes.is_empty() || bytes.len() > 2048 { return Err("d6-payload-size"); } product_access(Some(runtime), |owner| { changed(owner)?; let free_before = bound_free_pages(); let handle = owner .heap .as_mut() .ok_or("d6-heap-not-initialized")? .allocate(token, bytes.len(), 8, kernel_heap::Context::Task) .map_err(|_| "d6-payload-allocate")?; for (offset, byte) in bytes.iter().enumerate() { unsafe { core::ptr::write_volatile((handle.address() + offset) as *mut u8, *byte); } } owner.allocated = owner.allocated.checked_add(1).ok_or("d6-payload-counter")?; owner.bytes_written = owner .bytes_written .checked_add(bytes.len() as u64) .ok_or("d6-payload-counter")?; let payload = Payload { handle, owner: id, length: bytes.len(), }; heap_event( owner, 1, &payload, physical_prefix(&payload), free_before, bound_free_pages(), )?; Ok(payload) }) } pub(super) fn heap_read( payload: &Payload, id: super::process_owner::Id, output: &mut [u8], ) -> Result { require_process(id)?; if payload.owner != id || output.len() < payload.length { return Err("d6-payload-owner-or-buffer"); } product_access(None, |owner| { let heap = owner.heap.as_ref().ok_or("d6-heap-not-initialized")?; heap.audit().map_err(|_| "d6-payload-heap-audit")?; if !heap.object_records().any(|r| { r.address == payload.handle.address() && r.generation == payload.handle.generation() && r.owner == payload.handle.owner() && r.requested == payload.length }) { return Err("d6-payload-not-owned"); } for (offset, byte) in output[..payload.length].iter_mut().enumerate() { *byte = unsafe { core::ptr::read_volatile((payload.handle.address() + offset) as *const u8) }; } owner.bytes_read = owner .bytes_read .checked_add(payload.length as u64) .ok_or("d6-payload-counter")?; let mut prefix = [0u64; 4]; for (offset, byte) in output[..payload.length.min(32)].iter().copied().enumerate() { prefix[offset / 8] |= u64::from(byte) << ((offset % 8) * 8); } heap_event(owner, 2, payload, prefix, UNKNOWN, UNKNOWN)?; Ok(payload.length) }) } /// Failure borrows rather than consumes the token so the caller retains it. pub(super) fn heap_release( runtime: &mut OsK660Runtime, id: super::process_owner::Id, payload: &Payload, ) -> Result<(), &'static str> { if payload.owner != id { return Err("d6-payload-foreign-owner"); } product_access(Some(runtime), |owner| { changed(owner)?; let free_before = bound_free_pages(); let heap = owner.heap.as_ref().ok_or("d6-heap-not-initialized")?; heap.audit().map_err(|_| "d6-payload-heap-audit")?; if !heap.object_records().any(|r| { r.address == payload.handle.address() && r.generation == payload.handle.generation() && r.owner == payload.handle.owner() }) { return Err("d6-payload-not-owned"); } let prefix = physical_prefix(payload); owner .heap .as_mut() .ok_or("d6-heap-not-initialized")? .release( payload.handle, payload.handle.owner(), kernel_heap::Context::Task, ) .map_err(|_| "d6-payload-release")?; owner.released = owner.released.checked_add(1).ok_or("d6-payload-counter")?; heap_event(owner, 3, payload, prefix, free_before, bound_free_pages())?; Ok(()) }) } pub(super) fn channel_open(id: super::process_owner::Id, object: u64) -> Result { require_process(id)?; product_access(None, |owner| { changed(owner)?; owner .handles .open(id, handles::Object::Channel(object)) .map(|handle| handle.raw()) .map_err(|_| "d6-channel-handle-open") }) } pub(super) fn channel_validate( id: super::process_owner::Id, handle: u64, ) -> Result { require_process(id)?; product_access(None, |owner| { owner .handles .channel_send(id, handles::Handle::from_raw(handle)) .map_err(|_| "d6-channel-handle-refused") }) } pub(super) fn channel_close(id: super::process_owner::Id, handle: u64) -> Result<(), &'static str> { product_access(None, |owner| { changed(owner)?; owner .handles .close(id, handles::Handle::from_raw(handle)) .map_err(|_| "d6-channel-handle-close") }) } fn fingerprint_word(value: &mut u64, word: u64) { for byte in word.to_le_bytes() { *value = (*value ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3); } } /// Read-only fingerprint of the real capability owner, including generations /// of empty slots. No counters are substituted for rows and no table mutation /// occurs. Call before taking IPC rank 30; this operation owns only D6 state. pub(super) fn channel_inventory_fingerprint() -> Result { product_access(None, |owner| { let table = owner.handles.snapshot(); let mut hash = 0xcbf2_9ce4_8422_2325; fingerprint_word(&mut hash, 0x4436_4341_5053_3031); fingerprint_word(&mut hash, OWNER_CAPACITY as u64); for (index, entry) in table.entries.iter().enumerate() { fingerprint_word(&mut hash, index as u64); fingerprint_word(&mut hash, u64::from(table.generations[index])); fingerprint_word(&mut hash, u64::from(entry.is_some())); if let Some((raw, id, object, rights)) = entry { let (kind, object) = match *object { handles::Object::File(id) => (1, id), handles::Object::Channel(id) => (2, id), handles::Object::Task(id) => (3, id), }; let rights = u64::from(rights.contains(handles::Rights::READ)) | (u64::from(rights.contains(handles::Rights::WRITE)) << 1); for word in [*raw, id.slot as u64, id.generation, kind, object, rights] { fingerprint_word(&mut hash, word); } } } Ok(hash) }) } #[inline(never)] fn product_snapshot_into( owner: &ProductOwners, inventory: &NativeDmaInventory, value: &mut Snapshot, ) -> Result<(), &'static str> { value.native_valid = false; let pointer = unsafe { core::ptr::read_volatile(core::ptr::addr_of!(BOUND_ALLOCATOR)) }; if pointer.is_null() { return Err("d6-snapshot-runtime-unbound"); } value.frames.capture_into(unsafe { &*pointer })?; let heap_owner = owner.heap.as_ref().ok_or("d6-heap-not-initialized")?; let heap = value .heap .as_mut() .ok_or("d6-heap-scratch-not-initialized")?; heap.audit = heap_owner.audit().map_err(|_| "d6-heap-owner-audit")?; heap.objects.fill(None); heap.backing.fill(None); for (index, record) in heap_owner.object_records().enumerate() { if index == OWNER_CAPACITY { return Err("d6-heap-object-capacity"); } heap.objects[index] = Some(record); } for (index, record) in heap_owner.backing_records().enumerate() { if index == OWNER_CAPACITY { return Err("d6-heap-backing-capacity"); } heap.backing[index] = Some(record); } let handles = value .handles .as_mut() .ok_or("d6-handles-scratch-not-initialized")?; handles.fill(None); let table = owner.handles.snapshot(); for (index, entry) in table.entries.iter().enumerate() { if let Some((raw, id, object, rights)) = entry { let handle = handles::Handle::from_raw(*raw); if handle.slot() as usize != index + 1 || handle.generation() == 0 || handle.generation() != table.generations[index] || id.generation == 0 { return Err("d6-handle-generation-inventory"); } handles[index] = Some(HandleRecord { handle: *raw, owner: (id.slot as u64, id.generation), object: *object, rights: *rights, }); } } for record in inventory.records.iter().flatten() { if record.owner != super::boot_id()? { return Err("d6-dma-owner-different-boot"); } if !value.frames.live_addresses().contains(&record.address) { return Err("d6-dma-page-not-central-owner-live"); } if value .heap .as_ref() .ok_or("d6-heap-observation-missing")? .backing .iter() .flatten() .any(|backing| { record.address >= backing.address as u64 && record.address < backing.address as u64 + backing.pages as u64 * 4096 }) { return Err("d6-heap-dma-double-owner"); } } for backing in value .heap .as_ref() .ok_or("d6-heap-observation-missing")? .backing .iter() .flatten() { for page in 0..backing.pages { if !value .frames .live_addresses() .contains(&(backing.address as u64 + page as u64 * 4096)) { return Err("d6-heap-page-not-central-owner-live"); } } } let native = value .native_dma .as_mut() .ok_or("d6-dma-scratch-not-initialized")?; native.records.copy_from_slice(&inventory.records); native.device = inventory.device; native.epoch = inventory.epoch; native.reset_seen = inventory.reset_seen; value.native_valid = true; Ok(()) } fn raw_put(index: usize, value: u64) { unsafe { core::ptr::write_volatile( core::ptr::addr_of_mut!(OS_PRODUCT_D6_ACCOUNTING) .cast::() .add(index), value, ); } } /// Three exact 1536-word snapshots, phases baseline/live/final. Unused rows are /// zero, unobserved snapshots retain UNKNOWN. Raw layout is version one: /// header0..9, frameaudit16..22, counts32..34, freepairs48..175, /// live176..255, reservedpairs256..383, heapstats384..391, /// heapobjects400..591 (address,owner,generation,requested,capacity,valid), /// backing592..719 (address,pages,kind,class), handles720..975 /// (raw,pidslot,pidgen,kind,object,rights,valid,zero), DMA976..1103 /// (address,owner_epoch,owner,queue,kind,pins,active,quarantined). fn serialize(phase: usize, owner: &ProductOwners, value: &Snapshot) -> Result<(), &'static str> { if phase > 2 { return Err("d6-raw-phase"); } let destination = unsafe { core::ptr::addr_of_mut!(OS_PRODUCT_D6_INVENTORY) .cast::() .add(phase * 1536) }; serialize_at(destination, owner, value) } fn serialize_at( destination: *mut u64, owner: &ProductOwners, value: &Snapshot, ) -> Result<(), &'static str> { if destination.is_null() || !value.complete() { return Err("d6-raw-incomplete"); } let put = |index: usize, word: u64| { // SAFETY: callers supply one exclusively borrowed 1536-word region. unsafe { core::ptr::write_volatile(destination.add(index), word); } }; for index in 0..1536 { put(index, 0); } let heap = value.heap.as_ref().ok_or("d6-heap-owner-missing")?; let handles = value.handles.as_ref().ok_or("d6-handles-owner-missing")?; let dma = value .native_dma .as_ref() .ok_or("d6-native-dma-owner-missing")?; for (index, word) in [ 1, 15, owner.epoch, dma.device, dma.epoch, dma.reset_seen as u64, dma.len() as u64, heap.audit.objects as u64, heap.audit.backing_pages as u64, handles.iter().flatten().count() as u64, ] .iter() .copied() .enumerate() { put(index, word); } let a = value.frames.audit; for (index, word) in [ a.ram_full_pages, a.firmware_withheld_pages, a.boot_reserved_pages, a.authorized_pages, a.free_pages, a.reserved_pages, a.live_pages, ] .iter() .copied() .enumerate() { put(16 + index, word); } put(32, value.frames.free_len as u64); put(33, value.frames.live_len as u64); put(34, value.frames.reserved_len as u64); for (index, r) in value.frames.free[..value.frames.free_len] .iter() .enumerate() { put(48 + index * 2, r.start); put(49 + index * 2, r.end); } for (index, address) in value.frames.live_addresses().iter().copied().enumerate() { put(176 + index, address); } for (index, r) in value.frames.reserved[..value.frames.reserved_len] .iter() .enumerate() { put(256 + index * 2, r.start); put(257 + index * 2, r.end); } let a = heap.audit; for (index, word) in [ a.objects, a.requested_bytes, a.capacity_bytes, a.backing_pages, a.slab_pages, a.large_pages, a.quarantined_pages, a.retired_slots, ] .iter() .copied() .enumerate() { put(384 + index, word as u64); } for (index, r) in heap.objects.iter().enumerate() { if let Some(r) = r { for (field, word) in [ r.address as u64, r.owner as u64, r.generation, r.requested as u64, r.capacity as u64, 1, ] .iter() .copied() .enumerate() { put(400 + index * 6 + field, word); } } } for (index, r) in heap.backing.iter().enumerate() { if let Some(r) = r { let (kind, class) = match r.kind { kernel_heap::Kind::Slab(class) => (1, class as u64), kernel_heap::Kind::Large => (2, 0), kernel_heap::Kind::Quarantined => (3, 0), }; for (field, word) in [r.address as u64, r.pages as u64, kind, class] .iter() .copied() .enumerate() { put(592 + index * 4 + field, word); } } } for (index, r) in handles.iter().enumerate() { if let Some(r) = r { let (kind, object) = match r.object { handles::Object::File(id) => (1, id), handles::Object::Channel(id) => (2, id), handles::Object::Task(id) => (3, id), }; let rights = u64::from(r.rights.contains(handles::Rights::READ)) | (u64::from(r.rights.contains(handles::Rights::WRITE)) << 1); for (field, word) in [r.handle, r.owner.0, r.owner.1, kind, object, rights, 1, 0] .iter() .copied() .enumerate() { put(720 + index * 8 + field, word); } } } for (index, r) in dma.records.iter().enumerate() { if let Some(r) = r { for (field, word) in [ r.address, r.owner_epoch, r.owner, r.queue, r.kind, r.pins, r.active as u64, r.quarantined as u64, ] .iter() .copied() .enumerate() { put(976 + index * 8 + field, word); } } } Ok(()) } fn probe_put(slot: usize, word: usize, value: u64) { unsafe { core::ptr::write_volatile( core::ptr::addr_of_mut!(OS_PRODUCT_D6_PROBE_OWNERSHIP) .cast::() .add(slot * 64 + word), value, ); } } fn probe_get(slot: usize, word: usize) -> u64 { unsafe { core::ptr::read_volatile( core::ptr::addr_of!(OS_PRODUCT_D6_PROBE_OWNERSHIP) .cast::() .add(slot * 64 + word), ) } } fn probe_inventory(slot: usize, after: bool) -> *mut u64 { unsafe { core::ptr::addr_of_mut!(OS_PRODUCT_D6_PROBE_INVENTORY) .cast::() .add(slot * 4096 + if after { 2048 } else { 0 }) } } fn probe_hash(slot: usize, after: bool, scope: u64) -> [u64; 4] { let pointer = probe_inventory(slot, after); let mut hashes = [ 0xcbf2_9ce4_8422_2325, 0x6c62_272e_07bb_0142, 0x9e37_79b9_7f4a_7c15, 0xd6e8_feb8_6659_fd93, ]; for hash in &mut hashes { fingerprint_word(hash, 0x4436_5052_4f42_4531); fingerprint_word(hash, scope); for index in 0..if scope == 2 { 2048 } else { 1536 } { // Word2 is D6's observation/invalidation sequence, not an owning // resource identity. DMA owner epochs and heap generations remain. if index == 2 { continue; } fingerprint_word(hash, unsafe { core::ptr::read_volatile(pointer.add(index)) }); } } hashes } /// Pure exact comparison over canonical observed records. This is the actual /// admission comparison; hashes are compact diagnostic fingerprints only. fn probe_equal(before: &[u64], after: &[u64], execution: bool) -> (bool, bool) { if before.len() != 2048 || after.len() != 2048 { return (false, false); } let resources = (0..1536).all(|i| i == 2 || before[i] == after[i]); let processes = !execution || before[1536..] == after[1536..]; (resources, processes) } #[inline(never)] fn probe_generation_tail(owner: &ProductOwners, destination: *mut u64) { let table = owner.handles.snapshot(); for (index, generation) in table.generations.iter().copied().enumerate() { // SAFETY: caller holds product_access and supplies the unique live // probe resource span. Main baseline/live/final ABI is never changed. unsafe { core::ptr::write_volatile(destination.add(1104 + index), u64::from(generation)); } } } fn probe_capture( owner: &ProductOwners, inventory: &NativeDmaInventory, slot: usize, after: bool, execution: Option<&[u64; 512]>, ) -> Result<[u64; 4], &'static str> { // SAFETY: called only while product_access owns MEM40 and the exclusive D5 // lease. The ordinary snapshot scratch and the probe export are separate // storage; no reference crosses a service resume or outlives this call. let scratch = unsafe { &mut *core::ptr::addr_of_mut!(PRODUCT_SCRATCH) }; product_snapshot_into(owner, inventory, scratch)?; let destination = probe_inventory(slot, after); serialize_at(destination, owner, scratch)?; probe_generation_tail(owner, destination); for index in 0..512 { let word = execution.map_or(0, |words| words[index]); unsafe { core::ptr::write_volatile(destination.add(1536 + index), word); } } Ok(probe_hash( slot, after, if execution.is_some() { 2 } else { 1 }, )) } /// Capture actual owners before one rejected operation. Read-only with respect /// to every resource owner; only the separate bounded witness is written. A /// caller with an already borrowed D3 owner supplies its copied execution /// inventory from that valid borrow, avoiding recursive D3/process borrowing. pub(super) fn probe_ownership_begin( runtime: &mut OsK660Runtime, inventory: &NativeDmaInventory, slot: usize, execution: Option<&[u64; 512]>, ) -> Result { if slot >= 12 { return Err("d6-probe-slot"); } product_access(Some(runtime), |owner| { if probe_get(slot, 0) != 0 { return Err("d6-probe-slot-already-used"); } let sequence = unsafe { core::ptr::read_volatile(core::ptr::addr_of!(PROBE_SEQUENCE)) } .checked_add(1) .ok_or("d6-probe-sequence")?; unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(PROBE_SEQUENCE), sequence); } let scope = if execution.is_some() { 2 } else { 1 }; for word in 0..64 { probe_put(slot, word, 0); } for (word, value) in [ (0, 0x4436_5052_4f42_4531), (1, 1), (2, super::boot_id()?), (3, slot as u64), (4, scope), (5, 1), (6, sequence), (7, super::counter()), (9, UNKNOWN), (10, UNKNOWN), (20, owner.epoch), (22, 1536), (23, if execution.is_some() { 512 } else { 0 }), (24, 32), ] { probe_put(slot, word, value); } let words = match probe_capture(owner, inventory, slot, false, execution) { Ok(words) => words, Err(error) => { probe_put(slot, 5, 5); return Err(error); } }; for (index, word) in words.iter().copied().enumerate() { probe_put(slot, 12 + index, word); } probe_put(slot, 11, 1); Ok(OwnershipFingerprint { slot, sequence, scope, words, }) }) } /// Capture after and require complete exact records to match. A mismatch stays /// independently observable in its class slot and returns an error. No failed /// probe can be overwritten by another class or by a retry. pub(super) fn probe_ownership_finish( runtime: &mut OsK660Runtime, inventory: &NativeDmaInventory, before: OwnershipFingerprint, execution: Option<&[u64; 512]>, ) -> Result { if before.slot >= 12 { return Err("d6-probe-slot"); } product_access(Some(runtime), |owner| { let slot = before.slot; if probe_get(slot, 0) != 0x4436_5052_4f42_4531 || probe_get(slot, 1) != 1 || probe_get(slot, 2) != super::boot_id()? || probe_get(slot, 3) != slot as u64 || probe_get(slot, 4) != before.scope || probe_get(slot, 5) != 1 || probe_get(slot, 6) != before.sequence || probe_get(slot, 11) != 1 || before.scope != if execution.is_some() { 2 } else { 1 } || (0..4).any(|i| probe_get(slot, 12 + i) != before.words[i]) { return Err("d6-probe-token-or-scope"); } probe_put(slot, 8, super::counter()); probe_put(slot, 21, owner.epoch); let words = match probe_capture(owner, inventory, slot, true, execution) { Ok(words) => words, Err(error) => { probe_put(slot, 5, 5); return Err(error); } }; for (index, word) in words.iter().copied().enumerate() { probe_put(slot, 16 + index, word); } probe_put(slot, 11, 3); probe_put(slot, 5, 2); // SAFETY: both slots are fully initialized, disjoint 2048-word spans // under exclusive product_access. Slice comparison does not mutate. let left = unsafe { core::slice::from_raw_parts(probe_inventory(slot, false), 2048) }; let right = unsafe { core::slice::from_raw_parts(probe_inventory(slot, true), 2048) }; let (resources, processes) = probe_equal(left, right, execution.is_some()); probe_put(slot, 9, resources as u64); probe_put( slot, 10, if execution.is_some() { processes as u64 } else { UNKNOWN }, ); if !resources || !processes { probe_put(slot, 5, 4); return Err("d6-probe-actual-owner-changed"); } probe_put(slot, 5, 3); Ok(OwnershipFingerprint { slot, sequence: before.sequence, scope: before.scope, words, }) }) } /// Read-only strict-source gate over an already completed real probe. The /// requested scope is a bitmask:1 resource ownership,3 resource+execution. /// Stored ABI scopes remain enum1/enum2 respectively. Called under RUNQUEUE10 /// or by the boot CPU after real join/endmode; product_access still owns MEM40. pub(super) fn require_completed_probe( slot: usize, required_scope: u64, ) -> Result<(), &'static str> { if slot >= 12 || !matches!(required_scope, 1 | 3) { return Err("d6-required-probe-slot-or-scope"); } product_access(None, |_| { let scope = if required_scope == 3 { 2 } else { 1 }; if probe_get(slot, 0) != 0x4436_5052_4f42_4531 || probe_get(slot, 1) != 1 || probe_get(slot, 2) != super::boot_id()? || probe_get(slot, 3) != slot as u64 || probe_get(slot, 4) != scope || probe_get(slot, 5) != 3 || probe_get(slot, 6) == 0 || probe_get(slot, 7) == 0 || probe_get(slot, 7) >= probe_get(slot, 8) || probe_get(slot, 9) != 1 || probe_get(slot, 10) != if scope == 2 { 1 } else { UNKNOWN } || probe_get(slot, 11) != 3 || probe_get(slot, 20) > probe_get(slot, 21) || probe_get(slot, 22) != 1536 || probe_get(slot, 23) != if scope == 2 { 512 } else { 0 } || probe_get(slot, 24) != 32 || (25..64).any(|i| probe_get(slot, i) != 0) { return Err("d6-required-probe-incomplete"); } // SAFETY: slot bounds precede these disjoint, initialized exports. // The global lease and MEM40 exclude writers for the full comparison. let before = unsafe { core::slice::from_raw_parts(probe_inventory(slot, false), 2048) }; let after = unsafe { core::slice::from_raw_parts(probe_inventory(slot, true), 2048) }; if before[0] != 1 || before[1] != 15 || after[0] != 1 || after[1] != 15 || before[2] != probe_get(slot, 20) || after[2] != probe_get(slot, 21) || before[1104..1136] .iter() .chain(after[1104..1136].iter()) .any(|g| *g > u32::MAX as u64) || before[1136..1536] .iter() .chain(after[1136..1536].iter()) .any(|v| *v != 0) || (scope == 1 && before[1536..] .iter() .chain(after[1536..].iter()) .any(|v| *v != 0)) { return Err("d6-required-probe-raw-shape"); } let (resources, execution) = probe_equal(before, after, scope == 2); if !resources || !execution { return Err("d6-required-probe-actual-owner-changed"); } // Recomputed hashes are additional bindings; they never substitute // for the complete, exact raw comparison immediately above. let left = probe_hash(slot, false, scope); let right = probe_hash(slot, true, scope); if (0..4).any(|i| probe_get(slot, 12 + i) != left[i] || probe_get(slot, 16 + i) != right[i]) { return Err("d6-required-probe-fingerprint-binding"); } Ok(()) }) } fn summary(owner: &ProductOwners, phase: u64, value: &Snapshot) -> Result<(), &'static str> { let heap = value.heap.as_ref().ok_or("d6-summary-heap")?; raw_put(0, 0x4436_4143_4354_3031); // v2 adds real Scheduler retirement fields44/45 and the separately captured // before/after ownership probes. Historical v1 records retain their scope. raw_put(1, 2); raw_put(2, super::boot_id()?); raw_put(3, phase); raw_put(4, 15); raw_put(5, owner.epoch); raw_put(6, owner.finalized_epoch); raw_put(10, owner.allocated); raw_put(11, owner.released); raw_put(12, owner.bytes_written); raw_put(13, owner.bytes_read); raw_put(14, heap.audit.backing_pages as u64); raw_put(15, heap.audit.objects as u64); raw_put(16, owner.handles.len() as u64); raw_put( 17, value.native_dma.as_ref().ok_or("d6-summary-dma")?.len() as u64, ); Ok(()) } /// Called before D3 loads its first resident image. It does not reset live /// owners or erase a previous baseline. Device inventory must be borrowed from /// the actual not-yet-started D4 device owner at this same boot. pub(super) fn initialize( runtime: &mut OsK660Runtime, inventory: &NativeDmaInventory, ) -> Result<(), &'static str> { product_access(Some(runtime), |owner| { if owner.baseline_present || owner.heap.is_some() || owner.handles.len() != 0 || inventory.len() != 0 { return Err("d6-baseline-not-fresh"); } changed(owner)?; owner.heap = Some( ProductHeap::new(ProductBacking, super::boot_id()?) .map_err(|_| "d6-heap-initialize")?, ); // SAFETY: product_access holds the authorized global execution lease // and local reentry guard. This storage is disjoint from owner and // scratch; no reference escapes the closure or crosses an EL0 resume. let baseline = unsafe { &mut *core::ptr::addr_of_mut!(PRODUCT_BASELINE) }; product_snapshot_into(owner, inventory, baseline)?; serialize(0, owner, baseline)?; raw_put(7, 1); raw_put(8, 0); raw_put(9, 0); raw_put(40, 0); raw_put(41, 0); raw_put(42, core::ptr::addr_of!(OS_PRODUCT_D6_HEAP_HISTORY) as u64); raw_put(43, 512); summary(owner, 1, baseline)?; owner.baseline_present = true; Ok(()) }) } pub(super) fn observe_live( runtime: &mut OsK660Runtime, inventory: &NativeDmaInventory, ) -> Result<(), &'static str> { product_access(Some(runtime), |owner| { changed(owner)?; if !owner.baseline_present { return Err("d6-baseline-missing"); } // SAFETY: exclusive product_access ownership as for initialize; the // immutable baseline is separate storage and never overwritten here. let live = unsafe { &mut *core::ptr::addr_of_mut!(PRODUCT_SCRATCH) }; product_snapshot_into(owner, inventory, live)?; serialize(1, owner, live)?; summary(owner, 2, live)?; raw_put(8, 1); // Still-owned resources are classified as retained, not as leaks and // not as released. Only final exact reconciliation can close them. let baseline = unsafe { &*core::ptr::addr_of!(PRODUCT_BASELINE) }; let delta = Delta::between(baseline, live)?; raw_put(18, delta.newly_live_frames); raw_put(19, delta.missing_live_frames); raw_put(20, delta.final_dma_active); raw_put(21, delta.final_dma_quarantined); raw_put(22, 1); // active-workload retained classification Ok(()) }) } pub(super) fn finalize_shutdown( runtime: &mut OsK660Runtime, inventory: &NativeDmaInventory, ) -> Result<(), &'static str> { product_access(Some(runtime), |owner| { changed(owner)?; if !owner.baseline_present { return Err("d6-baseline-missing"); } // SAFETY: both storage regions have valid Rust initialization and are // borrowed only under product_access; neither overlaps ProductOwners. let final_state = unsafe { &mut *core::ptr::addr_of_mut!(PRODUCT_SCRATCH) }; product_snapshot_into(owner, inventory, final_state)?; serialize(2, owner, final_state)?; summary(owner, 3, final_state)?; raw_put(9, 1); let baseline = unsafe { &*core::ptr::addr_of!(PRODUCT_BASELINE) }; let delta = Delta::between(baseline, final_state)?; raw_put(23, delta.newly_live_frames); raw_put(24, delta.missing_live_frames); raw_put(25, delta.frame_inventory_changed as u64); raw_put(26, delta.heap_inventory_changed as u64); raw_put(27, delta.dma_inventory_changed as u64); raw_put(28, delta.handle_inventory_changed as u64); raw_put(29, delta.final_heap_quarantined_pages); raw_put(30, delta.final_dma_active); raw_put(31, delta.final_dma_quarantined); delta.require_reconciled()?; // A zero-use heap could be observed but cannot prove actual integration. if owner.allocated == 0 || owner.allocated != owner.released || owner.bytes_written == 0 || owner.bytes_read == 0 { return Err("d6-heap-not-used-by-real-service"); } if super::d5_smp::lifecycle_initialized() { super::d5_smp::require_scheduler_retired()?; raw_put(44, super::d5_smp::retired_tasks()?); raw_put(45, 1); } else { // No D5 owner existed in a historical non-D5 path. Missing is // explicit, never a fabricated zero-task retirement receipt. raw_put(44, UNKNOWN); raw_put(45, UNKNOWN); } owner.finalized_epoch = owner.epoch; raw_put(6, owner.finalized_epoch); raw_put(3, 4); raw_put(22, 2); RECONCILED.store(true, Ordering::Release); Ok(()) }) } /// ABI words: 0 version; 1..7 measured frame audit before; 8 allocated physical /// frame; 9 allocation generation; 10 free with lease; 11 free after; 12 exact /// restoration; 13 duplicate release refusal; 14..16 heap/DMA/handle UNKNOWN; /// 17 native classes observed bitmask (frame=1); 18 full reconciliation (0). /// This baseline can prove a real allocator cycle, but cannot bless absent /// integrated owner registries. It therefore returns an explicit error. pub fn run( runtime: &mut super::super::OsK660Runtime, _tables: &super::super::mmu::Tables, _boot: &super::super::BootData, out: &mut [u64; 32], ) -> Result<(), &'static str> { if initialized()? { let inventory = super::d4_device::accounting_inventory()?; observe_live(runtime, &inventory)?; out.fill(UNKNOWN); out[0] = 2; // actual complete owner observation; teardown still pending out[17] = 15; out[18] = 0; let pointer = core::ptr::addr_of!(OS_PRODUCT_D6_ACCOUNTING).cast::(); for index in 1..17 { out[index] = unsafe { core::ptr::read_volatile(pointer.add(index)) }; } return Ok(()); } RECONCILED.store(false, Ordering::Release); out.fill(UNKNOWN); out[0] = 1; out[18] = 0; let daif: u64; unsafe { core::arch::asm!("mrs {value}, DAIF", value = out(reg) daif, options(nomem, nostack, preserves_flags)); } if daif & 0x80 == 0 { return Err("d6-owner-observation-needs-irq-mask"); } let memory = runtime.memory_mut().map_err(os_k660_policy::Error::tag)?; let before = FrameSnapshot::capture(&memory.allocator)?; let audit = before.audit; out[1..8].copy_from_slice(&[ audit.ram_full_pages, audit.firmware_withheld_pages, audit.boot_reserved_pages, audit.authorized_pages, audit.free_pages, audit.reserved_pages, audit.live_pages, ]); let owner = memory.allocator.os_authority_mut(); let lease = owner.allocate().map_err(|_| "d6-native-frame-allocation")?; out[8] = lease.address(); out[9] = lease.generation(); // Always try to relinquish the actual typed lease even when its live-state // observation fails. Failed cleanup never manufactures a restored count. let observed_live = owner.audit(); let valid_lease = owner.validate_lease(&lease).is_ok(); owner .release(&lease) .map_err(|_| "d6-native-frame-release")?; let live = observed_live.map_err(|_| "d6-native-live-audit")?; out[10] = live.free_pages; if !valid_lease || live.free_pages.checked_add(1) != Some(audit.free_pages) || live.live_pages != audit.live_pages.checked_add(1).ok_or("d6-count-overflow")? { return Err("d6-native-frame-transition"); } out[13] = owner.release(&lease).is_err() as u64; if out[13] != 1 { return Err("d6-double-frame-release-accepted"); } let after = FrameSnapshot::capture(&memory.allocator)?; out[11] = after.audit.free_pages; before.require_restored(&after)?; out[12] = 1; out[17] = 1; Err("d6-accounting-missing-product-owner-registry") }