//! 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 == 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 { pub fn capture(allocator: &memory::FrameAllocator) -> Result { let owner = allocator.os_authority(); let mut snapshot = Self { audit: owner.audit().map_err(|_| "d6-frame-owner-audit")?, 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, }; 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(snapshot) } 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, } impl Snapshot { pub fn capture_frames(allocator: &memory::FrameAllocator) -> Result { Ok(Self { frames: FrameSnapshot::capture(allocator)?, heap: None, dma: None, handles: None, native_dma: None, }) } 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.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.is_none() || owner.finalized_epoch == UNKNOWN || owner.finalized_epoch != owner.epoch { return Err("d6-accounting-receipt-stale"); } Ok(()) }) } // The heap backend never retains an allocator reference across an API call. // Its pointer is bound only while the fully masked boot CPU borrows runtime. 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: Option, epoch: u64, finalized_epoch: u64, allocated: u64, released: u64, bytes_written: u64, bytes_read: u64, } static mut PRODUCT_OWNERS: ProductOwners = ProductOwners { heap: None, handles: ProductHandles::new(), baseline: None, epoch: 0, finalized_epoch: UNKNOWN, allocated: 0, released: 0, bytes_written: 0, bytes_read: 0, }; #[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]; 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 cpu: u64; let el: u64; let daif: u64; 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("d6-owner-masked-boot-cpu-required"); } } #[cfg(not(target_arch = "aarch64"))] if !cfg!(test) { return Err("d6-native-el1-required"); } 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, } 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 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")?; Ok(Payload { handle, owner: id, length: bytes.len(), }) }) } 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")?; 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)?; 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")?; 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 product_snapshot( owner: &ProductOwners, inventory: &NativeDmaInventory, ) -> Result { let pointer = unsafe { core::ptr::read_volatile(core::ptr::addr_of!(BOUND_ALLOCATOR)) }; if pointer.is_null() { return Err("d6-snapshot-runtime-unbound"); } let mut value = Snapshot::capture_frames(unsafe { &*pointer })?; value.observe_heap(owner.heap.as_ref().ok_or("d6-heap-not-initialized")?)?; value.observe_handles(&owner.handles, |id| (id.slot as u64, id.generation))?; for record in inventory.records.iter().flatten() { 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"); } } } value.native_dma = Some(inventory.clone()); Ok(value) } 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, ); } } fn snapshot_put(phase: usize, index: usize, value: u64) { unsafe { core::ptr::write_volatile( core::ptr::addr_of_mut!(OS_PRODUCT_D6_INVENTORY) .cast::() .add(phase * 1536 + 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 || !value.complete() { return Err("d6-raw-incomplete"); } for index in 0..1536 { snapshot_put(phase, 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() { snapshot_put(phase, 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() { snapshot_put(phase, 16 + index, word); } snapshot_put(phase, 32, value.frames.free_len as u64); snapshot_put(phase, 33, value.frames.live_len as u64); snapshot_put(phase, 34, value.frames.reserved_len as u64); for (index, r) in value.frames.free[..value.frames.free_len] .iter() .enumerate() { snapshot_put(phase, 48 + index * 2, r.start); snapshot_put(phase, 49 + index * 2, r.end); } for (index, address) in value.frames.live_addresses().iter().copied().enumerate() { snapshot_put(phase, 176 + index, address); } for (index, r) in value.frames.reserved[..value.frames.reserved_len] .iter() .enumerate() { snapshot_put(phase, 256 + index * 2, r.start); snapshot_put(phase, 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() { snapshot_put(phase, 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() { snapshot_put(phase, 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() { snapshot_put(phase, 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() { snapshot_put(phase, 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() { snapshot_put(phase, 976 + index * 8 + field, word); } } } 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); raw_put(1, 1); 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.is_some() || 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")?, ); let baseline = product_snapshot(owner, inventory)?; serialize(0, owner, &baseline)?; raw_put(7, 1); raw_put(8, 0); raw_put(9, 0); summary(owner, 1, &baseline)?; owner.baseline = Some(baseline); Ok(()) }) } pub(super) fn observe_live( runtime: &mut OsK660Runtime, inventory: &NativeDmaInventory, ) -> Result<(), &'static str> { product_access(Some(runtime), |owner| { changed(owner)?; if owner.baseline.is_none() { return Err("d6-baseline-missing"); } let live = product_snapshot(owner, inventory)?; 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 delta = Delta::between(owner.baseline.as_ref().ok_or("d6-baseline-missing")?, &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)?; let final_state = product_snapshot(owner, inventory)?; serialize(2, owner, &final_state)?; summary(owner, 3, &final_state)?; raw_put(9, 1); let delta = Delta::between( owner.baseline.as_ref().ok_or("d6-baseline-missing")?, &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"); } 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") }