diff --git a/crates/stela-boot-core/src/heap.rs b/crates/stela-boot-core/src/heap.rs index 29658a4007..f0cba8b6f0 100644 --- a/crates/stela-boot-core/src/heap.rs +++ b/crates/stela-boot-core/src/heap.rs @@ -1138,6 +1138,113 @@ unsafe impl GlobalAlloc for Heap { unsafe { release(state, pointer) }; } } + + unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + // SAFETY: GlobalAlloc's realloc contract guarantees that this size + // rounded to the original alignment fits in isize. + let new_layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; + if layout.size() == new_size { + return pointer; + } + let (old_class, new_class) = (class(layout), class(new_layout)); + if old_class.is_some() && old_class == new_class { + // The live block already has the full size-class capacity, and + // this resize leaves all class accounting and ownership intact. + return pointer; + } + if old_class.is_none() && new_class.is_none() { + let resized = { + let _guard = self.lock(); + // SAFETY: the guard excludes other accesses to the state. + let state = unsafe { &mut *self.state.get() }; + // SAFETY: the old layout identifies a live free-list block + // exclusively owned by the caller, and the lock is held. + let resized = unsafe { resize_large(state, pointer, new_size) }; + if resized { + state.live = state.live - layout.size() + new_size; + state.count_large(layout.size(), false); + state.count_large(new_size, true); + } + resized + }; + if resized { + self.count_own(layout, false); + self.count_own(new_layout, true); + return pointer; + } + } + // SAFETY: both layouts meet GlobalAlloc's realloc contract. A new + // successful allocation is disjoint, and only then can the old one + // be freed. On failure the old owner keeps its block. + unsafe { + let next = self.alloc(new_layout); + if !next.is_null() { + ptr::copy_nonoverlapping(pointer, next, layout.size().min(new_size)); + self.dealloc(pointer, layout); + } + next + } + } +} + +/// Resize a free-list allocation without moving its payload, using or +/// returning the following free space in the same pool. +/// +/// # Safety +/// The heap's lock is held. `pointer` identifies a live free-list block, +/// exclusively owned by the caller, and `new_size` is nonzero. +unsafe fn resize_large(state: &mut State, pointer: *mut u8, new_size: usize) -> bool { + let Some(wanted) = aligned(new_size, GRANULE).and_then(|bytes| bytes.checked_add(HEADER_BYTES)) + else { + return false; + }; + // SAFETY: the old block and its neighbours have live headers, and the + // lock protects both the boundary tags and bins. The replacement header + // lies beyond the retained payload and inside the old or joined block. + unsafe { + let block = pointer.sub(HEADER_BYTES).cast::
(); + let old_bytes = size(block); + if wanted == old_bytes { + return true; + } + let following = block as usize + old_bytes; + let next = following as *mut Header; + let join = following < state.end && following != state.floor && (*next).size & FREE != 0; + let available = if join { + old_bytes + size(next) + } else { + old_bytes + }; + if wanted > available { + return false; + } + let new_bytes = if available - wanted >= MIN_BLOCK { + wanted + } else { + available + }; + if join { + state.remove(next); + } + (*block).size = new_bytes | ((*block).size & PREVIOUS_FREE); + if new_bytes < available { + let rest = (block as usize + new_bytes) as *mut Header; + rest.write(Header { + previous: block as usize, + size: (available - new_bytes) | FREE, + }); + state.tell_following(rest); + state.insert(rest); + } else { + state.tell_following(block); + } + state.carved = state.carved - old_bytes + new_bytes; + if block as usize >= state.floor { + state.carved_reserve = state.carved_reserve - old_bytes + new_bytes; + } + state.peak = state.peak.max(state.carved); + } + true } /// Where a payload of `payload` bytes aligned to `alignment` fits in free diff --git a/crates/stela-boot-core/src/heap/tests.rs b/crates/stela-boot-core/src/heap/tests.rs index 51f1ff753c..fca3b30937 100644 --- a/crates/stela-boot-core/src/heap/tests.rs +++ b/crates/stela-boot-core/src/heap/tests.rs @@ -391,6 +391,129 @@ fn size_class_reuse_preserves_other_live_bytes() { assert_eq!(heap.usage().live, 0); } +#[test] +fn resizing_within_a_size_class_keeps_the_allocation() { + let heap = Heap::new(); + let mut ram = backing(); + let layout = Layout::from_size_align(50, 16).unwrap(); + let smaller = Layout::from_size_align(34, 16).unwrap(); + let larger = Layout::from_size_align(62, 16).unwrap(); + let next_class = Layout::from_size_align(65, 16).unwrap(); + // SAFETY: exclusive backing, valid nonzero layouts, and each resize + // receives the immediately preceding live allocation and layout. + unsafe { + heap.initialize(ram.0.as_mut_ptr(), ram.0.len()); + let before = heap.alloc(layout); + assert!(!before.is_null()); + before.write_bytes(0x5a, layout.size()); + let usage = usage_values(&heap); + let after = heap.realloc(before, layout, larger.size()); + assert_eq!(after, before); + assert_eq!(usage_values(&heap), usage); + let shrunk = heap.realloc(after, larger, smaller.size()); + assert_eq!(shrunk, after); + assert_eq!(usage_values(&heap), usage); + let moved = heap.realloc(shrunk, smaller, next_class.size()); + assert!(!moved.is_null() && moved != shrunk); + assert_eq!( + core::slice::from_raw_parts(moved, smaller.size()), + &[0x5a; 34] + ); + heap.dealloc(moved, next_class); + } + assert_eq!(heap.usage().live, 0); +} + +#[test] +fn large_resize_uses_the_right_extent_and_preserves_live_neighbours() { + let heap = Heap::new(); + let mut ram = backing(); + let layout = |kib: usize| Layout::from_size_align(kib * 1024, 16).unwrap(); + let (original, gap, guard) = (layout(28), layout(68), layout(28)); + let (grown, shrunk, reused) = (layout(90), layout(20), layout(70)); + // SAFETY: the backing stays exclusive, and each operation uses a live + // allocation with the layout most recently assigned to it. + unsafe { + heap.initialize(ram.0.as_mut_ptr(), ram.0.len()); + let block = heap.alloc(original); + let neighbour = heap.alloc(gap); + let sentinel = heap.alloc(guard); + assert!(!block.is_null() && !neighbour.is_null() && !sentinel.is_null()); + block.write_bytes(0x5a, original.size()); + sentinel.write_bytes(0xa5, guard.size()); + heap.dealloc(neighbour, gap); + + let before = heap.usage(); + assert!(before.largest < grown.size()); + let larger = heap.realloc(block, original, grown.size()); + assert_eq!(larger, block); + let after = heap.usage(); + assert_eq!(after.carves, before.carves); + assert_eq!(after.live, grown.size() + guard.size()); + assert_eq!(after.large[large_bucket(grown.size())], (1, grown.size())); + assert!( + core::slice::from_raw_parts(larger, original.size()) + .iter() + .all(|&byte| byte == 0x5a) + ); + + let smaller = heap.realloc(larger, grown, shrunk.size()); + assert_eq!(smaller, larger); + assert_eq!(heap.usage().live, shrunk.size() + guard.size()); + let reuse = heap.alloc(reused); + assert!(!reuse.is_null()); + assert!(reuse.addr() > smaller.addr() && reuse.addr() < sentinel.addr()); + reuse.write_bytes(0xc3, reused.size()); + assert!( + core::slice::from_raw_parts(smaller, shrunk.size()) + .iter() + .all(|&byte| byte == 0x5a) + ); + assert!( + core::slice::from_raw_parts(sentinel, guard.size()) + .iter() + .all(|&byte| byte == 0xa5) + ); + heap.dealloc(smaller, shrunk); + heap.dealloc(sentinel, guard); + heap.dealloc(reuse, reused); + } + let after = heap.usage(); + assert_eq!((after.live, after.carved, after.extents), (0, 0, 1)); + assert_eq!(after.largest, ram.0.len()); +} + +#[test] +fn failed_large_growth_preserves_the_owner_and_the_reserve_boundary() { + let heap = Heap::new(); + let mut ram = backing(); + let reserve = 32 * 1024; + let original = Layout::from_size_align(ram.0.len() - reserve - HEADER_BYTES, 16).unwrap(); + // SAFETY: exclusive backing, with one main-pool allocation held through + // the failed growth and returned using its unchanged layout. + unsafe { + heap.initialize(ram.0.as_mut_ptr(), ram.0.len()); + heap.reserve_tail(reserve); + let block = heap.alloc(original); + assert!(!block.is_null()); + block.write_bytes(0x96, original.size()); + let before = usage_values(&heap); + assert!( + heap.realloc(block, original, original.size() + GRANULE) + .is_null() + ); + assert_eq!(usage_values(&heap), before); + assert!( + core::slice::from_raw_parts(block, original.size()) + .iter() + .all(|&byte| byte == 0x96) + ); + heap.dealloc(block, original); + } + let after = heap.usage(); + assert_eq!((after.live, after.carved, after.extents), (0, 0, 2)); +} + #[test] fn the_class_lists_return_to_the_bins_when_a_request_needs_them() { let mut ram = backing(); diff --git a/crates/stela-boot-core/src/memory_budget.rs b/crates/stela-boot-core/src/memory_budget.rs index 55cf1c8936..a3baeedcc1 100644 --- a/crates/stela-boot-core/src/memory_budget.rs +++ b/crates/stela-boot-core/src/memory_budget.rs @@ -4,6 +4,10 @@ const PAGE: u64 = 4096; const MIB: u64 = 1024 * 1024; const MINIMUM: u64 = 16 * MIB; const MAXIMUM: u64 = 384 * MIB; + +/// Largest persistent translation pack the mount reads into firmware RAM. +pub const MAX_TRANSLATION_PACK_BYTES: u64 = 1024 * MIB; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct InsufficientMemory; impl fmt::Display for InsufficientMemory { diff --git a/crates/stela-boot-core/src/native_resources.rs b/crates/stela-boot-core/src/native_resources.rs index f1bc407163..e1536c23bd 100644 --- a/crates/stela-boot-core/src/native_resources.rs +++ b/crates/stela-boot-core/src/native_resources.rs @@ -2,6 +2,8 @@ //! shadow pool. Each executor owns its own ranges; none is shared. use crate::Result; use crate::topology::MAX_CORES; +use alloc::vec::Vec; +use core::ops::Range; use stela_contracts::refuse; const PAGE: u64 = 4096; @@ -9,6 +11,60 @@ const PAGE: u64 = 4096; pub const STACK_BYTES: u64 = 2 * 1024 * 1024; pub const STACK_STRIDE: u64 = STACK_BYTES + PAGE; pub const INVOCATION_STACK_BYTES: u64 = 128 * 1024; +pub const CODE_INSTALL_ALIGNMENT: u64 = 16; + +/// Initialized code extents of one private arena part, stored by exclusive +/// end. Installs start at the aligned end of the preceding one, so retaining +/// that start as well would duplicate information. +#[derive(Default)] +pub struct CodeExtents(Vec); + +impl CodeExtents { + /// Reserve one ledger entry, initialize its code, then record the extent. + /// A refusal leaves both the ledger and its code unchanged. + pub fn append( + &mut self, + part_bytes: u64, + code_bytes: usize, + initialize: impl FnOnce(u64), + ) -> Option> { + let previous = u64::from(self.0.last().copied().unwrap_or(0)); + let start = previous.next_multiple_of(CODE_INSTALL_ALIGNMENT); + let end = start.checked_add(code_bytes as u64)?; + if code_bytes == 0 || end > part_bytes { + return None; + } + let finish = u32::try_from(end).ok()?; + self.0.try_reserve(1).ok()?; + initialize(start); + self.0.push(finish); + Some(start..end) + } + + /// Whether one install owns the whole part-relative interval. Alignment + /// gaps and spans across separately initialized installs are refused. + pub fn contains(&self, range: Range) -> bool { + if range.is_empty() { + return false; + } + let index = self.0.partition_point(|&end| u64::from(end) <= range.start); + self.0.get(index).is_some_and(|&end| { + let previous = if index == 0 { 0 } else { self.0[index - 1] }; + let start = u64::from(previous).next_multiple_of(CODE_INSTALL_ALIGNMENT); + start <= range.start && range.end <= u64::from(end) + }) + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Forget a part's code when the ring reuses it, keeping the ledger's + /// capacity ready for new code. + pub fn clear(&mut self) { + self.0.clear(); + } +} pub fn invocation_stacks( cores: usize, @@ -113,6 +169,50 @@ pub fn partition( mod tests { use super::*; + #[test] + fn installed_code_extents_cover_only_individual_initialized_ranges() { + let mut ledger = CodeExtents::default(); + let mut exact = Vec::new(); + for bytes in [13, 16, 2, 9, 25, 1] { + let start = exact.last().map_or(0, |range: &Range| { + range.end.next_multiple_of(CODE_INSTALL_ALIGNMENT) + }); + let range = ledger + .append(128, bytes, |at| assert_eq!(at, start)) + .unwrap(); + assert_eq!(range, start..start + bytes as u64); + exact.push(range); + } + for start in 0..=128 { + for end in start..=129 { + let expected = start < end + && exact + .iter() + .any(|extent| extent.start <= start && end <= extent.end); + assert_eq!(ledger.contains(start..end), expected, "{start}..{end}"); + } + } + ledger.clear(); + assert!(ledger.is_empty()); + assert!(!ledger.contains(0..1)); + assert_eq!(ledger.append(64, 7, |_| {}), Some(0..7)); + } + + #[test] + fn refused_code_installs_leave_the_end_and_backing_untouched() { + let mut ledger = CodeExtents::default(); + assert_eq!(ledger.append(32, 13, |_| {}), Some(0..13)); + assert_eq!(ledger.append(32, 0, |_| panic!("empty code")), None); + assert_eq!(ledger.append(32, 17, |_| panic!("over the part")), None); + assert_eq!( + ledger.append(u64::MAX, u32::MAX as usize, |_| panic!("over the ledger")), + None + ); + assert_eq!(ledger.append(32, 16, |_| {}), Some(16..32)); + assert!(!ledger.contains(13..16)); + assert!(ledger.contains(16..32)); + } + #[test] fn task_plan_keeps_exact_payload_padding_guards_and_classes() { let layout = task_stacks(0x8_0000_0000).unwrap(); diff --git a/crates/stela-boot-core/src/options.rs b/crates/stela-boot-core/src/options.rs index 9743c70329..088b435382 100644 --- a/crates/stela-boot-core/src/options.rs +++ b/crates/stela-boot-core/src/options.rs @@ -338,6 +338,8 @@ pub struct System { pub traces: Vec, /// Log raw guarded entries, exits, exceptions and returns (`--monitor-trace`). pub monitor_trace: bool, + /// Log every display swap's DCP calls, present and callback (`--display-trace`). + pub display_trace: bool, /// Log every device access in these physical ranges (`--watch BASE,BYTES`). pub watches: Vec<(u64, u64)>, /// Guest virtual ranges the stop's report shows (`--dump BASE,BYTES`). @@ -408,6 +410,7 @@ impl Default for System { breakpoints: Vec::new(), traces: Vec::new(), monitor_trace: false, + display_trace: false, watches: Vec::new(), dumps: Vec::new(), } @@ -757,6 +760,7 @@ impl fmt::Display for System { line.flag("--serialized", !self.parallel && !implied_serial)?; line.flag("--profile", self.profile)?; line.flag("--monitor-trace", self.monitor_trace)?; + line.flag("--display-trace", self.display_trace)?; line.value("--network-check", self.network_check.as_deref())?; line.value("--audio-check", self.audio_check.map(AudioCheck::name))?; if self.dram_explicit { diff --git a/crates/stela-boot-core/src/options/parse.rs b/crates/stela-boot-core/src/options/parse.rs index 676601cd99..9cd3a44b3f 100644 --- a/crates/stela-boot-core/src/options/parse.rs +++ b/crates/stela-boot-core/src/options/parse.rs @@ -38,6 +38,7 @@ impl ParseState<'_> { "--profile" => options.profile = true, MAINTENANCE_WRITE => options.maintenance_write = true, "--monitor-trace" => options.monitor_trace = true, + "--display-trace" => options.display_trace = true, "--native-shared-check" => flag( &mut options.native_shared_check, Error::DuplicateNativeShared, diff --git a/crates/stela-boot-core/src/options/tests.rs b/crates/stela-boot-core/src/options/tests.rs index 4fd02226b7..44393720c3 100644 --- a/crates/stela-boot-core/src/options/tests.rs +++ b/crates/stela-boot-core/src/options/tests.rs @@ -99,13 +99,15 @@ fn every_option_survives_a_round_trip() { "--system --storage {DISK} --nor {DISK} --bundle b --install p.json \ --install-source 11111111-2222-3333-4444-555555555555 --tss --verify-on-read \ --usb-storage A --usb-storage B --input --idle-skip --sep-observe --native-cores 3 \ - --native-artifacts --serialized --profile --monitor-trace \ + --native-artifacts --serialized --profile --monitor-trace --display-trace \ --network-check http://h/p --audio-check transport-duplex --dram-base 0x10000000000 \ --load 0x10000004000 --entry 0x10000008000 --x0 7 --budget 99 --break 0x10 \ --trace 0x20 --watch 0x30,0x40 --dump x21-0x8,0x10 --dump 0x50,0x60" )); assert_eq!(options.usb_storage, ["A", "B"]); assert_eq!(options.audio_check, Some(AudioCheck::TransportDuplex)); + assert!(options.display_trace); + assert!(!System::default().display_trace); assert!(!options.parallel); assert_eq!(options.dumps[0], (Base::Register(21, -8), 0x10)); let restore = round_trip(&format!( diff --git a/crates/stela-boot-core/src/page_window.rs b/crates/stela-boot-core/src/page_window.rs index b1619c90e9..ea89c7b8b2 100644 --- a/crates/stela-boot-core/src/page_window.rs +++ b/crates/stela-boot-core/src/page_window.rs @@ -99,6 +99,20 @@ pub fn indices(address: u64) -> [usize; 3] { ] } +/// Group the leaf slots of a validated page range by their parent table. +pub fn leaf_runs(address: u64, pages: usize) -> impl Iterator)> { + let mut offset = 0; + core::iter::from_fn(move || { + if offset == pages { + return None; + } + let [pointer, directory, first] = indices(address + offset as u64 * PAGE); + let count = (ENTRIES as usize - first).min(pages - offset); + offset += count; + Some((pointer, directory, first..first + count)) + }) +} + /// The page window of the engine's window at `base`: the rest of the /// directory-pointer table its fixed parts start. pub fn span(base: u64) -> core::ops::Range { @@ -188,6 +202,20 @@ mod tests { const GIB: u64 = 1 << 30; + #[test] + fn leaf_runs_cover_exactly_the_requested_slots_across_table_boundaries() { + let address = GIB - 2 * PAGE; + assert_eq!( + leaf_runs(address, 516).collect::>(), + [(0, 511, 510..512), (1, 0, 0..512), (1, 1, 0..2)] + ); + assert_eq!(leaf_runs(address, 0).next(), None); + assert_eq!( + leaf_runs(!(PAGE - 1), 1).collect::>(), + [(511, 511, 511..512)] + ); + } + #[test] fn retiring_ranges_remain_excluded_until_acknowledged() { let mut retiring = Retirements::default(); diff --git a/crates/stela-boot-core/src/topology.rs b/crates/stela-boot-core/src/topology.rs index 7903af59a0..5d350d7358 100644 --- a/crates/stela-boot-core/src/topology.rs +++ b/crates/stela-boot-core/src/topology.rs @@ -336,13 +336,17 @@ pub fn common_native_target( const POPCNT: u32 = 1 << 23; const AES: u32 = 1 << 25; const SHA: u32 = 1 << 29; + const GFNI: u32 = 1 << 8; + const LZCNT: u32 = 1 << 5; const CX8: u32 = 1 << 8; const CX16: u32 = 1 << 13; if observations.is_empty() || observations.len() > MAX_CORES { return Err(CapabilityRefusal::InvalidSnapshot); } - let (mut ecx, mut edx, mut structured) = (u32::MAX, u32::MAX, u32::MAX); + let (mut ecx, mut edx, mut structured_ebx, mut structured_ecx) = + (u32::MAX, u32::MAX, u32::MAX, u32::MAX); let mut atomic16 = true; + let mut lzcnt = true; for snapshot in observations { let vendor = snapshot .get(0, 0) @@ -353,11 +357,19 @@ pub fn common_native_target( .ok_or(CapabilityRefusal::InvalidSnapshot)?; ecx &= basic.ecx; edx &= basic.edx; - structured &= if vendor.eax >= 7 { - snapshot.get(7, 0).map_or(0, |record| record.ebx) + let structured = if vendor.eax >= 7 { + snapshot.get(7, 0).unwrap_or_default() } else { - 0 + Cpuid::default() }; + structured_ebx &= structured.ebx; + structured_ecx &= structured.ecx; + lzcnt &= snapshot + .get(0x8000_0000, 0) + .is_some_and(|maximum| maximum.eax >= 0x8000_0001) + && snapshot + .get(0x8000_0001, 0) + .is_some_and(|record| record.ecx & LZCNT != 0); atomic16 &= TargetCpu::atomic_load16_guaranteed([vendor.ebx, vendor.edx, vendor.ecx], basic.ecx); } @@ -374,7 +386,9 @@ pub fn common_native_target( ), (ecx & POPCNT != 0, TargetCpu::with_popcnt), (ecx & AES != 0, TargetCpu::with_aes), - (structured & SHA != 0, TargetCpu::with_sha), + (structured_ebx & SHA != 0, TargetCpu::with_sha), + (structured_ecx & GFNI != 0, TargetCpu::with_gfni), + (lzcnt, TargetCpu::with_lzcnt), (edx & CX8 != 0, TargetCpu::with_cx8), (ecx & CX16 != 0, TargetCpu::with_cx16), (atomic16, TargetCpu::with_atomic_load16), diff --git a/crates/stela-boot-core/src/topology/tests.rs b/crates/stela-boot-core/src/topology/tests.rs index 21b459b33b..e74edbc485 100644 --- a/crates/stela-boot-core/src/topology/tests.rs +++ b/crates/stela-boot-core/src/topology/tests.rs @@ -675,6 +675,43 @@ fn common_target_obeys_leaf_maxima_vendor_atomicity_and_complete_sse_tiers() { ); } +#[test] +fn common_target_keeps_legacy_extensions_independently_and_checks_both_leaf_maxima() { + use stela_compiler::TargetCpu; + let mut rich = target_snapshot(TargetCpu::INTEL_VENDOR); + rich.records[0].ecx &= !((1 << 19) | (1 << 20) | (1 << 28)); + rich.records[1].ecx |= 1 << 5; + rich.records[2].ecx |= 1 << 8; + rich.records[4] = Cpuid { + leaf: 0x8000_0000, + eax: 0x8000_0001, + ..Cpuid::default() + }; + rich.count = 5; + let mut older = rich; + for (maximum, feature_lost, feature_kept) in [ + (3, TargetCpu::Gfni, TargetCpu::Lzcnt), + (4, TargetCpu::Lzcnt, TargetCpu::Gfni), + ] { + older.records[maximum].eax -= 1; + let common = common_native_target(&[&rich, &older]).unwrap(); + assert!(common.supports(TargetCpu::Ssse3)); + assert!(!common.supports(TargetCpu::Sse41)); + assert!(common.supports(feature_kept)); + assert!(!common.supports(feature_lost)); + assert!(!common.supports(TargetCpu::Fma)); + older = rich; + } + let common = common_native_target(&[&rich, &older]).unwrap(); + assert!(common.supports(TargetCpu::Gfni.with_lzcnt())); + older.count -= 1; + assert!( + !common_native_target(&[&rich, &older]) + .unwrap() + .supports(TargetCpu::Lzcnt) + ); +} + #[test] fn core_floor_and_la57_are_required_independently_of_bsp() { let baseline = native_snapshot(); diff --git a/crates/stela-boot-core/src/xstate/owner.rs b/crates/stela-boot-core/src/xstate/owner.rs index b326f1467d..d004614582 100644 --- a/crates/stela-boot-core/src/xstate/owner.rs +++ b/crates/stela-boot-core/src/xstate/owner.rs @@ -277,6 +277,7 @@ mod tests { fn each_entry_accounts_for_its_own_image_metadata_and_alignment_slop() { // Private layout/extent model only, not a CPU owner or save. let owner = XstateOwner { + #[cfg(target_arch = "x86_64")] processor: 0, layout: layout(), _local: PhantomData, diff --git a/crates/stela-boot/src/engine.rs b/crates/stela-boot/src/engine.rs index 7eae34148e..2a4eb37e4e 100644 --- a/crates/stela-boot/src/engine.rs +++ b/crates/stela-boot/src/engine.rs @@ -220,6 +220,10 @@ fn development_hardware_model(tree: &mut DeviceTree) -> Result { "the selected Apple board hardware model is not first in compatible" )); } + // A prepared bundle may already carry the development identity. + if value.ends_with(b"DEV") { + return Ok(target); + } let mut development_compatible = Vec::with_capacity(compatible.len()); development_compatible.extend_from_slice(target.as_bytes()); development_compatible.push(0); @@ -701,6 +705,14 @@ fn run_machine( if !options.breakpoints.is_empty() { machine.set_breakpoints(&options.breakpoints); } + machine + .devices + .with(|devices| devices.set_display_swap_tracing(options.display_trace)); + if options.display_trace { + output::arguments(format_args!( + "DISPLAY TRACE enabled: per-swap DCP reports\n" + )); + } machine.set_monitor_tracing(options.monitor_trace); if options.monitor_trace { output::arguments(format_args!( diff --git a/crates/stela-boot/src/engine/bundle.rs b/crates/stela-boot/src/engine/bundle.rs index 1dff2ede99..9626a48d9c 100644 --- a/crates/stela-boot/src/engine/bundle.rs +++ b/crates/stela-boot/src/engine/bundle.rs @@ -486,7 +486,7 @@ pub(super) fn entropy(buffer: &mut [u8]) -> Result<()> { /// The bundle's `bundle.json`, from the files the loader read or a bundle /// built in the heap. -fn manifest(files: &[File], built: Option<&[(String, Vec)]>) -> Result { +pub(super) fn manifest(files: &[File], built: Option<&[(String, Vec)]>) -> Result { let json = match built { Some(built) => built .iter() @@ -501,18 +501,6 @@ fn manifest(files: &[File], built: Option<&[(String, Vec)]>) -> Result)]>) -> Result { - Ok(manifest(files, built)?.options.dram_base) -} - -/// Whether the bundle's system was personalized for a development board. -pub fn development_board(files: &[File], built: Option<&[(String, Vec)]>) -> Result { - Ok(manifest(files, built)? - .target - .is_some_and(|target| target.device_class.ends_with("dev"))) -} - /// The guest's DRAM: `backed` bytes of host RAM from `base`, within the /// `installed` bytes the Mac reports. #[derive(Debug, Clone, Copy)] diff --git a/crates/stela-boot/src/engine/gpu/display.rs b/crates/stela-boot/src/engine/gpu/display.rs index 1d4f3a1baa..f9cbd85f55 100644 --- a/crates/stela-boot/src/engine/gpu/display.rs +++ b/crates/stela-boot/src/engine/gpu/display.rs @@ -9,7 +9,7 @@ use crate::{Result, output}; use alloc::{boxed::Box, format}; use core::{cell::UnsafeCell, ffi::c_int, ffi::c_void, ptr::NonNull}; use stela_contracts::refuse; -use stela_drivers::gpu::metal::kms::{Display, Drm}; +use stela_drivers::gpu::metal::kms::{Display, Drm, Error as DisplayError}; use stela_soc::machine::{Scanout, ScanoutFormat, ScanoutMode}; /// A GPU's primary node, the DRM master. @@ -47,6 +47,23 @@ impl Scanout for KmsScanout { fn present(&mut self, rows: &[u8]) -> Result<()> { console::release(); let presented = self.0.present(rows); + self.finish_present(presented) + } + + fn try_present_rows( + &mut self, + fill: &mut dyn FnMut(usize, &mut [u8]) -> Result<()>, + ) -> Result { + let prepared = self.0.prepare_rows(fill)?; + console::release(); + let presented = prepared.present(); + self.finish_present(presented)?; + Ok(true) + } +} + +impl KmsScanout { + fn finish_present(&self, presented: Result<(), DisplayError>) -> Result<()> { // A stop's reason shows on the buffer that does. console::parked_on(screen(&self.0)); presented.map_err(|error| { diff --git a/crates/stela-boot/src/engine/host.rs b/crates/stela-boot/src/engine/host.rs index b8b1973fdd..23d9f52cc1 100644 --- a/crates/stela-boot/src/engine/host.rs +++ b/crates/stela-boot/src/engine/host.rs @@ -33,6 +33,7 @@ use crate::{ }; use alloc::{sync::Arc, vec::Vec}; use core::arch::{asm, global_asm}; +use stela_boot_core::native_resources::{CODE_INSTALL_ALIGNMENT, CodeExtents}; use stela_compiler::{GuestState, block::BlockExit}; use stela_contracts::refuse; use stela_engine::machine::FaultCause; @@ -234,6 +235,8 @@ struct Bank { used: u64, } const ROOTS: usize = 2 * VIEWS; +const SHADOW_ROOTS: usize = ROOTS * (BANKS + 1); +const _: () = assert!(SHADOW_ROOTS <= u64::BITS as usize); /// Root `view`'s TLB context while PCIDE is set. const fn view_context(view: usize) -> u64 { @@ -301,22 +304,29 @@ impl Contexts { fn forget(&mut self, page: u64, current: usize) { invlpg(page); for view in 0..ROOTS { - if view == current || self.stale[view] { - continue; - } - if self.invpcid { - let descriptor = [view_context(view), page]; - // SAFETY: a valid single-address INVPCID of a tagged context: - // a context is fresh only under PCIDE ([`State::load_view`]). - unsafe { - asm!("invpcid {}, [{}]", in(reg) 0u64, in(reg) &descriptor, - options(nostack, preserves_flags)) - }; - } else { - self.stale[view] = true; + if view != current { + self.forget_inactive(page, view); } } } + + /// Drop a page from one inactive view, whose context can be retained + /// across CR3 loads only while tagged and fresh. + fn forget_inactive(&mut self, page: u64, view: usize) { + if !self.tagged || self.stale[view] { + return; + } + if self.invpcid { + let descriptor = [view_context(view), page]; + // SAFETY: a valid single-address INVPCID of an inactive PCID. + unsafe { + asm!("invpcid {}, [{}]", in(reg) 0u64, in(reg) &descriptor, + options(nostack, preserves_flags)) + }; + } else { + self.stale[view] = true; + } + } } /// Frames reserved for roots and other permanent tables. const PERMANENT_FRAMES: u64 = 64; @@ -397,13 +407,11 @@ pub struct State { code_virtual: u64, code_physical: u64, code_bytes: u64, - /// The arena's part new code goes to, and the offset after the code - /// installed last. + /// The arena part new code goes to. code_unit: u64, - code_used: u64, /// Successful initialized installs in each arena unit, from its start. - /// These metadata ranges require this State's backing/root/CPU owner. - installed_ranges: [Vec<(u32, u32)>; CODE_UNITS as usize], + /// These extents require this State's backing, root and CPU owner. + installed_extents: [CodeExtents; CODE_UNITS as usize], /// The furthest the arena's code has reached: what the run needed of it /// until it first filled and new code reclaimed the oldest. code_peak: u64, @@ -440,6 +448,9 @@ pub struct State { /// The lower half's root entries any root may hold, by index: a switch /// of TTBR0 visits these, a few, rather than every entry of the half. lower_used: [u64; ROOT_ENTRIES / 64], + /// Physical shadow roots that may hold any lower entry, indexed by + /// their permanent pool frame after the host root. + lower_roots: u64, /// Switches of the lower half to another TTBR0, those that found its /// half kept, and the kept halves a TLBI or a bank's replacement /// dropped. @@ -552,16 +563,17 @@ pub unsafe fn install(config: Config) -> Result { }; let host_root = root()?; let mut roots = [0; ROOTS]; - for slot in &mut roots { - *slot = root()?; - } let mut banks = [Bank { rights: None, roots: [0; ROOTS], used: 0, }; BANKS]; - for slot in banks.iter_mut().flat_map(|bank| &mut bank.roots) { + let shadow_roots = roots + .iter_mut() + .chain(banks.iter_mut().flat_map(|bank| &mut bank.roots)); + for (index, slot) in shadow_roots.enumerate() { *slot = root()?; + assert_eq!(*slot, host_root + (index as u64 + 1) * PAGE); } load_root(host_root); let apic = Apic::new( @@ -596,8 +608,7 @@ pub unsafe fn install(config: Config) -> Result { code_physical: config.code_physical, code_bytes: config.code_bytes, code_unit: 0, - code_used: 0, - installed_ranges: core::array::from_fn(|_| Vec::new()), + installed_extents: core::array::from_fn(|_| CodeExtents::default()), code_peak: 0, installed_immutable: InstalledCodeCache::default(), recorded: None, @@ -624,6 +635,7 @@ pub unsafe fn install(config: Config) -> Result { lower_globals: None, kept: Kept::new(), lower_used: [0; ROOT_ENTRIES / 64], + lower_roots: 0, lower_switches: 0, lower_found: 0, kept_dropped: 0, @@ -840,15 +852,11 @@ impl State { if unit == 0 || end > self.code_bytes { return false; } - let Some(ranges) = self.installed_ranges.get((offset / unit) as usize) else { + let Some(extents) = self.installed_extents.get((offset / unit) as usize) else { return false; }; let base = offset / unit * unit; - let (offset, end) = (offset - base, end - base); - let index = ranges.partition_point(|&(_, finish)| u64::from(finish) <= offset); - ranges - .get(index) - .is_some_and(|&(start, finish)| u64::from(start) <= offset && end <= u64::from(finish)) + extents.contains(offset - base..end - base) } fn host_physical(&self, guest: u64) -> Option { @@ -868,6 +876,8 @@ impl State { fn reset_shadow(&mut self, cause: Cause) { if !self.legacy_translations_dirty { + // Device translations can exist without any populated RAM view. + self.tlb.clear_devices(); return; } self.clear(LOWER); @@ -889,12 +899,18 @@ impl State { /// TTBR0 or the lower half's TCR fields changed from `from` to `to`: /// detach the lower half from every root and keep it, and attach the - /// half kept for `to`, if any. - fn switch_lower(&mut self, from: (u64, u64), to: (u64, u64)) { + /// half kept for `to`, if any. Return the views the caller must flush. + fn switch_lower(&mut self, from: (u64, u64), to: (u64, u64)) -> [bool; ROOTS] { self.lower_switches += 1; let mut entries = Vec::new(); - for root in self.all_roots() { - for entry in self.lower_entries() { + let mut changed = 0; + let lower_roots = core::mem::take(&mut self.lower_roots); + for entry in self.lower_entries() { + let mut roots = lower_roots; + while roots != 0 { + let index = roots.trailing_zeros(); + roots &= roots - 1; + let root = self.host_root + (u64::from(index) + 1) * PAGE; // SAFETY: permanent root frames through the physmap. let slot = unsafe { (layout::physical(root) as *mut u64).add(entry) }; // SAFETY: as above. @@ -903,6 +919,7 @@ impl State { entries.push((root, entry, value)); // SAFETY: as above. unsafe { slot.write(0) }; + changed |= 1 << index; } } } @@ -913,13 +930,29 @@ impl State { for &(root, entry, value) in &half.entries { // SAFETY: as above; the half's tables are still the pool's. unsafe { (layout::physical(root) as *mut u64).add(entry).write(value) }; - self.lower_used[entry / 64] |= 1 << (entry % 64); + self.record_lower(root, entry); + changed |= self.lower_root_bit(root); } self.extents[LOWER] = half.extents; } - // The software TLB is tagged by view, not root. - self.tlb.clear(); - self.reload(); + if changed == 0 { + [false; ROOTS] + } else { + // Inactive bank roots have no PCID; selecting a bank flushes it. + self.roots + .map(|root| changed & self.lower_root_bit(root) != 0) + } + } + + fn lower_root_bit(&self, root: u64) -> u64 { + let index = (root - self.host_root) / PAGE - 1; + debug_assert!(root.is_multiple_of(PAGE) && index < SHADOW_ROOTS as u64); + 1 << index + } + + fn record_lower(&mut self, root: u64, entry: usize) { + self.lower_used[entry / 64] |= 1 << (entry % 64); + self.lower_roots |= self.lower_root_bit(root); } /// The lower half's root entries [`State::lower_used`] names. @@ -945,7 +978,7 @@ impl State { /// Take the roots of rights `to` from their bank, leaving those of /// `from` there: a bank of `to`, or else the least recently used, - /// emptied. + /// emptied. The caller must flush the views. fn switch_bank(&mut self, from: Rights, to: Rights) { self.bank_switches += 1; let index = match self.banks.iter().position(|bank| bank.rights == Some(to)) { @@ -972,9 +1005,6 @@ impl State { core::mem::swap(&mut bank.roots, &mut self.roots); bank.rights = Some(from); bank.used = self.bank_switches; - // The software TLB is tagged by view, not root. - self.tlb.clear(); - self.reload(); } /// Every root the shadow fills: the current ones and the banks'. @@ -993,6 +1023,7 @@ impl State { } if half == LOWER { self.lower_used = [0; ROOT_ENTRIES / 64]; + self.lower_roots = 0; self.drop_kept(); } } diff --git a/crates/stela-boot/src/engine/host/bare_host.rs b/crates/stela-boot/src/engine/host/bare_host.rs index 91d4a5d321..11ab9e28e3 100644 --- a/crates/stela-boot/src/engine/host/bare_host.rs +++ b/crates/stela-boot/src/engine/host/bare_host.rs @@ -17,7 +17,7 @@ pub struct BareHost<'a> { pub(super) const CODE_UNITS: u64 = 32; pub(super) fn code_unit_bytes(state: &State) -> u64 { - state.code_bytes / CODE_UNITS / 16 * 16 + state.code_bytes / CODE_UNITS / CODE_INSTALL_ALIGNMENT * CODE_INSTALL_ALIGNMENT } impl Host for BareHost<'_> { @@ -83,6 +83,21 @@ impl Host for BareHost<'_> { }) } + fn read_ram_descriptor(&mut self, physical: u64) -> Option { + super::super::speculation::fence(); + if let Some(ram) = &state().registered_ram { + return ram.read_descriptor(physical).ok(); + } + let (host, bytes) = state().run(physical)?; + if bytes < 8 || !host.is_multiple_of(8) { + return None; + } + // SAFETY: this aligned descriptor fits in one live RAM run and + // the physical window maps the entire run. No Rust reference to + // guest memory is formed. + Some(unsafe { (layout::physical(host) as *const u64).read_volatile() }) + } + fn write_ram(&mut self, physical: u64, data: &[u8]) -> bool { if let Some(ram) = &state().registered_ram { // SAFETY: private copyout staging; the canonical owner performs @@ -168,34 +183,29 @@ impl Host for BareHost<'_> { } fn install(&mut self, code: &[u8]) -> Result { let state = state(); - let offset = state.code_used.next_multiple_of(16); - let end = offset + code.len() as u64; - if end > (state.code_unit + 1) * code_unit_bytes(state) { - return Err(InstallError::Full); - } - state.installed_ranges[state.code_unit as usize] - .try_reserve(1) - .map_err(|_| InstallError::Full)?; - if code.is_empty() { - return Err(InstallError::Full); - } - // SAFETY: arena bytes through the writable physmap alias. - unsafe { - core::ptr::copy_nonoverlapping( - code.as_ptr(), - layout::physical(state.code_physical + offset) as *mut u8, - code.len(), - ); - } - serialize_code(); - let unit = state.code_unit * code_unit_bytes(state); - state.installed_ranges[state.code_unit as usize] - .push(((offset - unit) as u32, (end - unit) as u32)); - state.code_used = end; - state.code_peak = state.code_peak.max(end); + let part_bytes = code_unit_bytes(state); + let part_offset = state.code_unit * part_bytes; + let physical = state.code_physical + part_offset; + let extent = state.installed_extents[state.code_unit as usize] + .append(part_bytes, code.len(), |start| { + // SAFETY: the ledger reserves this nonoverlapping extent in + // the owned arena. The writable physmap reaches it. + unsafe { + core::ptr::copy_nonoverlapping( + code.as_ptr(), + layout::physical(physical + start) as *mut u8, + code.len(), + ); + } + serialize_code(); + }) + .ok_or(InstallError::Full)?; + state.code_peak = state.code_peak.max(part_offset + extent.end); #[cfg(feature = "native-profile")] state.native_profile.copied(code.len()); - Ok(NativeCode((state.code_virtual + offset) as usize)) + Ok(NativeCode( + (state.code_virtual + part_offset + extent.start) as usize, + )) } fn install_immutable(&mut self, code: &Arc>) -> Result { @@ -257,20 +267,27 @@ impl Host for BareHost<'_> { let state = state(); state.installed_immutable.clear(); state.code_unit = 0; - state.code_used = 0; - for ranges in &mut state.installed_ranges { - ranges.clear(); + for extents in &mut state.installed_extents { + extents.clear(); } } + fn code_partitions(&self) -> Option { + let state = state(); + Some(stela_engine::machine::engine::CodePartitions { + base: state.code_virtual as usize, + bytes_per_part: code_unit_bytes(state) as usize, + parts: CODE_UNITS as usize, + }) + } + fn reclaim_code(&mut self) -> Option> { let state = state(); state.installed_immutable.clear(); let unit = code_unit_bytes(state); state.code_unit = (state.code_unit + 1) % CODE_UNITS; - state.installed_ranges[state.code_unit as usize].clear(); - state.code_used = state.code_unit * unit; - let start = (state.code_virtual + state.code_used) as usize; + state.installed_extents[state.code_unit as usize].clear(); + let start = (state.code_virtual + state.code_unit * unit) as usize; Some(start..start + unit as usize) } @@ -283,12 +300,13 @@ impl Host for BareHost<'_> { // blocks again. let Some(part) = (1..CODE_UNITS) .map(|step| (state.code_unit + step) % CODE_UNITS) - .find(|&part| !state.installed_ranges[part as usize].is_empty()) + .find(|&part| !state.installed_extents[part as usize].is_empty()) else { return Some(0..0); }; state.installed_immutable.clear(); - state.installed_ranges[part as usize].clear(); + // This reclaim is for heap pressure, so give back the ledger too. + state.installed_extents[part as usize] = CodeExtents::default(); let unit = code_unit_bytes(state); let start = (state.code_virtual + part * unit) as usize; Some(start..start + unit as usize) @@ -352,6 +370,7 @@ impl Host for BareHost<'_> { fn set_regime(&mut self, regime: &Regime) { let state = state(); + let mut changed_roots = None; if let Some(current) = state.regime && current.controls != regime.controls { @@ -386,12 +405,18 @@ impl Host for BareHost<'_> { if rest == to && (!lower || asid || !state.extents[UPPER].private()) { if lower { let key = |c: &mmu::Controls| (c.ttbr0, c.tcr & lower_tcr); - state.switch_lower(key(&from), key(&to)); + changed_roots = Some(state.switch_lower(key(&from), key(&to))); } let rights = |c: &mmu::Controls| (c.sprr.el0, c.sprr.el1, c.tcr & user_tcr); let (from, to) = (rights(&from), rights(&to)); - if from != to { + let bank = from != to; + if bank { state.switch_bank(from, to); + changed_roots = Some([true; ROOTS]); + } + // The helper's software TLB keys neither TTBR0 nor the bank. + if lower || bank { + state.tlb.clear(); } } else { let ttbr0 = mmu::Controls { @@ -438,13 +463,21 @@ impl Host for BareHost<'_> { (_, false, false) => EL1_VIEW, (_, true, false) => PAN_VIEW, } + if regime.tag_checked() { VIEWS } else { 0 }; - if state.current != view { - let load = state.root_of(view) != state.root_of(state.current); - state.current = view; - if load { - state.view_switches += 1; - state.load_view(view); + let root = state.root_of(view); + let switch_view = root != state.root_of(state.current); + state.current = view; + state.view_switches += u64::from(switch_view); + // Lower-half and bank changes, and a switch of the active view, + // can coincide. Load the final view after applying all of them. + let mut load = switch_view; + if let Some(changed) = changed_roots { + for (stale, changed) in state.contexts.stale.iter_mut().zip(changed) { + *stale |= changed; } + load |= changed[root]; + } + if load { + state.load_view(view); } } @@ -482,38 +515,66 @@ impl Host for BareHost<'_> { return state.reset_shadow(Cause::Maintained); } state.tlb.clear(); - let mut unmapped = Vec::new(); + // Most maintenance addresses reach a single extent, without a + // large overlapping leaf or a second half. + let mut first_range = None; + let mut extra_ranges = Vec::new(); + let mut pages = 0u64; let mut whole = false; for half in [LOWER, UPPER] { - match state.extents[half].ranges(reach, state.half_range(half)) { - None => { - state.clear(half); - whole = true; + let bounds = state.half_range(half); + if !state.extents[half].visit_ranges(reach, bounds, |first, last| { + pages = pages.saturating_add(((last >> 12) - (first >> 12)) + 1); + if first_range.is_none() { + first_range = Some((first, last)); + } else { + extra_ranges.push((first, last)); } - Some(ranges) => unmapped.extend(ranges), + }) { + state.clear(half); + whole = true; } } - let mut pages = 0u64; - for &(first, last) in &unmapped { - for root in state.all_roots() { - tables::unmap(&state.pool, root, first, last); - } - pages = pages.saturating_add(((last - first) >> 12) + 1); - } - if whole || pages > INVLPG_PAGES { - state.reload(); - } else { - for &(first, last) in &unmapped { - let mut page = first & !(PAGE - 1); - loop { - let current = state.root_of(state.current); - state.contexts.forget(page, current); - if page >= last & !(PAGE - 1) { - break; + const { assert!(INVLPG_PAGES <= u16::BITS as u64) }; + let precise = !whole && pages <= INVLPG_PAGES; + let current = state.root_of(state.current); + let mut reload_current = false; + for (first, last) in first_range.into_iter().chain(extra_ranges) { + let base = first & !(PAGE - 1); + for (view, root) in state.roots.into_iter().enumerate() { + let mut removed = 0u16; + tables::unmap(&state.pool, root, first, last, |address| { + let bit = if precise { (address - base) / PAGE } else { 0 }; + removed |= 1 << bit; + }); + if whole || removed == 0 { + continue; + } + if !precise { + state.contexts.stale[view] = true; + reload_current |= view == current; + continue; + } + while removed != 0 { + let page = base + u64::from(removed.trailing_zeros()) * PAGE; + removed &= removed - 1; + if view == current { + invlpg(page); + } else { + state.contexts.forget_inactive(page, view); } - page += PAGE; } } + // A bank has no PCID while it is inactive. Switching to it + // flushes the views before they can use its entries again. + for root in state.banks.iter().flat_map(|bank| bank.roots) { + tables::unmap(&state.pool, root, first, last, |_| {}); + } + } + if whole { + state.reload(); + } else if reload_current { + state.load_view(state.current); } if whole { state.resets += 1; diff --git a/crates/stela-boot/src/engine/host/faults.rs b/crates/stela-boot/src/engine/host/faults.rs index 6d6da1cd64..810fba52b5 100644 --- a/crates/stela-boot/src/engine/host/faults.rs +++ b/crates/stela-boot/src/engine/host/faults.rs @@ -154,12 +154,22 @@ pub(super) fn resolve( write: bool, unprivileged: bool, ) -> Result<(mmu::Translation, u64), FaultCause> { - let regime = state.regime.ok_or(FaultCause::NonCanonical)?; + let regime = state.regime.as_ref().ok_or(FaultCause::NonCanonical)?; let access = if write { Access::Write } else { Access::Read }; let requester = mmu::Requester { unprivileged: regime.requester.unprivileged || unprivileged, ..regime.requester }; + let virtual_page = address & !(PAGE - 1); + if let Some(physical) = state.tlb.device_physical(address, requester, write) { + // The cached translation already passed both stages and data + // permissions. Watchpoint passes can change without a new walk. + return Err(if regime.watch.blocks(virtual_page) { + FaultCause::Watched + } else { + FaultCause::Device { physical } + }); + } let translation = match mmu::translate( ®ime.controls, address, @@ -171,16 +181,20 @@ pub(super) fn resolve( Outcome::Fault(fault) => return Err(FaultCause::Guest(fault)), Outcome::Unsupported(unsupported) => return Err(FaultCause::Translation(unsupported)), }; - if regime.watch.blocks(address & !(PAGE - 1)) { + if regime.watch.blocks(virtual_page) { return Err(FaultCause::Watched); } if regime.tag_blocks(address, translation.attributes) { return Err(FaultCause::TagChecked); } let page = translation.physical & !(PAGE - 1); - let host = state.host_physical(page).ok_or(FaultCause::Device { - physical: translation.physical, - })?; + let Some(host) = state.host_physical(page) else { + // This walker makes no AF or dirty descriptor updates. + state.tlb.record_device(address, requester, translation); + return Err(FaultCause::Device { + physical: translation.physical, + }); + }; Ok((translation, host)) } @@ -200,7 +214,7 @@ pub(crate) fn page_fault( super::super::interrupts::fatal(frame); } state.follow_pan(frame.rflags & RFLAGS_AC == 0); - let Some(regime) = state.regime else { + let Some(tag_checks) = state.regime.as_ref().map(|regime| regime.tag_checks) else { super::super::interrupts::fatal(frame); }; // Only the native ranges are shadow; the rest is the engine's. An @@ -221,23 +235,11 @@ pub(crate) fn page_fault( Ok(resolved) => resolved, Err(cause) => return abandon(state, frame, address, write, cause, saved), }; - // Filled for EL1 without PAN, a leaf is one PAN guards unless it would - // translate the same with PAN set; one filled with PAN set never is. + // EL1 and PAN share a root. SMAP guards a leaf if a read with PAN set + // would be denied by either stage, or by stage 1's PAN rules. let guarded = state.contexts.pan_flag && state.current % VIEWS == EL1_VIEW - && !matches!( - mmu::translate( - ®ime.controls, - address, - Access::Read, - mmu::Requester { - pan: true, - ..regime.requester - }, - &mut GuestTables(state), - ), - Outcome::Mapped(same) if same.writable == translation.writable - ); + && (!translation.readable || translation.pan_sensitive); let rights = PRESENT | NX | if translation.writable { WRITABLE } else { 0 } @@ -276,17 +278,22 @@ pub(crate) fn page_fault( } } }; - invlpg(virtual_page); + // A not-present fault has no cached translation to invalidate. Every + // shadow removal already invalidates that view or marks it stale. + // A protection fault can replace a present mapping. + if frame.error & 1 != 0 { + invlpg(virtual_page); + } if half == LOWER { let entry = tables::index(virtual_page, layout::top_level()); - state.lower_used[entry / 64] |= 1 << (entry % 64); + state.record_lower(root, entry); } state.extents[half].record(address, translation.size, translation.global); // The rest of the leaf's window has the same translation and rights: // map its RAM pages that are not watched now, as a TLB entry covers // the whole leaf. Pages that were absent need no flush. A Tagged leaf // whose tags are checked maps only the passed page. - if regime.tag_checks[half] && translation.attributes == mmu::attributes::TAGGED { + if tag_checks[half] && translation.attributes == mmu::attributes::TAGGED { state.fills += 1; return; } @@ -301,9 +308,10 @@ pub(crate) fn page_fault( // fall back to page lookups past the end of that physical run. let (first_host, available) = state.run(physical).unwrap_or((0, 0)); let table = slot.wrapping_sub(tables::index(virtual_page, 0)); + let watch = &state.regime.as_ref().expect("checked above").watch; let mut page = first; loop { - if page != virtual_page && !regime.watch.blocks(page) { + if page != virtual_page && !watch.blocks(page) { let offset = page - first; let host = if offset < available { first_host.checked_add(offset) diff --git a/crates/stela-boot/src/engine/remote.rs b/crates/stela-boot/src/engine/remote.rs index d9134468b5..a15c69eb88 100644 --- a/crates/stela-boot/src/engine/remote.rs +++ b/crates/stela-boot/src/engine/remote.rs @@ -97,6 +97,17 @@ impl Remote { } } + /// Release the restore-only range and ring after the protocol has ended. + pub(super) fn retire(&mut self) { + self.stop(); + self.ahead = false; + let bytes = self.buffer.capacity(); + self.buffer = VecDeque::new(); + output::arguments(format_args!( + "REMOTE IMAGE retired read-ahead capacity={bytes}\n" + )); + } + /// Takes what has arrived, opening a range at the buffer's end first /// when none is open. fn step(&mut self) -> Result<(), NetError> { diff --git a/crates/stela-boot/src/engine/restore.rs b/crates/stela-boot/src/engine/restore.rs index 8c9fb27cca..0804eba452 100644 --- a/crates/stela-boot/src/engine/restore.rs +++ b/crates/stela-boot/src/engine/restore.rs @@ -738,8 +738,16 @@ impl Experiment { } /// Read ahead from the host's storage, without the guest's devices. pub fn pump(&mut self) { - if !self.terminal { - self.driver.answers.store.reader_mut().pump(); + let source = self.driver.answers.store.reader_mut(); + if self.terminal { + // The service owns the restore and its network here. Retire the + // remote range outside the device lock and leave queued disk I/O + // to its existing owner. + if let Some(remote) = source.remote.take() { + remote.borrow_mut().retire(); + } + } else { + source.pump(); } } @@ -799,7 +807,7 @@ impl Experiment { if let Some(proxy) = &mut self.proxy { proxy.poll(&mut client); } - let result = self.driver.poll_ports(&mut client); + let result = self.driver.poll_prefetched(&mut client); self.backpressure = client.backpressure(); for message in &self.driver.session.ledger()[self.ledger..] { output::arguments(format_args!("{label} ledger={message:?}\n")); diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index 489d7756a4..2b962f00ab 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -340,25 +340,23 @@ fn open_host( .map(|partition| from_disk(partition, options, bluetooth)); // A system boots as the board it was installed on: libignition finds its // Cryptex1 tickets by that board's model. - if built.is_some() { + if options.bundle || built.is_some() { let files = &handoff.files[..handoff.file_count]; - options.development_board = bundle::development_board(files, built.as_deref()) - .unwrap_or_else(|error| { - output::arguments(format_args!("bundle refusal: {error}\n")); - output::fatal("the boot bundle's board could not be read") - }); - } - // A bundle runs at the DRAM base it was prepared for, its SoC's. - if options.bundle && !options.dram_explicit { - let files = &handoff.files[..handoff.file_count]; - options.dram_base = match bundle::dram_base(files, built.as_deref()) { - Ok(base) if base.is_multiple_of(LARGE) => base, - Ok(_) => output::fatal("the bundle's DRAM base is not 2 MiB aligned"), - Err(error) => { - output::arguments(format_args!("bundle refusal: {error}\n")); - output::fatal("the boot bundle's DRAM base could not be read") + let manifest = bundle::manifest(files, built.as_deref()).unwrap_or_else(|error| { + output::arguments(format_args!("bundle refusal: {error}\n")); + output::fatal("the boot bundle's manifest could not be read") + }); + options.development_board = manifest + .target + .is_some_and(|target| target.device_class.ends_with("dev")); + // A bundle runs at the DRAM base it was prepared for, its SoC's. + if options.bundle && !options.dram_explicit { + let base = manifest.options.dram_base; + if !base.is_multiple_of(LARGE) { + output::fatal("the bundle's DRAM base is not 2 MiB aligned"); } - }; + options.dram_base = base; + } } ram::place(&mut ram, options.dram_base); host_owner @@ -727,7 +725,7 @@ fn run_guest(boot: Boot<'_>, host: OpenedHost, storage: Storage, processors: Pro "ENTRY pc={entry:#x} x0={x0:#x} el={el} mmu=off profile={} target={} apic_hz={apic_hz} \ prediction_isolation={} faulting_data_barrier={}\n", profile.name, - target.id(), + canonical_ram.target().id(), speculation.contexts, speculation.faulting_data, )); @@ -1418,6 +1416,7 @@ fn check_processors( let OpenedHost { owner: ref mut host_owner, mmio: native_mmio, + ram: ref worker_ram, .. } = *host; for processor in executors.processors() { @@ -1447,15 +1446,29 @@ fn check_processors( doorbells, )); } - if let Some(mmio) = &native_mmio { - // SAFETY: the check owns the host's devices; bus 0's first - // function is only read here. - let generation = unsafe { mmio.check_shootdown() }.unwrap_or_else(|error| { + if handoff.native_resources.cores == 1 && executors.processors().is_empty() { + output::arguments(format_args!( + "CHECK native-shootdown SKIP reason=no-remote-processor\n" + )); + } else if let Some(mmio) = &native_mmio { + let waiter = executors + .processors() + .first() + .unwrap_or_else(|| output::fatal("the shootdown check requires a started AP")); + // SAFETY: both processors keep the live loader root. This diagnostic + // owns the host's devices and only reads bus 0's first function. + let generation = unsafe { + waiter.check_driver_wait(handoff.root, sender, handoff.tsc_hz, || { + mmio.check_shootdown() + }) + } + .unwrap_or_else(|error| output::fatal(error)) + .unwrap_or_else(|error| { output::arguments(format_args!("CHECK native-shootdown FAIL {error:?}\n")); output::fatal("the MMIO aperture's shootdown failed") }); output::arguments(format_args!( - "CHECK native-shootdown PASS generation={generation} processors={}\n", + "CHECK native-shootdown PASS generation={generation} processors={} waiter=driver-lock-if0\n", executors.processors().len() )); } @@ -1469,6 +1482,7 @@ fn check_processors( executors, host_owner, sender, + worker_ram, ) } .unwrap_or_else(|error| output::fatal(error)); diff --git a/crates/stela-boot/src/engine/storage.rs b/crates/stela-boot/src/engine/storage.rs index 5167263eee..32b745ff42 100644 --- a/crates/stela-boot/src/engine/storage.rs +++ b/crates/stela-boot/src/engine/storage.rs @@ -148,6 +148,9 @@ fn lock_host_drivers() { .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) .is_err() { + // A driver holding this lock can be retiring an aperture mapping. + // An interrupt cannot reach this waiter if it entered with IF clear. + crate::native_mmio::shootdown::service(); core::hint::spin_loop(); } let waited = super::host::rdtsc().wrapping_sub(started); @@ -180,7 +183,8 @@ impl RestoreRoot { /// driver never calls back into the engine's host interfaces. /// /// # Safety - /// `root` is the live loader root, keeping the engine window. + /// `root` is the live loader root, keeping the engine window. The + /// processor's pinned local record is active. pub(super) unsafe fn enter(root: u64) -> Self { lock_host_drivers(); let (previous, flags): (u64, u64); @@ -247,6 +251,17 @@ impl Drop for RestoreRoot { } } +/// Enter the real host-driver lock for the native contention diagnostic. +/// +/// # Safety +/// `root` is the kept loader root, with the current processor installed. +#[cfg(feature = "diagnostics")] +pub(crate) unsafe fn with_driver_root(root: u64, operation: impl FnOnce() -> T) -> T { + // SAFETY: the caller supplies the live root and local owner. + let _guard = unsafe { RestoreRoot::enter(root) }; + operation() +} + struct Service { inner: Box, root: u64, diff --git a/crates/stela-boot/src/engine/translations.rs b/crates/stela-boot/src/engine/translations.rs index 10168320c3..f8dd248a21 100644 --- a/crates/stela-boot/src/engine/translations.rs +++ b/crates/stela-boot/src/engine/translations.rs @@ -21,8 +21,9 @@ use alloc::{boxed::Box, format, string::String, vec}; use core::{ cell::UnsafeCell, ptr::NonNull, - sync::atomic::{AtomicBool, Ordering}, + sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}, }; +use stela_boot_core::memory_budget::MAX_TRANSLATION_PACK_BYTES; use stela_drivers::block::BlockDevice; use stela_engine::machine::Offer; use stela_engine::machine::Translations; @@ -30,8 +31,8 @@ use stela_engine::translations; use stela_engine::translations::Digest; use stela_engine::translations::Record; use stela_engine::translations::pack; -use stela_engine::translations::pack::Pack; use stela_engine::translations::pack::Store; +use stela_engine::translations::pack::{DecodedRecord, Pack, StagedOffer}; use stela_runtime::pc::fat32::Fat32; use stela_runtime::pc::gpt::Guid; use uefi::{ @@ -62,9 +63,6 @@ const PACK_EXTENSION: &str = "pak"; const SPARE: &str = "spare.bin"; /// The pack is read in steps of this many bytes, each shown as progress. const PROGRESS_STEP: usize = 16 << 20; -/// The largest pack the boot holds in memory and writes: the bound of -/// `store.cfg` is cut to it. -const MAX_PACK_BYTES: u64 = 1 << 30; /// The placement record at the start of the handoff file: magic, bound, /// partition GUID, flags, pack bytes; the pack follows. const PLACEMENT_MAGIC: [u8; 8] = *b"STLTSTOR"; @@ -163,7 +161,7 @@ pub fn read() -> Option<(Region, bool)> { let Some(bound) = bound(&mut root) else { continue; }; - let bound = bound.min(MAX_PACK_BYTES); + let bound = bound.min(MAX_TRANSLATION_PACK_BYTES); let path = pack_path(&translator, "\\"); if open(&mut root, &path, FileMode::Read).is_none() { claim_spare(&mut root, &translator); @@ -322,11 +320,26 @@ static BOOT: Cell = Cell { boot: UnsafeCell::new(None), }; -/// Availability rarely changes. Keep it off the lock's cache line so a PE -/// checking for a store does not contend with a PE using it. +/// Keep the store's capabilities off the lock's cache line so a PE can +/// skip operations that have no backing without contending with its users. #[repr(align(64))] -struct Available(AtomicBool); -static AVAILABLE: Available = Available(AtomicBool::new(false)); +struct Available { + capabilities: AtomicU8, + /// A preflight limit for staging. Admission checks the live store bound. + shared_bound: AtomicUsize, +} + +static AVAILABLE: Available = Available { + capabilities: AtomicU8::new(0), + shared_bound: AtomicUsize::new(0), +}; +const READ_PACK: u8 = 1 << 0; +const WRITE_PACK: u8 = 1 << 1; +const SHARE_BLOCKS: u8 = 1 << 2; + +fn available(capabilities: u8) -> bool { + AVAILABLE.capabilities.load(Ordering::Acquire) & capabilities != 0 +} /// Run `f` on the boot's store, alone. No interrupt handler reaches it. fn with_boot(f: impl FnOnce(&mut Option) -> R) -> R { @@ -348,27 +361,49 @@ fn with_boot(f: impl FnOnce(&mut Option) -> R) -> R { /// The engine's view of the boot's store, from any PE's machine. pub struct Shared; +impl Shared { + fn publish_shared(offer: Offer) { + let bound = AVAILABLE.shared_bound.load(Ordering::Acquire); + let Some(mut staged) = StagedOffer::new(offer, bound) else { + return; + }; + let retired = with_boot(|boot| boot.as_mut()?.store.accept_shared(&mut staged)); + drop(retired); + } +} + impl Translations for Shared { - /// The record, decoded while the other PEs reach the store: the pack's - /// bytes outlive the lock. + /// The pack bytes outlive the lock, so other PEs can reach the store + /// while a record is decoded. A writer also tracks absent keys. fn record(&mut self, key: &Digest) -> Option> { - let (bytes, translator) = with_boot(|boot| { + if !available(READ_PACK | WRITE_PACK) { + return None; + } + let lookup = with_boot(|boot| { let store = &mut boot.as_mut()?.store; + if let Some(record) = store.cached_record(key) { + return Some(Ok(record)); + } match store.stored(key) { - Some(bytes) => Some((bytes, *store.translator())), + Some(bytes) => Some(Err((bytes, *store.translator()))), None => { store.looked_up(key, false, false); None } } })?; - let record = Record::decode(bytes, &translator, key).ok(); - with_boot(|boot| { - if let Some(boot) = boot { - boot.store.looked_up(key, true, record.is_some()); - } + let (bytes, translator) = match lookup { + Ok(record) => return Some(record), + Err(source) => source, + }; + let decoded = DecodedRecord::decode(bytes, &translator, key); + let evicted = with_boot(|boot| { + let store = &mut boot.as_mut()?.store; + store.looked_up(key, true, decoded.is_some()); + store.remember_record(decoded.as_ref()?) }); - record.map(alloc::sync::Arc::new) + drop(evicted); + decoded.map(DecodedRecord::into_record) } fn prepared( @@ -377,32 +412,39 @@ impl Translations for Shared { pc: u64, context: &Digest, ) -> Option> { + if !available(SHARE_BLOCKS) { + return None; + } with_boot(|boot| boot.as_mut()?.store.prepared(key, pc, context)) } fn offer(&mut self, offer: Offer) { - with_boot(|boot| { - if let Some(boot) = boot { - boot.store.offer(offer); - } - }); + let capabilities = AVAILABLE.capabilities.load(Ordering::Acquire); + if capabilities & WRITE_PACK != 0 { + with_boot(|boot| { + if let Some(boot) = boot { + if boot.partition.is_some() { + boot.store.offer(offer); + } else { + boot.store.lend(offer); + } + } + }); + } else if capabilities & SHARE_BLOCKS != 0 { + Self::publish_shared(offer); + } } fn lend(&mut self, offer: Offer) { - with_boot(|boot| { - if let Some(boot) = boot { - boot.store.lend(offer); - } - }); + if available(SHARE_BLOCKS) { + Self::publish_shared(offer); + } } } /// The store the engine uses, if the loader read one or the PEs share one. pub fn store() -> Option<&'static mut Shared> { - AVAILABLE - .0 - .load(Ordering::Acquire) - .then(|| Box::leak(Box::new(Shared))) + available(READ_PACK | WRITE_PACK | SHARE_BLOCKS).then(|| Box::leak(Box::new(Shared))) } /// Share compiled blocks between PEs, keeping up to `bound` bytes of buffers @@ -417,7 +459,16 @@ pub fn share(bound: usize) { partition: None, }); boot.store.share(bound); - AVAILABLE.0.store(true, Ordering::Release); + AVAILABLE.shared_bound.store(bound, Ordering::Release); + if bound != 0 { + AVAILABLE + .capabilities + .fetch_or(SHARE_BLOCKS, Ordering::Release); + } else { + AVAILABLE + .capabilities + .fetch_and(!SHARE_BLOCKS, Ordering::Release); + } }); } @@ -446,13 +497,15 @@ pub fn install(contents: &'static [u8]) -> Option { (None, None) => output::arguments(format_args!("TRANSLATIONS no pack yet\n")), } with_boot(|boot| { + let readable = if store.pack().is_some() { READ_PACK } else { 0 }; *boot = Some(Boot { store, bound, path: pack_path(&translator, "/"), partition: None, }); - AVAILABLE.0.store(true, Ordering::Release); + AVAILABLE.shared_bound.store(0, Ordering::Release); + AVAILABLE.capabilities.store(readable, Ordering::Release); }); let partition = Guid(contents[16..32].try_into().expect("a GUID")); (flags & WRITABLE != 0).then_some(partition) @@ -463,6 +516,9 @@ pub fn set_partition(partition: Box) { with_boot(|boot| { if let Some(boot) = boot { boot.partition = Some(partition); + AVAILABLE + .capabilities + .fetch_or(WRITE_PACK, Ordering::Release); } }); } @@ -476,7 +532,8 @@ pub fn write() { path, partition: Some(partition), }) = with_boot(|boot| { - AVAILABLE.0.store(false, Ordering::Release); + AVAILABLE.capabilities.store(0, Ordering::Release); + AVAILABLE.shared_bound.store(0, Ordering::Release); boot.take() }) else { diff --git a/crates/stela-boot/src/engine/usb.rs b/crates/stela-boot/src/engine/usb.rs index 6f24cf2440..3314b87b1c 100644 --- a/crates/stela-boot/src/engine/usb.rs +++ b/crates/stela-boot/src/engine/usb.rs @@ -160,8 +160,9 @@ impl HostUsb { } } - /// Poll each signalling controller that has work, and the others when - /// the interval has passed; the keyboards and pointers that arrived. + /// Poll controllers with work or a due attachment timer, and check + /// non-signalling controllers on the fallback interval. Return the + /// keyboards and pointers that arrived. pub fn poll(&mut self) -> Vec { let mut inputs = Vec::new(); let now = super::host::rdtsc(); @@ -176,7 +177,11 @@ impl HostUsb { // SAFETY: the loader root `storage::open` captured maps the // controller and DMA pages used by both readiness and polling. let _root = unsafe { RestoreRoot::enter(self.root) }; - if !(if host.signals() { host.due() } else { timed }) { + if !(if host.signals() { + host.due() + } else { + timed || host.attachment_due() + }) { continue; } host.poll(&mut self.dma, &firmware) diff --git a/crates/stela-boot/src/main.rs b/crates/stela-boot/src/main.rs index fafd267142..03e012a2a0 100644 --- a/crates/stela-boot/src/main.rs +++ b/crates/stela-boot/src/main.rs @@ -113,7 +113,7 @@ static HOST_FIRMWARE_INTERFACE: [u8; 21] = stela_loader::host_firmware::MOUNT_CA #[uefi::entry] fn main() -> Status { // Before any Rust state exists: the system engine runs from this copy. - system::take_snapshot(); + let snapshot = system::take_snapshot(); // Referenced, so the linker keeps the marker setup reads. core::hint::black_box(&MOUNT_INTERFACE); core::hint::black_box(&HOST_FIRMWARE_INTERFACE); @@ -151,8 +151,9 @@ fn main() -> Status { let options = choice::choose(&mut volume, options, held); status::take_screen(console::Framebuffer::from_firmware()); if options.starts_with(b"--system") { - system::boot(options, volume, log, host_firmware); + system::boot(options, volume, log, host_firmware, snapshot); } + drop(snapshot); if options.starts_with(stela_boot_core::options::HOST_CHECK.as_bytes()) { drop(volume); #[cfg(feature = "diagnostics")] diff --git a/crates/stela-boot/src/native_clock.rs b/crates/stela-boot/src/native_clock.rs index 3cfc6fda9c..88769e3681 100644 --- a/crates/stela-boot/src/native_clock.rs +++ b/crates/stela-boot/src/native_clock.rs @@ -8,7 +8,7 @@ use crate::{ apic::{self, Apic}, engine::{host, interrupts}, }; -use alloc::sync::Arc; +use alloc::{boxed::Box, sync::Arc}; use core::{ arch::asm, cell::{Cell, UnsafeCell}, @@ -421,6 +421,16 @@ unsafe impl stela_linux::owner::MinimumDeadline for MinimumDeadline { } } +impl stela_drivers::bus::pci::power::Interval for MinimumDeadline { + fn elapsed(&self) -> Result { + use stela_drivers::bus::pci::power::Error; + if self.epoch.cpu.in_interrupt() { + return Err(Error::Clock); + } + stela_linux::owner::MinimumDeadline::ready(self).map_err(|_| Error::Clock) + } +} + // SAFETY: the epoch retains and checks the actual HPET/CPU/root on every // sample, derives the target from the outward lower bound, and does not wait // in PCI interrupt context. @@ -445,6 +455,22 @@ unsafe impl stela_drivers::bus::pci::power::Timer for CounterEpoch { self.minimum_delay_us(microseconds) .map_err(|_| Error::Clock) } + + fn begin_interval( + &self, + microseconds: u64, + ) -> Result< + Option>, + stela_drivers::bus::pci::power::Error, + > { + use stela_drivers::bus::pci::power::Error; + if self.cpu.in_interrupt() { + return Err(Error::Clock); + } + let ns = microseconds.checked_mul(1_000).ok_or(Error::Clock)?; + let interval = self.minimum_deadline(ns).map_err(|_| Error::Clock)?; + Ok(Some(Box::new(interval))) + } } struct Counter { diff --git a/crates/stela-boot/src/native_clock/source.rs b/crates/stela-boot/src/native_clock/source.rs index 433001b184..91b635df71 100644 --- a/crates/stela-boot/src/native_clock/source.rs +++ b/crates/stela-boot/src/native_clock/source.rs @@ -1,9 +1,9 @@ //! Source selection. No nominal TSC/frequency or bootstrap Cpu. use super::{WorkError, counter::Counter, pm}; -use alloc::{rc::Rc, sync::Arc}; +use alloc::{boxed::Box, rc::Rc, sync::Arc}; pub(crate) use stela_boot_core::hpet::ElapsedBounds; pub(super) use stela_boot_core::source_health::Health; -use stela_drivers::bus::pci::power::{Error as TimerError, Timer}; +use stela_drivers::bus::pci::power::{Error as TimerError, Interval, Timer}; #[derive(Clone)] pub(crate) enum Prepared { @@ -13,6 +13,26 @@ pub(crate) enum Prepared { /// Process-only physical minimum from a retained native HPET handoff. struct HpetMinimum(Arc); +struct HpetInterval { + counter: Arc, + start: u64, + ticks: u64, +} + +impl Interval for HpetInterval { + fn elapsed(&self) -> Result { + self.counter + .check_process() + .map_err(|_| TimerError::Clock)?; + let now = self.counter.read_irq().map_err(|_| TimerError::Clock)?; + let elapsed = now.wrapping_sub(self.start); + if elapsed > u64::MAX / 2 { + return Err(TimerError::Clock); + } + Ok(elapsed >= self.ticks) + } +} + impl HpetMinimum { fn target(&self, microseconds: u64) -> Result { self.0.check_process()?; @@ -62,6 +82,16 @@ unsafe impl Timer for HpetMinimum { } Ok(()) } + + fn begin_interval(&self, microseconds: u64) -> Result>, TimerError> { + let ticks = self.target(microseconds).map_err(|_| TimerError::Clock)?; + let start = self.0.read_irq().map_err(|_| TimerError::Clock)?; + Ok(Some(Box::new(HpetInterval { + counter: self.0.clone(), + start, + ticks, + }))) + } } #[derive(Debug)] diff --git a/crates/stela-boot/src/native_mmio/diagnostic.rs b/crates/stela-boot/src/native_mmio/diagnostic.rs index 51a689b14f..b0b1bbb79b 100644 --- a/crates/stela-boot/src/native_mmio/diagnostic.rs +++ b/crates/stela-boot/src/native_mmio/diagnostic.rs @@ -171,10 +171,14 @@ unsafe fn check_native_hpet( let counter = prepared.hpet_counter().ok_or(Error::Unavailable)?.clone(); { let minimum = prepared.pci_minimum()?; + let interval = minimum + .begin_interval(20) + .map_err(|_| Error::Unavailable)? + .ok_or(Error::Unavailable)?; let start = counter.read_irq()?; minimum.wait_us(20).map_err(|_| Error::Unavailable)?; let elapsed = counter.elapsed_bounds(counter.read_irq()?.wrapping_sub(start))?; - if elapsed.lower_ns < 20_000 { + if elapsed.lower_ns < 20_000 || !interval.elapsed().map_err(|_| Error::Unavailable)? { return Err(Error::InvalidPlatformReply.into()); } } diff --git a/crates/stela-boot/src/native_mmio/shootdown.rs b/crates/stela-boot/src/native_mmio/shootdown.rs index 4c54564173..ff0659b5c9 100644 --- a/crates/stela-boot/src/native_mmio/shootdown.rs +++ b/crates/stela-boot/src/native_mmio/shootdown.rs @@ -77,6 +77,9 @@ fn flush() { /// has not flushed it yet. Cheap when nothing is requested: two loads. pub(crate) fn service() { let requested = PROCESSORS.requested(); + if requested == 0 { + return; + } let (slot, flushed) = crate::engine::host::shootdown(); if flushed.load(Ordering::Relaxed) >= requested { return; @@ -85,7 +88,9 @@ pub(crate) fn service() { return; }; flush(); - flushed.store(requested, Ordering::Relaxed); + // A waiter may have IF set. An interrupt between the flush and this + // publication must not let its newer local acknowledgement regress. + flushed.fetch_max(requested, Ordering::Relaxed); PROCESSORS.acknowledge(slot, requested); } diff --git a/crates/stela-boot/src/native_mmio/window.rs b/crates/stela-boot/src/native_mmio/window.rs index 0f80671d52..4ed4f8b68b 100644 --- a/crates/stela-boot/src/native_mmio/window.rs +++ b/crates/stela-boot/src/native_mmio/window.rs @@ -207,9 +207,7 @@ impl Window { if !guard.state().retiring.begin(range.clone()) { return false; } - for page in 0..count as u64 { - let at = address + page * PAGE; - let [pointer, directory, _] = page_window::indices(at); + for (pointer, directory, slots) in page_window::leaf_runs(address, count) { // SAFETY: the aperture's table, a bounded index. let upper = unsafe { self.pointers.add(pointer).read_volatile() }; if upper & PRESENT == 0 { @@ -220,9 +218,11 @@ impl Window { if middle & PRESENT == 0 { continue; } - if let Some(leaf) = self.leaf(guard.state(), at) { - // SAFETY: a leaf this window owns, under its lock. - unsafe { leaf.write_volatile(0) }; + let table = entry_table(middle); + for slot in slots { + // SAFETY: each slot belongs to this existing leaf table and + // the held guard excludes other edits. + unsafe { table.add(slot).write_volatile(0) }; } } drop(guard); diff --git a/crates/stela-boot/src/native_smp/executor/mailbox.rs b/crates/stela-boot/src/native_smp/executor/mailbox.rs index 21bee6a6df..d784acf052 100644 --- a/crates/stela-boot/src/native_smp/executor/mailbox.rs +++ b/crates/stela-boot/src/native_smp/executor/mailbox.rs @@ -268,6 +268,63 @@ impl Processor { Ok(()) } } +#[cfg(feature = "diagnostics")] +impl Processor { + /// Run `check` with this AP spinning for the driver's real loader-root + /// lock. The mailbox command cannot acknowledge a new shootdown at a + /// native return or take an IPI while the BSP keeps the lock. + /// + /// # Safety + /// `root` is the live loader root shared by the BSP and this installed AP. + pub(crate) unsafe fn check_driver_wait( + &self, + root: u64, + sender: &Apic, + tsc_hz: u64, + check: impl FnOnce() -> T, + ) -> Result { + let ready = alloc::sync::Arc::new(AtomicU8::new(0)); + let observed = ready.clone(); + let work = Spawned(Box::new(move |_| { + let flags: u64; + // SAFETY: observes the AP mailbox's real interrupt mask. + unsafe { asm!("pushfq", "pop {}", out(reg) flags) }; + if flags & (1 << 9) != 0 { + observed.store(2, Ordering::Release); + return; + } + observed.store(1, Ordering::Release); + // SAFETY: the live loader root and this AP's pinned local owner. + unsafe { crate::engine::storage::with_driver_root(root, || ()) }; + })); + // SAFETY: the same live root belongs to this BSP. Keep the lock + // through the check and release it before collecting the AP. + let (pending, value) = unsafe { + crate::engine::storage::with_driver_root(root, || -> Result<_> { + let pending = self + .send(work, sender, tsc_hz) + .map_err(|_| refuse!("AP driver wait mailbox busy"))?; + let started = apic::rdtsc(); + let value = loop { + match ready.load(Ordering::Acquire) { + 1 => break Ok(check()), + 2 => { + break Err(refuse!("AP driver waiter entered with interrupts enabled")); + } + _ if apic::rdtsc().wrapping_sub(started) >= tsc_hz => { + break Err(refuse!("AP did not enter the driver wait")); + } + _ => core::hint::spin_loop(), + } + }; + Ok((pending, value)) + }) + }?; + pending.finish(); + value + } +} + struct Spawned(Box); impl Command for Spawned { type Output = (); diff --git a/crates/stela-boot/src/native_smp/kernel_check.rs b/crates/stela-boot/src/native_smp/kernel_check.rs index f274d76d1f..10a271b733 100644 --- a/crates/stela-boot/src/native_smp/kernel_check.rs +++ b/crates/stela-boot/src/native_smp/kernel_check.rs @@ -9,7 +9,6 @@ use stela_compiler::{GuestState, TargetCpu}; use stela_contracts::Chip; use stela_contracts::identity::Identity; use stela_contracts::refuse; -use stela_drivers::bus::dma::memory::{CacheAttribute, CpuMapping, PageSource, PinnedPages}; use stela_engine::machine::Cpu; use stela_engine::machine::CpuProfile; use stela_engine::machine::DeviceError; @@ -22,15 +21,10 @@ use stela_engine::machine::Stop; use stela_engine::machine::engine; use stela_engine::machine::engine::publication::WorkerBinding; use stela_engine::machine::engine::publication::WorkerId; -use stela_engine::machine::exception::Pstate; +use stela_engine::machine::exception::{DAIF_I, Pstate}; use stela_engine::memory::RegisteredSystemRam; -use stela_engine::memory::ReservedSystemRamRange; use stela_soc::machine; -struct Reservation { - pages: PinnedPages, - mapping: CpuMapping, -} struct TestDevices { starts: Vec, ready: Vec, @@ -156,43 +150,62 @@ impl TestDevices { Ok(engine::ConsumedWrite::Complete { settlement: Ok(()) }) } } -fn reservation() -> Result> { - let pages = crate::native_memory::SOURCE - .allocate(source::BYTES, 4096, CacheAttribute::WriteBack) - .map_err(|_| refuse!("native kernel actual WB page allocation refused"))?; - let mapping = pages - .cpu_mapping(CacheAttribute::WriteBack) - .map_err(|_| refuse!("native kernel CPU mapping refused"))?; - let owner = Arc::new(Reservation { pages, mapping }); - let physical = owner.pages.physical_pages(); - if physical.windows(2).any(|pages| pages[1] != pages[0] + 4096) { - return Err(refuse!( - "native kernel actual page allocation is not contiguous" - )); - } - let range = ReservedSystemRamRange { - source_pa: source::BASE, - host_pa: physical[0], - host_base: owner - .mapping - .address(0, source::BYTES) - .map_err(|_| refuse!("native kernel mapping extent refused"))?, - bytes: source::BYTES, +/// # Safety +/// `loader_ram` is the complete loader backing, reserved exclusively for +/// the guest. No guest, direct publisher or DMA accesses it during the check. +unsafe fn reservation( + handoff: &'static Handoff, + loader_ram: &[host::RamRange], +) -> Result> { + const UNUSED_GUEST_BASE: u64 = 0x8_0000_0000; + const { assert!(source::BASE + source::BYTES as u64 <= source::READY) }; + let bytes = source::BYTES as u64; + let mut ranges = loader_ram.to_vec(); + let index = ranges + .iter() + .position(|range| range.bytes >= bytes) + .ok_or(refuse!( + "native kernel has no contiguous loader RAM for its fixture" + ))?; + let mut backing = ranges.remove(index); + let fixture = host::RamRange { + guest: source::BASE, + host: backing.host, + bytes, }; - // SAFETY: exclusive heap page pin and checked WB CPU mapping. No - // DMA/direct writer is admitted. Arc keeps both through all native frames, - // callbacks, fault recovery and source-PC/publication settlement. - let ram = Arc::new( - unsafe { - RegisteredSystemRam::register( - &[range], - owner, - stela_engine::machine::cpu::RESERVATION_GRANULE, - 64, - ) - } - .map_err(|_| refuse!("native kernel canonical RAM registration refused"))?, - ); + if backing.bytes > bytes { + backing.host = backing + .host + .checked_add(bytes) + .ok_or(refuse!("native kernel loader RAM extent wraps"))?; + backing.bytes -= bytes; + ranges.insert(index, backing); + } + // Keep the retained physical union while leaving the fixture's MMIO + // addresses unbacked. The authored guest only touches its low extent. + let mut guest = UNUSED_GUEST_BASE; + for range in &mut ranges { + range.guest = guest; + guest = guest + .checked_add(range.bytes) + .ok_or(refuse!("native kernel guest RAM extent wraps"))?; + } + ranges.insert(0, fixture); + // SAFETY: only the guest addresses changed. The loader's complete + // physical reservation and the closed writer contract remain held. + let ram = unsafe { super::canonical::reserve(handoff, &ranges) }?; + let zeros = [0; 4096]; + for offset in (0..source::BYTES).step_by(zeros.len()) { + let length = (source::BYTES - offset).min(zeros.len()); + // SAFETY: the validated loader RAM has no other writer, and this + // source slice is disjoint from it. Clear only the fixture. + unsafe { ram.publish_physical(source::BASE + offset as u64, &zeros[..length]) } + .map_err(|_| refuse!("native kernel fixture zeroing failed"))?; + } + Ok(ram) +} + +fn publish_scheduler(ram: &RegisteredSystemRam) -> Result<()> { for (address, descriptor) in source::tables() { // SAFETY: the source bytes are private locals, disjoint from the registered RAM, and `ram` // keeps its registration live. @@ -204,7 +217,7 @@ fn reservation() -> Result> { // keeps its registration live. unsafe { ram.publish_physical(source::CODE, &program) } .map_err(|_| refuse!("native kernel source publication failed"))?; - Ok(ram) + Ok(()) } fn profile(cores: usize) -> Result { let chip = Chip::AppleM1; @@ -264,13 +277,17 @@ pub(crate) unsafe fn check( executors: &Executors, host_owner: &mut host::HostOwner, sender: &Apic, + loader_ram: &[host::RamRange], ) -> Result<()> { let cores = handoff.native_resources.cores as usize; + // SAFETY: this diagnostic owns the complete loader backing and will stop + // before the normal guest or any asynchronous producer can use it. + let ram = unsafe { reservation(handoff, loader_ram) }?; if cores == 1 { // SAFETY: same bootstrap/physical-owner fixture contract. - return unsafe { cold::check(handoff, capture, executors, host_owner, sender) }; + return unsafe { cold::check(handoff, capture, executors, host_owner, sender, ram) }; } - let ram = reservation()?; + publish_scheduler(&ram)?; // Preserve a nonzero guest boot PE while the physical BSP // remains worker0. Other identities and their source affinity stay ordered. let boot_processor = cores - 1; @@ -432,6 +449,9 @@ pub(crate) unsafe fn check( let after = states(&machine)?; for (old, actual) in before.iter().zip(&after) { let mut expected = old.clone(); + // Both READY writes leave the fixture's IRQ asserted. The timer FIQ + // was disabled by its handler, so only IRQ remains in the frame. + expected.pending = u32::from(DAIF_I); for register in [0, 1, 2, 3, 4, 5, 6, 7, 10, 19, 20, 22, 23, 24] { expected.x[register] = actual.x[register]; } diff --git a/crates/stela-boot/src/native_smp/kernel_check/cold.rs b/crates/stela-boot/src/native_smp/kernel_check/cold.rs index 8e3864206e..c0395ae51a 100644 --- a/crates/stela-boot/src/native_smp/kernel_check/cold.rs +++ b/crates/stela-boot/src/native_smp/kernel_check/cold.rs @@ -148,28 +148,8 @@ pub(super) unsafe fn check( executors: &Executors, owner: &mut host::HostOwner, sender: &Apic, + ram: Arc, ) -> Result<()> { - let reservation = handoff.guest[..handoff.guest_count] - .iter() - .find(|region| region.bytes >= source::BYTES as u64) - .ok_or(refuse!("cold fixture has no actual loader RAM reservation"))?; - let range = host::RamRange { - guest: source::BASE, - host: reservation.physical, - bytes: source::BYTES as u64, - }; - // SAFETY: bounded loader-owned scratch reservation, before registration or - // any guest frame/publisher; this check does not enter original macOS. - unsafe { - core::ptr::write_bytes( - crate::layout::physical(range.host) as *mut u8, - 0, - source::BYTES, - ) - }; - // SAFETY: the loader reserved this scratch range for the boot and zeroed it above; nothing else - // reaches it. - let ram = unsafe { super::super::canonical::reserve(handoff, &[range]) }?; // SAFETY: before any frame, guest entry or other publisher; this exact // registered allocation is held by the following Machine. unsafe { tree::check(&ram) }?; diff --git a/crates/stela-boot/src/system.rs b/crates/stela-boot/src/system.rs index 4b95fe51dc..49438ac8d0 100644 --- a/crates/stela-boot/src/system.rs +++ b/crates/stela-boot/src/system.rs @@ -4,8 +4,9 @@ //! this image (taken before any Rust state exists), chooses the host //! placement, places a relocated copy in the Stela window, allocates the //! engine's memory, builds its page tables (five-level under LA57, else -//! four-level), leaves boot services, loads them, through the LA57 -//! trampoline when five-level, and calls the engine phase in the window. See +//! four-level), releases the pristine copy, and leaves boot services. It +//! loads the tables through the LA57 trampoline when five-level and calls +//! the engine phase in the window. See //! `docs/design/system.md#host-placement`. use crate::Result; use crate::{ @@ -20,8 +21,8 @@ use crate::{ use alloc::{format, string::String, vec::Vec}; use core::{ arch::asm, - cell::UnsafeCell, ops::{Range, RangeInclusive}, + ptr::NonNull, }; use stela_boot_core::options::{DEFAULT_WIFI_KEY, System}; use stela_contracts::refuse; @@ -62,36 +63,39 @@ const RELOCATION_DIRECTORY: usize = 5; const IMAGE_REL_BASED_ABSOLUTE: u16 = 0; const IMAGE_REL_BASED_DIR64: u16 = 10; -#[derive(Clone, Copy)] -struct Snapshot { - copy: usize, +/// Private firmware pages owned only while boot services are active. +pub(crate) struct Snapshot { + copy: NonNull, start: usize, bytes: usize, } -struct Pristine(UnsafeCell>); -// SAFETY: written once by the boot processor before anything else runs. -unsafe impl Sync for Pristine {} -static PRISTINE: Pristine = Pristine(UnsafeCell::new(None)); +impl Drop for Snapshot { + fn drop(&mut self) { + let physical = self.copy.as_ptr() as usize; + // SAFETY: this owner holds exactly the pages allocated in take_snapshot. + // The entry and system loader both drop it before exiting boot services. + let result = unsafe { boot::free_pages(self.copy, self.bytes / PAGE as usize) }; + output::arguments(format_args!( + "BOOT IMAGE snapshot physical={physical:#x} bytes={:#x} release={result:?}\n", + self.bytes, + )); + } +} /// Copy this image as the firmware loaded it, before Rust state changes it. /// Only the firmware entry glue has run; its statics are not used later. -pub fn take_snapshot() { - let Ok(image) = boot::open_protocol_exclusive::(boot::image_handle()) else { - return; - }; +pub(crate) fn take_snapshot() -> Option { + let image = boot::open_protocol_exclusive::(boot::image_handle()).ok()?; let (base, bytes) = image.info(); - let Ok(extent) = firmware::loaded_extent(base as usize, bytes) else { - return; - }; + let extent = firmware::loaded_extent(base as usize, bytes).ok()?; let bytes = extent.mapped_bytes; - let Ok(copy) = boot::allocate_pages( + let copy = boot::allocate_pages( AllocateType::AnyPages, MemoryType::LOADER_DATA, bytes / PAGE as usize, - ) else { - return; - }; + ) + .ok()?; // SAFETY: exact checked firmware source extent and distinct fresh owned // pages. Zero only the destination tail, without reading source padding. unsafe { @@ -99,12 +103,12 @@ pub fn take_snapshot() { copy.as_ptr() .add(extent.bytes) .write_bytes(0, bytes - extent.bytes); - *PRISTINE.0.get() = Some(Snapshot { - copy: copy.as_ptr() as usize, - start: base as usize, - bytes, - }); } + Some(Snapshot { + copy, + start: base as usize, + bytes, + }) } fn low_page(kind: MemoryType) -> Result { @@ -602,11 +606,12 @@ pub fn held_at_start(options: &[u8]) -> Option<&'static str> { /// Run the engine; never returns. /// `log` is the partition holding the USB's boot log, when the loader keeps /// one there (`log_file`). -pub fn boot( +pub(crate) fn boot( mut options: Vec, mut volume: FileSystem, log: Option, host_firmware: crate::host_firmware::Resources, + snapshot: Option, ) -> ! { // NVRAM chooses macOS or recoveryOS before any input is read. A machine // NVRAM holds in recovery mode waits at the startup choices, as LLB @@ -635,15 +640,13 @@ pub fn boot( // `inputs` closes the volume: protocols must be closed before boot // services end. let inputs = inputs(&options, volume); - let result = inputs.and_then(|(source, files, storage, wifi_key)| { + let result = inputs.and_then(|inputs| { load( options, - source, - files, - storage, - wifi_key, + inputs, log, host_firmware, + snapshot.ok_or(refuse!("no pristine image copy"))?, ) }); match result { @@ -654,15 +657,14 @@ pub fn boot( fn load( options: Vec, - source: Vec, - bundle: BundleFiles, - storage: Option, - wifi_key: Vec, + inputs: Inputs, log: Option, host_firmware: crate::host_firmware::Resources, + snapshot: Snapshot, ) -> Result { + let (source, bundle, storage, wifi_key) = inputs; crate::status::begin("Setting up Stela's memory"); - let image = memory::prepare_image()?; + let image = memory::prepare_image(&snapshot)?; let text = core::str::from_utf8(&options).map_err(|_| refuse!("stela.cfg is not UTF-8"))?; let system = System::parse(text).map_err(stela_boot_core::options::Error::message)?; let (native_processors, cores) = @@ -750,6 +752,9 @@ fn load( boot_heap.live >> 20, )); release_loader_heap(); + // Reservations have already been sized and the relocated image owns its + // bytes. The final firmware map can now offer the pristine pages to macOS. + drop(snapshot); // SAFETY: the fresh immutable MP observation is held LOADER_DATA. Identity // mappings and the calibrated local APIC remain valid across EBS. let capture = unsafe { diff --git a/crates/stela-boot/src/system/memory.rs b/crates/stela-boot/src/system/memory.rs index 9775f45fae..54e0572743 100644 --- a/crates/stela-boot/src/system/memory.rs +++ b/crates/stela-boot/src/system/memory.rs @@ -15,7 +15,6 @@ fn allocate_large(bytes: u64) -> Result { /// The relocated engine image and the host ranges its mappings must reach. pub(super) struct EngineImage { - pub snapshot: Snapshot, pub image: firmware::Image, pub engine: Region, pub resident: crate::native_image::ResidentImage, @@ -41,9 +40,7 @@ pub(super) struct EngineMemory { } /// Copy and relocate the pristine image into the selected host window. -pub(super) fn prepare_image() -> Result { - // SAFETY: written once at entry, read here. - let snapshot = unsafe { *PRISTINE.0.get() }.ok_or(refuse!("no pristine image copy"))?; +pub(super) fn prepare_image(snapshot: &Snapshot) -> Result { let image = firmware::Image::loaded()?; if image.start != snapshot.start || image.end - image.start != snapshot.bytes { return Err(refuse!("image layout changed after the snapshot")); @@ -71,7 +68,7 @@ pub(super) fn prepare_image() -> Result { // are distinct and each covers exactly snapshot.bytes. unsafe { core::ptr::copy_nonoverlapping( - snapshot.copy as *const u8, + snapshot.copy.as_ptr(), engine.physical as *mut u8, snapshot.bytes, ); @@ -82,7 +79,6 @@ pub(super) fn prepare_image() -> Result { layout::image().wrapping_sub(image.start as u64), )?; Ok(EngineImage { - snapshot, image, engine, resident, @@ -195,7 +191,6 @@ pub(super) fn map( host_firmware: &crate::host_firmware::Resources, ) -> Result { let EngineImage { - snapshot, image, engine, ram, @@ -254,7 +249,7 @@ pub(super) fn map( )?; } // The window: the engine image with section rights, heap, stack, code. - let bytes = snapshot.bytes as u64; + let bytes = engine.bytes; let mut page = 0; while page < bytes { let rights = image.rights(image.start + page as usize); diff --git a/crates/stela-boot/src/tables.rs b/crates/stela-boot/src/tables.rs index 0b56613d17..7f08cc42ce 100644 --- a/crates/stela-boot/src/tables.rs +++ b/crates/stela-boot/src/tables.rs @@ -140,14 +140,11 @@ pub fn map_range( Ok(()) } -/// Unmap `first..=last`, a canonical address range in one half: clear the -/// pages it holds, descending into every table it reaches. The tables stay -/// linked, empty where the range covers them, so a later map of the range -/// takes no new frame: clearing their entries instead would leave their -/// frames taken and unreachable until the whole pool resets. The TLB is the -/// caller's. -pub fn unmap(frames: &dyn Frames, root: u64, first: u64, last: u64) { - clear(frames, root, layout::top_level(), first, last); +/// Unmap `first..=last`, a canonical address range in one half, reporting +/// an address in each present leaf removed. Intermediate tables stay linked +/// for reuse. The caller invalidates any cached translations of those leaves. +pub fn unmap(frames: &dyn Frames, root: u64, first: u64, last: u64, mut removed: impl FnMut(u64)) { + clear(frames, root, layout::top_level(), first, last, &mut removed); } /// [`unmap`] the part of `first..=last` that the root entry `entry` maps, @@ -160,33 +157,44 @@ pub fn unmap_under(frames: &dyn Frames, entry: u64, first: u64, last: u64) { layout::top_level() - 1, first, last, + &mut |_| {}, ); } } -fn clear(frames: &dyn Frames, table: u64, level: u32, first: u64, last: u64) { +fn clear( + frames: &dyn Frames, + table: u64, + level: u32, + first: u64, + last: u64, + removed: &mut impl FnMut(u64), +) { let shift = 12 + 9 * level; // The table maps the aligned region holding the range. let region = first & !((1u64 << (shift + 9)) - 1); + let entries = frames.table(table); for slot in index(first, level)..=index(last, level) { - let start = region | (slot as u64) << shift; - let end = start | ((1u64 << shift) - 1); - let entry = frames.table(table).wrapping_add(slot); + let entry = entries.wrapping_add(slot); // SAFETY: `table` is a live table page of these frames. let value = unsafe { entry.read_volatile() }; if value & PRESENT == 0 { continue; } + let start = region | (slot as u64) << shift; if level == 0 || value & HUGE != 0 { // SAFETY: as above. unsafe { entry.write_volatile(0) }; + removed(start.max(first)); } else { + let end = start | ((1u64 << shift) - 1); clear( frames, value & ADDRESS, level - 1, first.max(start), last.min(end), + removed, ); } } diff --git a/crates/stela-cli/Cargo.toml b/crates/stela-cli/Cargo.toml index 37d5eccb7f..bf14b06c1d 100644 --- a/crates/stela-cli/Cargo.toml +++ b/crates/stela-cli/Cargo.toml @@ -68,8 +68,6 @@ windows-sys = { version = "0.61", features = [ [dev-dependencies] miniz_oxide = { version = "0.9", default-features = false, features = ["with-alloc"] } -# `block::RamDisk`, the disk setup's erase layout is written to in tests. -stela-drivers = { workspace = true, features = ["ram-disk"] } [lints] diff --git a/crates/stela-cli/src/boot.rs b/crates/stela-cli/src/boot.rs index 217e8ef5ee..a7c80d2481 100644 --- a/crates/stela-cli/src/boot.rs +++ b/crates/stela-cli/src/boot.rs @@ -9,7 +9,8 @@ use std::{fs::OpenOptions, io::Write, path::PathBuf}; use stela_formats::payload::Purpose; use stela_loader::aux_kc::{Linked, TRUSTED_CODE_FILE}; use stela_loader::boot_bundle::{ - self, Input, Inputs, Options, OverlayProperty, RootHash, Source, Target, + self, Input, Inputs, Options, OverlayProperty, OwnedRamdisk, RAMDISK_FILE, RootHash, Source, + Target, }; use stela_loader::boot_policy::{ KextGrant, OsEnvironment, SealedVolume, SecurityMode, SecurityPolicy, @@ -776,29 +777,43 @@ impl Prepare { } else { format!("{name} ({})", owner.variant) }; - let (bytes, receipt) = match payload_type { - Some(expected) => { - let (bytes, receipt) = stela_loader::im4p::decode(&container, limit)?; - if receipt.payload_type != expected { - bail!( - "{name} is IM4P type {}, expected {expected}", - receipt.payload_type - ); + let (bytes, container_sha256, payload_type, description, decoded_sha256) = + match payload_type { + Some(expected) => { + let (bytes, receipt) = stela_loader::im4p::decode_owned(container, limit)?; + if receipt.payload_type != expected { + bail!( + "{name} is IM4P type {}, expected {expected}", + receipt.payload_type + ); + } + ( + bytes, + receipt.container_sha256, + receipt.payload_type, + receipt.description, + receipt.decoded_sha256, + ) } - (bytes, Some(receipt)) - } - None => (container.clone(), None), - }; + None => { + let digest = stela_formats::sha256(&container); + ( + container, + digest.clone(), + "opaque".into(), + String::new(), + digest, + ) + } + }; let source = Source { component: label, member: entry.path.clone(), - container_sha256: stela_formats::sha256(&container), - payload_type: receipt - .as_ref() - .map_or_else(|| "opaque".into(), |r| r.payload_type.clone()), - description: receipt.map(|r| r.description).unwrap_or_default(), + container_sha256, + payload_type, + description, decoded_bytes: bytes.len() as u64, - decoded_sha256: stela_formats::sha256(&bytes), + decoded_sha256, }; Ok(Decoded { bytes, @@ -840,6 +855,7 @@ impl Prepare { return Ok(None); } let bytes = restore::archive::read_member(&ipsw, &member, COMPONENT_LIMIT)?; + let digest = stela_formats::sha256(&bytes); let source = Source { component: if cryptex1 { "Cryptex1 manifest" @@ -848,11 +864,11 @@ impl Prepare { } .into(), member, - container_sha256: stela_formats::sha256(&bytes), + container_sha256: digest.clone(), payload_type: "im4m".into(), description: String::new(), decoded_bytes: bytes.len() as u64, - decoded_sha256: stela_formats::sha256(&bytes), + decoded_sha256: digest, }; Ok(Some(Decoded { bytes, @@ -897,13 +913,13 @@ impl Prepare { cryptex_trust_caches.push(component(name, None, COMPONENT_LIMIT).and_then( |raw| { let (bytes, receipt) = - stela_loader::im4p::decode(&raw.bytes, COMPONENT_LIMIT)?; + stela_loader::im4p::decode_owned(raw.bytes, COMPONENT_LIMIT)?; Ok(Decoded { source: Source { payload_type: receipt.payload_type, description: receipt.description, decoded_bytes: bytes.len() as u64, - decoded_sha256: stela_formats::sha256(&bytes), + decoded_sha256: receipt.decoded_sha256, ..raw.source }, bytes, @@ -967,10 +983,7 @@ impl Prepare { let extensions = kexts(&bundles); let (auxiliary, kexts) = Self::auxiliary_collection(&kernel.bytes, &extensions)?.unzip(); let kext_code = Self::kext_code(&extensions)?; - // Set below when the images come from the restore ramdisk. - let sourced: Vec<(String, Decoded)>; - let ramdisk_component: Decoded; - let mut inputs = Inputs { + let inputs = Inputs { target: Target { product_type: model.clone(), device_class: identity.device_class.clone(), @@ -980,7 +993,7 @@ impl Prepare { chip_id: parse_id(identity.ap_chip_id.as_deref())?, board_id: parse_id(identity.ap_board_id.as_deref())?, }, - kernel_collection: input(&kernel), + kernel_collection: input(&kernel).into(), auxiliary_collection: auxiliary.as_ref().map(input), sptm: input(&sptm), txm: input(&txm), @@ -994,7 +1007,7 @@ impl Prepare { .chain(&kext_code) .map(input) .collect(), - ramdisk: ramdisk.as_ref().map(input), + ramdisk: None, root_hash: root_hash.as_ref().map(|(volume, decoded)| RootHash { volume: *volume, im4p: decoded.as_ref().map(input), @@ -1009,7 +1022,13 @@ impl Prepare { }; let mut options = self.options(inputs.dram_base()?)?; options.security.kexts = kexts; - let mut bundle = boot_bundle::prepare(&inputs, &options)?; + let ramdisk_source = ramdisk.as_ref().map(|ramdisk| ramdisk.source.clone()); + let mut bundle = match ramdisk { + Some(Decoded { bytes, source, .. }) => { + boot_bundle::prepare_owned(&inputs, OwnedRamdisk { bytes, source }, &options)? + } + None => boot_bundle::prepare(&inputs, &options)?, + }; let mut unresolved = vec![]; // The board the bundle's DeviceTree describes names its images, each // die the one its own node or its flash's names; the same IPSW's @@ -1021,29 +1040,34 @@ impl Prepare { .filter(|name| !board_firmware.iter().any(|(given, _)| given == name)) .collect(); if !names.is_empty() { - let ramdisk = match &ramdisk { - Some(ramdisk) - if ramdisk.source.component == components::RESTORE_RAMDISK => - { - ramdisk + let separate_ramdisk; + let (bytes, source) = match &ramdisk_source { + Some(source) if source.component == components::RESTORE_RAMDISK => { + let (_, bytes) = bundle + .files + .iter() + .find(|(name, _)| name == RAMDISK_FILE) + .context("the bundle has no restore ramdisk")?; + (bytes.as_slice(), source) } _ => { - ramdisk_component = component( + separate_ramdisk = component( components::RESTORE_RAMDISK, Some("rdsk"), RAMDISK_LIMIT, )?; - &ramdisk_component + (separate_ramdisk.bytes.as_slice(), &separate_ramdisk.source) } }; - sourced = - board_firmware::from_ramdisk(ramdisk, board_firmware::DIRECTORY, &names)?; - inputs.board_firmware.extend( - sourced - .iter() - .map(|(name, decoded)| (name.clone(), input(decoded))), - ); - bundle = boot_bundle::prepare(&inputs, &options)?; + let sourced = board_firmware::from_ramdisk( + bytes, + source, + board_firmware::DIRECTORY, + &names, + )?; + for (name, Decoded { bytes, source, .. }) in sourced { + bundle.append_board_firmware(name, bytes, source)?; + } } } Err(error) if board_firmware.is_empty() => unresolved.push(format!( diff --git a/crates/stela-cli/src/boot/board_firmware.rs b/crates/stela-cli/src/boot/board_firmware.rs index 099c87a2ac..f66db30ce3 100644 --- a/crates/stela-cli/src/boot/board_firmware.rs +++ b/crates/stela-cli/src/boot/board_firmware.rs @@ -54,12 +54,13 @@ impl ReadAt for Slice<'_> { /// Each of `names` from `directory` of the decoded restore ramdisk's APFS /// volumes, with its source. pub(super) fn from_ramdisk( - ramdisk: &Decoded, + ramdisk: &[u8], + ramdisk_source: &Source, directory: &str, names: &[String], ) -> Result> { - let member = &ramdisk.source.member; - let mut source = Slice(&ramdisk.bytes); + let member = &ramdisk_source.member; + let mut source = Slice(ramdisk); let offsets = apfs::containers(&mut source) .with_context(|| format!("the restore ramdisk {member} holds no APFS container"))?; let [offset] = offsets[..] else { @@ -93,11 +94,11 @@ pub(super) fn from_ramdisk( let source = Source { component: "BoardFirmware".into(), member: member.clone(), - container_sha256: ramdisk.source.container_sha256.clone(), + container_sha256: ramdisk_source.container_sha256.clone(), payload_type: "raw".into(), description: format!( "board device firmware /{path} in the {} (decoded SHA-256 {})", - ramdisk.source.component, ramdisk.source.decoded_sha256 + ramdisk_source.component, ramdisk_source.decoded_sha256 ), decoded_bytes: bytes.len() as u64, decoded_sha256: digest, @@ -145,7 +146,8 @@ mod tests { #[test] fn named_images_come_from_the_ramdisk_with_their_source() { let ramdisk = ramdisk(); - let found = from_ramdisk(&ramdisk, "", &["pattern.bin".into()]).unwrap(); + let found = + from_ramdisk(&ramdisk.bytes, &ramdisk.source, "", &["pattern.bin".into()]).unwrap(); let [(name, image)] = &found[..] else { panic!("one image"); }; @@ -165,7 +167,12 @@ mod tests { image.source.description ); - let Err(error) = from_ramdisk(&ramdisk, DIRECTORY, &["USB-C_HPM,47.bin".into()]) else { + let Err(error) = from_ramdisk( + &ramdisk.bytes, + &ramdisk.source, + DIRECTORY, + &["USB-C_HPM,47.bin".into()], + ) else { panic!("an image the ramdisk lacks is refused"); }; assert_eq!( diff --git a/crates/stela-cli/src/setup/command.rs b/crates/stela-cli/src/setup/command.rs index e894d05608..dc4ef561cd 100644 --- a/crates/stela-cli/src/setup/command.rs +++ b/crates/stela-cli/src/setup/command.rs @@ -332,8 +332,8 @@ struct Create { #[arg(long)] install_volume: Option, /// The bound of each translation pack `stela.efi` keeps on the USB, in - /// bytes (64 MiB to 4 GiB; 0 for none). By default 2 GiB, or what the - /// USB's FAT32 volumes have room for. + /// bytes (64 MiB to the FAT32 file limit; 0 for none). Defaults to 1 GiB + /// or what fits. The mount uses up to 1 GiB of each allocation. #[arg(long, value_name = "BYTES")] translation_store_bytes: Option, /// The model or size, as setup shows it, of the whole disk `--usb` diff --git a/crates/stela-cli/src/setup/format.rs b/crates/stela-cli/src/setup/format.rs index fe07820e6a..6299618abe 100644 --- a/crates/stela-cli/src/setup/format.rs +++ b/crates/stela-cli/src/setup/format.rs @@ -245,39 +245,106 @@ fn volume_label(label: &str) -> Result<[u8; 11]> { #[cfg(test)] mod tests { use super::*; - use stela_drivers::block::RamDisk; + use std::ops::Range; + use stela_drivers::block::{BlockDevice, BlockError, Identity, Transport}; use {stela_formats::payload::ReadAt, stela_runtime::pc::fat32::Fat32}; - /// A disk holding the layout's writes over bytes that are not zero. - fn image(bytes: u64, block_size: u32, layout: &Layout) -> RamDisk { - let mut disk = RamDisk::new("USB", bytes / u64::from(block_size), block_size); - disk.bytes.fill(0xa5); - for write in &layout.writes { - match write { - Write::Bytes(at, data) => { - let at = *at as usize; - disk.bytes[at..at + data.len()].copy_from_slice(data); + /// A dirty disk with the layout's ordered writes applied only to reads. + struct Image<'a> { + identity: Identity, + writes: Vec<(Range, Option<&'a [u8]>)>, + } + + impl<'a> Image<'a> { + fn new(bytes: u64, block_size: u32, layout: &'a Layout) -> Self { + let block = u64::from(block_size); + assert!(bytes.is_multiple_of(block)); + let writes = layout + .writes + .iter() + .map(|write| { + let (start, length, data) = match write { + Write::Bytes(at, data) => (*at, data.len() as u64, Some(data.as_slice())), + Write::Zeros(at, length) => (*at, *length, None), + }; + let end = start.checked_add(length).expect("layout write overflows"); + assert!(end <= bytes, "layout write exceeds disk capacity"); + (start..end, data) + }) + .collect(); + Self { + identity: Identity { + transport: Transport::Ram, + location: "test".into(), + model: "layout".into(), + serial: "USB".into(), + blocks: bytes / block, + block_size, + read_only: true, + features: Default::default(), + }, + writes, + } + } + + fn read_bytes(&self, offset: u64, buffer: &mut [u8]) { + let end = offset + buffer.len() as u64; + assert!(end <= self.identity.bytes()); + buffer.fill(0xa5); + for (write, data) in &self.writes { + let start = offset.max(write.start); + let end = end.min(write.end); + if start >= end { + continue; } - Write::Zeros(at, length) => { - disk.bytes[*at as usize..(*at + *length) as usize].fill(0); + let output = &mut buffer[(start - offset) as usize..(end - offset) as usize]; + if let Some(data) = data { + output.copy_from_slice( + &data[(start - write.start) as usize..(end - write.start) as usize], + ); + } else { + output.fill(0); } } } - disk + } + + impl BlockDevice for Image<'_> { + fn identity(&self) -> &Identity { + &self.identity + } + + fn read(&mut self, lba: u64, buffer: &mut [u8]) -> Result<(), BlockError> { + self.identity.check(lba, buffer.len())?; + self.read_bytes(lba * u64::from(self.identity.block_size), buffer); + Ok(()) + } + + fn write(&mut self, _lba: u64, _data: &[u8]) -> Result<(), BlockError> { + Err(BlockError::ReadOnly) + } } /// One partition's bytes, as the FAT reader reads them. - struct Volume<'a>(&'a [u8]); + struct Volume<'a> { + disk: &'a Image<'a>, + start: u64, + bytes: u64, + } impl ReadAt for Volume<'_> { type Error = &'static str; fn len(&self) -> u64 { - self.0.len() as u64 + self.bytes } fn read_at(&mut self, offset: u64, buffer: &mut [u8]) -> Result<(), Self::Error> { - let at = usize::try_from(offset).map_err(|_| "offset")?; - let bytes = self.0.get(at..at + buffer.len()).ok_or("past the end")?; - buffer.copy_from_slice(bytes); + if offset + .checked_add(buffer.len() as u64) + .is_none_or(|end| end > self.bytes) + { + return Err("past the end"); + } + self.disk.read_bytes(self.start + offset, buffer); Ok(()) } } @@ -297,7 +364,7 @@ mod tests { fn erase_creates_bootable_fat32_layout() { let bytes = 2u64 << 30; let layout = layout(bytes, 512, "STELA", &mut counter()).unwrap(); - let mut disk = image(bytes, 512, &layout); + let mut disk = Image::new(bytes, 512, &layout); let table = gpt::read(&mut disk).unwrap(); let [esp, data] = &table.partitions[..] else { panic!("{:?}", table.partitions) @@ -310,22 +377,34 @@ mod tests { assert_eq!(data.first_lba * 512 % ALIGNMENT, 0); // The backup GPT ends the disk. assert!((data.last_lba + 1) * 512 <= bytes - 33 * 512); + let mut sector = [0; 512]; + disk.read_bytes(bytes - 512, &mut sector); + assert_eq!(§or[..8], b"EFI PART"); assert_ne!(esp.unique, data.unique); // The gap before the ESP is zeroed but for the GPT. - assert!( - disk.bytes[34 * 512..ALIGNMENT as usize] - .iter() - .all(|b| *b == 0) - ); + let mut buffer = [0; 4096]; + for start in (34 * 512..ALIGNMENT).step_by(buffer.len()) { + let len = (ALIGNMENT - start).min(buffer.len() as u64) as usize; + disk.read_bytes(start, &mut buffer[..len]); + assert!(buffer[..len].iter().all(|&byte| byte == 0)); + } + disk.read_bytes(data.last_lba * 512, &mut sector); + assert_eq!(sector, [0xa5; 512]); for (partition, label) in [(esp, b"EFI "), (data, b"STELA ")] { - let first = (partition.first_lba * 512) as usize; - let end = ((partition.last_lba + 1) * 512) as usize; - let volume = &disk.bytes[first..end]; - assert_eq!(&volume[71..82], label); - assert_eq!(&volume[82..90], b"FAT32 "); + let first = partition.first_lba * 512; + disk.read_bytes(first, &mut sector); + assert_eq!(§or[71..82], label); + assert_eq!(§or[82..90], b"FAT32 "); // The backup boot sector, and an empty root directory. - assert_eq!(volume[..512], volume[6 * 512..7 * 512]); - let mut fat = Fat32::open(Volume(volume)).unwrap(); + let mut backup = [0; 512]; + disk.read_bytes(first + 6 * 512, &mut backup); + assert_eq!(sector, backup); + let mut fat = Fat32::open(Volume { + disk: &disk, + start: first, + bytes: partition.blocks() * 512, + }) + .unwrap(); assert!(fat.file("EFI/BOOT/BOOTX64.EFI").is_err()); } } diff --git a/crates/stela-cli/src/setup/medium.rs b/crates/stela-cli/src/setup/medium.rs index f74dd1247d..49095336c7 100644 --- a/crates/stela-cli/src/setup/medium.rs +++ b/crates/stela-cli/src/setup/medium.rs @@ -13,10 +13,10 @@ //! 4 GiB limit, so their concatenation is the IPSW byte for byte. Each piece //! is written as `ipsw.NNN.partial`, read back, and renamed; a rerun keeps //! every complete piece whose bytes still match the IPSW and writes only -//! the rest. The IPSW's SHA-256 and SHA-1 are taken while its pieces are -//! written, and compared with its download receipt and Apple's catalog -//! digest; `payload.json` is written only when they match, so a medium -//! without it is never taken for a complete one. +//! the rest. While writing the IPSW, setup checks its SHA-256 and any +//! catalog SHA-1 supplied by the download receipt. It writes +//! `payload.json` after verification, so a medium without it is never +//! taken for a complete one. //! //! A remote medium ([`write_remote`]) holds only `payload.json` and //! `blocks.bin`: `stela.efi` streams the IPSW from Apple's servers during @@ -331,27 +331,35 @@ fn stream( Ok(()) } +fn stream_file( + path: &Path, + size: u64, + progress: &crate::progress::Phase, + mut consume: impl FnMut(&[u8]), +) -> Result<()> { + let mut file = + fs::File::open(path).with_context(|| format!("cannot read {}", path.display()))?; + stream(&mut file, size, |bytes| { + consume(bytes); + progress.advance(bytes.len() as u64); + Ok(()) + }) +} + fn hash_file( path: &Path, size: u64, progress: &crate::progress::Phase, ) -> Result<(String, Vec)> { - let mut file = - fs::File::open(path).with_context(|| format!("cannot read {}", path.display()))?; let mut hashes = Hashes::default(); - stream(&mut file, size, |bytes| { - hashes.update(bytes); - progress.advance(bytes.len() as u64); - Ok(()) - })?; + stream_file(path, size, progress, |bytes| hashes.update(bytes))?; Ok(hashes.finish()) } -/// The whole IPSW's SHA-256 and catalog SHA-1. -#[derive(Default)] -struct Whole { +/// The whole IPSW's SHA-256 and its SHA-1 if the catalog supplies one. +struct Whole<'a> { sha256: Sha256, - sha1: Sha1, + catalog: Option<(&'a str, Sha1)>, } /// Read `size` bytes of `ipsw` from `offset` and return their hashes; @@ -362,7 +370,7 @@ fn piece( offset: u64, size: u64, partial: Option<&Path>, - mut whole: Option<&mut Whole>, + mut whole: Option<&mut Whole<'_>>, progress: &crate::progress::Phase, ) -> Result<(String, Vec)> { ipsw.seek(SeekFrom::Start(offset))?; @@ -376,7 +384,9 @@ fn piece( hashes.update(bytes); if let Some(whole) = whole.as_deref_mut() { whole.sha256.update(bytes); - whole.sha1.update(bytes); + if let Some((_, hash)) = &mut whole.catalog { + hash.update(bytes); + } } match (&mut out, partial) { (Some(out), Some(path)) => out @@ -445,7 +455,10 @@ pub(super) fn write(options: WriteOptions<'_>) -> Result { ipsw.display(), sizes.len() ); - let mut whole = Whole::default(); + let mut whole = Whole { + sha256: Sha256::new(), + catalog: expected.sha1.as_deref().map(|digest| (digest, Sha1::new())), + }; let mut pieces = Vec::new(); let mut piece_blocks = Vec::new(); let mut written = Written::default(); @@ -506,7 +519,6 @@ pub(super) fn write(options: WriteOptions<'_>) -> Result { } } let sha256 = hex::encode(whole.sha256.finalize()); - let sha1 = hex::encode(whole.sha1.finalize()); ensure!( manifest.source.sha256.as_ref() == Some(&sha256), "{} changed while setup read it: its SHA-256 is now {sha256}", @@ -520,14 +532,17 @@ pub(super) fn write(options: WriteOptions<'_>) -> Result { ipsw.display() ); } - if let Some(catalog) = &expected.sha1 { + manifest.source.catalog_sha1 = if let Some((catalog, hash)) = whole.catalog { + let sha1 = hex::encode(hash.finalize()); ensure!( sha1.eq_ignore_ascii_case(catalog), "{}'s SHA-1 {sha1} differs from Apple's catalog digest {catalog}; download it again", ipsw.display() ); - } - manifest.source.catalog_sha1 = expected.sha1.as_ref().map(|_| sha1); + Some(sha1) + } else { + None + }; manifest.layout = Layout::Pieces { piece_bytes, pieces, @@ -722,6 +737,20 @@ pub(super) mod tests { .flat_map(|index| fs::read(directory.join(piece_name(index))).unwrap()) .collect(); assert_eq!(joined, bytes); + + let manual = write(WriteOptions { + volume: &volume, + ipsw: &ipsw, + inventory: inventory(&ipsw), + expected: &Expected::default(), + piece_bytes: PIECE_BYTES, + }) + .unwrap(); + assert_eq!((manual.kept, manual.wrote), (count, 0)); + let manual_manifest = + PayloadManifest::parse(&fs::read(directory.join(MANIFEST_FILE)).unwrap()).unwrap(); + assert_eq!(manual_manifest.source.sha256, manifest.source.sha256); + assert!(manual_manifest.source.catalog_sha1.is_none()); } #[test] diff --git a/crates/stela-cli/src/setup/medium/download.rs b/crates/stela-cli/src/setup/medium/download.rs index 8a1dba22f8..d6b7b415db 100644 --- a/crates/stela-cli/src/setup/medium/download.rs +++ b/crates/stela-cli/src/setup/medium/download.rs @@ -74,7 +74,8 @@ fn write_from( } let mut pieces = Vec::new(); let mut piece_blocks = Vec::new(); - let mut whole = Whole::default(); + let mut whole_sha256 = Sha256::new(); + let mut whole_sha1 = Sha1::new(); let progress = crate::progress::Phase::bytes("Downloading macOS onto USB", total); for (index, &size) in sizes.iter().enumerate() { let mut file = fs::File::create(directory.join(format!("{}.partial", piece_name(index))))?; @@ -82,8 +83,8 @@ fn write_from( stream(&mut source, size, |bytes| { file.write_all(bytes)?; hashes.update(bytes); - whole.sha256.update(bytes); - whole.sha1.update(bytes); + whole_sha256.update(bytes); + whole_sha1.update(bytes); progress.advance(bytes.len() as u64); Ok(()) })?; @@ -99,8 +100,8 @@ fn write_from( source.read(&mut [0])? == 0, "download exceeds the expected image size" ); - let sha256 = hex::encode(whole.sha256.finalize()); - let sha1 = hex::encode(whole.sha1.finalize()); + let sha256 = hex::encode(whole_sha256.finalize()); + let sha1 = hex::encode(whole_sha1.finalize()); ensure!( image .sha1 @@ -113,8 +114,14 @@ fn write_from( for (index, piece) in pieces.iter().enumerate() { let path = directory.join(piece_name(index)); let partial = directory.join(format!("{}.partial", piece_name(index))); + // The download already recorded the per-block hashes. Readback + // verifies the piece's digest before publishing it. + let mut readback = Sha256::new(); + stream_file(&partial, piece.bytes, &progress, |bytes| { + readback.update(bytes); + })?; ensure!( - hash_file(&partial, piece.bytes, &progress)?.0 == piece.sha256, + hex::encode(readback.finalize()) == piece.sha256, "USB data does not read back as written" ); if path.exists() { @@ -255,11 +262,38 @@ mod tests { written.wrote > 1, "the fixture must exercise joined-piece reads" ); - let manifest = fs::read(directory(&volume, &image.build).join(MANIFEST_FILE))?; + let written_dir = directory(&volume, &image.build); + let manifest = fs::read(written_dir.join(MANIFEST_FILE))?; let manifest = stela_formats::payload::PayloadManifest::parse(&manifest) .map_err(anyhow::Error::msg)?; - assert!(matches!(manifest.layout, Layout::Pieces { .. })); assert_eq!(manifest.source.sha256, Some(stela_formats::sha256(&bytes))); + let Layout::Pieces { + pieces, + block_hashes, + .. + } = manifest.layout + else { + panic!("download did not publish a pieces layout"); + }; + let mut expected_blocks = Vec::new(); + assert_eq!( + pieces.len(), + bytes.len().div_ceil(HASH_BLOCK_BYTES as usize) + ); + for (index, (piece, expected)) in pieces + .iter() + .zip(bytes.chunks(HASH_BLOCK_BYTES as usize)) + .enumerate() + { + let digest = Sha256::digest(expected); + expected_blocks.extend_from_slice(&digest); + assert_eq!(piece.sha256, hex::encode(digest)); + assert_eq!(fs::read(written_dir.join(piece_name(index)))?, expected); + } + assert_eq!( + fs::read(written_dir.join(block_hashes.file))?, + expected_blocks + ); let mut damaged = bytes.clone(); damaged[0] ^= 1; let mut oversized = bytes.clone(); diff --git a/crates/stela-cli/src/setup/tests.rs b/crates/stela-cli/src/setup/tests.rs index 38559962d6..8514403904 100644 --- a/crates/stela-cli/src/setup/tests.rs +++ b/crates/stela-cli/src/setup/tests.rs @@ -1770,6 +1770,16 @@ fn additional_disk_gets_separate_machine_identity() { assert!(!f.esp.join("EFI/stela").exists()); } +#[test] +fn translation_store_defaults_to_the_firmware_pack_limit() { + let f = fixture(64 * GIB, true); + let (store, _) = translations::choose(&f.host, &[&f.data], |_| 0, None).unwrap(); + assert_eq!(store.unwrap().pack_bytes, GIB); + + let (store, _) = translations::choose(&f.host, &[&f.data], |_| 0, Some(2 * GIB)).unwrap(); + assert_eq!(store.unwrap().pack_bytes, 2 * GIB); +} + #[test] fn same_revision_update_preserves_options() { let mut f = fixture(64 * GIB, false); diff --git a/crates/stela-cli/src/setup/translations.rs b/crates/stela-cli/src/setup/translations.rs index 7c0a65b5ec..63b8a071e8 100644 --- a/crates/stela-cli/src/setup/translations.rs +++ b/crates/stela-cli/src/setup/translations.rs @@ -36,6 +36,7 @@ use std::{ path::{Path, PathBuf}, time::SystemTime, }; +use stela_boot_core::memory_budget::MAX_TRANSLATION_PACK_BYTES; /// The store's directory on its volume. pub(super) const DIRECTORY: &str = "stela/store"; @@ -54,7 +55,7 @@ const ID_BYTES: usize = 32; const HEADER_BYTES: usize = PACK_MAGIC.len() + 4 + 4 + ID_BYTES; const MIB: u64 = 1024 * 1024; /// One pack's bound by default. -pub(super) const DEFAULT_PACK_BYTES: u64 = 2 * 1024 * MIB; +pub(super) const DEFAULT_PACK_BYTES: u64 = MAX_TRANSLATION_PACK_BYTES; /// The smallest bound worth keeping a store for. pub(super) const MIN_PACK_BYTES: u64 = 64 * MIB; /// FAT32's largest file, on a 1 MiB boundary. diff --git a/crates/stela-compiler/src/aarch64/system/synchronization.rs b/crates/stela-compiler/src/aarch64/system/synchronization.rs index 05e718c1d8..1a43144f9e 100644 --- a/crates/stela-compiler/src/aarch64/system/synchronization.rs +++ b/crates/stela-compiler/src/aarch64/system/synchronization.rs @@ -96,6 +96,10 @@ pub enum Operation { } pub fn decode(word: u32) -> Option { + // All the modeled hint, barrier and timed-wait forms share this class. + if word >> 16 != 0xd503 { + return None; + } if word & BARRIER_MASK == DSB_CLASS { let option = ((word >> OPTION_SHIFT) & OPTION_MASK) as u8; if option == SSBB_OPTION || option == PSSBB_OPTION { diff --git a/crates/stela-compiler/src/block.rs b/crates/stela-compiler/src/block.rs index c183fd0c9b..1825907487 100644 --- a/crates/stela-compiler/src/block.rs +++ b/crates/stela-compiler/src/block.rs @@ -562,7 +562,12 @@ impl CompilationPlan { checked.emit(parsed.terminal.as_ref(), parsed.next_pc, target, recipes)? } else if let Some(resident) = resident { resident - .emit(&parsed.instructions) + .emit( + &parsed.instructions, + parsed.terminal.as_ref(), + parsed.next_pc, + target, + ) .map_err(CompileError::from)? } else if profile.has(Features::RESIDENT_LOOPS) { crate::x86_64::block::emit_resident_fallback_for_target( diff --git a/crates/stela-compiler/src/block/analysis.rs b/crates/stela-compiler/src/block/analysis.rs index e18e9854a6..2e52ad5388 100644 --- a/crates/stela-compiler/src/block/analysis.rs +++ b/crates/stela-compiler/src/block/analysis.rs @@ -318,15 +318,12 @@ pub(super) fn parse( }); continue; } - if let Some(decoded) = - system::decode_system_mode_instruction(pc, word).map_err(|error| { - BlockAnalysisError { - pc, - encoding: Some(word), - kind: error.kind, - } - })? - { + if let Some(decoded) = system::decode_system_mode_with_sync(pc, word, synchronization) + .map_err(|error| BlockAnalysisError { + pc, + encoding: Some(word), + kind: error.kind, + })? { // The shared lane executes these through the existing typed // all-writer memory service, not the single-agent CPU monitor. let checked = checked_memory diff --git a/crates/stela-compiler/src/block/pointer_authentication.rs b/crates/stela-compiler/src/block/pointer_authentication.rs index bf5c78a97a..b8f6522f5d 100644 --- a/crates/stela-compiler/src/block/pointer_authentication.rs +++ b/crates/stela-compiler/src/block/pointer_authentication.rs @@ -125,6 +125,11 @@ pub fn decode_pointer_authentication( .at_instruction(pc, word), ); } + // The PAuth and PAuth_LR forms below occupy these encoding classes. + // Reject other words before probing the exact forms and operand masks. + if !matches!(word >> 24, 0x55 | 0x9a | 0xd5..=0xd7 | 0xda | 0xf3 | 0xf8) { + return Ok(None); + } let operation = if let Some(instruction) = pauth_lr::decode(word) { PointerAuthenticationOperation::LinkRegister(instruction) } else { diff --git a/crates/stela-compiler/src/block/recovery.rs b/crates/stela-compiler/src/block/recovery.rs index 52ffc1556d..c0a0a97d49 100644 --- a/crates/stela-compiler/src/block/recovery.rs +++ b/crates/stela-compiler/src/block/recovery.rs @@ -110,7 +110,8 @@ impl FaultRecovery { state: &mut crate::GuestState, ) -> Result, FaultRecoveryError> { let mut settlement: Option = None; - let mut values = [None; 32]; + let mut values = [0; 32]; + let mut present = 0u32; for entry in table { if entry.start >= entry.end { return Err(FaultRecoveryError::InvalidNativeRange { @@ -166,21 +167,23 @@ impl FaultRecovery { .ok_or(FaultRecoveryError::NativeSpillUnavailable { offset })?, }; let slot = &mut values[usize::from(binding.guest)]; - if slot.is_some_and(|previous| previous != value) { + let bit = 1 << binding.guest; + if present & bit != 0 && *slot != value { return Err(FaultRecoveryError::ConflictingGuestBinding { register: binding.guest, }); } - *slot = Some(value); + *slot = value; + present |= bit; } } - for (guest, value) in values.into_iter().enumerate() { - if let Some(value) = value { - if guest == 31 { - state.sp = value; - } else { - state.x[guest] = value; - } + while present != 0 { + let guest = present.trailing_zeros() as usize; + present &= present - 1; + if guest == 31 { + state.sp = values[guest]; + } else { + state.x[guest] = values[guest]; } } Ok(settlement) diff --git a/crates/stela-compiler/src/block/recovery/packed.rs b/crates/stela-compiler/src/block/recovery/packed.rs index 400d33589d..16a0971b97 100644 --- a/crates/stela-compiler/src/block/recovery/packed.rs +++ b/crates/stela-compiler/src/block/recovery/packed.rs @@ -7,10 +7,15 @@ use super::{ SpillOffset, }; use crate::GuestAddress; -use alloc::{boxed::Box, vec::Vec}; +use alloc::{borrow::Cow, boxed::Box, vec::Vec}; const AFTER_FALLTHROUGH: u8 = 1 << 2; const TRANSLATED: u8 = 1 << 3; +const SEPARATE_PC_DELTA: u8 = 1 << 4; +const BINDINGS_SHIFT: u32 = 5; +const LONG_BINDINGS: usize = 7; +const RETAINED_ROWS: usize = 4; +const RETAINED_BINDINGS: usize = 32; fn zigzag(value: i64) -> u64 { ((value << 1) ^ (value >> 63)) as u64 @@ -53,10 +58,31 @@ impl Reader<'_> { shift += 7; } } + + fn skip_bindings(&mut self, count: usize) { + // A guest byte and a single-byte source, as for every host GPR. + let (head, tail) = self.bytes.split_at(2 * count); + if head + .as_chunks::<2>() + .0 + .iter() + .all(|binding| binding[1] < 0x80) + { + self.bytes = tail; + return; + } + for _ in 0..count { + self.byte(); + self.value(); + } + } } impl PackedRecovery { pub fn new(rows: &[FaultRecovery]) -> Self { + if rows.is_empty() { + return Self(Box::default()); + } let mut out = Vec::with_capacity(rows.len() * 12 + 2); put(&mut out, rows.len() as u64); let (mut end, mut pc, mut retired) = (0, 0, 0); @@ -64,27 +90,42 @@ impl PackedRecovery { let point = row.retirement; let at = point.instruction_pc().0; let site = row.site; - put(&mut out, zigzag(row.start as i64 - end)); - put(&mut out, (row.end - row.start) as u64); - put(&mut out, zigzag(at.wrapping_sub(pc) as i64)); - put( - &mut out, - zigzag(i64::from(point.retired_before()) - retired), - ); + let pc_delta = at.wrapping_sub(pc) as i64; + let retired_delta = i64::from(point.retired_before()) - retired; + let separate_pc = pc_delta != retired_delta * 4; + let inline_bindings = row.bindings.len().min(LONG_BINDINGS); + let start = zigzag(row.start as i64 - end); + let span = (row.end - row.start) as u64; + let delta = zigzag(retired_delta); let translated = site.translated_access(); - out.push( - site.kind() as u8 - | if point.phase() == RetirementPhase::AfterFallthrough { - AFTER_FALLTHROUGH - } else { - 0 - } - | if translated.is_some() { TRANSLATED } else { 0 }, - ); + let tag = site.kind() as u8 + | if point.phase() == RetirementPhase::AfterFallthrough { + AFTER_FALLTHROUGH + } else { + 0 + } + | if translated.is_some() { TRANSLATED } else { 0 } + | if separate_pc { SEPARATE_PC_DELTA } else { 0 } + | (inline_bindings as u8) << BINDINGS_SHIFT; + if (start | span | delta) < 0x80 { + out.extend_from_slice(&[start as u8, span as u8, delta as u8, tag]); + } else { + put(&mut out, start); + put(&mut out, span); + put(&mut out, delta); + out.push(tag); + } + // The PC normally advances by four bytes for each instruction + // retired. Keep a separate delta only when the row differs. + if separate_pc { + put(&mut out, zigzag(pc_delta)); + } if let Some(access) = translated { out.extend_from_slice(&[access.bytes, access.flags]); } - put(&mut out, row.bindings.len() as u64); + if inline_bindings == LONG_BINDINGS { + put(&mut out, row.bindings.len() as u64); + } for binding in &row.bindings { out.push(binding.guest); put( @@ -107,36 +148,100 @@ impl PackedRecovery { /// The rows given to [`Self::new`]. pub fn rows(&self) -> Vec { + let mut rows = Vec::new(); + self.decode(None, &mut rows); + rows + } + + /// Rows that apply at this native offset, plus any malformed ranges that + /// the caller must reject regardless of where the fault occurred. + pub fn rows_at(&self, offset: usize) -> Vec { + let mut rows = Vec::new(); + self.decode(Some(offset), &mut rows); + rows + } + + /// Like [`Self::rows_at`], reusing storage across fault lookups. Large + /// tables are owned by this lookup alone, so the scratch retains only + /// enough space for a few rows and a register file's worth of bindings + /// in each. + pub fn rows_at_reusing<'a>( + &self, + offset: usize, + scratch: &'a mut Vec, + ) -> Cow<'a, [FaultRecovery]> { + let count = self.decode(Some(offset), scratch); + if scratch.capacity() > RETAINED_ROWS + || scratch + .iter() + .any(|row| row.bindings.capacity() > RETAINED_BINDINGS) + { + let mut rows = core::mem::take(scratch); + rows.truncate(count); + Cow::Owned(rows) + } else { + Cow::Borrowed(&scratch[..count]) + } + } + + fn decode(&self, offset: Option, rows: &mut Vec) -> usize { + if self.0.is_empty() { + return 0; + } let mut reader = Reader { bytes: &self.0 }; let count = reader.value() as usize; - let mut rows = Vec::with_capacity(count); + if offset.is_none() { + rows.reserve(count); + } + let mut kept = 0; let (mut end, mut pc, mut retired) = (0, 0, 0); for _ in 0..count { let start = end + unzigzag(reader.value()); let row_end = start + reader.value() as i64; - pc = u64::wrapping_add(pc, unzigzag(reader.value()) as u64); - retired += unzigzag(reader.value()); + let retired_delta = unzigzag(reader.value()); + retired += retired_delta; let tag = reader.byte(); + let pc_delta = if tag & SEPARATE_PC_DELTA == 0 { + retired_delta * 4 + } else { + unzigzag(reader.value()) + }; + pc = u64::wrapping_add_signed(pc, pc_delta); let translated = (tag & TRANSLATED != 0).then(|| (reader.byte(), reader.byte())); - let bindings = (0..reader.value()) - .map(|_| { - let guest = reader.byte(); - let source = reader.value(); - RecoveryBinding { - guest, - source: if source & 1 == 0 { - RecoverySource::HostRegister((source >> 1) as u8) - } else { - RecoverySource::NativeSpill( - SpillOffset::new((source >> 1) as u16).expect("packed by new"), - ) - }, - } - }) - .collect(); - rows.push(FaultRecovery { - start: start as usize, - end: row_end as usize, + let inline_bindings = usize::from(tag >> BINDINGS_SHIFT); + let binding_count = if inline_bindings == LONG_BINDINGS { + reader.value() as usize + } else { + inline_bindings + }; + let range = start as usize..row_end as usize; + end = row_end; + if offset.is_some_and(|at| range.start < range.end && !range.contains(&at)) { + reader.skip_bindings(binding_count); + continue; + } + let mut bindings = rows.get_mut(kept).map_or_else(Vec::new, |row| { + let mut bindings = core::mem::take(&mut row.bindings); + bindings.clear(); + bindings + }); + bindings.extend((0..binding_count).map(|_| { + let guest = reader.byte(); + let source = reader.value(); + RecoveryBinding { + guest, + source: if source & 1 == 0 { + RecoverySource::HostRegister((source >> 1) as u8) + } else { + RecoverySource::NativeSpill( + SpillOffset::new((source >> 1) as u16).expect("packed by new"), + ) + }, + } + })); + let row = FaultRecovery { + start: range.start, + end: range.end, bindings, retirement: RetirementPoint::packed( GuestAddress(pc), @@ -148,10 +253,15 @@ impl PackedRecovery { }, ), site: RecoverySite::packed(tag & 3, translated), - }); - end = row_end; + }; + if let Some(prior) = rows.get_mut(kept) { + *prior = row; + } else { + rows.push(row); + } + kept += 1; } - rows + kept } } @@ -160,6 +270,78 @@ mod tests { use super::*; use alloc::vec; + #[test] + fn empty_tables_keep_no_payload() { + let packed = PackedRecovery::new(&[]); + assert_eq!(packed.bytes(), 0); + assert!(packed.rows().is_empty()); + } + + #[test] + fn a_large_binding_count_round_trips_with_a_separate_pc_delta() { + let row = FaultRecovery { + start: 10, + end: 15, + bindings: (0..12) + .map(|register| RecoveryBinding::gpr(register, register)) + .collect(), + retirement: RetirementPoint::before(GuestAddress(0x1234_8000), 26).unwrap(), + site: RecoverySite::guest_access(), + }; + let packed = PackedRecovery::new(core::slice::from_ref(&row)); + assert_eq!(packed.rows(), [row]); + } + + #[test] + fn selected_rows_keep_overlaps_and_malformed_ranges() { + let row = |start, end| FaultRecovery { + start, + end, + bindings: vec![RecoveryBinding::gpr(1, 2)], + retirement: RetirementPoint::before(GuestAddress(0x4000), 0).unwrap(), + site: RecoverySite::guest_access(), + }; + let rows = [row(0, 4), row(8, 16), row(9, 11), row(100, 100)]; + let packed = PackedRecovery::new(&rows); + assert_eq!( + packed.rows_at(10), + [rows[1].clone(), rows[2].clone(), rows[3].clone()], + ); + assert_eq!(packed.rows_at(16), [rows[3].clone()]); + + let mut scratch = Vec::new(); + let selected = packed.rows_at_reusing(10, &mut scratch); + assert_eq!(selected.as_ref(), packed.rows_at(10)); + let bindings = selected[0].bindings.as_ptr(); + let selected = packed.rows_at_reusing(16, &mut scratch); + assert_eq!(selected.as_ref(), packed.rows_at(16)); + assert_eq!(selected[0].bindings.as_ptr(), bindings); + } + + #[test] + fn oversized_fault_tables_do_not_grow_the_scratch() { + let row = FaultRecovery { + start: 0, + end: 4, + bindings: vec![RecoveryBinding::gpr(1, 2)], + retirement: RetirementPoint::before(GuestAddress(0x4000), 0).unwrap(), + site: RecoverySite::guest_access(), + }; + let rows = vec![row.clone(); RETAINED_ROWS + 1]; + let bindings = FaultRecovery { + bindings: vec![RecoveryBinding::gpr(1, 2); RETAINED_BINDINGS + 1], + ..row + }; + for table in [&rows[..], &[bindings][..]] { + let packed = PackedRecovery::new(table); + let mut scratch = Vec::new(); + let selected = packed.rows_at_reusing(0, &mut scratch); + assert!(matches!(selected, Cow::Owned(_))); + assert_eq!(selected.as_ref(), table); + assert_eq!(scratch.capacity(), 0); + } + } + #[test] fn rows_survive_packing_exactly_and_in_order() { let pc = 0xffff_fe00_0912_3000; @@ -172,7 +354,7 @@ mod tests { end: 47, bindings: vec![ RecoveryBinding::gpr(3, 9), - RecoveryBinding::spill(30, SpillOffset::new(8).unwrap()), + RecoveryBinding::spill(30, SpillOffset::new(96).unwrap()), ], retirement: point(8, 2), site: RecoverySite::guest_access(), @@ -202,6 +384,7 @@ mod tests { ]; let packed = PackedRecovery::new(&rows); assert_eq!(packed.rows(), rows); + assert_eq!(packed.rows_at(13), [rows[1].clone()]); assert!(packed.0.len() < 64); assert_eq!(PackedRecovery::new(&[]).rows(), []); } diff --git a/crates/stela-compiler/src/block/system.rs b/crates/stela-compiler/src/block/system.rs index 90e6771b42..d621be3349 100644 --- a/crates/stela-compiler/src/block/system.rs +++ b/crates/stela-compiler/src/block/system.rs @@ -2,7 +2,6 @@ //! //! Native blocks return only the instruction's PC and exit kind; the runtime //! re-decodes the source word before applying the effect. -use crate::aarch64::Unsupported; use crate::{ CompileError, GuestAddress, @@ -225,6 +224,53 @@ fn serialize_family( pub fn decode_system_instruction( pc: GuestAddress, word: u32, +) -> Result, CompileError> { + decode_instruction(pc, word, synchronization::decode(word), false) +} + +/// Decode the EL1 system instructions the platform completes. NOP, PAuth +/// aliases and other hints keep their existing decoding. +pub(super) fn decode_el1_system_instruction( + pc: GuestAddress, + word: u32, +) -> Result, CompileError> { + let sync = synchronization::decode(word); + if let Some(instruction) = decode_instruction(pc, word, sync, false)? { + return Ok(Some(instruction)); + } + let Some(operation @ synchronization::Operation::DataCompletion { .. }) = sync else { + return Ok(None); + }; + request(pc, word, SystemOperation::Synchronization(operation)).map(Some) +} + +/// Decode every instruction the system-mode profile hands to the runtime: the +/// [`decode_el1_system_instruction`] families, SYS/SYSL, and the barriers and +/// hints that the ordinary decoder does not own (DSB, SSBB/PSSBB, ESB, +/// TSB and unallocated hints), Apple's GXF instructions, SDSB, WKDMC and +/// WKDMD, the Debug-state-only MOVT GPR/ZT0 forms, and the FEAT_CPA pointer +/// arithmetic. YIELD, CSDB, SB and DMB stay ordinary and BTI compiles as NOP; +/// PAuth hints belong to the PAuth decoder, which the profile consults first. +pub fn decode_system_mode_instruction( + pc: GuestAddress, + word: u32, +) -> Result, CompileError> { + decode_system_mode_with_sync(pc, word, synchronization::decode(word)) +} + +pub(super) fn decode_system_mode_with_sync( + pc: GuestAddress, + word: u32, + sync: Option, +) -> Result, CompileError> { + decode_instruction(pc, word, sync, true) +} + +fn decode_instruction( + pc: GuestAddress, + word: u32, + sync: Option, + system_mode: bool, ) -> Result, CompileError> { if !pc.0.is_multiple_of(INSTRUCTION_BYTES) { return Err( @@ -232,7 +278,76 @@ pub fn decode_system_instruction( .at_instruction(pc, word), ); } - let synchronization = match synchronization::decode(word) { + // Route by the fixed high byte of the encoding classes. Ordinary ALU, + // branch and memory words outside these classes need no family probes. + // The family decoders still own every fixed bit and operand check. + let operation = match word >> 24 { + 0x00 => exception::decode(word) + .map(SystemOperation::Exception) + .or_else(|| { + if !system_mode { + return None; + } + GuardedOperation::decode(word) + .map(SystemOperation::Guarded) + .or_else(|| { + AppleMaintenance::decode(word).map(SystemOperation::AppleMaintenance) + }) + .or_else(|| decode_sdsb(word).map(SystemOperation::Synchronization)) + .or_else(|| crate::wkdm::decode(word).map(SystemOperation::Compression)) + }), + 0x08 | 0x48 | 0x88 | 0xc8 if system_mode => { + crate::aarch64::exclusive::decode(word).map(SystemOperation::Exclusive) + } + 0x38 | 0x78 | 0xb8 | 0xf8 if system_mode => { + // Reserved sizes and opcodes stay with the ordinary decoder. + crate::aarch64::unprivileged::decode(word) + .and_then(Result::ok) + .map(SystemOperation::Unprivileged) + } + 0x68 | 0x69 | 0xd9 => tag_memory::decode(word).map(SystemOperation::TagMemory), + 0x91 | 0xd1 if system_mode => match tag_arithmetic::decode(word) { + Some( + operand @ tag_arithmetic::Operand { + kind: tag_arithmetic::Kind::Offset { .. }, + .. + }, + ) => Some(SystemOperation::TagOffset(operand)), + _ => None, + }, + 0x9a => tag_memory::decode(word) + .map(SystemOperation::TagMemory) + .or_else(|| { + if system_mode { + decode_checked_pointer(word) + } else { + None + } + }), + 0x9b | 0xda if system_mode => decode_checked_pointer(word), + 0xc0 if system_mode => { + DebugStateOperation::decode(word).map(SystemOperation::DebugStateOnly) + } + 0xd4 | 0xd6 => exception::decode(word).map(SystemOperation::Exception), + 0xd5 => decode_system_class(word, sync, system_mode)?, + _ => None, + }; + operation + .map(|operation| request(pc, word, operation)) + .transpose() +} + +fn decode_checked_pointer(word: u32) -> Option { + crate::aarch64::checked_pointer::decode(word).map(SystemOperation::CheckedPointer) +} + +/// Hints, barriers, CLREX, system registers, PSTATE and SYS/SYSL share 0xd5. +fn decode_system_class( + word: u32, + sync: Option, + system_mode: bool, +) -> Result, CompileError> { + let terminal_sync = match sync { Some(synchronization::Operation::SendEvent { local }) => { Some(SystemOperation::SendEvent { local }) } @@ -249,128 +364,53 @@ pub fn decode_system_instruction( _ => None, }; let mut operations = [ - exception::decode(word).map(SystemOperation::Exception), - tag_memory::decode(word).map(SystemOperation::TagMemory), - synchronization, + terminal_sync, registers::decode(word).map(SystemOperation::Register), registers::decode_pstate_immediate(word).map(SystemOperation::PstateImmediate), ] .into_iter() .flatten(); - let Some(operation) = operations.next() else { - return Ok(None); - }; - if operations.next().is_some() { - return Err(CompileError::new( - crate::CompileErrorKind::AmbiguousSystemInstruction, - )); - } - let next_pc = GuestAddress( - pc.0.checked_add(INSTRUCTION_BYTES) - .ok_or_else(|| CompileError::new(crate::CompileErrorKind::GuestAddressOverflow))?, - ); - Ok(Some(SystemInstruction { - instruction_pc: pc, - next_pc, - word, - operation, - })) -} - -/// Decode the EL1 system instructions the platform completes. NOP, PAuth -/// aliases and other hints keep their existing decoding. -pub(super) fn decode_el1_system_instruction( - pc: GuestAddress, - word: u32, -) -> Result, CompileError> { - if let Some(instruction) = decode_system_instruction(pc, word)? { - return Ok(Some(instruction)); - } - let Some(operation @ synchronization::Operation::DataCompletion { .. }) = - synchronization::decode(word) - else { - return Ok(None); - }; - let next_pc = GuestAddress( - pc.0.checked_add(INSTRUCTION_BYTES) - .ok_or_else(|| CompileError::new(crate::CompileErrorKind::GuestAddressOverflow))?, - ); - Ok(Some(SystemInstruction { - instruction_pc: pc, - next_pc, - word, - operation: SystemOperation::Synchronization(operation), - })) -} - -/// Decode every instruction the system-mode profile hands to the runtime: the -/// [`decode_el1_system_instruction`] families, SYS/SYSL, and the barriers and -/// hints that the ordinary decoder does not own (DSB, SSBB/PSSBB, ESB, -/// TSB and unallocated hints), Apple's GXF instructions, SDSB, WKDMC and -/// WKDMD, the Debug-state-only MOVT -/// GPR/ZT0 forms, and -/// the FEAT_CPA pointer arithmetic. -/// YIELD, CSDB, SB and DMB stay ordinary and BTI compiles as NOP; PAuth hints belong to the PAuth -/// decoder, which the profile consults first. -pub fn decode_system_mode_instruction( - pc: GuestAddress, - word: u32, -) -> Result, CompileError> { - if let Some(instruction) = decode_system_instruction(pc, word)? { - return Ok(Some(instruction)); - } - let operation = if let Some(operation) = GuardedOperation::decode(word) { - SystemOperation::Guarded(operation) - } else if let Some(operation) = AppleMaintenance::decode(word) { - SystemOperation::AppleMaintenance(operation) - } else if let Some(operation) = decode_sdsb(word) { - SystemOperation::Synchronization(operation) - } else if let Some(instruction) = crate::wkdm::decode(word) { - SystemOperation::Compression(instruction) - } else if let Some(operation) = DebugStateOperation::decode(word) { - SystemOperation::DebugStateOnly(operation) - } else if let Some(decoded) = crate::aarch64::exclusive::decode(word) { - SystemOperation::Exclusive(decoded) - } else if let Some(operand) = crate::aarch64::checked_pointer::decode(word) { - SystemOperation::CheckedPointer(operand) - } else if let Some( - operand @ tag_arithmetic::Operand { - kind: tag_arithmetic::Kind::Offset { .. }, - .. - }, - ) = tag_arithmetic::decode(word) - { - SystemOperation::TagOffset(operand) - } else if let Some(decoded) = crate::aarch64::unprivileged::decode(word) { - // Reserved sizes and opcodes stay with the ordinary decoder. - match decoded { - Ok(operand) => SystemOperation::Unprivileged(operand), - Err(Unsupported) => return Ok(None), + if let Some(operation) = operations.next() { + if operations.next().is_some() { + return Err(CompileError::new( + crate::CompileErrorKind::AmbiguousSystemInstruction, + )); } - } else if let Some(access) = registers::decode_sys(word) { - SystemOperation::Maintenance(access) - } else { - match synchronization::decode(word) { + return Ok(Some(operation)); + } + if !system_mode { + return Ok(None); + } + Ok(crate::aarch64::exclusive::decode(word) + .map(SystemOperation::Exclusive) + .or_else(|| registers::decode_sys(word).map(SystemOperation::Maintenance)) + .or(match sync { Some( operation @ (synchronization::Operation::DataCompletion { .. } | synchronization::Operation::StoreBypassBarrier { .. } | synchronization::Operation::ErrorSynchronization | synchronization::Operation::TraceSynchronization | synchronization::Operation::OtherHint { .. }), - ) if word != NOP => SystemOperation::Synchronization(operation), - _ => return Ok(None), - } - }; + ) if word != NOP => Some(SystemOperation::Synchronization(operation)), + _ => None, + })) +} + +fn request( + pc: GuestAddress, + word: u32, + operation: SystemOperation, +) -> Result { let next_pc = GuestAddress( pc.0.checked_add(INSTRUCTION_BYTES) .ok_or_else(|| CompileError::new(crate::CompileErrorKind::GuestAddressOverflow))?, ); - Ok(Some(SystemInstruction { + Ok(SystemInstruction { instruction_pc: pc, next_pc, word, operation, - })) + }) } const NOP: u32 = 0xd503_201f; diff --git a/crates/stela-compiler/src/block/system/tests.rs b/crates/stela-compiler/src/block/system/tests.rs index efaa21a9a1..3d6efd3786 100644 --- a/crates/stela-compiler/src/block/system/tests.rs +++ b/crates/stela-compiler/src/block/system/tests.rs @@ -203,8 +203,16 @@ fn system_mode_claims_cpa_arithmetic_with_its_operands() { fn system_mode_claims_exclusives_and_their_undefined_overlaps() { use crate::aarch64::exclusive::{ConstrainedUndefined, Operand}; let pc = GuestAddress(0x1000); - // LDXR X1, [X2]; STXR W3, X1, [X2]; LDAXP X1, X4, [X2]; CLREX. - for word in [0xc85f_7c41, 0xc803_7c41, 0xc87f_9041, 0xd503_305f] { + // LDXRB/H, LDXR W/X, STXR, LDAXP and CLREX. + for word in [ + 0x085f_7c41, + 0x485f_7c41, + 0x885f_7c41, + 0xc85f_7c41, + 0xc803_7c41, + 0xc87f_9041, + 0xd503_305f, + ] { let instruction = decode_system_mode_instruction(pc, word).unwrap().unwrap(); assert!( matches!(instruction.operation, SystemOperation::Exclusive(Ok(_))), @@ -231,8 +239,8 @@ fn system_mode_claims_exclusives_and_their_undefined_overlaps() { #[test] fn system_mode_claims_unprivileged_transfers_but_not_reserved_forms() { let pc = GuestAddress(0x1000); - // LDTR X1, [X2, #8]; STTR W1, [X2]; LDTRSB W3, [X2]. - for word in [0xf840_8841, 0xb800_0841, 0x38c0_0843] { + // LDTR X1, [X2, #8]; STTR W1, [X2]; LDTRSH and LDTRSB W3, [X2]. + for word in [0xf840_8841, 0xb800_0841, 0x78c0_0843, 0x38c0_0843] { let instruction = decode_system_mode_instruction(pc, word).unwrap().unwrap(); assert!( matches!(instruction.operation, SystemOperation::Unprivileged(_)), diff --git a/crates/stela-compiler/src/x86_64.rs b/crates/stela-compiler/src/x86_64.rs index d8461531aa..9f41cba5dd 100644 --- a/crates/stela-compiler/src/x86_64.rs +++ b/crates/stela-compiler/src/x86_64.rs @@ -1009,8 +1009,19 @@ pub(super) enum Rax { } /// What RAX holds after `operation`'s emission by [`emit_instruction`]. -pub(super) fn rax_after(operation: &Operation) -> Rax { +pub(super) fn rax_after(operation: &Operation, pinned: bool) -> Rax { match *operation { + Operation::Memory { + transfer: MemoryTransfer::Load { .. }, + data, + mode: AddressMode::Offset, + .. + } + | Operation::MemoryRegisterOffset(crate::aarch64::register_offset::Operand { + transfer: MemoryTransfer::Load { .. }, + data, + .. + }) if pinned && data != Register::Zero => Rax::Guest(data), Operation::AddSub { flags: true, .. } | Operation::AddSubRegister { flags: true, .. } | Operation::AddSubExtended { flags: true, .. } @@ -1038,18 +1049,26 @@ pub(super) fn rax_after(operation: &Operation) -> Rax { } } -/// [`load`]'s bytes for a register in code like `like`, but for XZR. -pub(super) fn register_load(like: &Code, register: Register) -> Option { - let mut code = like.alike(); - load(&mut code, register); - offset(register).map(|_| code) +/// [`load`]'s bytes for a register, but for XZR. +pub(super) fn register_load(scratch: &mut Code, register: Register, pinned: bool) -> Option<&[u8]> { + offset(register)?; + scratch.clear(); + scratch.set_pinned(pinned); + load(scratch, register); + Some(scratch) } -/// [`store`]'s bytes for a register in code like `like`, but for XZR. -pub(super) fn register_store(like: &Code, register: Register) -> Option { - let mut code = like.alike(); - store(&mut code, register); - offset(register).map(|_| code) +/// [`store`]'s bytes for a register, but for XZR. +pub(super) fn register_store( + scratch: &mut Code, + register: Register, + pinned: bool, +) -> Option<&[u8]> { + offset(register)?; + scratch.clear(); + scratch.set_pinned(pinned); + store(scratch, register); + Some(scratch) } /// `movabs rax,value`. @@ -1127,10 +1146,16 @@ pub(crate) fn emit_instruction( Alu, Gpr::{Rax, Rcx}, }; - if pinned::emit_direct(code, &instruction.operation) { + if pinned::emit_direct(code, &instruction.operation, target) { return; } match instruction.operation { + Operation::AddSub { .. } + | Operation::AddSubRegister { .. } + | Operation::LogicalImmediate { .. } + | Operation::LogicalRegister { .. } => { + unreachable!("common integer emitter handled the operation") + } Operation::FloatingPoint(_) => { unreachable!("numerical instructions require block emission") } @@ -1139,7 +1164,9 @@ pub(crate) fn emit_instruction( Operation::Bitfield(operand) => bitfield::emit(code, &operand), Operation::PcRelative(operand) => pc_relative::emit(code, &operand), Operation::ConditionalSelect(operand) => conditional_select::emit(code, &operand, false), - Operation::ConditionalCompare(operand) => conditional_select::emit_compare(code, &operand), + Operation::ConditionalCompare(operand) => { + conditional_select::emit_compare(code, &operand, false) + } Operation::Crc(operand) => crc::emit(code, &operand, target), Operation::Flags(operand) => flags::emit(code, &operand), Operation::Synchronization(operand) => system::synchronization::emit(code, &operand) @@ -1246,24 +1273,6 @@ pub(crate) fn emit_instruction( nzcv(code, false); } } - Operation::AddSubRegister { - width, - subtract, - flags, - destination, - left, - right, - shift, - amount, - } => { - load(code, left); - right_operand(code, right, width, shift, amount); - add_sub(code, width, subtract); - store(code, destination); - if flags { - nzcv(code, subtract); - } - } Operation::AddSubExtended { width, subtract, @@ -1276,17 +1285,22 @@ pub(crate) fn emit_instruction( } => { // Read both operands before a possibly overlapping destination/SP write. load(code, left); - right_operand(code, right, Width::X64, Shift::Lsl, 0); use asm::Size::{Byte, Dword, Qword, Word}; let mut asm = code.asm(); - match extend { - RegisterExtend::Uxtb => asm.movzx(Dword, Rcx, Byte, Rcx), - RegisterExtend::Uxth => asm.movzx(Dword, Rcx, Word, Rcx), - RegisterExtend::Uxtw => asm.mov(Dword, Rcx, Rcx), - RegisterExtend::Sxtb => asm.movsx(Qword, Rcx, Byte, Rcx), - RegisterExtend::Sxth => asm.movsx(Qword, Rcx, Word, Rcx), - RegisterExtend::Sxtw => asm.movsxd(Rcx, Rcx), - RegisterExtend::Uxtx | RegisterExtend::Sxtx => {} + if let Some(storage) = asm.guest(right) { + match extend { + RegisterExtend::Uxtb => asm.movzx(Dword, Rcx, Byte, storage), + RegisterExtend::Uxth => asm.movzx(Dword, Rcx, Word, storage), + RegisterExtend::Uxtw => asm.mov_load(Dword, Rcx, storage), + RegisterExtend::Sxtb => asm.movsx(Qword, Rcx, Byte, storage), + RegisterExtend::Sxth => asm.movsx(Qword, Rcx, Word, storage), + RegisterExtend::Sxtw => asm.movsxd(Rcx, storage), + RegisterExtend::Uxtx | RegisterExtend::Sxtx => { + asm.mov_load(Qword, Rcx, storage) + } + } + } else { + asm.alu(Alu::Xor, Dword, Rcx, Rcx); } if amount != 0 { asm.shift_imm(asm::ShiftOp::Shl, Qword, Rcx, amount); @@ -1305,47 +1319,6 @@ pub(crate) fn emit_instruction( Operation::Atomic(operand) => atomic::emit(code, &operand, target, checks), Operation::Ordered(operand) => ordered::emit(code, &operand, target, checks), Operation::Prefetch(operand) => prefetch::emit(code, &operand), - Operation::LogicalImmediate { - width, - kind, - flags, - destination, - source, - immediate, - } => { - load(code, source); - let mut asm = code.asm(); - asm.mov_imm64(Rcx, immediate); - asm.alu(logical(kind), asm::Size::of(width == Width::X64), Rax, Rcx); - store(code, destination); // MOV preserves the logical result flags. - if flags { - nzcv(code, false); // AND clears CF/OF, matching ARM C/V=0. - } - } - Operation::LogicalRegister { - width, - kind, - invert, - flags, - destination, - left, - right, - shift, - amount, - } => { - load(code, left); - right_operand(code, right, width, shift, amount); - let size = asm::Size::of(width == Width::X64); - let mut asm = code.asm(); - if invert { - asm.unary(asm::Unary::Not, size, Rcx); - } - asm.alu(logical(kind), size, Rax, Rcx); - store(code, destination); - if flags { - nzcv(code, false); - } // AND clears host CF/OF, matching ARM C/V=0. - } Operation::Return => code.asm().ret(), Operation::Exclusive(_) => unreachable!("exclusive requires checked context emitter"), Operation::CheckedPointer(_) => { @@ -1379,26 +1352,6 @@ pub(crate) fn emit_instruction( } store(code, destination); } - Operation::AddSub { - width, - subtract, - flags, - destination, - source, - immediate, - } => { - load(code, source); - code.asm().alu_imm32( - if subtract { Alu::Sub } else { Alu::Add }, - asm::Size::of(width == Width::X64), - Rax, - immediate as i32, - ); - store(code, destination); // MOV leaves arithmetic flags unchanged. - if flags { - nzcv(code, subtract); - } - } } } diff --git a/crates/stela-compiler/src/x86_64/asm/code.rs b/crates/stela-compiler/src/x86_64/asm/code.rs index 6314f6e516..550c8138bd 100644 --- a/crates/stela-compiler/src/x86_64/asm/code.rs +++ b/crates/stela-compiler/src/x86_64/asm/code.rs @@ -94,14 +94,6 @@ impl Code { ..Self::new() } } - /// Empty code of this one's kind. - pub(crate) fn alike(&self) -> Self { - Self { - pinned: self.pinned, - constant_time: self.constant_time, - ..Self::new() - } - } /// The instructions from here on have `index` in the block's source map. pub(crate) fn set_instruction(&mut self, index: usize) { self.instruction = index; @@ -318,25 +310,33 @@ impl Code { pub(crate) fn remove_instruction(&mut self, range: core::ops::Range) { assert!(!range.is_empty()); let removed = range.len(); - self.sites.retain_mut(|site| { + // Sites and check jumps are appended in code order. Forwarding + // removes an instruction near the end, so visit only the suffix. + let mut removed_site = None; + for (index, site) in self.sites.iter_mut().enumerate().rev() { if site.end <= range.start { - true - } else if site.start >= range.end { + break; + } + if site.start >= range.end { site.start -= removed; site.end -= removed; - true } else { assert!( site.start == range.start && site.end == range.end, "remove one complete faulting instruction" ); - false + removed_site = Some(index); + break; } - }); - for (jump, _) in &mut self.failures { - if jump.at >= range.end { - jump.at -= removed; + } + if let Some(index) = removed_site { + self.sites.remove(index); + } + for (jump, _) in self.failures.iter_mut().rev() { + if jump.at < range.end { + break; } + jump.at -= removed; } self.bytes.drain(range); self.instructions = self @@ -345,11 +345,12 @@ impl Code { .expect("counted instruction"); } /// Remove every byte and instruction. - #[cfg(test)] pub(crate) fn clear(&mut self) { self.bytes.clear(); self.instructions = 0; self.sites.clear(); + self.instruction = 0; + self.failures.clear(); } } diff --git a/crates/stela-compiler/src/x86_64/asm/integer.rs b/crates/stela-compiler/src/x86_64/asm/integer.rs index 9282391ab6..c96b1bb703 100644 --- a/crates/stela-compiler/src/x86_64/asm/integer.rs +++ b/crates/stela-compiler/src/x86_64/asm/integer.rs @@ -97,6 +97,21 @@ impl Asm<'_> { self.legacy(size, None, &[0x0f, 0xa4], source as u8, false, rm.into()); self.data(&[amount]); } + /// `andn dst, inverted, rm`: `~inverted & rm` (BMI1). + pub(crate) fn andn(&mut self, size: Size, destination: Gpr, inverted: Gpr, rm: Rm) { + self.vex( + Vex { + map: Map::M0f38, + pp: Pp::None, + w: size == Size::Qword, + l: false, + }, + 0xf2, + destination.number(), + inverted.number(), + rm, + ); + } /// A BMI1 group 17 form (VEX.0F38 F3 /digit) writing `destination`. fn bmi1_group(&mut self, digit: u8, size: Size, destination: Gpr, rm: Rm) { self.vex( diff --git a/crates/stela-compiler/src/x86_64/asm/tests/span.rs b/crates/stela-compiler/src/x86_64/asm/tests/span.rs index 5e51279369..4123911112 100644 --- a/crates/stela-compiler/src/x86_64/asm/tests/span.rs +++ b/crates/stela-compiler/src/x86_64/asm/tests/span.rs @@ -90,6 +90,32 @@ fn guest_site_markers_follow_span_copy_split_and_instruction_elision() { assert!(copied.sites().is_empty()); } +#[test] +fn removing_an_access_preserves_sites_on_both_sides() { + let mut code = Code::new(); + code.asm().guest_check(); + let start = code.len(); + code.asm() + .guest_access(|asm| asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base(Gpr::Rax, 0))); + let end = code.len(); + code.asm().guest_check(); + let before = code.sites()[0]; + let after = code.sites()[2]; + code.remove_instruction(start..end); + assert_eq!(code.instructions(), 2); + assert_eq!( + code.sites(), + &[ + before, + EmissionSite { + start: 2, + end: 4, + ..after + } + ] + ); +} + #[test] fn lock_prefix_is_part_of_the_guest_operand_site() { let mut code = Code::new(); diff --git a/crates/stela-compiler/src/x86_64/block.rs b/crates/stela-compiler/src/x86_64/block.rs index c88424071a..bc2484c5b3 100644 --- a/crates/stela-compiler/src/x86_64/block.rs +++ b/crates/stela-compiler/src/x86_64/block.rs @@ -9,7 +9,7 @@ pub(crate) use super::region::ResidentLoopPlan; use super::chain::ExitWord; use crate::{ GuestAddress, NativeBlock, - aarch64::{Instruction, Operation, Register}, + aarch64::{Instruction, Operation, Register, Width, integer_math, integer_unary, pc_relative}, block::{ExitKind, Terminator}, }; @@ -89,6 +89,31 @@ pub(crate) fn emit_ordinary_for_target( optimize: true, fault_table: false, pinned: false, + frame_loop: None, + }, + super::MemoryChecks::DEFAULT, + super::NativeSystem::NONE, + ) + .0 +} + +pub(crate) fn emit_frame_loop( + instructions: &[Instruction], + terminal: Option<&(GuestAddress, Terminator)>, + fallthrough: GuestAddress, + target: crate::TargetCpu, + entry: GuestAddress, +) -> NativeBlock { + emit_selected( + instructions, + terminal, + fallthrough, + target, + RegionPolicy { + optimize: true, + fault_table: false, + pinned: false, + frame_loop: Some(entry), }, super::MemoryChecks::DEFAULT, super::NativeSystem::NONE, @@ -129,6 +154,7 @@ pub(crate) fn emit_for_target( optimize: false, fault_table: false, pinned: false, + frame_loop: None, }, checks, super::NativeSystem::NONE, @@ -162,6 +188,7 @@ pub(crate) fn emit_system_mode( optimize: false, fault_table: true, pinned: true, + frame_loop: None, }, super::MemoryChecks { guest_range: true, @@ -178,6 +205,32 @@ struct RegionPolicy { fault_table: bool, /// Keep guest registers in host registers ([`super::pinned`]). pinned: bool, + frame_loop: Option, +} + +/// The final address of a flagless ADD that overwrites its adjacent ADR(P). +pub(super) fn fold_address_pair( + first: &Operation, + second: &Operation, +) -> Option { + let Operation::PcRelative(address) = *first else { + return None; + }; + let Operation::AddSub { + width: Width::X64, + subtract: false, + flags: false, + destination: destination @ Register::X(_), + source, + immediate, + } = *second + else { + return None; + }; + (destination == address.destination && source == destination).then_some(pc_relative::Operand { + destination, + address: address.address.wrapping_add(u64::from(immediate)), + }) } /// With `fault_table`, region accesses keep dirty values in registers and @@ -195,6 +248,7 @@ fn emit_selected( optimize: optimize_regions, fault_table, pinned, + frame_loop, } = regions; let mut fault_recovery = vec![]; let mut block = super::Emitted::default(); @@ -209,10 +263,12 @@ fn emit_selected( code.set_linked_block(first.0); } code.set_constant_time(target.data_independent_timing()); + let frame_loop = frame_loop.map(|entry| super::region::FrameLoop::begin(code, entry)); let mut fixups = vec![]; // The DIT audit covers each instruction's own lowering, not the // register-allocated and clean-load regions' recipes. let optimize_regions = optimize_regions && !target.data_independent_timing(); + let fuse_pairs = optimize_regions && frame_loop.is_none() && !fault_table && !pinned; // Which accesses check the guest range (`guest_range`), and each // instruction's checks. let ranges = if checks.guest_range && checks.checks_every_access() { @@ -240,6 +296,9 @@ fn emit_selected( // What the last instruction emitted left in registers. let mut after = Held::NOTHING; let mut out_of_line = OutOfLine::default(); + // Forwarding probes encode one expected MOV at a time. Keep their + // bytes in one buffer across the block and its temporary candidates. + let mut scratch = Code::default(); // Each branch the block runs past: its jump to a side exit, its target // and the instructions up to it. let mut side_exits = vec![]; @@ -283,7 +342,7 @@ fn emit_selected( { let count = region.consumed_instructions; let chunk = &instructions[cursor..cursor + count]; - let baseline = |checks_at: &dyn Fn(usize) -> super::MemoryChecks| { + let mut baseline = |checks_at: &dyn Fn(usize) -> super::MemoryChecks| { let mut code = Code::new(); let mut map = vec![]; let mut fixups = vec![]; @@ -292,11 +351,14 @@ fn emit_selected( map.push((instruction.pc, code.len())); after = emit_single( &mut code, + &mut scratch, None, instruction, &mut fixups, - target, - checks_at(cursor + index), + SingleOptions { + target, + checks: checks_at(cursor + index), + }, after, ); } @@ -351,6 +413,58 @@ fn emit_selected( continue; } let instruction = &instructions[cursor]; + // System chains only enter and poll at block boundaries. Neither + // operation has a guest fault site, and an independent entry at ADD + // still compiles from its own source. Preserve both retirement rows. + if pinned + && !code.constant_time() + && let Some(second) = instructions.get(cursor + 1) + && instruction.pc.0.checked_add(4) == Some(second.pc.0) + && let Some(address) = fold_address_pair(&instruction.operation, &second.operation) + { + block.source_map.push((instruction.pc, code.len())); + code.set_instruction(block.source_map.len() - 1); + code.asm().nop(); + block.source_map.push((second.pc, code.len())); + code.set_instruction(block.source_map.len() - 1); + super::pinned::emit_pc_relative(code, address); + if code.host(address.destination).is_none() { + after.rax = super::Rax::Guest(address.destination); + } + cursor += 2; + continue; + } + // An ordinary block runs the pair together. A truncated block or + // an entry at CLZ still emits its original operation. + if fuse_pairs + && let Operation::IntegerMath(reverse) = instruction.operation + && let integer_math::Kind::ReverseBits { width } = reverse.kind + && let Some(second) = instructions.get(cursor + 1) + && let Operation::IntegerMath(count) = second.operation + && count.kind == (integer_math::Kind::LeadingZeros { width }) + && reverse.destination != Register::Zero + && count.left == reverse.destination + && count.destination == reverse.destination + && instruction.pc.0.checked_add(4) == Some(second.pc.0) + { + block.source_map.push((instruction.pc, code.len())); + code.set_instruction(block.source_map.len() - 1); + code.asm().nop(); + block.source_map.push((second.pc, code.len())); + code.set_instruction(block.source_map.len() - 1); + super::integer_unary::emit( + code, + &integer_unary::Operand { + kind: integer_unary::Kind::TrailingZeros, + width, + destination: count.destination, + source: reverse.left, + }, + target, + ); + cursor += 2; + continue; + } block.source_map.push((instruction.pc, code.len())); code.set_instruction(block.source_map.len() - 1); if let Some(target) = instruction.operation.conditional_target() { @@ -367,11 +481,14 @@ fn emit_selected( } after = emit_single( code, + &mut scratch, Some(&mut out_of_line), instruction, &mut fixups, - target, - checks_at(cursor), + SingleOptions { + target, + checks: checks_at(cursor), + }, held, ); if frame_bound { @@ -385,18 +502,30 @@ fn emit_selected( "ordinary instruction prefix cannot branch" ); out_of_line.place(code); - emit_terminal( - code, - &mut block.source_map, - terminal, - TerminalContext { - fallthrough, - native, - checks, - rax: after.rax, - target, - }, - ); + if let Some(frame_loop) = frame_loop { + let Some((pc, Terminator::Branch(operation))) = terminal else { + unreachable!("a frame loop has a validated direct branch") + }; + debug_assert!(side_exits.is_empty()); + block.source_map[0].1 = 0; + block.source_map.push((*pc, code.len())); + code.set_instruction(block.source_map.len() - 1); + let taken = branch_condition(code, operation, after.rax); + frame_loop.finish(code, taken, fallthrough); + } else { + emit_terminal( + code, + &mut block.source_map, + terminal, + TerminalContext { + fallthrough, + native, + checks, + rax: after.rax, + target, + }, + ); + } // After the terminal, whose direct exits end the code before them. let instructions_run = block.source_map.len(); for (jump, target, run) in side_exits { @@ -432,6 +561,11 @@ impl Held { }; } +struct SingleOptions { + target: crate::TargetCpu, + checks: super::MemoryChecks, +} + /// One instruction outside the regions, after an emission that left /// `held`; returns what it leaves. An instruction that first loads the /// register the previous one just stored from RAX finds it there, and one @@ -439,13 +573,14 @@ impl Held { /// `out_of_line`, numerical instructions move their slow paths there. fn emit_single( code: &mut Code, + scratch: &mut Code, out_of_line: Option<&mut OutOfLine>, instruction: &Instruction, fixups: &mut Vec<(GuestAddress, GuestAddress, usize)>, - target: crate::TargetCpu, - checks: super::MemoryChecks, + options: SingleOptions, held: Held, ) -> Held { + let SingleOptions { target, checks } = options; if let Operation::FloatingPoint(operand) = &instruction.operation { let Some(out_of_line) = out_of_line else { super::simd::emit_numerical(code, operand, instruction.pc, target); @@ -469,8 +604,8 @@ fn emit_single( super::simd::emit_after(code, operand, target, checks, held.xmm0); // A first load of the vector XMM0 holds changes nothing. if let Some(vector) = held.xmm0 { - let load = super::simd::xmm0_load(vector); - if code[start..].starts_with(&load) && code.len() > start + load.len() { + let load = super::simd::xmm0_load(scratch, vector); + if code[start..].starts_with(load) && code.len() > start + load.len() { code.remove_instruction(start..start + load.len()); } } @@ -481,29 +616,65 @@ fn emit_single( && matches!( operand.otherwise, crate::aarch64::conditional_select::Otherwise::Unchanged + | crate::aarch64::conditional_select::Otherwise::Increment | crate::aarch64::conditional_select::Otherwise::Invert ) { - // The preceding pinned capture preserves the host flags. MOV and - // NOT keep them live while preparing these select operands. + // The preceding pinned capture preserves the host flags. The + // select keeps them live while preparing its operands. super::conditional_select::emit(code, operand, true); + } else if let Operation::ConditionalCompare(operand) = &instruction.operation + && code.is_pinned() + && !code.constant_time() + && held.rax == super::Rax::Nzcv + { + super::conditional_select::emit_compare(code, operand, true); + } else if let super::Rax::Guest(register) = held.rax + && let Operation::AddSub { + width, + subtract: true, + flags: true, + destination: Register::Zero, + source, + immediate, + } = instruction.operation + && source == register + { + super::pinned::compare_held_immediate(code, width, immediate); + } else if code.is_pinned() + && !code.constant_time() + && let super::Rax::Guest(register) = held.rax + && let Operation::AddSubRegister { + width, + subtract: true, + flags: true, + destination: Register::Zero, + left: left @ Register::X(_), + right, + amount: 0, + .. + } = instruction.operation + && right == register + && left != right + { + super::pinned::compare_held_right(code, width, left); } else { super::emit_instruction(code, instruction, fixups, target, checks); } // The instruction keeps a non-empty native range for its source map. if let super::Rax::Guest(register) = held.rax - && let Some(load) = super::register_load(code, register) - && code[start..].starts_with(&load) + && let Some(load) = super::register_load(scratch, register, code.is_pinned()) + && code[start..].starts_with(load) && code.len() > start + load.len() { code.remove_instruction(start..start + load.len()); } - let rax = match super::rax_after(&instruction.operation) { + let rax = match super::rax_after(&instruction.operation, code.is_pinned()) { // A direct form may leave the result only in its host register. super::Rax::Guest(register) if code.is_pinned() - && !super::register_store(code, register) - .is_some_and(|store| code.ends_with(&store)) => + && !super::register_store(scratch, register, true) + .is_some_and(|store| code.ends_with(store)) => { super::Rax::Unknown } @@ -512,11 +683,13 @@ fn emit_single( debug_assert!(match rax { super::Rax::Unknown => true, super::Rax::Nzcv => code.ends_with(&nzcv_store(code.is_pinned())), - super::Rax::Guest(register) => - super::register_store(code, register).is_some_and(|store| code.ends_with(&store)), + super::Rax::Guest(register) => super::register_store(scratch, register, code.is_pinned()) + .is_some_and(|store| code.ends_with(store)), }); let xmm0 = match &instruction.operation { - Operation::Simd(operand) => super::simd::xmm0_after(operand, &code[start..], held.xmm0), + Operation::Simd(operand) => { + super::simd::xmm0_after(scratch, operand, &code[start..], held.xmm0) + } _ => None, }; Held { rax, xmm0 } diff --git a/crates/stela-compiler/src/x86_64/block/tests.rs b/crates/stela-compiler/src/x86_64/block/tests.rs index 4a8273b55c..0d46e4558c 100644 --- a/crates/stela-compiler/src/x86_64/block/tests.rs +++ b/crates/stela-compiler/src/x86_64/block/tests.rs @@ -4,18 +4,114 @@ use crate::block::{SynchronousTrap, TrapKind}; use alloc::vec; use alloc::vec::Vec; +#[test] +fn system_address_pair_keeps_source_rows_and_the_following_fault_boundary() { + use crate::{Lifter, TargetCpu, aarch64::Decoder, block::RecoverySiteKind}; + + let entry = GuestAddress(0x1030); + let add_pc = GuestAddress(entry.0 + 4); + let load_pc = GuestAddress(entry.0 + 8); + let fallthrough = GuestAddress(entry.0 + 12); + let checks = super::super::MemoryChecks::DEFAULT; + for (register, opcode) in [(0, [0x49, 0xbf]), (20, [0x48, 0xb8])] { + let instructions = [ + Decoder.lift(entry, 0xb000_0000 | register).unwrap(), + Decoder + .lift(add_pc, 0x9140_2000 | register << 5 | register) + .unwrap(), + Decoder.lift(load_pc, 0xf940_0002 | register << 5).unwrap(), + ]; // adrp; add #8, lsl #12; ldr x2,[register] + let system = |input: &[Instruction], next, target| { + emit_system_mode( + input, + None, + next, + target, + checks, + super::super::NativeSystem::NONE, + ) + }; + let (native, recovery) = system(&instructions, fallthrough, TargetCpu::Baseline); + let (dit, _) = system( + &instructions, + fallthrough, + TargetCpu::Baseline.with_data_independent_timing(), + ); + let expected_end = if register == 0 { 11 } else { 18 }; + assert_eq!( + native.source_map, + [(entry, 0), (add_pc, 1), (load_pc, expected_end)] + ); + assert_eq!(native.x86_64_code[0], 0x90); + assert_eq!(native.x86_64_code[1..3], opcode); + assert_eq!(native.x86_64_code[3..11], 0xa000_u64.to_le_bytes()); + assert!(dit.source_map[1].1 > 1); + assert!(native.x86_64_code.len() < dit.x86_64_code.len()); + assert!(!recovery.is_empty()); + assert!(recovery.iter().all(|row| row.start >= expected_end)); + let access = recovery + .iter() + .find(|row| row.site.kind() == RecoverySiteKind::GuestAccess) + .unwrap(); + assert_eq!(access.retirement.instruction_pc(), load_pc); + assert_eq!(access.retirement.retired_before(), 2); + + let (truncated, _) = system(&instructions[..1], add_pc, TargetCpu::Baseline); + assert_eq!(truncated.source_map, [(entry, 0)]); + assert_eq!(truncated.x86_64_code[2..10], 0x2000_u64.to_le_bytes()); + let (standalone, _) = system(&instructions[1..2], load_pc, TargetCpu::Baseline); + assert_eq!(standalone.source_map, [(add_pc, 0)]); + assert_ne!(standalone.x86_64_code[0], 0x90); + } +} + +#[test] +fn system_address_pair_requires_an_adjacent_flagless_x64_overwrite() { + use crate::{Lifter, TargetCpu, aarch64::Decoder}; + + let entry = GuestAddress(0x1000); + let first = Decoder.lift(entry, 0xb000_0000).unwrap(); + for (pc, word) in [ + (0x1008, 0x9100_2000), // Gap. + (0x1004, 0x1100_2000), // W destination. + (0x1004, 0xb100_2000), // Flag-setting ADD. + (0x1004, 0xd100_2000), // SUB. + (0x1004, 0x9100_2001), // Different destination. + (0x1004, 0x9100_2020), // Different source. + ] { + let second = Decoder.lift(GuestAddress(pc), word).unwrap(); + let (native, _) = emit_system_mode( + &[first.clone(), second], + None, + GuestAddress(pc + 4), + TargetCpu::Baseline, + super::super::MemoryChecks::DEFAULT, + super::super::NativeSystem::NONE, + ); + assert_eq!(native.source_map, [(entry, 0), (GuestAddress(pc), 10)]); + assert_eq!(native.x86_64_code[2..10], 0x2000_u64.to_le_bytes()); + } +} + /// A reload removed before a check takes the check's jump along. #[test] fn removed_instructions_move_the_check_failures_after_them() { use super::super::asm::{Cond, Gpr, Mem, Size}; let mut code = Code::new(); + code.check_failure(Cond::E); + let start = code.len(); code.asm() .mov_load(Size::Qword, Gpr::Rax, Mem::base(Gpr::Rdi, 0)); - let load = code.len(); + let end = code.len(); code.check_failure(Cond::Ne); - code.remove_instruction(0..load); + code.remove_instruction(start..end); code.place_failures(); - assert_eq!(code[..], [0x0f, 0x85, 0, 0, 0, 0, 0x0f, 0x0b]); + assert_eq!( + code[..], + [ + 0x0f, 0x84, 6, 0, 0, 0, 0x0f, 0x85, 2, 0, 0, 0, 0x0f, 0x0b, 0x0f, 0x0b + ], + ); } /// A conditional exit's branch skips its fallthrough exit, and each of @@ -37,6 +133,122 @@ fn conditional_exits_branch_over_the_fallthrough_exit() { assert_eq!(code.instructions(), 15); } +#[test] +fn hosted_trailing_zero_pair_preserves_instruction_boundaries() { + use crate::{Lifter, TargetCpu, aarch64::Decoder}; + + let entry = GuestAddress(0x1000); + for words in [[0xdac0_0020_u32, 0xdac0_1000], [0x5ac0_0020, 0x5ac0_1000]] { + let instructions = [ + Decoder.lift(entry, words[0]).unwrap(), + Decoder.lift(GuestAddress(entry.0 + 4), words[1]).unwrap(), + ]; + let end = GuestAddress(entry.0 + 8); + for target in [TargetCpu::Baseline, TargetCpu::Baseline.with_bmi1()] { + let ordinary = emit_ordinary_for_target(&instructions, None, end, target); + let separate = emit_for_target( + &instructions, + None, + end, + target, + super::super::MemoryChecks::DEFAULT, + ); + assert_eq!(ordinary.source_map, [(entry, 0), (instructions[1].pc, 1)]); + assert_eq!(ordinary.x86_64_code[0], 0x90); + assert!(ordinary.x86_64_code.len() < separate.x86_64_code.len()); + let tzcnt = if words[0] >> 31 == 1 { + &[0xf3, 0x48, 0x0f, 0xbc][..] + } else { + &[0xf3, 0x0f, 0xbc][..] + }; + assert_eq!( + ordinary + .x86_64_code + .windows(tzcnt.len()) + .any(|window| window == tzcnt), + target.supports(TargetCpu::Bmi1) + ); + } + let dit = TargetCpu::Baseline.with_data_independent_timing(); + assert_eq!( + emit_ordinary_for_target(&instructions, None, end, dit).x86_64_code, + emit_for_target( + &instructions, + None, + end, + dit, + super::super::MemoryChecks::DEFAULT, + ) + .x86_64_code + ); + let (system, _) = emit_system_mode( + &instructions, + None, + end, + TargetCpu::Baseline, + super::super::MemoryChecks::DEFAULT, + super::super::NativeSystem::NONE, + ); + assert!(system.source_map[1].1 > 1); + } + + // A different width, source or destination leaves the original pair. + let first = Decoder.lift(entry, 0xdac0_0020).unwrap(); + for word in [0x5ac0_1000, 0xdac0_1020, 0xdac0_1001] { + let second = Decoder.lift(GuestAddress(entry.0 + 4), word).unwrap(); + let instructions = [first.clone(), second]; + assert_eq!( + emit_ordinary_for_target( + &instructions, + None, + GuestAddress(entry.0 + 8), + TargetCpu::Baseline + ) + .x86_64_code, + emit(&instructions, None, GuestAddress(entry.0 + 8)).x86_64_code + ); + } +} + +#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] +#[test] +fn hosted_trailing_zero_pair_matches_both_scalar_widths_and_aliases() { + use crate::{GuestState, Lifter, TargetCpu, aarch64::Decoder, x86_64::native}; + + let entry = GuestAddress(0x1000); + let end = GuestAddress(entry.0 + 8); + for (reverse, count) in [(0xdac0_0000, 0xdac0_1000), (0x5ac0_0000, 0x5ac0_1000)] { + for source in [0, 1, 31] { + let instructions = [ + Decoder.lift(entry, reverse | source << 5).unwrap(), + Decoder.lift(GuestAddress(entry.0 + 4), count).unwrap(), + ]; + for target in [TargetCpu::Baseline, TargetCpu::Baseline.with_bmi1()] { + if !TargetCpu::detect().supports(target) { + continue; + } + let block = emit_ordinary_for_target(&instructions, None, end, target); + assert_eq!(block.source_map[1].1, 1); + for input in [0, 1, 0x1234_5678_0000_0000, 1 << 31, 1 << 63, u64::MAX] { + let mut state = GuestState::default(); + state.x[0] = input; + state.x[1] = input; + state.nzcv = 0xa000_0000; + let mut expected = state.clone(); + let input = if source == 31 { 0 } else { input }; + expected.x[0] = u64::from(if reverse >> 31 == 1 { + input.trailing_zeros() + } else { + (input as u32).trailing_zeros() + }); + assert_eq!(native::run(&block.x86_64_code, &mut state), end.0); + assert_eq!(state, expected); + } + } + } + } +} + /// add x10, x10, #4; cmp x10, #0x600; b.ne: the CMP takes X10 from /// RAX where the ADD stored it, and the branch tests the NZCV word the /// CMP left in EAX, so neither reloads from the frame. @@ -63,7 +275,8 @@ fn values_left_in_rax_are_not_reloaded() { condition: 1, }), ); - let code = emit(&instructions, Some(&terminal), GuestAddress(branch.0 + 4)).x86_64_code; + let native = emit(&instructions, Some(&terminal), GuestAddress(branch.0 + 4)); + let code = &native.x86_64_code; let count = |pattern: &[u8]| { code.windows(pattern.len()) .filter(|w| *w == pattern) @@ -71,6 +284,205 @@ fn values_left_in_rax_are_not_reloaded() { }; assert_eq!(count(&LOAD_X10), 1); assert_eq!(count(&LOAD_NZCV), 0); + let compare = native.source_map[1].1; + assert_eq!(&code[compare..compare + 3], &[0x48, 0x81, 0xf8]); // CMP RAX,imm32. +} + +#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] +#[test] +fn pinned_compare_reuses_the_preceding_unshifted_right_operand() { + use crate::{GuestState, Lifter, TargetCpu, aarch64::Decoder, x86_64::native}; + + let pc = GuestAddress(0x1000); + let compare = GuestAddress(pc.0 + 4); + let branch = GuestAddress(pc.0 + 8); + let next = GuestAddress(pc.0 + 12); + let terminal = ( + branch, + Terminator::Branch(Operation::BranchCondition { + target: pc, + condition: 3, // LO: borrow. + }), + ); + for (sf, mask) in [(0, u64::from(u32::MAX)), (1 << 31, u64::MAX)] { + for left in [1, 9] { + let instructions = [ + Decoder.lift(pc, sf | 0x1100_0694).unwrap(), // ADD R20,R20,#1 + Decoder.lift(compare, sf | 0x6b14_001f | left << 5).unwrap(), // CMP Rleft,R20 + ]; + let system = |input: &[Instruction], target| { + emit_system_mode( + input, + Some(&terminal), + next, + target, + super::super::MemoryChecks::DEFAULT, + super::super::NativeSystem::NONE, + ) + .0 + }; + let native = system(&instructions, TargetCpu::Baseline); + let dit = system( + &instructions, + TargetCpu::Baseline.with_data_independent_timing(), + ); + let standalone = system(&instructions[1..], TargetCpu::Baseline); + let code = &native.x86_64_code; + let at = native.source_map[1].1; + let opcode = if sf == 0 { at } else { at + 1 }; + let cmp = if left == 1 { + &[0x39, 0xc5][..] // CMP EBP/RBP,EAX/RAX. + } else { + &[0x39, 0x47, 72][..] // CMP [frame+X9],EAX/RAX. + }; + assert_eq!(&code[opcode..opcode + cmp.len()], cmp); + assert!( + !dit.x86_64_code[dit.source_map[1].1..].starts_with(&code[at..opcode + cmp.len()]) + ); + assert!( + !standalone + .x86_64_code + .starts_with(&code[at..opcode + cmp.len()]) + ); + assert_eq!( + native + .source_map + .iter() + .map(|row| row.0) + .collect::>(), + [pc, compare, branch] + ); + + let entered = super::super::pinned::entered(code); + let sign = (mask >> 1) + 1; + for (a, before) in [ + (1, 0), + (0, 0), + (mask, 0), + (sign - 1, mask - 1), + (0, sign - 1), + ] { + let mut state = GuestState::default(); + state.x[left as usize] = a; + state.x[20] = before | !mask; + let mut expected = state.clone(); + let b = before.wrapping_add(1) & mask; + let difference = a.wrapping_sub(b) & mask; + expected.x[20] = b; + expected.nzcv = (u32::from(difference & sign != 0) << 31) + | (u32::from(difference == 0) << 30) + | (u32::from(a >= b) << 29) + | (u32::from((a ^ b) & (a ^ difference) & sign != 0) << 28); + assert_eq!( + native::run(&entered, &mut state), + if a < b { pc.0 } else { next.0 } + ); + assert_eq!(state, expected); + } + } + } +} + +#[test] +fn ordinary_integer_operations_read_frame_operands_directly() { + use crate::{Lifter, aarch64::Decoder}; + let pc = GuestAddress(0x1000); + // MOV W5,W1; AND W1,W1,W14; CMP W13,W1; CMP W13,#7; ADD X6,X4,W12,SXTW. + let instructions: Vec<_> = [ + 0x2a01_03e5_u32, + 0x0a0e_0021, + 0x6b01_01bf, + 0x7100_1dbf, + 0x8b2c_c086, + ] + .into_iter() + .enumerate() + .map(|(index, word)| { + Decoder + .lift(GuestAddress(pc.0 + 4 * index as u64), word) + .unwrap() + }) + .collect(); + let native = emit(&instructions, None, GuestAddress(0x1014)); + let code = &native.x86_64_code; + let map = &native.source_map; + assert_eq!( + &code[..map[1].1], + &[0x8b, 0x87, 8, 0, 0, 0, 0x48, 0x89, 0x87, 40, 0, 0, 0], + ); // MOV EAX,[RDI+8]; MOV [RDI+40],RAX. + assert_eq!( + &code[map[1].1 + 7..map[1].1 + 13], + &[0x23, 0x87, 112, 0, 0, 0] + ); + assert_eq!( + &code[map[2].1 + 7..map[2].1 + 13], + &[0x3b, 0x87, 8, 0, 0, 0] + ); + assert_eq!( + &code[map[3].1..map[3].1 + 7], + &[0x83, 0xbf, 104, 0, 0, 0, 7] + ); + assert_eq!( + &code[map[4].1 + 7..map[4].1 + 14], + &[0x48, 0x63, 0x8f, 96, 0, 0, 0], + ); // MOVSXD RCX,[RDI+96]. +} + +#[test] +fn pinned_scalar_loads_forward_through_the_block() { + use crate::{Lifter, aarch64::Decoder, block::RecoverySiteKind}; + const FRAME_LOAD: [u8; 4] = [0x48, 0x8b, 0x47, 0x50]; + let pc = GuestAddress(0x1000); + let second = GuestAddress(0x1004); + let branch = GuestAddress(0x1008); + // LDR X10,[X10]; LDR X10,[X10,X2]; CBZ X10,entry. + let instructions = [ + Decoder.lift(pc, 0xf940_014a).unwrap(), + Decoder.lift(second, 0xf862_694a).unwrap(), + ]; + let terminal = ( + branch, + Terminator::Branch(Operation::BranchZero { + source: Register::X(10), + width: crate::aarch64::Width::X64, + nonzero: false, + target: pc, + }), + ); + let (native, recovery) = emit_system_mode( + &instructions, + Some(&terminal), + GuestAddress(0x100c), + crate::TargetCpu::Baseline, + super::super::MemoryChecks::DEFAULT, + super::super::NativeSystem::NONE, + ); + let code = &native.x86_64_code; + assert_eq!(native.source_map.len(), 3); + let [(pc1, at1), (pc2, at2), (pc3, at3)] = native.source_map.as_slice() else { + unreachable!() + }; + assert_eq!([*pc1, *pc2, *pc3], [pc, second, branch]); + assert!(at1 < at2 && at2 < at3); + assert_eq!( + code.windows(FRAME_LOAD.len()) + .filter(|w| *w == FRAME_LOAD) + .count(), + 1 + ); + assert_eq!(&code[*at3..*at3 + 3], &[0x48, 0x85, 0xc0]); // TEST RAX,RAX + let accesses: Vec<_> = recovery + .iter() + .filter(|row| row.site.kind() == RecoverySiteKind::GuestAccess) + .collect(); + assert_eq!(accesses.len(), 2); + for (index, access) in accesses.into_iter().enumerate() { + let (pc, start) = native.source_map[index]; + assert!(start <= access.start && access.end <= native.source_map[index + 1].1); + let position = access.retirement.position().unwrap(); + assert_eq!(position.pc, pc); + assert_eq!(usize::from(position.retired_instructions), index); + } } /// ldr x0, [sp, #8]; ldr x1, [sp, #16]; sub sp, sp, #8; ldr x2, [sp]: @@ -753,3 +1165,160 @@ fn pinned_select_consumes_the_preceding_compare_flags() { assert_eq!(state.nzcv, nzcv); } } + +#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] +#[test] +fn pinned_conditional_increment_consumes_the_preceding_compare_flags() { + use crate::{ + GuestState, + block::{BlockProfile, Features}, + x86_64::{native, pinned}, + }; + // CMP X0, #1; CSET W2, EQ; RET. + let cset = 0x1a9f_17e2; + // CMP X0, #1; CSINC W8, W2, W8, HI; RET. + let csinc = 0x1a88_8448; + for (select, prefix) in [ + (cset, &[0x0f, 0x94, 0xc0][..]), // SETE AL + (csinc, &[0x44, 0x8b, 0xc6, 0x45, 0x8d, 0x40, 0x01, 0xf5]), // MOV, LEA, CMC + ] { + let source: Vec<_> = [0xf100_041fu32, select, 0xd65f_03c0] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + let code = crate::testing::block_with( + &source, + GuestAddress(0x1000), + BlockProfile::new(Features::SYSTEM_MODE), + ) + .unwrap() + .native; + let selected = &code.x86_64_code[code.source_map[1].1..code.source_map[2].1]; + assert!(selected.starts_with(prefix), "{selected:02x?}"); + let entry = pinned::entered(&code.x86_64_code); + for (compared, equal, higher, nzcv) in [ + (0, 0, false, 0x8000_0000), + (1, 1, false, 0x6000_0000), + (2, 0, true, 0x2000_0000), + ] { + let mut state = GuestState::default(); + state.x[0] = compared; + state.x[2] = 0xaabb_ccdd_0000_0016; + state.x[8] = u64::MAX; + state.x[30] = 0x2000; + let mut expected = state.x; + if select == cset { + expected[2] = equal; + } else { + expected[8] = if higher { 22 } else { 0 }; + } + assert_eq!(native::run(&entry, &mut state), 0x2000); + assert_eq!(state.x, expected); + assert_eq!(state.nzcv, nzcv); + } + } +} + +#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] +#[test] +fn pinned_conditional_compare_consumes_the_preceding_flags() { + use crate::{ + GuestState, Lifter, TargetCpu, + aarch64::{Decoder, conditional_select::decode_compare}, + x86_64::{native, pinned}, + }; + + let pc = GuestAddress(0x1000); + let compare_pc = GuestAddress(pc.0 + 4); + let end = GuestAddress(pc.0 + 8); + for wide in [0, 1] { + for producer_subtract in [0, 1] { + // CMP or CMN of X0/W0 and X4/W4. + let producer = 0x2b04_001f | wide << 31 | producer_subtract << 30; + for subtract in [0, 1] { + for right in [2 << 16, (1 << 11) | (31 << 16)] { + for condition in 0..16 { + // CCMP or CCMN of X1/W1 and X2/W2 or immediate 31. + let compare = + 0x3a40_0025 | wide << 31 | subtract << 30 | right | condition << 12; + let instructions = [ + Decoder.lift(pc, producer).unwrap(), + Decoder.lift(compare_pc, compare).unwrap(), + ]; + let (system, _) = emit_system_mode( + &instructions, + None, + end, + TargetCpu::Baseline, + super::super::MemoryChecks::DEFAULT, + super::super::NativeSystem::NONE, + ); + assert_eq!(system.source_map[0], (pc, 0)); + let (at, offset) = system.source_map[1]; + assert_eq!(at, compare_pc); + let (single, _) = emit_system_mode( + &instructions[1..], + None, + end, + TargetCpu::Baseline, + super::super::MemoryChecks::DEFAULT, + super::super::NativeSystem::NONE, + ); + let bytes = &system.x86_64_code[offset..]; + if condition < 14 { + assert!(bytes.len() < single.x86_64_code.len(), "{compare:08x}"); + let predicate_at = usize::from(matches!(condition, 8 | 9)); + assert_eq!(bytes[predicate_at..predicate_at + 2], [0x41, 0x0f]); + } else { + assert_eq!(bytes, single.x86_64_code); + } + + let dit = TargetCpu::Baseline.with_data_independent_timing(); + let (system_dit, _) = emit_system_mode( + &instructions, + None, + end, + dit, + super::super::MemoryChecks::DEFAULT, + super::super::NativeSystem::NONE, + ); + let mut baseline = Code::pinned(); + baseline.set_constant_time(true); + super::super::conditional_select::emit_compare( + &mut baseline, + &decode_compare(compare).unwrap(), + false, + ); + assert!( + system_dit.x86_64_code[system_dit.source_map[1].1..] + .starts_with(&baseline) + ); + + let frame = emit(&instructions, None, end); + let entered = pinned::entered(&system.x86_64_code); + for (left, right) in [ + (0, 0), + (1, 0), + (0, 1), + (1 << 31, 1), + (1 << 63, 1), + (u64::MAX, 1), + (u64::MAX, u64::MAX), + ] { + let mut initial = GuestState::default(); + initial.x[0] = left; + initial.x[1] = left ^ 1; + initial.x[2] = right; + initial.x[4] = right; + initial.nzcv = 0xf000_0000; + let mut expected = initial.clone(); + assert_eq!(native::run(&frame.x86_64_code, &mut expected), end.0); + assert_eq!(native::run(&entered, &mut initial), end.0); + assert_eq!(initial, expected, "{producer:08x} {compare:08x}"); + } + } + } + } + } + } +} diff --git a/crates/stela-compiler/src/x86_64/chain.rs b/crates/stela-compiler/src/x86_64/chain.rs index cb62d3adf8..90f4d7f44a 100644 --- a/crates/stela-compiler/src/x86_64/chain.rs +++ b/crates/stela-compiler/src/x86_64/chain.rs @@ -233,13 +233,15 @@ impl LookupTable { /// The entry of `pc` in `context`'s set for `slot`: one in `context` if /// there is one, as a thunk would find it, else one in another context. + #[inline] pub fn find(&self, slot: usize, pc: u64, context: u64) -> LookupEntry { - let (first, second) = (self[slot], self[neighbour(slot)]); - if second.pc == pc && (first.pc != pc || first.context != context) { - second - } else { - first + let set = &self.0[slot / 2].0; + let first = &set[slot % 2]; + if first.pc == pc && first.context == context { + return *first; } + let second = &set[(slot % 2) ^ 1]; + if second.pc == pc { *second } else { *first } } /// Put `entry` in the slot its PC and context pick, and what held it diff --git a/crates/stela-compiler/src/x86_64/conditional_select.rs b/crates/stela-compiler/src/x86_64/conditional_select.rs index e83fb9bed3..b1ac48c5e9 100644 --- a/crates/stela-compiler/src/x86_64/conditional_select.rs +++ b/crates/stela-compiler/src/x86_64/conditional_select.rs @@ -1,35 +1,45 @@ -//! Branchless conditional select from the saved guest NZCV. -use super::{capture_nzcv, condition_holds, flag_word, load, right_operand, store, store_nzcv}; +//! Branchless conditional select and compare using guest NZCV. +use super::{capture_nzcv, condition_holds, flag_word, load_with, pinned, store, store_nzcv}; use crate::aarch64::{ - Register, Shift, Width, + Register, Width, conditional_select::{CompareOperand, CompareRight, Operand, Otherwise}, }; use crate::x86_64::asm::{ Alu, Asm, Code, Cond, - Gpr::{R8, Rax, Rcx, Rdx}, - Rm, Size, Unary, + Gpr::{R8, Rax, Rdx}, + Mem, Rm, Size, Unary, }; const NZCV_SHIFT: u8 = 28; /// The comparison runs on both arms and a CMOV picks its flags or the -/// fallback, so the timing depends on neither the condition nor the data. -pub(super) fn emit_compare(code: &mut Code, operand: &CompareOperand) { - let predicate = condition_holds(code, operand.condition, false); +/// fallback. A preceding pinned capture can supply the predicate directly. +pub(super) fn emit_compare(code: &mut Code, operand: &CompareOperand, live_nzcv: bool) { + let predicate = condition_holds(code, operand.condition, live_nzcv); if let Some(cond) = predicate { // R8 is scratch under the native leaf ABI. code.asm().setcc(cond, R8); } - load(code, operand.left); + let size = Size::of(operand.width == Width::X64); + let op = if operand.subtract { Alu::Cmp } else { Alu::Add }; match operand.right { CompareRight::Register(register) => { - right_operand(code, register, operand.width, Shift::Lsl, 0) + let emitted = + pinned::unshifted_binary(&mut code.asm(), op, size, Rax, operand.left, register); + debug_assert!(emitted, "RAX is scratch for conditional compare"); + } + CompareRight::Immediate(value) => { + let mut asm = code.asm(); + let destination = match asm.guest(operand.left) { + Some(left) if operand.subtract => left, + _ => { + load_with(&mut asm, operand.left); + Rax.into() + } + }; + asm.alu_imm(op, size, destination, i32::from(value)); } - CompareRight::Immediate(value) => code.asm().mov_imm32(Rcx, u32::from(value)), } - let op = if operand.subtract { Alu::Sub } else { Alu::Add }; - code.asm() - .alu(op, Size::of(operand.width == Width::X64), Rax, Rcx); let pinned = code.is_pinned(); if pinned { flag_word::capture_in_rax(code, operand.subtract); @@ -53,6 +63,25 @@ pub(super) fn emit_compare(code: &mut Code, operand: &CompareOperand) { pub(super) fn emit(code: &mut Code, operand: &Operand, live_nzcv: bool) { let size = Size::of(operand.width == Width::X64); + let destination = code.host(operand.destination); + let output = destination.unwrap_or(Rax); + if operand.left == Register::Zero + && operand.right == Register::Zero + && matches!(operand.otherwise, Otherwise::Increment | Otherwise::Invert) + && let Some(predicate) = condition_holds(code, operand.condition, live_nzcv) + { + // CSET and CSETM materialize the condition as a bit or a mask. + let mut asm = code.asm(); + asm.setcc(predicate.negate(), output); + asm.movzx(Size::Dword, output, Size::Byte, output); + if operand.otherwise == Otherwise::Invert { + asm.unary(Unary::Neg, size, output); + } + if destination.is_none() { + store(code, operand.destination); + } + return; + } let otherwise = if operand.condition >= 14 { // AL and NV always select Rn. None @@ -66,6 +95,7 @@ pub(super) fn emit(code: &mut Code, operand: &Operand, live_nzcv: bool) { let mut asm = code.asm(); select_input(&mut asm, R8, size, operand.right); match operand.otherwise { + Otherwise::Increment if live_nzcv => asm.lea(size, R8, Mem::base(R8, 1)), Otherwise::Increment => asm.inc(size, R8), Otherwise::Invert => asm.unary(Unary::Not, size, R8), Otherwise::Negate => asm.unary(Unary::Neg, size, R8), @@ -73,13 +103,40 @@ pub(super) fn emit(code: &mut Code, operand: &Operand, live_nzcv: bool) { } Some(Rm::Reg(R8)) }; + // If the unchanged false arm already lives in the result register, + // keep it there and conditionally move the true arm instead. + let keep_false = operand.left != operand.destination + && matches!(otherwise, Some(Rm::Reg(source)) if source == output); + let (initial, alternate) = if keep_false { + let mut asm = code.asm(); + let source = asm.guest(operand.left).unwrap_or_else(|| { + asm.mov_imm32(R8, 0); + Rm::Reg(R8) + }); + (operand.destination, Some(source)) + } else { + (operand.left, otherwise) + }; let predicate = condition_holds(code, operand.condition, live_nzcv); let mut asm = code.asm(); - select_input(&mut asm, Rax, size, operand.left); - if let Some((predicate, otherwise)) = predicate.zip(otherwise) { - asm.cmov(predicate.negate(), size, Rax, otherwise); + let selected = predicate.zip(alternate); + let already_placed = destination.is_some() && initial == operand.destination; + // CMOVcc r32 in 64-bit mode clears the upper half even when its + // predicate is false (Intel SDM, CMOVcc). + if selected.is_none() || !already_placed { + select_input(&mut asm, output, size, initial); + } + if let Some((predicate, alternate)) = selected { + let take_alternate = if keep_false { + predicate + } else { + predicate.negate() + }; + asm.cmov(take_alternate, size, output, alternate); + } + if destination.is_none() { + store(code, operand.destination); } - store(code, operand.destination); } /// A W source is zero-extended by the sized MOV. XZR uses an immediate @@ -101,13 +158,78 @@ mod tests { use super::*; use crate::GuestState; + #[test] + fn compares_registers_and_immediates_without_changing_operands() { + for width in [Width::W32, Width::X64] { + let sign = match width { + Width::W32 => 1 << 31, + Width::X64 => 1 << 63, + }; + let initial = { + let mut state = GuestState::default(); + state.x[1] = sign; + state.x[2] = u64::MAX; + state.x[3] = sign; + state.x[8] = u64::MAX; + state + }; + use CompareRight::{Immediate, Register as FromRegister}; + use Register::{X, Zero}; + for (left, right, sub_flags, add_flags) in [ + (X(1), FromRegister(X(2)), 8, 3), + (X(3), FromRegister(X(8)), 8, 3), + (X(1), FromRegister(X(1)), 6, 7), + (X(1), FromRegister(Zero), 10, 8), + (X(3), Immediate(0), 10, 8), + (X(3), Immediate(31), 3, 8), + (Zero, Immediate(31), 8, 0), + ] { + for (subtract, flags) in [(true, sub_flags), (false, add_flags)] { + for condition in [0, 14, 15] { + let operand = CompareOperand { + width, + subtract, + left, + right, + condition, + fallback: 5, + }; + let mut frame = Code::new(); + let mut pinned = Code::pinned(); + emit_compare(&mut frame, &operand, false); + emit_compare(&mut pinned, &operand, false); + pinned.asm().ret(); + let pinned = super::super::pinned::entered(&pinned); + for nzcv in [0, 4] { + let expected = if condition == 0 && nzcv == 0 { + 5 + } else { + flags + }; + for bytes in [&frame[..], &pinned[..]] { + let mut state = initial.clone(); + state.nzcv = nzcv << NZCV_SHIFT; + super::super::native::run(bytes, &mut state); + assert_eq!(state.x, initial.x, "{operand:?}"); + assert_eq!(state.nzcv, expected << NZCV_SHIFT, "{operand:?}"); + } + } + } + } + } + } + } + #[test] fn selects_preserve_nzcv_and_zero_extend_w_results() { const LEFT: u64 = 0x1234_5678_9abc_def0; const RIGHT: u64 = 0xfedc_ba98_7654_3210; - for width in [Width::W32, Width::X64] { + let cases = [Width::W32, Width::X64] + .into_iter() + .flat_map(|width| [1, 2, 8].map(|destination| (width, destination))); + for (width, destination) in cases { for (left, lhs) in [(Register::X(1), LEFT), (Register::Zero, 0)] { - for (right, rhs) in [(Register::X(2), RIGHT), (Register::Zero, 0)] { + for (right, rhs) in [(Register::X(8), RIGHT), (Register::Zero, 0)] { for (otherwise, alternate) in [ (Otherwise::Unchanged, rhs), (Otherwise::Increment, rhs.wrapping_add(1)), @@ -117,7 +239,7 @@ mod tests { for condition in [0, 1, 10, 12, 14, 15] { let operand = Operand { width, - destination: Register::X(1), + destination: Register::X(destination), left, right, condition, @@ -152,9 +274,13 @@ mod tests { ..Default::default() }; state.x[1] = LEFT; - state.x[2] = RIGHT; + state.x[8] = RIGHT; super::super::native::run(code, &mut state); - assert_eq!(state.x[1], expected, "{operand:?}"); + let mut expected_registers = [0; 31]; + expected_registers[1] = LEFT; + expected_registers[8] = RIGHT; + expected_registers[usize::from(destination)] = expected; + assert_eq!(state.x, expected_registers, "{operand:?}"); assert_eq!(state.nzcv, flags << 28); } } diff --git a/crates/stela-compiler/src/x86_64/memory_recipe.rs b/crates/stela-compiler/src/x86_64/memory_recipe.rs index fed8e54a9f..ba1f6235bb 100644 --- a/crates/stela-compiler/src/x86_64/memory_recipe.rs +++ b/crates/stela-compiler/src/x86_64/memory_recipe.rs @@ -280,7 +280,15 @@ pub(super) fn scalar( accessed() }; // A fault leaves a host destination as it was. - let host = code.host(data).unwrap_or(Gpr::Rcx); + // Offset loads have no pending writeback. Keep an unpinned + // result in RAX so the following instruction can use it + // without reloading it from the frame. + let scratch = if code.is_pinned() && mode == AddressMode::Offset { + Gpr::Rax + } else { + Gpr::Rcx + }; + let host = code.host(data).unwrap_or(scratch); let checkpoint = code.checkpoint(); { let mut asm = code.asm(); @@ -302,14 +310,14 @@ pub(super) fn scalar( code, checkpoint, Kind::Load { element: 0, host }, - mask(Gpr::Rcx), + mask(host), ); // A discarded load still performs its faultable access. - if host == Gpr::Rcx + if host == scratch && let Some(data) = code.asm().guest(data) { let start = code.checkpoint(); - code.asm().mov_store(Size::Qword, data, Gpr::Rcx); + code.asm().mov_store(Size::Qword, data, host); mark(&mut recipe, code, start, Kind::Commit, 0); } } diff --git a/crates/stela-compiler/src/x86_64/pinned.rs b/crates/stela-compiler/src/x86_64/pinned.rs index 7e28809ce9..3ff2e4c3fb 100644 --- a/crates/stela-compiler/src/x86_64/pinned.rs +++ b/crates/stela-compiler/src/x86_64/pinned.rs @@ -15,8 +15,8 @@ use super::asm::{Alu, Asm, Code, Gpr, Mem, Rm, ShiftOp, Size}; use super::{flag_word, logical, nzcv, right_operand, store}; use crate::{ - GuestState, - aarch64::{Logical, Operation, Register, Shift, WideMove, Width, simd}, + GuestState, TargetCpu, + aarch64::{Logical, Operation, Register, Shift, WideMove, Width, pc_relative, simd}, block::HostGprSnapshot, }; @@ -129,13 +129,65 @@ fn right( } } -/// `operation` straight in the host registers of its operands: the few forms -/// that make up most of a program. Any other, and the ones here in frame -/// code, go through their emitters. -pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool { - if !code.is_pinned() { - return false; +/// A binary operation without a shifted operand can read a frame slot +/// directly. A commutative operation can start with the right operand +/// when it already lives in the destination. +pub(super) fn unshifted_binary( + asm: &mut Asm, + op: Alu, + size: Size, + work: Gpr, + mut left: Register, + mut right: Register, +) -> bool { + if asm.guest(right) == Some(Rm::Reg(work)) && right != left { + if op == Alu::Sub { + return false; + } + debug_assert_ne!(op, Alu::Cmp, "CMP has no destination register"); + core::mem::swap(&mut left, &mut right); } + let destination = match asm.guest(left) { + Some(Rm::Reg(host)) if op == Alu::Cmp => host, + _ => { + // The ALU operation itself clears the upper half of a W result. + take(asm, Size::Qword, work, left); + work + } + }; + match asm.guest(right) { + Some(Rm::Reg(host)) => asm.alu(op, size, destination, host), + Some(frame) => asm.alu_load(op, size, destination, frame), + None => asm.alu_imm8(op, size, destination, 0), + } + true +} + +/// Compare the left operand against the prior instruction's result in RAX. +pub(super) fn compare_held_right(code: &mut Code, width: Width, left: Register) { + let mut asm = code.asm(); + let left = asm.guest(left).expect("CMP left register"); + asm.alu(Alu::Cmp, Size::of(width == Width::X64), left, Gpr::Rax); + nzcv(code, true); +} + +/// Compare the guest value that the previous instruction left in RAX. +pub(super) fn compare_held_immediate(code: &mut Code, width: Width, immediate: u32) { + let size = Size::of(width == Width::X64); + code.asm() + .alu_imm(Alu::Cmp, size, Gpr::Rax, immediate as i32); + nzcv(code, true); +} + +pub(super) fn emit_pc_relative(code: &mut Code, operand: pc_relative::Operand) { + // Fixed in size at every address, for a stored block's rebase. + let work = working(code, operand.destination); + code.asm().mov_imm64(work, operand.address); + finish(code, work, operand.destination, false, false); +} + +/// Common integer operations on their native register or frame operands. +pub(super) fn emit_direct(code: &mut Code, operation: &Operation, target: TargetCpu) -> bool { match *operation { Operation::AddSub { width, @@ -146,13 +198,17 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool { immediate, } => { let size = Size::of(width == Width::X64); - let op = if subtract { Alu::Sub } else { Alu::Add }; + let op = match (subtract, destination) { + (true, Register::Zero) => Alu::Cmp, + (true, _) => Alu::Sub, + (false, _) => Alu::Add, + }; let work = working(code, destination); let immediate = immediate as i32; let mut asm = code.asm(); match asm.guest(source) { - Some(Rm::Reg(host)) if destination == Register::Zero && subtract => { - asm.alu_imm(Alu::Cmp, size, host, immediate); + Some(operand) if op == Alu::Cmp => { + asm.alu_imm(op, size, operand, immediate); } Some(Rm::Reg(host)) if !flags && host != work => { let distance = if subtract { -immediate } else { immediate }; @@ -176,17 +232,27 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool { amount, } => { let size = Size::of(width == Width::X64); - let op = if subtract { Alu::Sub } else { Alu::Add }; + let op = match (subtract, destination) { + (true, Register::Zero) => Alu::Cmp, + (true, _) => Alu::Sub, + (false, _) => Alu::Add, + }; let work = working(code, destination); - let second = right(code, operand, width, shift, amount, work); - let mut asm = code.asm(); - match asm.guest(left) { - Some(Rm::Reg(host)) if destination == Register::Zero && subtract => { - asm.alu(Alu::Cmp, size, host, second); + if amount != 0 || !unshifted_binary(&mut code.asm(), op, size, work, left, operand) { + let frame = !code.is_pinned(); + if frame { + take(&mut code.asm(), Size::Qword, work, left); } - _ => { - take(&mut asm, Size::Qword, work, left); - asm.alu(op, size, work, second); + let second = right(code, operand, width, shift, amount, work); + let mut asm = code.asm(); + match asm.guest(left) { + Some(Rm::Reg(host)) if op == Alu::Cmp => asm.alu(op, size, host, second), + _ => { + if !frame { + take(&mut asm, Size::Qword, work, left); + } + asm.alu(op, size, work, second); + } } } finish(code, work, destination, flags, subtract); @@ -204,10 +270,37 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool { } => { let size = Size::of(width == Width::X64); let work = working(code, destination); - if kind == Logical::Or && left == Register::Zero && !invert && amount == 0 && !flags { + if kind == Logical::And + && invert + && target.supports(TargetCpu::Bmi1) + && !target.data_independent_timing() + && let Some(left) = code.asm().guest(left) + { + let inverted = match code.host(operand) { + Some(host) if amount == 0 => host, + _ => { + right_operand(code, operand, width, shift, amount); + Gpr::Rcx + } + }; + // ANDN folds a frame operand and sets N/Z with C/V clear. + code.asm().andn(size, work, inverted, left); + } else if kind == Logical::Or + && left == Register::Zero + && !invert + && amount == 0 + && !flags + { // MOV. take(&mut code.asm(), size, work, operand); - } else { + } else if invert + || amount != 0 + || !unshifted_binary(&mut code.asm(), logical(kind), size, work, left, operand) + { + let frame = !code.is_pinned(); + if frame { + take(&mut code.asm(), Size::Qword, work, left); + } let second = if invert { right_operand(code, operand, width, shift, amount); code.asm().unary(super::asm::Unary::Not, size, Gpr::Rcx); @@ -216,7 +309,9 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool { right(code, operand, width, shift, amount, work) }; let mut asm = code.asm(); - take(&mut asm, Size::Qword, work, left); + if !frame { + take(&mut asm, Size::Qword, work, left); + } asm.alu(logical(kind), size, work, second); } finish(code, work, destination, flags, false); @@ -248,7 +343,7 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool { destination, immediate, shift, - } => { + } if code.is_pinned() => { let work = working(code, destination); let value = u64::from(immediate) << shift; let mut asm = code.asm(); @@ -276,11 +371,10 @@ pub(super) fn emit_direct(code: &mut Code, operation: &Operation) -> bool { } finish(code, work, destination, false, false); } - Operation::PcRelative(operand) if operand.destination != Register::Zero => { - // Fixed in size at every address, for a stored block's rebase. - let work = working(code, operand.destination); - code.asm().mov_imm64(work, operand.address); - finish(code, work, operand.destination, false, false); + Operation::PcRelative(operand) + if code.is_pinned() && operand.destination != Register::Zero => + { + emit_pc_relative(code, operand); } _ => return false, } @@ -395,9 +489,51 @@ mod tests { assert_eq!(&frame[..], [0x48, 0x8b, 0x87, 0, 0, 0, 0]); } + #[test] + fn immediate_cmp_reads_the_frame_and_preserves_its_operand() { + let mut initial = GuestState { + sp: 0xfff000, + ..GuestState::default() + }; + for width in [Width::W32, Width::X64] { + initial.x[2] = match width { + Width::W32 => 0x1234_5678_8000_0000, + Width::X64 => 1 << 63, + }; + for (source, immediate, expected) in + [(Register::X(2), 31, 3), (Register::Sp, 0xfff000, 6)] + { + let operation = Operation::AddSub { + width, + subtract: true, + flags: true, + destination: Register::Zero, + source, + immediate, + }; + let mut frame = Code::new(); + assert!(emit_direct(&mut frame, &operation, TargetCpu::Baseline)); + let start = usize::from(width == Width::X64); + assert_eq!(frame[start], if immediate <= 127 { 0x83 } else { 0x81 }); + assert_eq!(frame[start + 1], 0xbf); // CMP with a frame displacement. + + let mut pinned = direct(operation); + pinned.asm().ret(); + let pinned = entered(&pinned); + for bytes in [&frame[..], &pinned[..]] { + let mut state = initial.clone(); + super::super::native::run(bytes, &mut state); + assert_eq!(state.x, initial.x); + assert_eq!(state.sp, initial.sp); + assert_eq!(state.nzcv, expected << 28); + } + } + } + } + fn direct(operation: Operation) -> Code { let mut code = Code::pinned(); - assert!(emit_direct(&mut code, &operation)); + assert!(emit_direct(&mut code, &operation, TargetCpu::Baseline)); code } @@ -441,6 +577,153 @@ mod tests { assert!(!narrow.is_empty()); } + #[test] + fn bmi1_bic_folds_the_frame_operand_and_keeps_older_targets() { + // BIC X8,X9,X10 from archived desktop code (8a2a0128). + let operation = Operation::LogicalRegister { + width: Width::X64, + kind: Logical::And, + invert: true, + flags: false, + destination: Register::X(8), + left: Register::X(9), + right: Register::X(10), + shift: Shift::Lsl, + amount: 0, + }; + let emit = |target| { + let mut code = Code::pinned(); + assert!(emit_direct(&mut code, &operation, target)); + code + }; + let fast = emit(TargetCpu::Bmi1); + // mov rcx,[rdi+80]; andn rsi,rcx,[rdi+72]. + assert_eq!( + &fast[..], + [0x48, 0x8b, 0x4f, 0x50, 0xc4, 0xe2, 0xf0, 0xf2, 0x77, 0x48] + ); + let baseline = emit(TargetCpu::Baseline); + assert_eq!(baseline.instructions(), 4); + assert_eq!(fast.instructions(), 2); + for target in [ + TargetCpu::Sse42, + TargetCpu::Bmi2, + TargetCpu::Bmi1.with_data_independent_timing(), + ] { + assert_eq!(emit(target), baseline); + } + } + + #[test] + fn bmi1_bic_preserves_aliases_and_bics_flags() { + if !TargetCpu::detect().supports(TargetCpu::Bmi1) { + return; + } + let mut initial = GuestState::default(); + initial.x[0] = 0x89ab_cdef_8000_0000; + initial.x[8] = 0x5555_5555_0000_0000; + initial.x[9] = u64::MAX; + initial.nzcv = 0xf000_0000; + for width in [Width::W32, Width::X64] { + for (shift, amount) in [(Shift::Lsl, 0), (Shift::Asr, 1), (Shift::Ror, 3)] { + for (destination, left, right) in [ + (Register::X(8), Register::X(8), Register::X(0)), + (Register::X(8), Register::X(0), Register::X(8)), + (Register::X(8), Register::X(9), Register::X(9)), + (Register::Zero, Register::X(0), Register::X(8)), + ] { + let operation = Operation::LogicalRegister { + width, + kind: Logical::And, + invert: true, + flags: true, + destination, + left, + right, + shift, + amount, + }; + let run = |target, pinned| { + let mut code = if pinned { Code::pinned() } else { Code::new() }; + assert!(emit_direct(&mut code, &operation, target)); + code.asm().ret(); + let bytes = if pinned { + entered(&code) + } else { + code.into_bytes() + }; + let mut state = initial.clone(); + super::super::native::run(&bytes, &mut state); + state + }; + for pinned in [false, true] { + let state = run(TargetCpu::Bmi1, pinned); + assert_eq!(state, run(TargetCpu::Baseline, pinned)); + assert_eq!(state.nzcv & 0x3000_0000, 0); + } + } + } + } + } + + #[test] + fn binary_operands_keep_aliases_widths_and_flags() { + use crate::{ + GuestAddress, Options, TargetCpu, + block::{BlockProfile, Features}, + }; + const BASE: GuestAddress = GuestAddress(0x1000); + let pinned = Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::Baseline, + ); + let frame = Options::new(BlockProfile::ORDINARY, TargetCpu::Baseline); + let mut initial = GuestState::default(); + initial.x[0] = 0x1234_5678_7fff_fffe; + initial.x[1] = 0xfedc_ba98_0000_0003; + initial.x[3] = 0x9182_7364_ffff_ffff; + initial.x[16] = 0xaaff_5500_8000_0000; + initial.x[17] = 0x0246_8ace_ffff_ff00; + initial.nzcv = 0x3000_0000; + for base in [ + 0x0b00_0000, // ADD + 0x0b00_0800, // ADD, LSL #2 + 0x2b00_0000, // ADDS + 0x4b00_0000, // SUB + 0x6b00_0000, // SUBS + 0x4a00_0000, // EOR + 0x6a00_0000, // ANDS + ] { + for (rd, rn, rm) in [ + (1, 0, 1), + (16, 17, 1), + (17, 1, 16), + (0, 3, 0), + (3, 0, 3), + (1, 1, 1), + (31, 16, 3), + (1, 31, 1), + (16, 17, 31), + ] { + for width in [0u32, 1 << 31] { + let word = base | width | rm << 16 | rn << 5 | rd; + let run = |options, wrap| { + let native = crate::compile(&word.to_le_bytes(), BASE, options).unwrap(); + let code = if wrap { + entered(&native.native.x86_64_code) + } else { + native.native.x86_64_code + }; + let mut state = initial.clone(); + crate::x86_64::native::run(&code, &mut state); + state + }; + assert_eq!(run(&pinned, true), run(&frame, false), "{word:08x}"); + } + } + } + } + struct Random(u64); impl Random { fn next(&mut self) -> u32 { diff --git a/crates/stela-compiler/src/x86_64/region.rs b/crates/stela-compiler/src/x86_64/region.rs index 0db56d585f..d54e9b2bdd 100644 --- a/crates/stela-compiler/src/x86_64/region.rs +++ b/crates/stela-compiler/src/x86_64/region.rs @@ -13,7 +13,7 @@ mod apx; mod self_loop; pub(super) use analysis::MAX_INSTRUCTIONS; pub(crate) use self_loop::Plan as ResidentLoopPlan; -pub(super) use self_loop::prefix_with_budget; +pub(super) use self_loop::{FrameLoop, prefix_with_budget}; mod constant; mod encoding; mod flags; @@ -698,6 +698,59 @@ impl Emitter<'_> { self.instruction_with_constant(instruction, None) } + fn emit_constant_write( + &mut self, + write: constant::ConstantWrite, + immediate_width: Width, + continuation: Option, + ) { + let guest = slot(write.destination).expect("known constant has a real destination"); + if next_use(self.effects, self.current + 1, guest) != usize::MAX { + let index = self.allocate(guest); + self.emit(|code| encoding::immediate(code, POOL[index], write.value, immediate_width)); + self.locations[guest] = Location::Host(POOL[index]); + self.resident[index] = Some(Resident { guest, dirty: true }); + self.output.stats.commits += 1; + if let Some(pc) = continuation { + // A resident value needs no separate frame store here. + self.output.source_map.push((pc, self.output.code.len())); + self.emit(encoding::nop); + } + } else { + self.emit(|code| encoding::immediate(code, RESULT, write.value, immediate_width)); + if let Some(pc) = continuation { + self.output.source_map.push((pc, self.output.code.len())); + } + self.commit(write.destination, Width::X64); + } + self.output.stats.constant_writes += 1; + } + + fn emit_constant_group( + &mut self, + group: &[Instruction], + write: constant::ConstantWrite, + immediate_width: Width, + ) { + let [markers @ .., materialization, last] = group else { + unreachable!("constant group needs two source rows"); + }; + self.pinned_hosts = 0; + self.coalesced = None; + for instruction in markers { + self.output + .source_map + .push((instruction.pc, self.output.code.len())); + self.emit(encoding::nop); + } + self.output + .source_map + .push((materialization.pc, self.output.code.len())); + self.current += group.len() - 1; + self.emit_constant_write(write, immediate_width, Some(last.pc)); + self.output.stats.commits += group.len() - 1; + } + fn instruction_with_constant( &mut self, instruction: &Instruction, @@ -709,18 +762,7 @@ impl Emitter<'_> { .source_map .push((instruction.pc, self.output.code.len())); if let Some(write) = constant { - let guest = slot(write.destination).expect("known constant has a real destination"); - if next_use(self.effects, self.current + 1, guest) != usize::MAX { - let index = self.allocate(guest); - self.emit(|code| encoding::immediate(code, POOL[index], write.value, Width::X64)); - self.locations[guest] = Location::Host(POOL[index]); - self.resident[index] = Some(Resident { guest, dirty: true }); - self.output.stats.commits += 1; - } else { - self.emit(|code| encoding::immediate(code, RESULT, write.value, Width::X64)); - self.commit(write.destination, Width::X64); - } - self.output.stats.constant_writes += 1; + self.emit_constant_write(write, Width::X64, None); return Ok(()); } match instruction.operation { @@ -1235,8 +1277,41 @@ fn emit_prefix_selected<'a>( fault_table, full: false, }; - for instruction in instructions.iter().take(consumed) { - emitter.instruction(instruction)?; + let span = &instructions[..consumed]; + while let Some(instruction) = span.get(emitter.current) { + // A hosted block enters at a guest block head and runs these + // non-faulting groups as units. A compile starting inside a group, + // or ending before its tail, still sees only the original slice. + let rest = &span[emitter.current..]; + let group = if clean_loads && !fault_table { + match instruction.operation { + Operation::PcRelative(_) => rest.get(1).and_then(|second| { + emitter + .constants + .fold_address_pair(&instruction.operation, &second.operation) + .map(|write| (2, write, Width::X64)) + }), + Operation::MoveWide { .. } => { + emitter.constants.fold_wide_run(rest).map(|(count, write)| { + // A numeric literal has no AOT relocation field. + let width = if u32::try_from(write.value).is_ok() { + Width::W32 + } else { + Width::X64 + }; + (count, write, width) + }) + } + _ => None, + } + } else { + None + }; + if let Some((count, write, immediate_width)) = group { + emitter.emit_constant_group(&rest[..count], write, immediate_width); + } else { + emitter.instruction(instruction)?; + } emitter.current += 1; } for index in 0..POOL.len() { diff --git a/crates/stela-compiler/src/x86_64/region/constant.rs b/crates/stela-compiler/src/x86_64/region/constant.rs index 1baf4f8984..07d43dd117 100644 --- a/crates/stela-compiler/src/x86_64/region/constant.rs +++ b/crates/stela-compiler/src/x86_64/region/constant.rs @@ -1,6 +1,6 @@ //! Compile-time constant facts for non-faulting scalar sequences. Each separately //! entered region starts with no facts. -use crate::aarch64::{Operation, Register, WideMove, Width}; +use crate::aarch64::{Instruction, Operation, Register, WideMove, Width}; const REGISTER_SLOTS: usize = 32; const SP_SLOT: usize = 31; @@ -59,6 +59,55 @@ impl ConstantRegisters { value.map(|value| ConstantWrite { destination, value }) } + pub(super) fn fold_address_pair( + &mut self, + first: &Operation, + second: &Operation, + ) -> Option { + let folded = super::super::block::fold_address_pair(first, second)?; + self.write(folded.destination, Some(folded.address)) + } + + pub(super) fn fold_wide_run( + &mut self, + instructions: &[Instruction], + ) -> Option<(usize, ConstantWrite)> { + let (first, rest) = instructions.split_first()?; + let Operation::MoveWide { + width, + kind: WideMove::Zero | WideMove::Not, + destination: destination @ Register::X(_), + .. + } = first.operation + else { + return None; + }; + let mut keeps = rest.iter().take_while(|instruction| { + matches!( + instruction.operation, + Operation::MoveWide { + width: next_width, + kind: WideMove::Keep, + destination: next_destination, + .. + } if next_width == width && next_destination == destination + ) + }); + let second = keeps.next()?; + self.step(&first.operation); + let mut write = self + .step(&second.operation) + .expect("wide move initializer supplies the destination"); + let mut count = 2; + for instruction in keeps { + write = self + .step(&instruction.operation) + .expect("wide move continuation retains its constant destination"); + count += 1; + } + Some((count, write)) + } + /// Observe exactly one guest instruction. Returned writes can replace only /// that instruction's value computation; they never authorize removing its /// native commit, source-map entry, or observable intermediate guest value. diff --git a/crates/stela-compiler/src/x86_64/region/self_loop.rs b/crates/stela-compiler/src/x86_64/region/self_loop.rs index 7651c21790..93f9ac40af 100644 --- a/crates/stela-compiler/src/x86_64/region/self_loop.rs +++ b/crates/stela-compiler/src/x86_64/region/self_loop.rs @@ -1,13 +1,12 @@ -//! Register residency for non-faulting scalar self-loops. Every exit writes back -//! the full guest register bank. +//! Bounded native self-loops. Every return settles the guest register bank. use super::{ AllocationStats, Effects, Emitter, FRAME_LOCATIONS, GPR_SLOTS, HostGpr, Location, MAX_INSTRUCTIONS, OptimizedRegion, POOL, Resident, analysis, constant, encoding, flags, }; -use crate::x86_64::asm::Code; +use crate::x86_64::asm::{Code, Cond, Gpr, Mem, Patch, Size}; use crate::{ GuestAddress, NativeBlock, - aarch64::{Instruction, Operation}, + aarch64::{AddressMode, Instruction, MemoryTransfer, Operation, Register}, block::{ExitKind, Terminator}, }; use alloc::vec; @@ -15,6 +14,139 @@ use alloc::vec::Vec; const ARM_CONDITION_INVERSE_BIT: u8 = 1; const INSTRUCTION_BYTES: u64 = core::mem::size_of::() as u64; +const MAX_FRAME_LOOP_INSTRUCTIONS: usize = 32; +const FRAME_LOOP_COUNTER: Gpr = Gpr::R12; + +/// The existing ordinary body finishes with a settled frame. Its regions +/// preserve callee-saved registers, including the native budget counter. +/// This wrapper is only used for reviewed direct-RAM bodies with no helper +/// exits, stack checks or fault-recoverable execution context. +pub(crate) struct FrameLoop { + entry: GuestAddress, + header: usize, + zero_budget: Patch, +} + +impl FrameLoop { + pub(crate) fn begin(code: &mut Code, entry: GuestAddress) -> Self { + const _: () = assert!(crate::block::loop_budget::REMAINING_OFFSET == 0); + let mut asm = code.asm(); + asm.push(FRAME_LOOP_COUNTER); + asm.push(Gpr::Rsi); + asm.mov_load(Size::Qword, FRAME_LOOP_COUNTER, Mem::base(Gpr::Rsi, 0)); + asm.test(Size::Qword, FRAME_LOOP_COUNTER, FRAME_LOOP_COUNTER); + let zero_budget = asm.jcc(Cond::E); + let header = asm.len(); + Self { + entry, + header, + zero_budget, + } + } + + pub(crate) fn finish(self, code: &mut Code, taken: Option, fallthrough: GuestAddress) { + let mut asm = code.asm(); + let normal = taken.map(|condition| asm.jcc(condition.negate())); + // The guest predicate is already consumed and NZCV is settled. A + // single decrement both accounts for this iteration and gates the + // native backedge. + asm.dec(Size::Qword, FRAME_LOOP_COUNTER); + let again = asm.jcc(Cond::Ne); + asm.bind_back(again, self.header); + asm.bind(self.zero_budget); + settle_frame_budget(&mut asm); + super::super::block::direct_exit_with(&mut asm, self.entry, ExitKind::Direct); + if let Some(normal) = normal { + asm.bind(normal); + asm.dec(Size::Qword, FRAME_LOOP_COUNTER); + settle_frame_budget(&mut asm); + super::super::block::direct_exit_with(&mut asm, fallthrough, ExitKind::Fallthrough); + } + } +} + +fn settle_frame_budget(asm: &mut crate::x86_64::asm::Asm<'_>) { + asm.pop(Gpr::Rsi); + asm.mov_store(Size::Qword, Mem::base(Gpr::Rsi, 0), FRAME_LOOP_COUNTER); + asm.pop(FRAME_LOOP_COUNTER); +} + +fn direct_ram_loop( + instructions: &[Instruction], + terminal: Option<&(GuestAddress, Terminator)>, + fallthrough: GuestAddress, +) -> Option { + let entry = instructions.first()?.pc; + let (branch_pc, Terminator::Branch(Operation::BranchCondition { target, .. })) = terminal? + else { + return None; + }; + if *target != entry + || instructions.len() > MAX_FRAME_LOOP_INSTRUCTIONS + || branch_pc.0 + != entry + .0 + .checked_add(instructions.len() as u64 * INSTRUCTION_BYTES)? + || fallthrough.0 != branch_pc.0.checked_add(INSTRUCTION_BYTES)? + { + return None; + } + let mut loads = 0; + for (index, instruction) in instructions.iter().enumerate() { + if instruction.pc.0 != entry.0.checked_add(index as u64 * INSTRUCTION_BYTES)? { + return None; + } + let operation = &instruction.operation; + match operation { + Operation::Memory { + transfer: MemoryTransfer::Load { signed: false, .. }, + base: Register::X(_), + mode: AddressMode::Offset, + .. + } + | Operation::MemoryPair { + transfer: MemoryTransfer::Load { signed: false, .. }, + base: Register::X(_), + mode: AddressMode::Offset, + .. + } if analysis::clean_load_effects(operation).is_some() => loads += 1, + operation if flags::analyze_value(operation).is_some() => {} + _ => return None, + } + } + // Prefer dense read loops over adding an ABI wrapper to short, occasional + // memory edges. Register-only loops have the earlier residency plans. + (loads >= 2).then_some(entry) +} + +#[cfg(test)] +#[test] +fn direct_ram_admission_excludes_stack_checks_and_stores() { + use crate::{ + Options, TargetCpu, + block::{BlockProfile, CompilationPlan, Features}, + }; + + let options = Options::new(BlockProfile::ORDINARY, TargetCpu::Baseline); + let second_load = 0xf940_0423_u32; + let subtract = 0xf100_0400; + let branch = 0x54ff_ffa1; + for (first_load, resident) in [ + (0xf940_0022_u32, true), // LDR X2, [X1] + (0xf940_03e2, false), // LDR X2, [SP] + (0xf900_0022, false), // STR X2, [X1] + (0xb980_0022, false), // LDRSW X2, [X1] + ] { + let source: Vec<_> = [first_load, second_load, subtract, branch] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + let plan = CompilationPlan::new(&source, GuestAddress(0x1000), &options) + .unwrap() + .with_resident_loops(); + assert_eq!(plan.profile().has(Features::RESIDENT_LOOPS), resident); + } +} pub(crate) fn prefix_with_budget(mut native: NativeBlock, base: GuestAddress) -> NativeBlock { let mut code = Code::new(); @@ -47,6 +179,7 @@ pub(crate) struct Plan { enum Choice { Legacy(LegacyPlan), + DirectRam(GuestAddress), Allocated { instructions: Vec, native: NativeBlock, @@ -64,21 +197,40 @@ impl Plan { choice: Choice::Legacy(plan), }); } - let native = allocated_loop(instructions, terminal, fallthrough)?; - Some(Self { - choice: Choice::Allocated { + let choice = if let Some(native) = allocated_loop(instructions, terminal, fallthrough) { + Choice::Allocated { instructions: instructions.to_vec(), native, - }, - }) + } + } else { + Choice::DirectRam(direct_ram_loop(instructions, terminal, fallthrough)?) + }; + Some(Self { choice }) } pub(crate) fn emit( self, instructions: &[Instruction], + terminal: Option<&(GuestAddress, Terminator)>, + fallthrough: GuestAddress, + target: crate::TargetCpu, ) -> Result { match self.choice { Choice::Legacy(plan) => plan.emit(instructions), + Choice::DirectRam(entry) => { + // The caller's immutable parse and source identity own the + // words. Recheck the emitter's no-helper contract here too. + if direct_ram_loop(instructions, terminal, fallthrough) != Some(entry) { + return Err(super::RegionError::ChangedInstructions); + } + Ok(super::super::block::emit_frame_loop( + instructions, + terminal, + fallthrough, + target, + entry, + )) + } Choice::Allocated { instructions: planned, native, diff --git a/crates/stela-compiler/src/x86_64/region/tests.rs b/crates/stela-compiler/src/x86_64/region/tests.rs index 6d1798de98..3136ac9d74 100644 --- a/crates/stela-compiler/src/x86_64/region/tests.rs +++ b/crates/stela-compiler/src/x86_64/region/tests.rs @@ -19,6 +19,96 @@ fn add(destination: Register, source: Register) -> Operation { immediate: 1, } } + +#[test] +fn address_pair_shares_one_literal_and_preserves_distinct_source_rows() { + let x0 = Register::X(0); + let instructions = [ + instruction( + 0, + Operation::PcRelative(crate::aarch64::pc_relative::Operand { + destination: x0, + address: u64::MAX, + }), + ), + instruction(1, add(x0, x0)), + instruction(2, add(Register::X(3), x0)), + ]; + for span in [&instructions[..2], &instructions[..]] { + let separate = emit_prefix(span).unwrap(); + let fused = emit_clean_load_prefix(span, true, None).unwrap(); + let precise = + emit_clean_load_prefix_with(span, crate::x86_64::MemoryChecks::DEFAULT, true, None) + .unwrap(); + assert_eq!(&precise.code[..], &separate.code[..]); + assert_eq!(fused.consumed_instructions, span.len()); + assert_eq!(fused.stats.commits, span.len()); + assert_eq!(fused.stats.constant_writes, span.len() - 1); + assert_eq!(&fused.code[2..10], &[0; 8]); // wrapped address + assert_eq!(fused.source_map[..2], [(span[0].pc, 0), (span[1].pc, 10)]); + assert!( + fused + .source_map + .windows(2) + .all(|pair| pair[0].1 < pair[1].1) + ); + assert!(fused.code.len() < separate.code.len()); + } +} + +#[test] +fn hosted_wide_constants_use_one_literal_and_keep_all_source_rows() { + let wide = |index, width, kind, immediate, shift| { + instruction( + index, + Operation::MoveWide { + width, + kind, + destination: Register::X(0), + immediate, + shift, + }, + ) + }; + let narrow = [ + wide(0, Width::W32, WideMove::Zero, 0x1234, 0), + wide(1, Width::W32, WideMove::Keep, 0x5678, 16), + ]; + let narrow_fused = emit_clean_load_prefix(&narrow, true, None).unwrap(); + assert_eq!( + narrow_fused.source_map, + [(narrow[0].pc, 0), (narrow[1].pc, 5)] + ); + assert_eq!(&narrow_fused.code[..5], &[0xb8, 0x34, 0x12, 0x78, 0x56]); + assert_eq!(narrow_fused.stats.commits, 2); + assert_eq!(narrow_fused.stats.constant_writes, 1); + + let wide = [ + wide(0, Width::X64, WideMove::Not, 0xabcd, 32), + wide(1, Width::X64, WideMove::Keep, 0x1234, 16), + wide(2, Width::X64, WideMove::Keep, 0x5678, 48), + ]; + let fused = emit_clean_load_prefix(&wide, true, None).unwrap(); + let precise = + emit_clean_load_prefix_with(&wide, crate::x86_64::MemoryChecks::DEFAULT, true, None) + .unwrap(); + assert_eq!( + fused.source_map, + [(wide[0].pc, 0), (wide[1].pc, 1), (wide[2].pc, 11)] + ); + assert_eq!(&fused.code[..3], &[0x90, 0x48, 0xb8]); + assert_eq!(&fused.code[3..11], &0x5678_5432_1234_ffff_u64.to_le_bytes()); + assert_eq!(fused.stats.commits, 3); + assert_eq!(fused.stats.constant_writes, 1); + assert_eq!(precise.stats.constant_writes, 3); + assert!(fused.code.len() < precise.code.len()); + assert!(fused.stats.native_instructions < precise.stats.native_instructions); + + let different_width = [narrow[0].clone(), wide[1].clone()]; + let separate = emit_clean_load_prefix(&different_width, true, None).unwrap(); + assert_eq!(separate.stats.constant_writes, 2); +} + #[test] fn chain_reuses_value_and_settles_once() { let instructions: Vec<_> = (0..256) @@ -1605,14 +1695,18 @@ fn wider_loop_admission_uses_capacity_not_five_participants() { condition: 1, }), ); - let plan = self_loop::Plan::new(&instructions, Some(&terminal), GuestAddress(0x1024)).unwrap(); - let native = plan.emit(&instructions).unwrap(); + let fallthrough = GuestAddress(0x1024); + let target = crate::TargetCpu::Baseline; + let plan = self_loop::Plan::new(&instructions, Some(&terminal), fallthrough).unwrap(); + let native = plan + .emit(&instructions, Some(&terminal), fallthrough, target) + .unwrap(); assert_eq!(native.source_map.len(), instructions.len() + 1); assert_eq!(native.source_map[0].1, 0); let changed = [instruction(0, Operation::Nop)]; - let plan = self_loop::Plan::new(&instructions, Some(&terminal), GuestAddress(0x1024)).unwrap(); + let plan = self_loop::Plan::new(&instructions, Some(&terminal), fallthrough).unwrap(); assert!(matches!( - plan.emit(&changed), + plan.emit(&changed, Some(&terminal), fallthrough, target), Err(RegionError::ChangedInstructions) )); } diff --git a/crates/stela-compiler/src/x86_64/register_offset.rs b/crates/stela-compiler/src/x86_64/register_offset.rs index 9b893a6ce5..3d09e490fc 100644 --- a/crates/stela-compiler/src/x86_64/register_offset.rs +++ b/crates/stela-compiler/src/x86_64/register_offset.rs @@ -145,7 +145,10 @@ fn transfer(code: &mut Code, operand: &Operand) { MemoryTransfer::Load { signed, width } => { let size = Size::of(width == Width::X64); let address = Mem::base(Gpr::Rax, 0); - let host = code.host(operand.data).unwrap_or(Gpr::Rcx); + // The result may replace the address in RAX. This leaves it + // available to the next instruction, with no base writeback. + let scratch = if code.is_pinned() { Gpr::Rax } else { Gpr::Rcx }; + let host = code.host(operand.data).unwrap_or(scratch); let mut asm = code.asm(); asm.guest_access(|asm| match (operand.bytes, signed) { (1, false) => asm.movzx(size, host, Size::Byte, address), @@ -160,10 +163,10 @@ fn transfer(code: &mut Code, operand: &Operand) { _ => unreachable!("decoder validates signed register-offset size"), }); // A load to ZR still accesses memory and can fault. - if host == Gpr::Rcx + if host == scratch && let Some(data) = asm.guest(operand.data) { - asm.mov_store(Size::Qword, data, Gpr::Rcx); + asm.mov_store(Size::Qword, data, host); } } } diff --git a/crates/stela-compiler/src/x86_64/simd.rs b/crates/stela-compiler/src/x86_64/simd.rs index f4ba175269..2e6737b3ff 100644 --- a/crates/stela-compiler/src/x86_64/simd.rs +++ b/crates/stela-compiler/src/x86_64/simd.rs @@ -4,7 +4,6 @@ use super::isa::SimdOpcode as Host; use super::{MemoryChecks, memory_address, memory_writeback}; use crate::aarch64::simd::{Comparison, IntegerOperation, Operand}; use crate::x86_64::asm::{Code, Gpr, Mem, vector_extensions}; -use alloc::vec::Vec; pub(in crate::x86_64) mod absolute_selection; mod aes; pub(super) mod arithmetic; @@ -671,11 +670,16 @@ pub(super) fn emit_after( /// destination of a branch-free emission that ends with its commit from /// XMM0; or, after a lane move to a general register, which leaves XMM0 /// alone, what it held. -pub(super) fn xmm0_after(operand: &Operand, code: &[u8], held: Option) -> Option { - let committed = |vector: u8| { - let mut store = Code::new(); - commit(&mut store, vector, 0); - code.ends_with(&store).then_some(vector) +pub(super) fn xmm0_after( + scratch: &mut Code, + operand: &Operand, + code: &[u8], + held: Option, +) -> Option { + let mut committed = |vector: u8| { + scratch.clear(); + commit(scratch, vector, 0); + code.ends_with(scratch).then_some(vector) }; match *operand { Operand::Immediate(crate::aarch64::simd::immediates::Operand::LaneMove( @@ -706,10 +710,10 @@ pub(super) fn xmm0_after(operand: &Operand, code: &[u8], held: Option) -> Op /// [`read_vector`]'s bytes for `vector` into XMM0, which an emission that /// begins with them does not need where XMM0 holds the vector already. -pub(super) fn xmm0_load(vector: u8) -> Vec { - let mut load = Code::new(); - read_vector(&mut load, vector, 0); - load.into_bytes() +pub(super) fn xmm0_load(scratch: &mut Code, vector: u8) -> &[u8] { + scratch.clear(); + read_vector(scratch, vector, 0); + scratch } #[cfg(test)] diff --git a/crates/stela-compiler/src/x86_64/simd/comparison.rs b/crates/stela-compiler/src/x86_64/simd/comparison.rs index c228eec76c..6689a2898d 100644 --- a/crates/stela-compiler/src/x86_64/simd/comparison.rs +++ b/crates/stela-compiler/src/x86_64/simd/comparison.rs @@ -488,6 +488,19 @@ fn emit_predicate(code: &mut Code, operand: &Operand, pc: GuestAddress) { }; let mut helper = Vec::new(); exception_guard(code, &mut helper); + if shape != Shape::Scalar + && operation == Predicate::Equal + && right == CompareSource::Register(left) + { + // Normal values, both zero signs and infinities equal themselves + // without changing FPSR. One guard suffices for the shared source. + read_numerical_vector(code, shape, left, LEFT_VECTOR); + vector_zero_guard(code, format, shape, &mut helper); + helper_section(code, &helper, pc); + packed(code, Host::EqualDword, LEFT_VECTOR, LEFT_VECTOR); + commit_predicate(code, format, shape, destination, LEFT_VECTOR, false, false); + return; + } let zero = right == CompareSource::Zero; let merge = shape == Shape::Scalar && !zero diff --git a/crates/stela-compiler/src/x86_64/simd/integer_conversion.rs b/crates/stela-compiler/src/x86_64/simd/integer_conversion.rs index 81016cffa1..b4f0c2db16 100644 --- a/crates/stela-compiler/src/x86_64/simd/integer_conversion.rs +++ b/crates/stela-compiler/src/x86_64/simd/integer_conversion.rs @@ -18,7 +18,7 @@ use crate::{ aarch64::{ Register, floating::{ - FPCR_EXCEPTION_ENABLE_MASK, FPCR_NEP, Format, INEXACT, + FPCR_EXCEPTION_ENABLE_MASK, FPCR_FIZ, FPCR_FZ, FPCR_NEP, Format, INEXACT, integer::{IntegerFormat, IntegerRounding, IntegerWidth}, }, simd::{ @@ -344,9 +344,8 @@ pub(in crate::x86_64) fn from_integer( finish_float(code, operand); } -fn guard_float_source(code: &mut Code, operand: &IntegerConversion) -> usize { +fn guard_float_input(code: &mut Code, operand: &IntegerConversion) -> usize { let shape = operand.integer.shape(); - read_numerical_vector(code, shape, operand.float, RESULT_VECTOR); if shape == Shape::Scalar { exponent_range(code, operand.format, RESULT_VECTOR, INPUT_MINIMUM_EXPONENT); branch(code, Condition::AboveOrEqual) @@ -526,10 +525,26 @@ pub(in crate::x86_64) fn to_integer( let packed_result = shape != Shape::Scalar && (signed_single || vector_extensions::packed_conversion_supported(operand.format, integer, target)); + let packed_truncate = signed_single + && packed_result + && mode == IntegerRounding::TowardZero + && operand.frac_bits == 0; let mut helper_patches = Vec::new(); - test_control(code, FPCR_EXCEPTION_ENABLE_MASK); - helper_patches.push(branch(code, Condition::NotZero)); - helper_patches.push(guard_float_source(code, operand)); + let other_controls = if packed_truncate { + read_numerical_vector(code, shape, operand.float, RESULT_VECTOR); + // With input flushing disabled, CVTTPS2DQ reports inexact for + // fractional inputs and invalid for NaNs or out-of-range values. + // Its status distinguishes those cases before any guest commit. + test_control(code, FPCR_EXCEPTION_ENABLE_MASK | FPCR_FIZ | FPCR_FZ); + Some(branch(code, Condition::NotZero)) + } else { + test_control(code, FPCR_EXCEPTION_ENABLE_MASK); + helper_patches.push(branch(code, Condition::NotZero)); + read_numerical_vector(code, shape, operand.float, RESULT_VECTOR); + helper_patches.push(guard_float_input(code, operand)); + None + }; + let convert = code.len(); environment_round(code, rounding(mode)); let mut environment_failures = Vec::new(); if packed_result { @@ -578,6 +593,15 @@ pub(in crate::x86_64) fn to_integer( } restore_environment(code); } + if let Some(other_controls) = other_controls { + let check_controls = code.len(); + resolve(code, other_controls, check_controls); + test_control(code, FPCR_EXCEPTION_ENABLE_MASK); + helper_patches.push(branch(code, Condition::NotZero)); + helper_patches.push(guard_float_input(code, operand)); + let resume = jump(code); + resolve(code, resume, convert); + } let helper_start = code.len(); for patch in helper_patches { resolve(code, patch, helper_start); diff --git a/crates/stela-compiler/src/x86_64/simd/precision.rs b/crates/stela-compiler/src/x86_64/simd/precision.rs index 0232ff3d36..0b209ca966 100644 --- a/crates/stela-compiler/src/x86_64/simd/precision.rs +++ b/crates/stela-compiler/src/x86_64/simd/precision.rs @@ -3,13 +3,13 @@ use super::super::isa::ShiftOpcode; use super::numerical::helper_section; use super::numerical::{ - Condition, INPUT_MINIMUM_EXPONENT, MINIMUM_EXPONENT_VECTOR, RESULT_MINIMUM_EXPONENT, Rounding, - branch, clear_scalar, commit_inexact, environment_round, exponent_range, - prepare_half_result_range, prepare_vector_input_range, prepare_vector_result_range, - read_numerical_vector, reject_other_status, resolve, restore_environment, test_control, - vector_exponent_range, + ArithmeticOpcode, Condition, INPUT_MINIMUM_EXPONENT, MINIMUM_EXPONENT_VECTOR, + RESULT_MINIMUM_EXPONENT, Rounding, branch, clear_scalar, commit_inexact, environment_round, + exponent_range, jump, prepare_half_result_range, prepare_vector_input_range, + prepare_vector_result_range, read_numerical_vector, reject_other_status, resolve, + restore_environment, single_vector_arithmetic, test_control, vector_exponent_range, }; -use super::{Host, commit, packed, read_vector}; +use super::{Host, commit, encode::guest, packed, read_vector, vector_offset}; use crate::x86_64::asm::FloatLanes; use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Rm, ShiftOp, Size, vector_extensions}; use crate::{ @@ -52,11 +52,16 @@ const HALF_FIELD_TO_DWORD_TOP: u8 = u32::BITS as u8 - HALF_TO_SINGLE_SIGN_SHIFT const HALF_EXPONENT_TO_DWORD_BOTTOM: u8 = u32::BITS as u8 - HALF_EXPONENT_BITS; const HALF_MAXIMUM_TO_BIAS_BITS: u8 = 2; const SINGLE_BIAS_POSITION: u8 = HALF_TO_SINGLE_BIAS.trailing_zeros() as u8; -const HALF_VALIDITY_MASK: u8 = 0x0f; -const HALF_EXPONENT_VECTOR: u8 = 2; -const HALF_VALIDITY_VECTOR: u8 = 3; +const HALF_VALIDITY_MASK: i8 = 0x0f; +const HALF_NORMAL_VECTOR: u8 = 2; +const HALF_FINITE_VECTOR: u8 = 3; const HALF_MAXIMUM_VECTOR: u8 = 4; -const HALF_MINIMUM_VECTOR: u8 = 5; +const HALF_ZERO_VECTOR: u8 = 5; +const HALF_SCALED_VECTOR: u8 = 6; +const HALF_SUBNORMAL_SCALE: u32 = (Format::Single.exponent_bias() + 1 + - Format::Half.exponent_bias() + - Format::Half.fraction_bits()) + << Format::Single.fraction_bits(); const DOUBLE_TO_SINGLE_DISCARDED_BITS: u8 = 29; const DOUBLE_TO_SINGLE_DISCARDED_MASK: u32 = (1 << DOUBLE_TO_SINGLE_DISCARDED_BITS) - 1; const COMPACT_QWORD_LOW_DWORDS: u8 = 0x88; @@ -211,7 +216,9 @@ fn emit_scalar( scalar_commit(code, operand.destination, destination); } -fn half_vector_guard(code: &mut Code, helper: &mut Vec) { +/// Branch if any exponent is outside the normal IEEE half range. Keep the +/// normal and finite lane masks for the zero and subnormal path. +fn half_normal_widening_guard(code: &mut Code) -> usize { packed( code, Host::EqualDword, @@ -219,63 +226,103 @@ fn half_vector_guard(code: &mut Code, helper: &mut Vec) { HALF_MAXIMUM_VECTOR, ); ShiftOpcode::RightDword.emit(code, HALF_MAXIMUM_VECTOR, HALF_EXPONENT_TO_DWORD_BOTTOM); - packed(code, Host::Xor, HALF_MINIMUM_VECTOR, HALF_MINIMUM_VECTOR); - packed(code, Host::MoveAligned, HALF_EXPONENT_VECTOR, SOURCE_VECTOR); - ShiftOpcode::LeftDword.emit(code, HALF_EXPONENT_VECTOR, HALF_FIELD_TO_DWORD_TOP); - ShiftOpcode::RightDword.emit(code, HALF_EXPONENT_VECTOR, HALF_EXPONENT_TO_DWORD_BOTTOM); + packed(code, Host::MoveAligned, HALF_NORMAL_VECTOR, SOURCE_VECTOR); + ShiftOpcode::LeftDword.emit(code, HALF_NORMAL_VECTOR, HALF_FIELD_TO_DWORD_TOP); + ShiftOpcode::RightDword.emit(code, HALF_NORMAL_VECTOR, HALF_EXPONENT_TO_DWORD_BOTTOM); packed( code, Host::MoveAligned, - HALF_VALIDITY_VECTOR, + HALF_FINITE_VECTOR, HALF_MAXIMUM_VECTOR, ); packed( code, Host::GreaterDword, - HALF_VALIDITY_VECTOR, - HALF_EXPONENT_VECTOR, + HALF_FINITE_VECTOR, + HALF_NORMAL_VECTOR, ); packed( code, Host::GreaterDword, - HALF_EXPONENT_VECTOR, - HALF_MINIMUM_VECTOR, + HALF_NORMAL_VECTOR, + HALF_ZERO_VECTOR, ); - packed(code, Host::And, HALF_EXPONENT_VECTOR, HALF_VALIDITY_VECTOR); - Host::DwordSignMask.register(code, 0, HALF_EXPONENT_VECTOR, crate::TargetCpu::Baseline); + packed(code, Host::And, HALF_NORMAL_VECTOR, HALF_FINITE_VECTOR); + Host::DwordSignMask.register(code, 0, HALF_NORMAL_VECTOR, TargetCpu::Baseline); code.asm() - .alu_imm8(Alu::Cmp, Size::Dword, Rax, HALF_VALIDITY_MASK as i8); + .alu_imm8(Alu::Cmp, Size::Dword, Rax, HALF_VALIDITY_MASK); + branch(code, Condition::NotZero) +} + +fn add_half_widening_bias(code: &mut Code) { + // The guard keeps exponent mask 31; 31 >> 2 gives 7, and 7 << 27 is + // exactly the S-vs-H exponent bias adjustment. Reuse that constant. + ShiftOpcode::RightDword.emit(code, HALF_MAXIMUM_VECTOR, HALF_MAXIMUM_TO_BIAS_BITS); + ShiftOpcode::LeftDword.emit(code, HALF_MAXIMUM_VECTOR, SINGLE_BIAS_POSITION); + packed(code, Host::AddDword, SOURCE_VECTOR, HALF_MAXIMUM_VECTOR); +} + +fn widen_finite_half(code: &mut Code, helper: &mut Vec) { + // Exponent 31 needs exact completion for AHP, infinity, and NaNs. + Host::DwordSignMask.register(code, 0, HALF_FINITE_VECTOR, TargetCpu::Baseline); + code.asm() + .alu_imm8(Alu::Cmp, Size::Dword, Rax, HALF_VALIDITY_MASK); helper.push(branch(code, Condition::NotZero)); + // Every 15-bit integer converts exactly to single, and scaling by 2^-24 + // produces a normal single or +0. The temporary leaves MXCSR untouched + // even in lanes where the result comes from the normal representation. + ShiftOpcode::LeftDword.emit(code, SOURCE_VECTOR, HALF_FIELD_TO_DWORD_TOP); + ShiftOpcode::RightDword.emit(code, SOURCE_VECTOR, HALF_FIELD_TO_DWORD_TOP); + packed( + code, + Host::ConvertPackedDwordToSingle, + HALF_SCALED_VECTOR, + SOURCE_VECTOR, + ); + code.asm().mov_imm32(Rax, HALF_SUBNORMAL_SCALE); + code.asm().movd_to_xmm(HALF_FINITE_VECTOR, Rax); + super::shuffle(code, HALF_FINITE_VECTOR, HALF_FINITE_VECTOR, 0); + single_vector_arithmetic( + code, + ArithmeticOpcode::Multiply, + HALF_SCALED_VECTOR, + HALF_FINITE_VECTOR, + ); + ShiftOpcode::LeftDword.emit(code, SOURCE_VECTOR, HALF_TO_SINGLE_FRACTION_SHIFT); + add_half_widening_bias(code); + packed(code, Host::And, SOURCE_VECTOR, HALF_NORMAL_VECTOR); + packed(code, Host::AndNot, HALF_NORMAL_VECTOR, HALF_SCALED_VECTOR); + packed(code, Host::Or, SOURCE_VECTOR, HALF_NORMAL_VECTOR); } fn emit_widen_half(code: &mut Code, operand: &PrecisionOperand, upper: bool, pc: GuestAddress) { let mut helper = Vec::new(); exception_guard(code, &mut helper); - read_vector(code, operand.source, SOURCE_VECTOR); - if upper { - ShiftOpcode::RightBytes.emit(code, SOURCE_VECTOR, UPPER_QWORD_BYTES); - } - packed(code, Host::Xor, RESULT_VECTOR, RESULT_VECTOR); - packed(code, Host::UnpackLowWord, SOURCE_VECTOR, RESULT_VECTOR); - half_vector_guard(code, &mut helper); + let part = vector_offset(operand.source) + u32::from(upper) * u32::from(UPPER_QWORD_BYTES); + Host::MoveQword.emit(code, SOURCE_VECTOR, guest(part), TargetCpu::Baseline); + packed(code, Host::Xor, HALF_ZERO_VECTOR, HALF_ZERO_VECTOR); + packed(code, Host::UnpackLowWord, SOURCE_VECTOR, HALF_ZERO_VECTOR); packed(code, Host::MoveAligned, RESULT_VECTOR, SOURCE_VECTOR); - // Strip each half sign, align the remaining fields and adjust the bias. + let needs_scaling = half_normal_widening_guard(code); + // Normal half lanes need only an exponent bias and a field shift. ShiftOpcode::LeftDword.emit(code, SOURCE_VECTOR, HALF_FIELD_TO_DWORD_TOP); ShiftOpcode::RightDword.emit( code, SOURCE_VECTOR, HALF_FIELD_TO_DWORD_TOP - HALF_TO_SINGLE_FRACTION_SHIFT, ); - // The guard keeps exponent mask 31; 31 >> 2 gives 7, and 7 << 27 is - // exactly the S-vs-H exponent bias adjustment. Reuse that constant. - ShiftOpcode::RightDword.emit(code, HALF_MAXIMUM_VECTOR, HALF_MAXIMUM_TO_BIAS_BITS); - ShiftOpcode::LeftDword.emit(code, HALF_MAXIMUM_VECTOR, SINGLE_BIAS_POSITION); - packed(code, Host::AddDword, SOURCE_VECTOR, HALF_MAXIMUM_VECTOR); + add_half_widening_bias(code); + let normal = jump(code); + let other = code.len(); + resolve(code, needs_scaling, other); + widen_finite_half(code, &mut helper); + helper_section(code, &helper, pc); + let complete = code.len(); + resolve(code, normal, complete); ShiftOpcode::LeftDword.emit(code, RESULT_VECTOR, HALF_TO_SINGLE_SIGN_SHIFT); ShiftOpcode::RightDword.emit(code, RESULT_VECTOR, DWORD_SIGN_TO_LSB_SHIFT); ShiftOpcode::LeftDword.emit(code, RESULT_VECTOR, DWORD_SIGN_TO_LSB_SHIFT); packed(code, Host::Or, RESULT_VECTOR, SOURCE_VECTOR); - helper_section(code, &helper, pc); commit(code, operand.destination, RESULT_VECTOR); } diff --git a/crates/stela-contracts/src/chip.rs b/crates/stela-contracts/src/chip.rs index 9d88b09cfe..f206d68e5a 100644 --- a/crates/stela-contracts/src/chip.rs +++ b/crates/stela-contracts/src/chip.rs @@ -93,6 +93,15 @@ struct AbsentGroup { forms: &'static [AbsentForm], } +/// The slice of one mask's sorted forms that contains its absent +/// candidates for one instruction prefix. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct AdmitRange { + group: u16, + first: u16, + end: u16, +} + /// `UDF #0`: an absent form's word is UNDEFINED as UDF is (EC 0x00, ISS 0). const UDF: u32 = 0; const NOP: u32 = 0xd503_201f; @@ -116,14 +125,16 @@ pub struct AdmitTable { withheld: u64, /// The chip's features without them. presented: u64, - /// The range of `groups` for each prefix, and its end. - starts: Vec, - groups: Vec, + /// One packed start and end in `groups` per prefix. Zero preserves the + /// word, and `UNALLOCATED` returns UDF without searching any groups. + spans: Vec, + groups: Vec, } impl AdmitTable { const SHIFT: u32 = 21; const PREFIXES: usize = 1 << (32 - Self::SHIFT); + const UNALLOCATED: u32 = u32::MAX; /// The immutable chip policy used to construct this table. pub fn chip(&self) -> Chip { @@ -133,17 +144,22 @@ impl AdmitTable { /// [`Chip::admit`] of the table's chip, where the forms of the features /// its PE withholds are absent too. pub fn admit(&self, word: u32) -> u32 { - if unallocated_group(word) { - return UDF; - } let prefix = (word >> Self::SHIFT) as usize; - let groups = &self.groups[self.starts[prefix] as usize..self.starts[prefix + 1] as usize]; + let span = match self.spans[prefix] { + 0 => return word, + Self::UNALLOCATED => return UDF, + span => span, + }; + let start = (span & u32::from(u16::MAX)) as usize; + let end = (span >> u16::BITS) as usize; self.chip.admit_in( word, self.presented, - groups - .iter() - .map(|&group| &forms::ABSENT[usize::from(group)]), + self.groups[start..end].iter().map(|range| { + let group = &forms::ABSENT[usize::from(range.group)]; + let forms = &group.forms[usize::from(range.first)..usize::from(range.end)]; + (group.mask, forms) + }), ) } @@ -229,14 +245,30 @@ impl Chip { // Every prefix that agrees with a form on the group's mask. let free = !(group.mask >> AdmitTable::SHIFT) & PREFIX; let absent = - |form: &&AbsentForm| form.chips & bit != 0 || !met(form.requires, presented); - for form in group.forms.iter().filter(absent) { + |form: &AbsentForm| form.chips & bit != 0 || !met(form.requires, presented); + for (position, form) in group + .forms + .iter() + .enumerate() + .filter(|(_, form)| absent(form)) + { + let end = u16::try_from(position + 1).expect("form ranges fit in u16"); let fixed = form.value >> AdmitTable::SHIFT & !free; let mut varying = free; loop { - let groups: &mut Vec = &mut by_prefix[(fixed | varying) as usize]; - if groups.last() != Some(&index) { - groups.push(index); + let groups: &mut Vec = &mut by_prefix[(fixed | varying) as usize]; + if let Some(last) = groups.last_mut() + && last.group == index + { + // The slice can include present forms between its + // first and last absent candidates. + last.end = end; + } else { + groups.push(AdmitRange { + group: index, + first: end - 1, + end, + }); } if varying == 0 { break; @@ -245,18 +277,26 @@ impl Chip { } } } - let mut starts = Vec::with_capacity(AdmitTable::PREFIXES + 1); + let mut spans = Vec::with_capacity(AdmitTable::PREFIXES); let mut groups = Vec::new(); - for prefix in by_prefix { - starts.push(groups.len() as u32); - groups.extend(prefix); + for (prefix, matches) in by_prefix.into_iter().enumerate() { + let span = if unallocated_group((prefix as u32) << AdmitTable::SHIFT) { + AdmitTable::UNALLOCATED + } else if matches.is_empty() { + 0 + } else { + let start = groups.len() as u32; + groups.extend(matches); + let end = u16::try_from(groups.len()).expect("absent-form group spans fit in u16"); + start | (u32::from(end) << u16::BITS) + }; + spans.push(span); } - starts.push(groups.len() as u32); Ok(AdmitTable { chip: self, withheld, presented, - starts, + spans, groups, }) } @@ -268,7 +308,11 @@ impl Chip { if unallocated_group(word) { return UDF; } - self.admit_in(word, self.features(), forms::ABSENT.iter()) + self.admit_in( + word, + self.features(), + forms::ABSENT.iter().map(|group| (group.mask, group.forms)), + ) } /// The first of `groups` holding a form that `word` is and that this @@ -277,17 +321,14 @@ impl Chip { self, word: u32, presented: u64, - groups: impl Iterator, + groups: impl Iterator, ) -> u32 { let bit = 1u8 << self as u8; - for group in groups { - let Ok(index) = group - .forms - .binary_search_by_key(&(word & group.mask), |form| form.value) - else { + for (mask, forms) in groups { + let Ok(index) = forms.binary_search_by_key(&(word & mask), |form| form.value) else { continue; }; - let form = &group.forms[index]; + let form = &forms[index]; let kept = form.unless.iter().any(|(mask, value, chips, requires)| { chips & bit != 0 && word & mask == *value && met(requires, presented) }); @@ -319,7 +360,6 @@ impl Chip { else { continue; }; - let single = ((word & checks::IMM5) >> checks::IMM5.trailing_zeros()).count_ones() == 1; return group.forms[index] .variants .iter() @@ -327,7 +367,9 @@ impl Chip { variant.chips & bit != 0 && match variant.class { WordClass::Any => true, - WordClass::SingleImm5(wanted) => wanted == single, + WordClass::SingleImm5(wanted) => { + wanted == (word & checks::IMM5).is_power_of_two() + } } }) .map_or(&[], |variant| variant.checks); diff --git a/crates/stela-contracts/src/interrupt.rs b/crates/stela-contracts/src/interrupt.rs index e1bf27535e..a02f182009 100644 --- a/crates/stela-contracts/src/interrupt.rs +++ b/crates/stela-contracts/src/interrupt.rs @@ -68,6 +68,9 @@ pub struct InterruptLatch { asserted: BTreeSet, aic_inputs: Vec<(AicInput, bool)>, } +/// Retain space for ordinary wire traffic without keeping a large burst. +const RETAINED_AIC_INPUTS: usize = 32; + impl InterruptLatch { pub fn new() -> Self { Self::default() @@ -76,6 +79,21 @@ impl InterruptLatch { pub fn take_aic_inputs(&mut self) -> Vec<(AicInput, bool)> { core::mem::take(&mut self.aic_inputs) } + + /// Move queued AIC input changes in order into an existing destination. + pub fn append_aic_inputs( + &mut self, + destination: &mut Vec, + map: impl FnMut((AicInput, bool)) -> T, + ) { + if self.aic_inputs.is_empty() { + return; + } + destination.extend(self.aic_inputs.drain(..).map(map)); + if self.aic_inputs.capacity() > RETAINED_AIC_INPUTS { + self.aic_inputs = Vec::new(); + } + } #[cfg(any(test, feature = "test-support"))] pub fn is_asserted(&self, wire: Wire) -> bool { self.asserted.contains(&wire) @@ -147,4 +165,30 @@ mod tests { assert_eq!(latch.take_aic_inputs(), vec![(uart, true), (uart, false)]); assert!(latch.take_aic_inputs().is_empty()); } + + #[test] + fn appending_aic_inputs_reuses_small_buffers_and_releases_large_ones() { + let mut latch = InterruptLatch::new(); + let input = AicInput::new(0, 739); + let mut output = vec![(input, false)]; + latch.set_level(Wire::Aic(input), true); + let capacity = latch.aic_inputs.capacity(); + assert_ne!(capacity, 0); + latch.append_aic_inputs(&mut output, core::convert::identity); + assert_eq!(output, [(input, false), (input, true)]); + assert_eq!(latch.aic_inputs.capacity(), capacity); + + for index in 0..=RETAINED_AIC_INPUTS { + latch.set_level(Wire::Aic(input), index % 2 != 0); + } + output.clear(); + latch.append_aic_inputs(&mut output, core::convert::identity); + assert!( + output + .iter() + .copied() + .eq((0..=RETAINED_AIC_INPUTS).map(|index| (input, index % 2 != 0))) + ); + assert_eq!(latch.aic_inputs.capacity(), 0); + } } diff --git a/crates/stela-driver-base/src/block.rs b/crates/stela-driver-base/src/block.rs index c351591dd7..18408c2cb8 100644 --- a/crates/stela-driver-base/src/block.rs +++ b/crates/stela-driver-base/src/block.rs @@ -727,7 +727,26 @@ impl Iterator for Plan { } } -type Commands = core::iter::Peekable>>; +/// The current request's plan lives inline. Only a batch has further plans +/// to allocate, and no caller consumes plans from the back. +struct Plans { + current: Option, + rest: alloc::vec::IntoIter, +} + +impl Iterator for Plans { + type Item = (usize, Command); + + fn next(&mut self) -> Option { + while let Some(plan) = &mut self.current { + if let Some(command) = plan.next() { + return Some(command); + } + self.current = self.rest.next(); + } + None + } +} impl Request { /// The commands that carry out `self` on a device with `identity`'s @@ -769,28 +788,80 @@ pub type Finished = Result>, BlockError>; /// flush alone once they completed, as Linux's flush sequence orders them. /// A device that runs no queued commands runs each where it is polled. pub struct Submission { - commands: Commands, - /// The started commands: each tag, a read's offset in the data, and - /// whether it is a flush. - running: Vec<(u32, usize, bool)>, - data: Option>, + commands: core::iter::Peekable, + running: Running, + read: Option, failed: Option, } +/// A started command's tag, a read's offset in the data, and whether the +/// command is a flush. +type InFlight = (u32, usize, bool); + +/// One command is enough for a request that fits the device's transfer +/// limit. Only overlapping commands require a queue allocation. +enum Running { + One(Option), + Many(Vec), +} + +impl Running { + fn as_slice(&self) -> &[InFlight] { + match self { + Self::One(command) => command.as_slice(), + Self::Many(commands) => commands, + } + } + + fn push(&mut self, command: InFlight) { + match self { + Self::One(Some(first)) => *self = Self::Many(vec![*first, command]), + Self::One(slot) => *slot = Some(command), + Self::Many(commands) => commands.push(command), + } + } + + fn remove(&mut self, index: usize) { + match self { + Self::One(slot) => { + debug_assert_eq!(index, 0); + *slot = None; + } + Self::Many(commands) => { + commands.swap_remove(index); + } + } + } +} + +/// A read can take ownership of a whole command result. Only a split read +/// needs an assembly buffer. +struct ReadData { + bytes: usize, + data: Option>, +} + /// New commands admitted by one polling call, including synchronous execution. const POLL_ADMISSIONS: usize = 64; impl Submission { pub fn new(request: Request, identity: &Identity) -> Result { let plan = Plan::new(request, identity)?; - let data = match &plan.request { - Request::Read { bytes, .. } => Some(vec![0; *bytes]), + let read = match &plan.request { + Request::Read { bytes, .. } => Some(ReadData { + bytes: *bytes, + data: None, + }), _ => None, }; Ok(Self { - commands: vec![plan].into_iter().flatten().peekable(), - running: Vec::new(), - data, + commands: Plans { + current: Some(plan), + rest: Default::default(), + } + .peekable(), + running: Running::One(None), + read, failed: None, }) } @@ -801,24 +872,33 @@ impl Submission { if let [Request::Read { .. }] = requests.as_slice() { return Self::new(requests.into_iter().next().unwrap(), identity); } - let mut plans = Vec::with_capacity(requests.len()); - for request in requests { + let plan = |request| { if let Request::Read { .. } = request { return Err(BlockError::Protocol("a read in a batch of requests")); } - plans.push(Plan::new(request, identity)?); + Plan::new(request, identity) + }; + let mut requests = requests.into_iter(); + let current = requests.next().map(plan).transpose()?; + let mut rest = Vec::with_capacity(requests.len()); + for request in requests { + rest.push(plan(request)?); } Ok(Self { - commands: plans.into_iter().flatten().peekable(), - running: Vec::new(), - data: None, + commands: Plans { + current, + rest: rest.into_iter(), + } + .peekable(), + running: Running::One(None), + read: None, failed: None, }) } /// The commands the device runs for this submission now. pub fn started(&self) -> usize { - self.running.len() + self.running.as_slice().len() } /// Collect the device's completions of this request's commands and @@ -831,13 +911,12 @@ impl Submission { /// entered synchronous execution may take longer than the caller's slice. pub fn poll(&mut self, device: &mut (impl BlockDevice + ?Sized)) -> Option { let mut index = 0; - while index < self.running.len() { - let (tag, offset, _) = self.running[index]; + while let Some(&(tag, offset, _)) = self.running.as_slice().get(index) { let Some(result) = device.finish(tag) else { index += 1; continue; }; - self.running.swap_remove(index); + self.running.remove(index); self.completed(offset, result); } let depth = device.depth(); @@ -848,11 +927,12 @@ impl Submission { break; }; let flush = matches!(command, Command::Flush); - if (flush && !self.running.is_empty()) || self.running.iter().any(|run| run.2) { + let running = self.running.as_slice(); + if (flush && !running.is_empty()) || running.iter().any(|run| run.2) { break; } if depth == 0 { - if !self.running.is_empty() { + if !running.is_empty() { break; } let (offset, command) = self.commands.next().unwrap(); @@ -861,7 +941,7 @@ impl Submission { self.completed(offset, result); continue; } - if self.running.len() >= capacity || !device.room() { + if running.len() >= capacity || !device.room() { break; } let (offset, command) = self.commands.next().unwrap(); @@ -871,20 +951,30 @@ impl Submission { Err(error) => self.failed = Some(error), } } - if !self.running.is_empty() || (self.failed.is_none() && self.commands.peek().is_some()) { + if !self.running.as_slice().is_empty() + || (self.failed.is_none() && self.commands.peek().is_some()) + { return None; } Some(match self.failed.take() { Some(error) => Err(error), - None => Ok(self.data.take()), + None => Ok(self + .read + .take() + .map(|read| read.data.unwrap_or_else(|| vec![0; read.bytes]))), }) } fn completed(&mut self, offset: usize, result: Finished) { match result { Ok(Some(bytes)) => { - if let Some(data) = self.data.as_mut() { - data[offset..offset + bytes.len()].copy_from_slice(&bytes); + if let Some(read) = &mut self.read { + if read.data.is_none() && offset == 0 && bytes.len() == read.bytes { + read.data = Some(bytes); + } else { + let data = read.data.get_or_insert_with(|| vec![0; read.bytes]); + data[offset..offset + bytes.len()].copy_from_slice(&bytes); + } } } Ok(None) => {} diff --git a/crates/stela-driver-base/src/block/shared.rs b/crates/stela-driver-base/src/block/shared.rs index 3d21996ad8..da5c42c08f 100644 --- a/crates/stela-driver-base/src/block/shared.rs +++ b/crates/stela-driver-base/src/block/shared.rs @@ -38,12 +38,13 @@ pub(super) struct Requests { pub(super) busy_since: u64, } -/// A device command and the tickets merged into it: each ticket's offset -/// and length in a read's data. What the accounting counts it as, and when -/// its first ticket was submitted. +/// A device command and its first ticket and read length. Additional tickets +/// carry their offset and length in the read's data. What the accounting +/// counts the command as, and when its first ticket was submitted. pub(super) struct Merged { pub(super) tag: u32, - pub(super) tickets: Vec<(u32, usize, usize)>, + pub(super) first: (u32, usize), + pub(super) more: Vec<(u32, usize, usize)>, pub(super) accounted: (Direction, u64), pub(super) submitted: u64, } @@ -231,14 +232,30 @@ impl Held<'_> { work.finishes = work.finishes.saturating_add(1); let merged = self.requests().running.swap_remove(index); let now = crate::Clock::ticks(); - let merges = merged.tickets.len() as u64 - 1; + let merges = merged.more.len() as u64; self.account(merged.accounted, merges, merged.submitted, now); let requests = self.requests(); if requests.running.is_empty() { requests.stats.busy += now.wrapping_sub(requests.busy_since); } let finished = &mut self.requests().finished; - for (ticket, offset, bytes) in merged.tickets { + let (ticket, bytes) = merged.first; + if merged.more.is_empty() { + let result = result.and_then(|data| match data { + Some(data) if data.len() < bytes => { + Err(BlockError::Protocol("a read returned too little data")) + } + Some(mut data) => { + data.truncate(bytes); + Ok(Some(data)) + } + None => Ok(None), + }); + finished.insert(ticket, result); + continue; + } + let tickets = core::iter::once((ticket, 0, bytes)).chain(merged.more); + for (ticket, offset, bytes) in tickets { let part = match &result { Ok(Some(data)) => Ok(Some(data[offset..offset + bytes].to_vec())), other => other.clone(), @@ -246,6 +263,9 @@ impl Held<'_> { finished.insert(ticket, part); } } + if self.requests().waiting.is_empty() { + return; + } let queued = self.depth() > 0; let (block, limit) = { let identity = self.identity(); @@ -268,13 +288,13 @@ impl Held<'_> { Command::Read { bytes, .. } => *bytes, _ => 0, }; - let mut tickets = vec![(ticket, 0, first)]; + let mut more = Vec::new(); let mut offset = first; while let Some((next, following, _)) = self.requests().waiting.front() { let Some(bytes) = merge(&mut command, following, block, limit) else { break; }; - tickets.push((*next, offset, bytes)); + more.push((*next, offset, bytes)); offset += bytes; self.requests().waiting.pop_front(); } @@ -288,14 +308,17 @@ impl Held<'_> { } requests.running.push(Merged { tag, - tickets, + first: (ticket, first), + more, accounted, submitted, }); requests.stats.deepest = requests.stats.deepest.max(requests.running.len()); } Err(error) => { - for (ticket, ..) in tickets { + for ticket in + core::iter::once(ticket).chain(more.into_iter().map(|(id, ..)| id)) + { self.requests().finished.insert(ticket, Err(error.clone())); } } diff --git a/crates/stela-driver-base/src/block/tests.rs b/crates/stela-driver-base/src/block/tests.rs index 5355c410ba..e005d90210 100644 --- a/crates/stela-driver-base/src/block/tests.rs +++ b/crates/stela-driver-base/src/block/tests.rs @@ -17,6 +17,7 @@ struct Delayed { released: Rc>, reads: Rc>, given: Rc>>, + last_read_address: Rc>, } type Probes = ( @@ -37,6 +38,7 @@ impl Delayed { released: probes.0.clone(), reads: probes.1.clone(), given: probes.2.clone(), + last_read_address: Default::default(), }; (delayed, probes) } @@ -48,6 +50,9 @@ impl Delayed { }; self.released.set(self.released.get() - 1); let result = self.disk.execute(command); + if let Ok(Some(data)) = &result { + self.last_read_address.set(data.as_ptr() as usize); + } self.done.insert(tag, result); } } @@ -211,6 +216,31 @@ fn windows_queue_commands_and_whichever_looks_moves_the_queue_on() { assert!(a.start(outside).is_err()); } +#[test] +fn a_single_queued_read_returns_the_devices_original_buffer() { + let data: Vec = (0..4096).map(|byte| (byte % 251) as u8).collect(); + let mut ram = RamDisk::new("single", 16, 512); + ram.write(1, &data).unwrap(); + let (delayed, (released, _, _)) = Delayed::new(ram, 1); + let address = delayed.last_read_address.clone(); + let disk = Shared::new(Box::new(delayed)); + let mut window = disk.whole(); + let mut read = Submission::new( + Request::Read { + lba: 1, + bytes: data.len(), + }, + window.identity(), + ) + .unwrap(); + assert_eq!(read.poll(&mut window), None); + released.set(1); + let result = read.poll(&mut window).unwrap().unwrap().unwrap(); + assert_eq!(result, data); + assert_eq!(result.as_ptr() as usize, address.get()); + assert_eq!(read.poll(&mut window), Some(Ok(None))); +} + #[test] fn bulk_submission_respects_window_capacity() { let blocks = 2 * WINDOW_DEPTH + 3; diff --git a/crates/stela-driver-base/src/bus/pci/power.rs b/crates/stela-driver-base/src/bus/pci/power.rs index 6545c178f4..079e3a31ca 100644 --- a/crates/stela-driver-base/src/bus/pci/power.rs +++ b/crates/stela-driver-base/src/bus/pci/power.rs @@ -75,6 +75,19 @@ pub enum WakeState { pub unsafe trait Timer { fn check(&self) -> Result<(), Error>; fn wait_us(&self, microseconds: u64) -> Result<(), Error>; + /// Start a nonblocking minimum interval, when the same source can retain + /// and revalidate it. A returned interval has the same physical guarantee + /// as `wait_us` and owns the source through every poll. + fn begin_interval( + &self, + _microseconds: u64, + ) -> Result>, Error> { + Ok(None) + } +} +pub trait Interval { + /// True only after the retained source proves the requested real interval. + fn elapsed(&self) -> Result; } // SAFETY: a shared timer is the same timer. unsafe impl Timer for alloc::rc::Rc { @@ -84,6 +97,12 @@ unsafe impl Timer for alloc::rc::Rc { fn wait_us(&self, microseconds: u64) -> Result<(), Error> { (**self).wait_us(microseconds) } + fn begin_interval( + &self, + microseconds: u64, + ) -> Result>, Error> { + (**self).begin_interval(microseconds) + } } /// The original endpoint configuration, platform power/exclusion and timing /// owners. Access is withheld throughout D3hot or an uncertain transition. diff --git a/crates/stela-driver-gpu/src/compiler/air_calls.c b/crates/stela-driver-gpu/src/compiler/air_calls.c index abb94cfa96..03fe164ed0 100644 --- a/crates/stela-driver-gpu/src/compiler/air_calls.c +++ b/crates/stela-driver-gpu/src/compiler/air_calls.c @@ -124,6 +124,16 @@ called(LLVMValueRef fn) return false; } +bool +stela_air_has_defined_calls(LLVMModuleRef module) +{ + for (LLVMValueRef fn = LLVMGetFirstFunction(module); fn; fn = LLVMGetNextFunction(fn)) { + if (stela_air_defined_function(fn) && called(fn)) + return true; + } + return false; +} + static unsigned attribute(const char *name) { @@ -288,19 +298,39 @@ unroll(struct stela_air_metadata *m, LLVMValueRef entry, unsigned depth, unsigne } } -bool -stela_air_inline_calls(struct stela_air_metadata *m, LLVMValueRef entry, - unsigned max_call_stack_depth, unsigned max_instructions) +/* A branch can make a direct call unreachable after specialization. */ +static bool +can_prune_calls(LLVMValueRef entry) +{ + bool branch = false, call = false; + for (LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(entry); block; + block = LLVMGetNextBasicBlock(block)) { + LLVMOpcode opcode = LLVMGetInstructionOpcode(LLVMGetBasicBlockTerminator(block)); + branch |= opcode == LLVMCondBr || opcode == LLVMSwitch; + for (LLVMValueRef inst = LLVMGetFirstInstruction(block); inst && !call; + inst = LLVMGetNextInstruction(inst)) + call = defined_callee(inst) != NULL; + if (branch && call) + return true; + } + return false; +} + +static bool +inline_calls(struct stela_air_metadata *m, LLVMValueRef entry, unsigned max_call_stack_depth, + unsigned max_instructions, LLVMValueRef specialized, bool *folded) { struct hash_table *states = _mesa_pointer_hash_table_create(NULL); if (!states) return fail(m, STELA_AIR_ALLOCATION, "call graph allocation failed"); bool walked = true, inlined = false, recursive = false; for (LLVMValueRef fn = LLVMGetFirstFunction(m->module); fn && walked; fn = LLVMGetNextFunction(fn)) { - bool cyclic; m->unoptimized |= LLVMGetEnumAttributeAtIndex(fn, LLVMAttributeFunctionIndex, attribute("optnone")) != NULL; - walked = !stela_air_defined_function(fn) || visit(m, states, fn, true, 0, &cyclic); + if (!stela_air_defined_function(fn)) + continue; + bool cyclic; + walked = visit(m, states, fn, true, 0, &cyclic); recursive |= walked && fn == entry && cyclic; } for (LLVMValueRef fn = LLVMGetFirstFunction(m->module); fn && walked; fn = LLVMGetNextFunction(fn)) { @@ -310,12 +340,36 @@ stela_air_inline_calls(struct stela_air_metadata *m, LLVMValueRef entry, inline_always(fn); inlined = true; } + /* Keep the original graph's depth and cycle checks before pruning calls. */ + struct hash_entry *state = walked && inlined && specialized && !m->unoptimized ? + _mesa_hash_table_search(states, specialized) : NULL; + bool fold = state && (uintptr_t)state->data == ACYCLIC && can_prune_calls(specialized); _mesa_hash_table_destroy(states, NULL); - if (!walked || (inlined && !run_inliner(m))) + if (!walked) + return false; + if (fold) { + *folded = true; + if (!stela_air_fold_constants(m, specialized)) + return false; + } + if (inlined && !run_inliner(m)) return false; return !recursive || unroll(m, entry, max_call_stack_depth, max_instructions); } +bool +stela_air_inline_calls(struct stela_air_metadata *m, LLVMValueRef entry, + unsigned max_call_stack_depth, unsigned max_instructions) +{ + return inline_calls(m, entry, max_call_stack_depth, max_instructions, NULL, NULL); +} + +bool +stela_air_inline_specialized_calls(struct stela_air_metadata *m, LLVMValueRef entry, bool *folded) +{ + return inline_calls(m, NULL, 0, 0, entry, folded); +} + /* Apple's compiler declares a visible function another module defines as * NAME.MTL_VISIBLE_FN_REF, and lists the NAME it means. Under that name the * linker resolves it as it does any declaration. */ diff --git a/crates/stela-driver-gpu/src/compiler/air_calls.h b/crates/stela-driver-gpu/src/compiler/air_calls.h index ee62d4d3ce..cacde7ee1a 100644 --- a/crates/stela-driver-gpu/src/compiler/air_calls.h +++ b/crates/stela-driver-gpu/src/compiler/air_calls.h @@ -10,6 +10,9 @@ * refuses its calls as AIR's. */ bool stela_air_defined_function(LLVMValueRef fn); +/* Whether module has a direct call to one of its defined AIR functions. */ +bool stela_air_has_defined_calls(LLVMModuleRef module); + /* Links modules into m's, after checking each is AIR compiled as m's was, * so one profile translates them, and specializing each with its own * function constant values. m's own are specialized first, since linking @@ -33,4 +36,9 @@ bool stela_air_dispatch_tables(struct stela_air_metadata *m, * recursion stay. */ bool stela_air_inline_calls(struct stela_air_metadata *m, LLVMValueRef entry, unsigned max_call_stack_depth, unsigned max_instructions); +/* The first inlining pass with an optional specialized entry. After checking + * the original graph, it folds constants in an acyclic entry before expanding + * its calls, setting *folded when that pass runs. */ +bool stela_air_inline_specialized_calls(struct stela_air_metadata *m, LLVMValueRef entry, + bool *folded); #endif diff --git a/crates/stela-driver-gpu/src/compiler/air_constants.c b/crates/stela-driver-gpu/src/compiler/air_constants.c index c141c7dc4f..96ed2e153f 100644 --- a/crates/stela-driver-gpu/src/compiler/air_constants.c +++ b/crates/stela-driver-gpu/src/compiler/air_constants.c @@ -22,6 +22,7 @@ * paths a false constant disables are removed rather than translated. */ #define STELA_AIR_METADATA_INTERNAL #include "air_constants.h" +#include "air_calls.h" #include "llvm-c/Transforms/PassBuilder.h" #include "util/macros.h" #include "util/set.h" @@ -283,55 +284,140 @@ constructed(LLVMModuleRef clone) !LLVMGetArrayLength2(LLVMTypeOf(entries))); } +/* The clone and original have their globals in the same order. Keep the + * constructor's destinations externally visible so LLVM commits their + * initializers instead of forwarding their values and removing them. */ +static bool +evaluate_constants(LLVMModuleRef original, LLVMModuleRef clone, + struct stela_air_constructed_constants *result) +{ + LLVMValueRef copies[AIR_MAX_ARGUMENTS]; + result->count = 0; + LLVMValueRef global = LLVMGetFirstGlobal(original); + for (LLVMValueRef copy = LLVMGetFirstGlobal(clone); copy && global; + copy = LLVMGetNextGlobal(copy), global = LLVMGetNextGlobal(global)) { + if (LLVMIsGlobalConstant(copy) || !stela_air_metadata_constructed(global)) + continue; + if (result->count == AIR_MAX_ARGUMENTS) + return false; + result->globals[result->count] = global; + copies[result->count++] = copy; + LLVMSetLinkage(copy, LLVMExternalLinkage); + } + cast_conversions(clone); + LLVMPassBuilderOptionsRef options = LLVMCreatePassBuilderOptions(); + if (!options) + return false; + LLVMErrorRef error = LLVMRunPasses(clone, "globalopt", NULL, options); + LLVMDisposePassBuilderOptions(options); + if (error) { + LLVMDisposeErrorMessage(LLVMGetErrorMessage(error)); + return false; + } + if (!constructed(clone)) + return false; + for (unsigned i = 0; i < result->count; i++) { + result->values[i] = LLVMGetInitializer(copies[i]); + if (!plain(result->values[i], 0)) + return false; + } + return true; +} + +/* An unassociated constructor whose only reference is its list entry and + * whose calls reach only declarations is independent of shader inlining. */ +static bool +leaf_constructor(LLVMValueRef entry) +{ + LLVMValueRef fn = LLVMGetOperand(entry, 1); + LLVMUseRef use = LLVMGetFirstUse(fn); + if (!LLVMIsAConstantPointerNull(LLVMGetOperand(entry, 2)) || + !use || LLVMGetUser(use) != entry || LLVMGetNextUse(use)) + return false; + for (LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(fn); block; block = LLVMGetNextBasicBlock(block)) { + for (LLVMValueRef inst = LLVMGetFirstInstruction(block); inst; inst = LLVMGetNextInstruction(inst)) { + if (LLVMIsAInvokeInst(inst) || LLVMIsACallBrInst(inst)) + return false; + if (LLVMIsACallInst(inst)) { + LLVMValueRef callee = LLVMGetCalledValue(inst); + if (!LLVMIsAFunction(callee) || !LLVMIsDeclaration(callee)) + return false; + } + } + } + return true; +} + bool -stela_air_construct_constants(struct stela_air_metadata *m) +stela_air_prepare_constants(struct stela_air_metadata *m, const struct stela_air_constants *constants, + struct stela_air_constructed_constants *prepared) +{ + LLVMValueRef constructors = stela_air_metadata_constructors(m->module); + if (!constructors || !stela_air_has_defined_calls(m->module)) + return false; + LLVMValueRef entries = LLVMGetInitializer(constructors); + uint64_t functions = LLVMGetArrayLength2(LLVMTypeOf(entries)); + if (functions > AIR_MAX_ARGUMENTS) + return false; + for (unsigned i = 0; i < functions; i++) { + if (!leaf_constructor(LLVMGetAggregateElement(entries, i))) + return false; + } + LLVMModuleRef clone = LLVMCloneModule(m->module); + if (!clone) + return false; + struct stela_air_error prior = *m->error; + struct stela_air_metadata copy = *m; + copy.module = clone; + bool ready = stela_air_specialize_constants(©, constants->values, constants->count) && + evaluate_constants(m->module, clone, prepared) && m->error->kind == STELA_AIR_OK; + LLVMDisposeModule(clone); + /* A compact clone that cannot evaluate uses the ordinary path and its diagnostic. */ + *m->error = prior; + return ready; +} + +/* Inlining can change whether a global is used only by AIR logging. Match + * the destinations of the post-inline module before using the staged values. */ +static bool +prepared_matches(LLVMModuleRef module, const struct stela_air_constructed_constants *prepared) +{ + unsigned index = 0; + for (LLVMValueRef global = LLVMGetFirstGlobal(module); global; global = LLVMGetNextGlobal(global)) { + if (!stela_air_metadata_constructed(global)) + continue; + if (index == prepared->count || prepared->globals[index++] != global) + return false; + } + return index == prepared->count; +} + +bool +stela_air_construct_prepared_constants(struct stela_air_metadata *m, + const struct stela_air_constructed_constants *prepared) { LLVMValueRef constructors = stela_air_metadata_constructors(m->module); if (!constructors) return true; LLVMValueRef entries = LLVMGetInitializer(constructors); - unsigned functions = LLVMGetArrayLength2(LLVMTypeOf(entries)); + uint64_t functions = LLVMGetArrayLength2(LLVMTypeOf(entries)); if (functions > AIR_MAX_ARGUMENTS) return fail(m, STELA_AIR_LIMIT, "constructor count exceeded"); - /* The globals constructors may store, paired with the clone's; those stay - * defined there, so the optimizer keeps them and only commits their - * values. */ - LLVMModuleRef clone = LLVMCloneModule(m->module); - if (!clone) - return fail(m, STELA_AIR_ALLOCATION, "module clone allocation failed"); - LLVMValueRef originals[AIR_MAX_ARGUMENTS], copies[AIR_MAX_ARGUMENTS]; - unsigned count = 0; - bool evaluated = true; - for (LLVMValueRef global = LLVMGetFirstGlobal(m->module), copy = LLVMGetFirstGlobal(clone); - global && copy && evaluated; global = LLVMGetNextGlobal(global), copy = LLVMGetNextGlobal(copy)) { - if (!stela_air_metadata_constructed(global)) - continue; - evaluated = count < AIR_MAX_ARGUMENTS; - originals[count] = global; - copies[count++] = copy; - LLVMSetLinkage(copy, LLVMExternalLinkage); + struct stela_air_constructed_constants evaluated; + if (!prepared || !prepared_matches(m->module, prepared)) { + LLVMModuleRef clone = LLVMCloneModule(m->module); + if (!clone) + return fail(m, STELA_AIR_ALLOCATION, "module clone allocation failed"); + bool ready = evaluate_constants(m->module, clone, &evaluated); + LLVMDisposeModule(clone); + if (!ready) + return fail(m, STELA_AIR_INSTRUCTION, + "program-scope constants depend on more than function constants"); + prepared = &evaluated; } - cast_conversions(clone); - LLVMPassBuilderOptionsRef options = evaluated ? LLVMCreatePassBuilderOptions() : NULL; - LLVMErrorRef error = options ? LLVMRunPasses(clone, "globalopt", NULL, options) : NULL; - if (options) - LLVMDisposePassBuilderOptions(options); - if (error) { - LLVMDisposeErrorMessage(LLVMGetErrorMessage(error)); - evaluated = false; - } - evaluated &= options && constructed(clone); - LLVMValueRef values[AIR_MAX_ARGUMENTS]; - for (unsigned i = 0; evaluated && i < count; i++) - evaluated = plain(values[i] = LLVMGetInitializer(copies[i]), 0); - /* The values are the context's, which outlives the clone. */ - LLVMDisposeModule(clone); - if (!evaluated) - return fail(m, STELA_AIR_INSTRUCTION, - "program-scope constants depend on more than function constants"); - for (unsigned i = 0; i < count; i++) { - LLVMSetInitializer(originals[i], values[i]); - LLVMSetGlobalConstant(originals[i], true); + for (unsigned i = 0; i < prepared->count; i++) { + LLVMSetInitializer(prepared->globals[i], prepared->values[i]); + LLVMSetGlobalConstant(prepared->globals[i], true); } LLVMValueRef dropped[AIR_MAX_ARGUMENTS]; for (unsigned i = 0; i < functions; i++) @@ -347,6 +433,12 @@ stela_air_construct_constants(struct stela_air_metadata *m) return true; } +bool +stela_air_construct_constants(struct stela_air_metadata *m) +{ + return stela_air_construct_prepared_constants(m, NULL); +} + static bool fold(struct stela_air_metadata *m, LLVMValueRef fn) { diff --git a/crates/stela-driver-gpu/src/compiler/air_constants.h b/crates/stela-driver-gpu/src/compiler/air_constants.h index 6a61103f4d..c1c9537456 100644 --- a/crates/stela-driver-gpu/src/compiler/air_constants.h +++ b/crates/stela-driver-gpu/src/compiler/air_constants.h @@ -12,10 +12,24 @@ bool stela_air_specialize_constants(struct stela_air_metadata *m, const struct stela_air_constant_value *values, unsigned count); +/* Initializers captured from a compact copy of a module before reflection + * inlines its shader functions. LLVM constants belong to the shared context. */ +struct stela_air_constructed_constants { + unsigned count; + LLVMValueRef globals[AIR_MAX_ARGUMENTS], values[AIR_MAX_ARGUMENTS]; +}; + +/* Prepares initialization when inlining cannot change the constructors. */ +bool stela_air_prepare_constants(struct stela_air_metadata *m, + const struct stela_air_constants *constants, + struct stela_air_constructed_constants *prepared); + /* Evaluates the specialized module's air.static_init constructors, making the * program-scope constants they compute constant data, and removes them; * refuses constructors that depend on more than function constants. */ bool stela_air_construct_constants(struct stela_air_metadata *m); +bool stela_air_construct_prepared_constants(struct stela_air_metadata *m, + const struct stela_air_constructed_constants *prepared); /* Folds what the constructed module's function constants decide in fn, its * entry with its callees inlined: the loads of constant data, the branches diff --git a/crates/stela-driver-gpu/src/compiler/air_metadata.c b/crates/stela-driver-gpu/src/compiler/air_metadata.c index 2ee8d479d1..66b9e9626d 100644 --- a/crates/stela-driver-gpu/src/compiler/air_metadata.c +++ b/crates/stela-driver-gpu/src/compiler/air_metadata.c @@ -181,7 +181,8 @@ stela_air_metadata_constructors(LLVMModuleRef module) return NULL; for (unsigned i = 0; i < LLVMGetArrayLength2(type); i++) { LLVMValueRef entry = LLVMGetAggregateElement(entries, i); - if (!entry || LLVMGetNumOperands(entry) != 3 || !static_init(LLVMGetOperand(entry, 1))) + if (!entry || LLVMGetNumOperands(entry) != 3 || !LLVMIsAConstantInt(LLVMGetOperand(entry, 0)) || + !static_init(LLVMGetOperand(entry, 1))) return NULL; } return list; @@ -370,6 +371,8 @@ stela_air_metadata_validate(struct stela_air_metadata *t) { /* Debug info says nothing a function does, and Xcode's Debug builds carry it. */ LLVMStripModuleDebugInfo(t->module); + if (LLVMGetNamedGlobal(t->module, "llvm.global_ctors") && !stela_air_metadata_constructors(t->module)) + return fail(t, STELA_AIR_METADATA, "invalid AIR constructor list"); for (LLVMNamedMDNodeRef node = LLVMGetFirstNamedMetadata(t->module); node; node = LLVMGetNextNamedMetadata(node)) { size_t size; @@ -2621,21 +2624,53 @@ command_use(LLVMModuleRef module) return use; } +/* In enum stela_air_stage order after the kernels. */ +static const char *const entry_lists[] = {"air.kernel", "air.vertex", "air.fragment", + "air.object", "air.mesh", "air.visible"}; + +static bool +entry_stage(struct stela_air_metadata *m, const char *entry, unsigned *stage) +{ + bool found = false; + LLVMValueRef fn = LLVMGetNamedFunction(m->module, entry); + for (unsigned list = 0; fn && list < ARRAY_SIZE(entry_lists); list++) { + LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS]; + unsigned count; + if (!stela_air_named_md(m, entry_lists[list], nodes, &count)) + return false; + for (unsigned i = 0; i < count; i++) { + LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; + unsigned fields_count; + if (!stela_air_md_node(m, nodes[i], fields, &fields_count) || !fields_count) + return false; + if (fields[0] != fn) + continue; + if (found) + return fail(m, STELA_AIR_METADATA, "entry listed more than once"); + found = true; + *stage = list; + } + } + return found || fail(m, STELA_AIR_ARGUMENT, "entry is not a listed AIR function"); +} + static bool inspect(const void *bitcode, size_t size, const struct stela_air_constants *constants, unsigned max_entries, - stela_air_visit_entry visit, void *data, struct stela_air_error *error, - const char *render_name, enum stela_air_stage stage, stela_air_visit_stage render_visit) + stela_air_visit_entry visit, void *data, struct stela_air_error *error, + const char *entry_name, enum stela_air_stage stage, stela_air_visit_stage render_visit, + unsigned *listed_stage) { struct stela_air_error local = {0}; if (!error) error = &local; *error = (struct stela_air_error){0}; - struct stela_air_metadata m = {.error = error, .render = render_name != NULL}; + struct stela_air_metadata m = {.error = error}; if (!bitcode || size < 4 || size > AIR_MAX_BITCODE_BYTES || memcmp(bitcode, "BC\xc0\xde", 4) || !max_entries || - max_entries > AIR_MAX_METADATA_OPERANDS || (!render_name && !visit) || - (render_name && (!render_visit || !stage_text(render_name, strlen(render_name))))) + max_entries > AIR_MAX_METADATA_OPERANDS || + (entry_name && (!render_visit || !stage_text(entry_name, strlen(entry_name)))) || + ((!entry_name || listed_stage) && !visit)) return fail(&m, STELA_AIR_INPUT, "invalid AIR inspection input/budget"); unsigned major, minor, patch; LLVMGetVersion(&major, &minor, &patch); @@ -2663,6 +2698,12 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons fail(&m, STELA_AIR_BITCODE, "LLVM refused AIR bitcode"); goto done; } + if (listed_stage) { + if (!entry_stage(&m, entry_name, listed_stage)) + goto done; + stage = (enum stela_air_stage)*listed_stage; + } + m.render = stage != 0; char *verification = NULL; if (LLVMVerifyModule(m.module, LLVMReturnStatusAction, &verification)) { fail(&m, STELA_AIR_VERIFY, "%s", verification ? verification : "invalid LLVM module"); @@ -2678,8 +2719,11 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons fail(&m, STELA_AIR_TARGET, "unsupported target/globals/inline assembly"); goto done; } - if (!stela_air_metadata_layout(&m) || !stela_air_metadata_validate(&m) || - !stela_air_inline_calls(&m, NULL, 0, 0)) + if (!stela_air_metadata_layout(&m) || !stela_air_metadata_validate(&m)) + goto done; + struct stela_air_constructed_constants prepared; + bool ready = constants && stela_air_prepare_constants(&m, constants, &prepared); + if (!stela_air_inline_calls(&m, NULL, 0, 0)) goto done; if (!stela_air_metadata_target(&m, target)) { fail(&m, STELA_AIR_TARGET, "AIR version and target triple disagree"); @@ -2689,7 +2733,7 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons unsigned constant_count; if (!stela_air_metadata_function_constants(&m, function_constants, NULL, &constant_count) || (constants && (!stela_air_specialize_constants(&m, constants->values, constants->count) || - !stela_air_construct_constants(&m)))) + !stela_air_construct_prepared_constants(&m, ready ? &prepared : NULL)))) goto done; struct stela_air_inspection info = { .target = target, .target_bytes = strlen(target), .air_minor = m.air_minor, @@ -2700,10 +2744,10 @@ inspect(const void *bitcode, size_t size, const struct stela_air_constants *cons .commands = command_use(m.module), .metadata = &m, }; - if (render_name) { + if (m.render) { struct stela_air_render render = {.entry = {.stage = stage}}; if (stage != STELA_AIR_VISIBLE && - !stela_air_metadata_stage(&m, LLVMGetNamedFunction(m.module, render_name), stage, &render)) goto done; + !stela_air_metadata_stage(&m, LLVMGetNamedFunction(m.module, entry_name), stage, &render)) goto done; success = render_visit(&info, &render.entry, data); if (!success) fail(&m, STELA_AIR_LIMIT, "AIR stage receiver refused entry"); goto done; @@ -2791,7 +2835,7 @@ stela_air_inspect(const void *bitcode, size_t size, const struct stela_air_const unsigned max_entries, stela_air_visit_entry visit, void *data, struct stela_air_error *error) { - return inspect(bitcode, size, constants, max_entries, visit, data, error, NULL, 0, NULL); + return inspect(bitcode, size, constants, max_entries, visit, data, error, NULL, 0, NULL, NULL); } bool @@ -2805,13 +2849,26 @@ stela_air_inspect_stage(const void *bitcode, size_t size, const struct stela_air return false; } return inspect(bitcode, size, constants, AIR_MAX_METADATA_OPERANDS, NULL, data, error, entry, - stage, visit); + stage, visit, NULL); } -/* Parses AIR bitcode into m->module, in *context; false after reporting - * why. close_module disposes of both. */ +bool +stela_air_inspect_entry(const void *bitcode, size_t size, const struct stela_air_constants *constants, + const char *entry, unsigned *stage, stela_air_visit_entry kernel_visit, + stela_air_visit_stage stage_visit, void *data, struct stela_air_error *error) +{ + if (!entry || !stage) { + if (error) *error = (struct stela_air_error){.kind = STELA_AIR_INPUT}; + return false; + } + return inspect(bitcode, size, constants, AIR_MAX_METADATA_OPERANDS, kernel_visit, data, error, + entry, 0, stage_visit, stage); +} + +/* Discovery needs globals and named metadata. Leave function bodies to the + * eager parser and verifier used by inspection and lowering. */ static bool -parse_module(struct stela_air_metadata *m, const void *bitcode, size_t size, +parse_metadata(struct stela_air_metadata *m, const void *bitcode, size_t size, LLVMContextRef *context) { *context = LLVMContextCreate(); @@ -2819,8 +2876,9 @@ parse_module(struct stela_air_metadata *m, const void *bitcode, size_t size, return fail(m, STELA_AIR_ALLOCATION, "LLVM context unavailable"); LLVMContextSetDiagnosticHandler(*context, inspection_diagnostic, m); LLVMMemoryBufferRef buffer = LLVMCreateMemoryBufferWithMemoryRangeCopy(bitcode, size, "Metal input"); - bool parsed = buffer && !LLVMParseBitcodeInContext2(*context, buffer, &m->module); - if (buffer) + bool parsed = buffer && !LLVMGetBitcodeModuleInContext2(*context, buffer, &m->module); + /* LLVM owns the buffer once it creates the lazy module. */ + if (buffer && !parsed) LLVMDisposeMemoryBuffer(buffer); return (parsed && m->error->kind == STELA_AIR_OK) || fail(m, STELA_AIR_BITCODE, "LLVM refused AIR bitcode"); @@ -2842,10 +2900,6 @@ valid_bitcode(const void *bitcode, size_t size) !memcmp(bitcode, "BC\xc0\xde", 4); } -/* In enum stela_air_stage order after the kernels. */ -static const char *const entry_lists[] = {"air.kernel", "air.vertex", "air.fragment", - "air.object", "air.mesh", "air.visible"}; - bool stela_air_functions(const void *bitcode, size_t size, stela_air_visit_function visit, void *data, struct stela_air_error *error) @@ -2856,9 +2910,7 @@ stela_air_functions(const void *bitcode, size_t size, stela_air_visit_function v if (!valid_bitcode(bitcode, size) || !visit) return fail(&m, STELA_AIR_INPUT, "invalid AIR function list query"); LLVMContextRef context; - if (!parse_module(&m, bitcode, size, &context)) - return false; - bool visited = true; + bool visited = parse_metadata(&m, bitcode, size, &context); for (unsigned list = 0; visited && list < ARRAY_SIZE(entry_lists); list++) { LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS]; unsigned count; @@ -2866,7 +2918,8 @@ stela_air_functions(const void *bitcode, size_t size, stela_air_visit_function v for (unsigned i = 0; visited && i < count; i++) { LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; unsigned fields_count; - visited = stela_air_md_node(&m, nodes[i], fields, &fields_count) && fields_count; + visited = stela_air_md_node(&m, nodes[i], fields, &fields_count) && fields_count && + fields[0] && LLVMIsAFunction(fields[0]); if (visited) { size_t name_bytes; const char *name = LLVMGetValueName2(fields[0], &name_bytes); @@ -2880,47 +2933,6 @@ stela_air_functions(const void *bitcode, size_t size, stela_air_visit_function v return visited; } -bool -stela_air_entry_stage(const void *bitcode, size_t size, const char *entry, unsigned *stage, - struct stela_air_error *error) -{ - struct stela_air_error local = {0}; - struct stela_air_metadata m = {.error = error ? error : &local}; - *m.error = (struct stela_air_error){0}; - if (!valid_bitcode(bitcode, size) || !entry || !stage_text(entry, strlen(entry))) - return fail(&m, STELA_AIR_INPUT, "invalid AIR entry query"); - LLVMContextRef context; - bool found = false; - if (!parse_module(&m, bitcode, size, &context)) - goto done; - LLVMValueRef fn = LLVMGetNamedFunction(m.module, entry); - for (unsigned list = 0; fn && list < ARRAY_SIZE(entry_lists); list++) { - LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS]; - unsigned count; - if (!stela_air_named_md(&m, entry_lists[list], nodes, &count)) - goto done; - for (unsigned i = 0; i < count; i++) { - LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; - unsigned fields_count; - if (!stela_air_md_node(&m, nodes[i], fields, &fields_count) || !fields_count) - goto done; - if (fields[0] != fn) - continue; - if (found) { - fail(&m, STELA_AIR_METADATA, "entry listed more than once"); - goto done; - } - found = true; - *stage = list; - } - } - if (!found) - fail(&m, STELA_AIR_ARGUMENT, "entry is not a listed AIR function"); -done: - close_module(&m, context); - return found && m.error->kind == STELA_AIR_OK; -} - bool stela_air_sampler_states(const void *bitcode, size_t size, uint64_t *states, unsigned *count, struct stela_air_error *error) @@ -2933,7 +2945,7 @@ stela_air_sampler_states(const void *bitcode, size_t size, uint64_t *states, uns return fail(&m, STELA_AIR_INPUT, "invalid AIR sampler state query"); LLVMContextRef context; LLVMValueRef globals[AIR_MAX_SAMPLER_STATES]; - bool listed = parse_module(&m, bitcode, size, &context) && + bool listed = parse_metadata(&m, bitcode, size, &context) && stela_air_metadata_sampler_states(&m, globals, states, count); close_module(&m, context); return listed; diff --git a/crates/stela-driver-gpu/src/compiler/air_metadata.h b/crates/stela-driver-gpu/src/compiler/air_metadata.h index 9b19a6f598..eb67a0f2fc 100644 --- a/crates/stela-driver-gpu/src/compiler/air_metadata.h +++ b/crates/stela-driver-gpu/src/compiler/air_metadata.h @@ -386,12 +386,13 @@ bool stela_air_inspect_stage(const void *, size_t, const struct stela_air_consta const char *entry, enum stela_air_stage, stela_air_visit_stage, void *, struct stela_air_error *); -/* The stage whose entry list names entry: *stage is zero for air.kernel. - * Only the lists are read; inspection validates the rest. */ -bool stela_air_entry_stage(const void *, size_t, const char *entry, unsigned *stage, - struct stela_air_error *); -/* Calls visit with each function the entry lists name and its list, zero for - * air.kernel, as stela_air_entry_stage numbers them, until it refuses one. */ +/* Looks up the entry's stage on the module being inspected. Zero names + * air.kernel, whose visitor still receives every validated kernel. */ +bool stela_air_inspect_entry(const void *, size_t, const struct stela_air_constants *, + const char *entry, unsigned *stage, stela_air_visit_entry, + stela_air_visit_stage, void *, struct stela_air_error *); +/* Calls visit with each function the entry lists name and its stage, + * zero for air.kernel, until it refuses one. */ typedef bool (*stela_air_visit_function)(void *, const char *name, size_t name_bytes, unsigned stage); bool stela_air_functions(const void *, size_t, stela_air_visit_function, void *, diff --git a/crates/stela-driver-gpu/src/compiler/air_to_nir.c b/crates/stela-driver-gpu/src/compiler/air_to_nir.c index a54ece4b03..02b59cddf1 100644 --- a/crates/stela-driver-gpu/src/compiler/air_to_nir.c +++ b/crates/stela-driver-gpu/src/compiler/air_to_nir.c @@ -4725,7 +4725,8 @@ static nir_shader * translate(const void *bitcode, size_t size, const char *entry, const nir_shader_compiler_options *nir_options, const struct stela_air_options *options, - struct stela_air_error *error, const struct stela_air_stage_options *stage) + struct stela_air_error *error, const struct stela_air_stage_options *stage, + bool *folded_early) { struct stela_air_error local_error = {0}; if (!error) @@ -4816,13 +4817,29 @@ translate(const void *bitcode, size_t size, const char *entry, if (!stela_air_metadata_layout(&t.metadata) || !stela_air_metadata_validate(&t.metadata) || !stela_air_specialize_constants(&t.metadata, options->constants, options->constant_count) || !stela_air_construct_constants(&t.metadata) || - !stela_air_link_modules(&t.metadata, options->modules, options->module_count) || - /* A table's pointer may pass through functions to the call it makes. */ - !stela_air_inline_calls(&t.metadata, NULL, 0, 0) || + !stela_air_link_modules(&t.metadata, options->modules, options->module_count)) + goto done; + LLVMValueRef specialized = NULL; + /* Calls through tables may depend on inlining, and logging admission uses + * the use lists of its globals. Keep those modules on the original path. */ + if (folded_early && stage && stage->stage == STELA_AIR_FRAGMENT && options->constant_count && + !options->module_count && !options->linked_function_count && + stela_air_metadata_target(&t.metadata, LLVMGetTarget(t.module)) && + LLVMGetNamedMetadataNumOperands(t.module, "air.function_constants") && + !LLVMGetNamedMetadataNumOperands(t.module, "air.visible") && + !LLVMGetNamedMetadataNumOperands(t.module, "air.visible_function_references") && + !LLVMGetNamedFunction(t.module, "air.get_size_visible_function_table") && + !LLVMGetNamedFunction(t.module, "air.get_function_pointer_visible_function_table") && + !LLVMGetNamedFunction(t.module, "air.os_log")) + specialized = LLVMGetNamedFunction(t.module, entry); + /* A table's pointer may pass through functions to the call it makes. */ + if (!stela_air_inline_specialized_calls(&t.metadata, specialized, folded_early) || !stela_air_dispatch_tables(&t.metadata, options->linked_functions, options->linked_function_count) || - !stela_air_inline_calls(&t.metadata, LLVMGetNamedFunction(t.module, entry), - options->max_call_stack_depth, options->max_instructions)) + /* Walk again only for calls the first pass left or table lowering added. */ + (stela_air_has_defined_calls(t.module) && + !stela_air_inline_calls(&t.metadata, LLVMGetNamedFunction(t.module, entry), + options->max_call_stack_depth, options->max_instructions))) goto done; t.layout = t.metadata.layout; t.air_minor = t.metadata.air_minor; @@ -4945,7 +4962,7 @@ stela_air_to_nir(const void *bitcode, size_t size, const char *entry, const nir_shader_compiler_options *nir_options, const struct stela_air_options *options, struct stela_air_error *error) { - return translate(bitcode, size, entry, nir_options, options, error, NULL); + return translate(bitcode, size, entry, nir_options, options, error, NULL, NULL); } nir_shader * @@ -4957,5 +4974,27 @@ stela_air_stage_to_nir(const void *bitcode, size_t size, const char *entry, if (error) *error = (struct stela_air_error){.kind = STELA_AIR_INPUT}; return NULL; } - return translate(bitcode, size, entry, nir_options, &options->resources, error, options); + return translate(bitcode, size, entry, nir_options, &options->resources, error, options, NULL); +} + +nir_shader * +stela_air_metal_stage_to_nir(const void *bitcode, size_t size, const char *entry, + const nir_shader_compiler_options *nir_options, + const struct stela_air_stage_options *options, + struct stela_air_error *error) +{ + if (!options) + return stela_air_stage_to_nir(bitcode, size, entry, nir_options, options, error); + struct stela_air_error local_error; + if (!error) + error = &local_error; + bool folded_early = false; + nir_shader *shader = translate(bitcode, size, entry, nir_options, &options->resources, error, + options, &folded_early); + /* Only a fragment that attempted the early pass can retry. Its temporary + * LLVM module and NIR are already gone, and the second call cannot fold + * early again. Avoid extra work after an allocation refusal. */ + if (!shader && folded_early && error->kind != STELA_AIR_ALLOCATION) + return stela_air_stage_to_nir(bitcode, size, entry, nir_options, options, error); + return shader; } diff --git a/crates/stela-driver-gpu/src/compiler/air_to_nir.h b/crates/stela-driver-gpu/src/compiler/air_to_nir.h index ed78290357..7a0f7e792c 100644 --- a/crates/stela-driver-gpu/src/compiler/air_to_nir.h +++ b/crates/stela-driver-gpu/src/compiler/air_to_nir.h @@ -378,6 +378,13 @@ nir_shader *stela_air_stage_to_nir(const void *, size_t, const char *entry, const struct stela_air_stage_options *, struct stela_air_error *); +/* Metal's stage callbacks write only to the temporary NIR, so translation + * can retry the ordinary lowering order when early specialization fails. */ +nir_shader *stela_air_metal_stage_to_nir(const void *, size_t, const char *entry, + const nir_shader_compiler_options *, + const struct stela_air_stage_options *, + struct stela_air_error *); + /* Input is the hash-checked raw AIR bitcode selected by the archive reader. * Success transfers ownership of a real NIR shader to the caller (ralloc_free). * Failure returns NULL, destroys partial NIR, and reports an explicit error. diff --git a/crates/stela-driver-gpu/src/compiler/metal_compiler.c b/crates/stela-driver-gpu/src/compiler/metal_compiler.c index a5f27d3fba..9defbb01bf 100644 --- a/crates/stela-driver-gpu/src/compiler/metal_compiler.c +++ b/crates/stela-driver-gpu/src/compiler/metal_compiler.c @@ -46,7 +46,7 @@ fail(struct stela_air_error *error, enum stela_air_error_kind kind, const char * return false; } -/* The function stages of stela_air_entry_stage's stages: kernels, then +/* AIR entry stages: kernels, then * enum stela_air_stage. */ static const enum stela_metal_function_stage function_stages[] = { STELA_METAL_KERNEL, STELA_METAL_VERTEX, STELA_METAL_FRAGMENT, STELA_METAL_OBJECT, @@ -313,13 +313,8 @@ inspect_entry(const void *air, size_t size, const char *entry, stela_air_visit_stage stage_entry, void *data, const bool *found, unsigned *stage, struct stela_air_error *error) { - if (!stela_air_entry_stage(air, size, entry, stage, error)) - return false; - bool inspected = *stage ? stela_air_inspect_stage(air, size, constants, entry, - (enum stela_air_stage)*stage, stage_entry, - data, error) : - stela_air_inspect(air, size, constants, AIR_MAX_METADATA_OPERANDS, - kernel, data, error); + bool inspected = stela_air_inspect_entry(air, size, constants, entry, stage, kernel, stage_entry, + data, error); /* A receiver's refusal is reported as the inspector's; keep the cause. */ return inspected ? *found || fail(error, STELA_AIR_ARGUMENT, "entry is not an AIR kernel") : false; @@ -684,10 +679,11 @@ varying_rows(const struct stela_metal_reflection *reflection, } nir_shader * -stela_metal_compile(const void *air, size_t size, const char *entry, - const struct stela_metal_target *target, - const struct stela_metal_specialization *specialization, - struct stela_air_error *error) +stela_metal_compile_reflected(const void *air, size_t size, const char *entry, + const struct stela_metal_target *target, + const struct stela_metal_specialization *specialization, + const struct stela_metal_reflection *reflection, + struct stela_air_error *error) { struct stela_air_error local = {0}; if (!error) @@ -703,17 +699,21 @@ stela_metal_compile(const void *air, size_t size, const char *entry, fail(error, STELA_AIR_INPUT, "invalid compilation request"); return NULL; } - struct stela_metal_reflection *reflection = malloc(sizeof(*reflection)); - if (!reflection) { - fail(error, STELA_AIR_ALLOCATION, "reflection allocation failed"); - return NULL; - } - struct reflecting r = {.entry = entry, .out = reflection, .error = error}; + struct stela_metal_reflection *owned_reflection = NULL; nir_shader *shader = NULL; - struct stela_air_constants constants = {specialization->constants, - specialization->constant_count}; - if (!reflect(air, size, entry, &constants, &r)) - goto done; + if (!reflection) { + owned_reflection = malloc(sizeof(*owned_reflection)); + if (!owned_reflection) { + fail(error, STELA_AIR_ALLOCATION, "reflection allocation failed"); + return NULL; + } + struct reflecting r = {.entry = entry, .out = owned_reflection, .error = error}; + struct stela_air_constants constants = {specialization->constants, + specialization->constant_count}; + if (!reflect(air, size, entry, &constants, &r)) + goto done; + reflection = owned_reflection; + } enum stela_metal_function_stage stage = reflection->stage; if (stage == STELA_METAL_VISIBLE) { fail(error, STELA_AIR_ARGUMENT, "visible functions compile into the functions that link them"); @@ -812,12 +812,21 @@ stela_metal_compile(const void *air, size_t size, const char *entry, .max_mesh_vertices = target->max_mesh_vertices, .max_mesh_primitives = target->max_mesh_primitives, }; - shader = stela_air_stage_to_nir(air, size, entry, target->nir, &options, error); + shader = stela_air_metal_stage_to_nir(air, size, entry, target->nir, &options, error); done: - free(reflection); + free(owned_reflection); return shader; } +nir_shader * +stela_metal_compile(const void *air, size_t size, const char *entry, + const struct stela_metal_target *target, + const struct stela_metal_specialization *specialization, + struct stela_air_error *error) +{ + return stela_metal_compile_reflected(air, size, entry, target, specialization, NULL, error); +} + void stela_metal_tessellation_stages(const struct stela_metal_target *target, const struct stela_metal_tessellation *tessellation, diff --git a/crates/stela-driver-gpu/src/compiler/metal_compiler.h b/crates/stela-driver-gpu/src/compiler/metal_compiler.h index bc94c3b47f..eb42704625 100644 --- a/crates/stela-driver-gpu/src/compiler/metal_compiler.h +++ b/crates/stela-driver-gpu/src/compiler/metal_compiler.h @@ -230,8 +230,8 @@ bool stela_metal_reflect_bindings(const void *air, size_t size, const char *entr struct stela_air_error *error); /* Calls visit with the name and stage of each function the AIR module lists, - * for a library of source, whose container has no list. False after reporting - * why, or when visit refuses one. */ + * for a library of source, whose container has no list. This reads only module + * metadata. False after reporting why, or when visit refuses one. */ typedef bool (*stela_metal_visit_function)(void *data, const char *name, size_t name_bytes, enum stela_metal_function_stage stage); bool stela_metal_functions(const void *air, size_t size, stela_metal_visit_function visit, @@ -246,7 +246,8 @@ bool stela_metal_stitch(const struct stela_air_stitch_source *sources, uint32_t #define STELA_METAL_SAMPLER_STATES 256u /* The constexpr sampler states the AIR module declares, each Apple's - * encoding, which metal/sampler.rs decodes. False after reporting why. */ + * encoding, which metal/sampler.rs decodes. This reads only module metadata. + * False after reporting why. */ bool stela_metal_sampler_states(const void *air, size_t size, uint64_t states[STELA_METAL_SAMPLER_STATES], uint32_t *count, struct stela_air_error *error); @@ -259,6 +260,16 @@ nir_shader *stela_metal_compile(const void *air, size_t size, const char *entry, const struct stela_metal_specialization *specialization, struct stela_air_error *error); +/* As stela_metal_compile, with the compiler's own successful reflection of + * this exact AIR, entry and constant values. This reads only the stage, patch, + * threadgroup bytes and varying descriptors with their identifiers. The + * caller owns the reflection through the call. NULL asks it to reflect. */ +nir_shader *stela_metal_compile_reflected(const void *air, size_t size, const char *entry, + const struct stela_metal_target *target, + const struct stela_metal_specialization *specialization, + const struct stela_metal_reflection *reflection, + struct stela_air_error *error); + /* The vertex and control stages a tessellated pipeline runs ahead of its * post-tessellation vertex function (metal_abi.h), each with entry point * main, which stela_metal_release frees. */ diff --git a/crates/stela-driver-gpu/src/compiler/tests/air_to_nir.c b/crates/stela-driver-gpu/src/compiler/tests/air_to_nir.c index 30bb13d8af..63ad2ade91 100644 --- a/crates/stela-driver-gpu/src/compiler/tests/air_to_nir.c +++ b/crates/stela-driver-gpu/src/compiler/tests/air_to_nir.c @@ -2335,9 +2335,35 @@ undefined_phi_values(void) ralloc_free(nir); } +/* An unrelated recursive function does not give a declared entry a body + * or make its recursion limit relevant. */ +static void +reject_declared_entry_in_a_recursive_module(void) +{ + LLVMMemoryBufferRef input = stela_air_test_custom_bitcode( + "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n" + "target triple = \"air64_v28-apple-macosx26.7.0\"\n", + "define internal void @cycle() {\ncall void @cycle()\nret void\n}\n" + "declare void @kernel()\n", + "!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n" + "!0 = !{i32 2, i32 8, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n" + "!2 = !{ptr @kernel, !3, !3}\n!3 = !{}\n", ""); + const struct stela_air_options options = { + .workgroup_size = {1, 1, 1}, .max_instructions = 100, .max_call_stack_depth = UINT32_MAX, + }; + struct stela_air_error error; + nir_shader *nir = stela_air_to_nir(LLVMGetBufferStart(input), LLVMGetBufferSize(input), "kernel", + &test_nir_options, &options, &error); + if (nir || error.kind != STELA_AIR_ARGUMENT) + fprintf(stderr, "declared entry: %u %s\n", error.kind, error.detail); + CHECK(!nir && error.kind == STELA_AIR_ARGUMENT && strstr(error.detail, "entry must be a defined")); + LLVMDisposeMemoryBuffer(input); +} + static void tests(void) { + reject_declared_entry_in_a_recursive_module(); struct stela_air_error error; LLVMMemoryBufferRef input = stela_air_test_bitcode(stela_air_test_store_body, ""); nir_shader *nir = translate(input, &test_nir_options, 100, &error); diff --git a/crates/stela-driver-gpu/src/compiler/tests/metal_compiler.c b/crates/stela-driver-gpu/src/compiler/tests/metal_compiler.c index 1f6db1ea6f..a677930c10 100644 --- a/crates/stela-driver-gpu/src/compiler/tests/metal_compiler.c +++ b/crates/stela-driver-gpu/src/compiler/tests/metal_compiler.c @@ -6,6 +6,8 @@ #include "../metal_compiler.h" #include "air_effect_oracle.h" #include "air_test_fixture.h" +#include "compiler/nir/nir_serialize.h" +#include "util/blob.h" #include "util/ralloc.h" #include #include @@ -171,6 +173,9 @@ static const char *derived = DERIVED("%x = shl nsw i32 %w, 1\n"); static const char *converted = DERIVED("%f = call float @air.convert.f.f32.s.i32(i32 %w)\n" "%d = fmul fast float %f, 2.000000e+00\n" "%x = call i32 @air.convert.s.i32.f.f32(float %d)\n"); +/* A constructor whose helper needs the ordinary inlining path. */ +static const char *derived_with_helper = DERIVED("%x = call i32 @twice(i32 %w)\n") + "define internal i32 @twice(i32 %w) {\n%x = shl nsw i32 %w, 1\nret i32 %x\n}\n"; /* A constructor that calls an AIR function, which no constant folds. */ static const char *called = DERIVED("%x = call i32 @air.unknown(i32 %w)\n"); @@ -229,6 +234,14 @@ static const char *called = DERIVED("%x = call i32 @air.unknown(i32 %w)\n"); static const char *conditional = CONDITIONAL("br i1 %on, label %tinted, label %untinted\n", "bool"); +/* A shader helper uses the same function constant as its leaf constructor. */ +static const char *conditional_with_helper = + CONDITIONAL("%choose = call i1 @choose_tint(i1 %on)\n" + "br i1 %choose, label %tinted, label %untinted\n", "bool") + "define internal i1 @choose_tint(i1 %enabled) {\n" + "%raw = load i8, ptr addrspace(2) @use_tint.init, align 1\n" + "%selected = icmp ne i8 %raw, 0\n" + "%both = and i1 %selected, %enabled\nret i1 %both\n}\n"; /* One reading tint whatever use_tint is. */ static const char *unguarded = CONDITIONAL("br label %tinted\n", "bool"); /* One whose read Apple's compiler hoists ahead of what decides it. */ @@ -898,6 +911,48 @@ modules_list_their_functions(void) assert(count == 1); } +static void +discovery_reports_malformed_metadata(void) +{ + struct stela_air_error error; + unsigned listed = 0; + const char header[] = "BC\xc0\xde"; + assert(!stela_metal_functions(header, sizeof(header) - 1, count_function, &listed, &error)); + assert(error.kind == STELA_AIR_BITCODE && !listed); + uint64_t states[STELA_METAL_SAMPLER_STATES]; + uint32_t count = 1; + assert(!stela_metal_sampler_states(header, sizeof(header) - 1, states, &count, &error)); + assert(error.kind == STELA_AIR_BITCODE && !count); + + char *fixture = ralloc_asprintf(NULL, "%s!air.visible = !{!90}\n!90 = !{null}\n", kernel); + LLVMMemoryBufferRef input = bitcode(fixture); + ralloc_free(fixture); + assert(!stela_metal_functions(LLVMGetBufferStart(input), LLVMGetBufferSize(input), + count_function, &listed, &error)); + assert(error.kind == STELA_AIR_METADATA); + LLVMDisposeMemoryBuffer(input); +} + +static void +reflection_requires_a_unique_listed_entry(void) +{ + struct stela_metal_reflection reflection; + struct stela_air_error error; + char *fixture = ralloc_asprintf(NULL, "%s!air.visible = !{!2}\n", kernel); + LLVMMemoryBufferRef input = bitcode(fixture); + ralloc_free(fixture); + assert(!stela_metal_reflect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), + "kernel", NULL, 0, &reflection, &error)); + assert(error.kind == STELA_AIR_METADATA && strstr(error.detail, "entry listed more than once")); + LLVMDisposeMemoryBuffer(input); + + input = bitcode(kernel); + assert(!stela_metal_reflect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), + "air.wg.barrier", NULL, 0, &reflection, &error)); + assert(error.kind == STELA_AIR_ARGUMENT); + LLVMDisposeMemoryBuffer(input); +} + static void render_stages_compile_at_their_linked_locations(void) { @@ -1102,6 +1157,23 @@ function_constants_reflect_and_specialize(void) fprintf(stderr, "constants: %u %s\n", error.kind, error.detail); /* Every read folds to its value; none is left in constant data. */ assert(shader && shader->constant_data_size == 0); + assert(reflect_specialized(constants, "constants", values, 3, &reflection, &error)); + LLVMMemoryBufferRef input = bitcode(constants); + nir_shader *prepared = stela_metal_compile_reflected( + LLVMGetBufferStart(input), LLVMGetBufferSize(input), "constants", + &target, &specialization, &reflection, &error); + LLVMDisposeMemoryBuffer(input); + assert(prepared); + struct blob normal, reused; + blob_init(&normal); + blob_init(&reused); + nir_serialize(&normal, shader, true); + nir_serialize(&reused, prepared, true); + assert(!normal.out_of_memory && !reused.out_of_memory); + assert(normal.size == reused.size && !memcmp(normal.data, reused.data, normal.size)); + blob_finish(&normal); + blob_finish(&reused); + stela_metal_release(prepared); stela_metal_release(shader); /* scale is optional, and its definedness test folds to false. */ @@ -1170,6 +1242,11 @@ derived_constants_are_constructed_from_their_function_constants(void) assert(shader && stores_constant(shader, 10)); stela_metal_release(shader); + assert(reflect_specialized(derived_with_helper, "derived", values, 1, &reflection, &error)); + shader = compile(derived_with_helper, "derived", &specialization, &error); + assert(shader && stores_constant(shader, 10)); + stela_metal_release(shader); + /* Without width, its definedness test selects eight. */ specialization.constant_count = 0; shader = compile(derived, "derived", &specialization, &error); @@ -1182,6 +1259,43 @@ derived_constants_are_constructed_from_their_function_constants(void) strstr(error.detail, "program-scope constants")); } +static void +constructed_globals_are_bounded(void) +{ + char *fixture = ralloc_strdup(NULL, derived); + for (unsigned i = 0; i < AIR_MAX_ARGUMENTS; i++) + assert(ralloc_asprintf_append(&fixture, "@extra%u = internal addrspace(2) global i32 0\n", i)); + LLVMMemoryBufferRef input = bitcode(fixture); + ralloc_free(fixture); + struct stela_metal_reflection reflection; + struct stela_air_error error; + const struct stela_air_constant_value unused = {0}; + assert(!stela_metal_reflect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), + "derived", &unused, 0, &reflection, &error)); + assert(error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, "program-scope constants")); + LLVMDisposeMemoryBuffer(input); +} + +static void +constructor_priorities_are_integer_literals(void) +{ + const char *priority = strstr(derived, "65535"); + assert(priority); + const char *invalid[] = {"undef", "poison"}; + for (unsigned i = 0; i < ARRAY_SIZE(invalid); i++) { + char *fixture = ralloc_asprintf(NULL, "%.*s%s%s", (int)(priority - derived), derived, + invalid[i], priority + strlen("65535")); + LLVMMemoryBufferRef input = bitcode(fixture); + ralloc_free(fixture); + struct stela_metal_reflection reflection; + struct stela_air_error error; + assert(!stela_metal_reflect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), + "derived", NULL, 0, &reflection, &error)); + assert(error.kind == STELA_AIR_METADATA && strstr(error.detail, "invalid AIR constructor list")); + LLVMDisposeMemoryBuffer(input); + } +} + static unsigned count_intrinsic(nir_shader *shader, nir_intrinsic_op op) { @@ -1215,6 +1329,10 @@ function_constants_select_arguments(void) STELA_METAL_ACCESS_READ | STELA_METAL_ACCESS_WRITE; assert(reflection.buffer_count == 2 && reflection.buffers[1].index == 1 && reflection.buffers[1].access == access); + assert(reflect_specialized(conditional_with_helper, "conditional", &value, 1, + &reflection, &error)); + assert(reflection.buffer_count == 2 && reflection.buffers[1].index == 1 && + reflection.buffers[1].access == access); const struct stela_metal_specialization specialization = { .workgroup_size = {64, 1, 1}, .constants = &value, .constant_count = 1, }; @@ -1250,6 +1368,85 @@ function_constants_select_arguments(void) } } +/* The false constant makes the helper unreachable, but admission of the + * original call graph still precedes early specialization. */ +static void +specialized_fragment_calls_preserve_graph_admission(void) +{ + const char *body = + "@enabled = external addrspace(2) constant i8\n" + "define <4 x float> @entry() {\n" + "%value = load i8, ptr addrspace(2) @enabled\n" + "%on = icmp ne i8 %value, 0\n" + "br i1 %on, label %active, label %inactive\n" + "active:\n%result = call <4 x float> @helper()\nret <4 x float> %result\n" + "inactive:\nret <4 x float> zeroinitializer\n}\n" + "!air.fragment = !{!2}\n!2 = !{ptr @entry, !3, !4}\n!3 = !{!30}\n!4 = !{}\n" + "!30 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"," + " !\"air.arg_name\", !\"color\"}\n" + "!air.function_constants = !{!50}\n!50 = !{ptr addrspace(2) @enabled, !\"bool\", !\"enabled\", i32 0}\n"; + const char *unsupported = "declare <4 x float> @unsupported()\n" + "define internal <4 x float> @helper() {\n" + "%result = call <4 x float> @unsupported()\nret <4 x float> %result\n}\n"; + char *fixture = ralloc_asprintf(NULL, "%s%s", body, unsupported); + struct stela_air_error error; + const struct stela_metal_specialization defaults = {0}; + uint8_t enabled = 0; + const struct stela_air_constant_value value = {0, &enabled, sizeof(enabled)}; + const struct stela_metal_specialization explicit = {.constants = &value, .constant_count = 1}; + nir_shader *a = compile(fixture, "entry", &defaults, &error); + nir_shader *b = compile(fixture, "entry", &explicit, &error); + assert(a && b); + struct blob original, folded; + blob_init(&original); + blob_init(&folded); + nir_serialize(&original, a, true); + nir_serialize(&folded, b, true); + assert(!original.out_of_memory && !folded.out_of_memory && original.size == folded.size && + !memcmp(original.data, folded.data, original.size)); + blob_finish(&original); + blob_finish(&folded); + stela_metal_release(a); + stela_metal_release(b); + + enabled = 1; + assert(!compile(fixture, "entry", &explicit, &error)); + assert(error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, "unresolved external function")); + const struct stela_air_error failure = error; + assert(ralloc_asprintf_append(&fixture, + "declare i32 @air.get_size_visible_function_table(ptr addrspace(1))\n")); + assert(!compile(fixture, "entry", &explicit, &error)); + assert(error.kind == failure.kind && error.instruction == failure.instruction && + !strcmp(error.detail, failure.detail)); + ralloc_free(fixture); + + enabled = 0; + fixture = ralloc_asprintf(NULL, "%s%s", body, "define internal <4 x float> @helper() {\n" + "%result = call <4 x float> @helper()\nret <4 x float> %result\n}\n"); + assert(!compile(fixture, "entry", &explicit, &error)); + assert(error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, "recursive calls outside")); + ralloc_free(fixture); + + fixture = ralloc_asprintf(NULL, "%s%s", body, "define internal <4 x float> @helper() {\n" + "%result = call <4 x float> @chain0()\nret <4 x float> %result\n}\n"); + for (unsigned i = 0; i < 256; i++) { + assert(ralloc_asprintf_append(&fixture, "define internal <4 x float> @chain%u() {\n" + "%%result = call <4 x float> @chain%u()\nret <4 x float> %%result\n}\n", i, i + 1)); + } + assert(ralloc_asprintf_append(&fixture, + "define internal <4 x float> @chain256() {\nret <4 x float> zeroinitializer\n}\n")); + LLVMMemoryBufferRef input = bitcode(fixture); + ralloc_free(fixture); + const struct stela_air_stage_options stage = { + .stage = STELA_AIR_FRAGMENT, .resources = {.max_instructions = 10000, .constants = &value, + .constant_count = 1}, + }; + assert(!stela_air_metal_stage_to_nir(LLVMGetBufferStart(input), LLVMGetBufferSize(input), + "entry", &nir_options, &stage, &error)); + assert(error.kind == STELA_AIR_LIMIT && strstr(error.detail, "call depth exceeded")); + LLVMDisposeMemoryBuffer(input); +} + /* An output a false function constant makes absent is not one. */ static void function_constants_select_outputs(void) @@ -1420,6 +1617,24 @@ defined_functions_inline_into_their_callers(void) error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, "recursive")); } +/* A module with no direct call edges still checks unsupported calls during lowering. */ +static void +unresolved_calls_are_rejected_without_a_call_graph(void) +{ + const char *callees[] = {"@external", "null"}; + const char *errors[] = {"unresolved external function external", "only from visible function tables"}; + const struct stela_metal_specialization specialization = {.workgroup_size = {64, 1, 1}}; + for (unsigned i = 0; i < ARRAY_SIZE(callees); i++) { + char *fixture = ralloc_asprintf(NULL, + "declare void @external()\ndefine void @unresolved() {\ncall void %s()\nret void\n}\n" + "!air.kernel = !{!2}\n!2 = !{ptr @unresolved, !3, !3}\n!3 = !{}\n", callees[i]); + struct stela_air_error error; + assert(!compile(fixture, "unresolved", &specialization, &error)); + assert(error.kind == STELA_AIR_INSTRUCTION && strstr(error.detail, errors[i])); + ralloc_free(fixture); + } +} + /* os_log.log_error("hi %d %f %ld", ...) through the method Apple's compiler * defines for it, in a kernel, with a float its call promotes and a long. */ static const char *logging = @@ -1873,6 +2088,8 @@ main(void) { glsl_type_singleton_init_or_ref(); modules_list_their_functions(); + discovery_reports_malformed_metadata(); + reflection_requires_a_unique_listed_entry(); kernels_reflect_and_compile_their_threadgroup_memory(); dynamic_kernels_take_their_dispatch_shape(); render_stages_compile_at_their_linked_locations(); @@ -1881,14 +2098,18 @@ main(void) mesh_stages_compile_with_their_launch(); function_constants_reflect_and_specialize(); derived_constants_are_constructed_from_their_function_constants(); + constructed_globals_are_bounded(); + constructor_priorities_are_integer_literals(); function_constants_select_outputs(); older_kernels_compile(); unoptimized_kernels_compile(); undefined_lanes_read_as_anything(); function_constants_select_arguments(); + specialized_fragment_calls_preserve_graph_admission(); arrays_reflect_each_slot(); bindings_reflect_their_structures(); defined_functions_inline_into_their_callers(); + unresolved_calls_are_rejected_without_a_call_graph(); stitched_functions_call_their_nodes_in_order(); os_log_appends_self_contained_records(); linked_functions_resolve_tables_and_externals(); diff --git a/crates/stela-driver-gpu/src/metal/binding.rs b/crates/stela-driver-gpu/src/metal/binding.rs index f856444000..c3446afedf 100644 --- a/crates/stela-driver-gpu/src/metal/binding.rs +++ b/crates/stela-driver-gpu/src/metal/binding.rs @@ -204,10 +204,13 @@ impl ArgumentTable { pub fn encode(&self) -> Vec { let mut bytes = alloc::vec![0; Self::BYTES as usize]; - let mut writer = Writer { - bytes: &mut bytes, - offset: 0, - }; + self.encode_into(&mut bytes); + bytes + } + + pub(super) fn encode_into(&self, bytes: &mut [u8]) { + debug_assert_eq!(bytes.len(), Self::BYTES as usize); + let mut writer = Writer { bytes, offset: 0 }; self.buffers .iter() .for_each(|buffer| writer.u64(buffer.address)); @@ -219,7 +222,6 @@ impl ArgumentTable { .chain(&self.samplers) .chain(&self.attachments) .for_each(|id| writer.u64(id.0)); - bytes } } diff --git a/crates/stela-driver-gpu/src/metal/capabilities.rs b/crates/stela-driver-gpu/src/metal/capabilities.rs index 38e9986e34..4ca2082928 100644 --- a/crates/stela-driver-gpu/src/metal/capabilities.rs +++ b/crates/stela-driver-gpu/src/metal/capabilities.rs @@ -20,7 +20,7 @@ use super::{ physical::{Features, FormatSupport, PhysicalDevice}, }, }; -use alloc::{string::String, vec::Vec}; +use alloc::{boxed::Box, string::String, vec::Vec}; pub mod block; @@ -162,6 +162,32 @@ option_set! { } } +#[derive(Clone, Debug, PartialEq)] +enum PixelFormats { + /// The capabilities of every known format, in `PixelFormat::ALL` order. + Indexed(Box), + /// A decoded list with its original omissions, order and duplicates. + Listed(Box<[(PixelFormat, FormatCapabilities)]>), +} + +type IndexedPixelFormats = [FormatCapabilities; PixelFormat::ALL.len()]; + +fn indexed_format(formats: &IndexedPixelFormats, format: PixelFormat) -> FormatCapabilities { + formats[format.index()] +} + +impl PixelFormats { + fn get(&self, format: PixelFormat) -> FormatCapabilities { + match self { + Self::Indexed(formats) => indexed_format(formats, format), + Self::Listed(formats) => formats + .iter() + .find(|(known, _)| *known == format) + .map_or(FormatCapabilities::EMPTY, |(_, capabilities)| *capabilities), + } + } +} + /// `MTLSize`. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Size { @@ -289,7 +315,7 @@ pub struct Capabilities { sparse_samples: Vec<(PixelFormat, SampleCounts)>, vertex_formats: Vec, families: Vec, - formats: Vec<(PixelFormat, FormatCapabilities)>, + formats: PixelFormats, gaps: Vec, linear_row_alignment: u64, linear_offset_alignment: u64, @@ -340,10 +366,7 @@ impl Capabilities { /// Capabilities of `format`; empty for formats this device cannot store. pub fn format(&self, format: PixelFormat) -> FormatCapabilities { - self.formats - .iter() - .find(|(known, _)| *known == format) - .map_or(FormatCapabilities::EMPTY, |(_, capabilities)| *capabilities) + self.formats.get(format) } /// Every refused capability, each listed once. @@ -605,12 +628,7 @@ impl Derivation<'_> { let features = &device.features; let formats = self.formats(); - let caps = |format: PixelFormat| { - formats - .iter() - .find(|(known, _)| *known == format) - .map_or(FormatCapabilities::EMPTY, |(_, capabilities)| *capabilities) - }; + let caps = |format| indexed_format(&formats, format); let float32 = [ PixelFormat::R32Float, PixelFormat::Rg32Float, @@ -933,7 +951,7 @@ impl Derivation<'_> { sparse_samples, vertex_formats, families: Vec::new(), - formats, + formats: PixelFormats::Indexed(formats), gaps: Vec::new(), linear_row_alignment: self.platform.linear_row_alignment, linear_offset_alignment: self.platform.linear_offset_alignment, @@ -950,23 +968,26 @@ impl Derivation<'_> { capabilities } - fn formats(&mut self) -> Vec<(PixelFormat, FormatCapabilities)> { - let mut formats = Vec::with_capacity(PixelFormat::ALL.len()); - for format in PixelFormat::ALL { + fn formats(&mut self) -> Box { + let mut formats = Box::new([FormatCapabilities::EMPTY; PixelFormat::ALL.len()]); + for (format, capabilities) in PixelFormat::ALL.iter().zip(formats.iter_mut()) { let description = format.describe(); - let capabilities = match description.realization { + *capabilities = match description.realization { Ok(realization) => { let support = self.device.formats.get(realization.format); self.format_capabilities(description, support, realization.is_identity()) } Err(_) => FormatCapabilities::EMPTY, }; - formats.push((*format, capabilities)); } self.compression_gaps(&formats); - if formats.iter().any(|(format, capabilities)| { - format.describe().realization.is_err() && capabilities.is_empty() - }) { + if PixelFormat::ALL + .iter() + .zip(formats.iter()) + .any(|(format, capabilities)| { + format.describe().realization.is_err() && capabilities.is_empty() + }) + { self.gap("extended-range and 4:2:2 pixel formats", Cause::Driver); } formats @@ -1016,7 +1037,7 @@ impl Derivation<'_> { supported } - fn compression_gaps(&mut self, formats: &[(PixelFormat, FormatCapabilities)]) { + fn compression_gaps(&mut self, formats: &IndexedPixelFormats) { let groups = [ (Compression::Bc, "BC pixel formats"), (Compression::Etc2Eac, "ETC2 and EAC pixel formats"), @@ -1025,8 +1046,9 @@ impl Derivation<'_> { (Compression::Pvrtc, "PVRTC pixel formats"), ]; for (compression, name) in groups { - let unusable = formats + let unusable = PixelFormat::ALL .iter() + .zip(formats) .filter(|(format, _)| format.describe().compression == compression) .all(|(_, capabilities)| !capabilities.contains(FormatCapabilities::READ)); if unusable { @@ -1140,10 +1162,7 @@ impl Derivation<'_> { /// Tier 1 reads and writes the 32-bit single-channel formats in one /// function; tier 2 adds Apple's listed 8-, 16- and 32-bit formats. - fn read_write_tier( - &mut self, - formats: &[(PixelFormat, FormatCapabilities)], - ) -> ReadWriteTextureTier { + fn read_write_tier(&mut self, formats: &IndexedPixelFormats) -> ReadWriteTextureTier { use PixelFormat as P; const TIER1: [PixelFormat; 3] = [P::R32Float, P::R32Uint, P::R32Sint]; const TIER2: [PixelFormat; 12] = [ @@ -1162,9 +1181,7 @@ impl Derivation<'_> { ]; const TIER2_8BIT: [PixelFormat; 3] = [P::R8Unorm, P::R8Uint, P::R8Sint]; let read_write = |format: &PixelFormat| { - formats.iter().any(|(known, capabilities)| { - known == format && capabilities.contains(FormatCapabilities::READ_WRITE) - }) + indexed_format(formats, *format).contains(FormatCapabilities::READ_WRITE) }; let tier1 = TIER1.iter().all(read_write); let tier2 = tier1 && TIER2.iter().chain(&TIER2_8BIT).all(read_write); diff --git a/crates/stela-driver-gpu/src/metal/capabilities/block.rs b/crates/stela-driver-gpu/src/metal/capabilities/block.rs index bbdbd59b4e..8d7d88b56a 100644 --- a/crates/stela-driver-gpu/src/metal/capabilities/block.rs +++ b/crates/stela-driver-gpu/src/metal/capabilities/block.rs @@ -10,7 +10,10 @@ //! the rest of their array zero; strings are UTF-8 with their length. //! Decoding accepts only a block the encoder writes, which it checks by //! encoding the result again. -use super::{Capabilities, Cause, FormatCapabilities, Gap, Limits, Size, TexelBufferAlignment}; +use super::{ + Capabilities, Cause, FormatCapabilities, Gap, IndexedPixelFormats, Limits, PixelFormats, Size, + TexelBufferAlignment, +}; use crate::metal::{ abi::{ ArgumentBuffersTier, CounterSamplingPoint, DeviceLocation, GpuFamily, ReadWriteTextureTier, @@ -354,9 +357,10 @@ impl Block { constant_vertex_step: has(Flags::CONSTANT_VERTEX_STEP), counter_sampling, sparse_volumes: has(Flags::SPARSE_VOLUMES), - sparse_samples: formats(&self.sparse_formats, self.sparse_format_count, |value| { - SampleCounts::from_bits(value) - })?, + sparse_samples: formats( + listed(&self.sparse_formats, self.sparse_format_count)?, + SampleCounts::from_bits, + )?, vertex_formats: VertexFormat::ALL .iter() .copied() @@ -366,11 +370,7 @@ impl Block { .iter() .map(|&raw| GpuFamily::from_raw(raw).ok_or(MALFORMED)) .collect::>()?, - formats: formats( - &self.formats, - self.format_count, - FormatCapabilities::from_bits, - )?, + formats: pixel_formats(listed(&self.formats, self.format_count)?)?, gaps, linear_row_alignment: self.linear_row_alignment, linear_offset_alignment: self.linear_offset_alignment, @@ -406,13 +406,12 @@ fn text(field: &[u8], offset: u32, bytes: u32) -> Result { )) } -/// The first `count` format entries, each value decoded. +/// Format entries in wire order, each value decoded. fn formats( entries: &[FormatEntry], - count: u32, decode: impl Fn(u32) -> Option, ) -> Result> { - listed(entries, count)? + entries .iter() .map(|entry| { Ok(( @@ -423,6 +422,24 @@ fn formats( .collect() } +fn pixel_formats(entries: &[FormatEntry]) -> Result { + if entries.len() == PixelFormat::ALL.len() + && entries + .iter() + .zip(PixelFormat::ALL) + .all(|(entry, format)| u64::from(entry.format) == format.raw()) + { + let mut formats: Box = + Box::new([FormatCapabilities::EMPTY; PixelFormat::ALL.len()]); + for (capabilities, entry) in formats.iter_mut().zip(entries) { + *capabilities = FormatCapabilities::from_bits(entry.value).ok_or(MALFORMED)?; + } + return Ok(PixelFormats::Indexed(formats)); + } + let formats = formats(entries, FormatCapabilities::from_bits)?; + Ok(PixelFormats::Listed(formats.into_boxed_slice())) +} + /// Copies `text` into the start of `field`, returning its length. fn put_text(field: &mut [u8], text: &str, what: &'static str) -> Result { let bytes = text.as_bytes(); @@ -456,6 +473,25 @@ fn format_entry(format: PixelFormat, value: u32) -> Result { }) } +fn put_pixel_formats(field: &mut [FormatEntry], formats: &PixelFormats) -> Result { + let what = "pixel format count"; + let encode = |(format, capabilities): (PixelFormat, FormatCapabilities)| { + format_entry(format, capabilities.bits()) + }; + match formats { + PixelFormats::Indexed(formats) => put_list( + field, + PixelFormat::ALL + .iter() + .copied() + .zip(formats.iter().copied()), + what, + encode, + ), + PixelFormats::Listed(formats) => put_list(field, formats.iter().copied(), what, encode), + } +} + impl Capabilities { /// The block that carries these capabilities across the boundary. pub fn block(&self) -> Result> { @@ -473,12 +509,7 @@ impl Capabilities { "GPU family count", |family| Ok(family.raw()), )?; - block.format_count = put_list( - &mut block.formats, - self.formats.iter(), - "pixel format count", - |&(format, capabilities)| format_entry(format, capabilities.bits()), - )?; + block.format_count = put_pixel_formats(&mut block.formats, &self.formats)?; block.sparse_format_count = put_list( &mut block.sparse_formats, self.sparse_samples.iter(), @@ -636,6 +667,44 @@ mod tests { let block = capabilities.block().unwrap(); assert_eq!(block.capabilities().unwrap(), capabilities); assert!(block.family_count > 0 && block.format_count > 0 && block.gap_count > 0); + for (format, entry) in PixelFormat::ALL.iter().zip(&block.formats) { + assert_eq!(format.raw(), u64::from(entry.format)); + assert_eq!(capabilities.format(*format).bits(), entry.value); + } + } + + #[test] + fn nonstandard_pixel_format_lists_keep_wire_order_and_first_match() { + let capabilities = fixture::capabilities(); + let mut block = capabilities.block().unwrap(); + let bgra = PixelFormat::Bgra8Unorm; + let rgba = PixelFormat::Rgba8Unorm; + let entry = |format: PixelFormat, value: FormatCapabilities| FormatEntry { + format: format.raw() as u32, + value: value.bits(), + }; + block.formats.fill(FormatEntry::default()); + block.formats[..3].copy_from_slice(&[ + entry(bgra, FormatCapabilities::EMPTY), + entry(rgba, FormatCapabilities::READ), + entry(bgra, FormatCapabilities::WRITE), + ]); + block.format_count = 3; + let decoded = block.capabilities().unwrap(); + assert_eq!(decoded.format(bgra), FormatCapabilities::EMPTY); + assert_eq!(decoded.format(rgba), FormatCapabilities::READ); + assert_eq!( + decoded.format(PixelFormat::Depth32Float), + FormatCapabilities::EMPTY + ); + assert_eq!(decoded.block().unwrap(), block); + + block.formats[3..].fill(entry(rgba, FormatCapabilities::EMPTY)); + block.format_count = FORMATS as u32; + assert_eq!(block.capabilities().unwrap().block().unwrap(), block); + + block.formats[1].format = u32::MAX; + assert_eq!(block.capabilities(), Err(MALFORMED)); } #[test] diff --git a/crates/stela-driver-gpu/src/metal/command_buffer.rs b/crates/stela-driver-gpu/src/metal/command_buffer.rs index 19015802ce..dbb0814da3 100644 --- a/crates/stela-driver-gpu/src/metal/command_buffer.rs +++ b/crates/stela-driver-gpu/src/metal/command_buffer.rs @@ -336,11 +336,12 @@ impl Bindings { let address = match table.address { Some(address) => address, None => { - let upload = recorder.upload( + let (upload, bytes) = recorder.uploads.zeroed( resolver, - &table.slots.encode(), + ArgumentTable::BYTES as usize, ArgumentTable::ALIGNMENT, )?; + table.slots.encode_into(bytes); table.address = Some(upload.address); upload.address } diff --git a/crates/stela-driver-gpu/src/metal/compiler.rs b/crates/stela-driver-gpu/src/metal/compiler.rs index 167b367b42..b61008de40 100644 --- a/crates/stela-driver-gpu/src/metal/compiler.rs +++ b/crates/stela-driver-gpu/src/metal/compiler.rs @@ -22,6 +22,7 @@ //! call. mod bindings; pub mod ffi; +mod library_cache; #[cfg(feature = "metal-linked")] mod linked; #[cfg(test)] @@ -31,13 +32,13 @@ use super::{ abi::{DataType, FunctionType, IndexType, TessellationControlPointIndexType, TextureType}, capabilities::ShaderFeatures, error::{Error, Result, ensure, require}, - library::{Air, Header, Library}, + library::Air, reflection::Binding, shader::{ Access, AttributeUse, BufferUse, ColorOutput, CompiledShader, Compiler, DeclaredAttribute, FunctionConstant, Interface, Linking, MAX_PATCH_CONTROL_POINTS, NumericClass, Patch, - PatchDomain, Provenance, Reflection, Refusal, Scalar, Specialization, Stage, Tessellation, - TessellationStages, TextureUse, ThreadgroupUse, Varying, + PatchDomain, PreparedFunction, Provenance, Reflection, Refusal, Scalar, Specialization, + Stage, Tessellation, TessellationStages, TextureUse, ThreadgroupUse, Varying, }, stitching::{StitchedGraph, StitchedNode}, vertex::{Attribute, STRIDE_DYNAMIC, StageInputDescriptor, VertexDescriptor}, @@ -56,6 +57,8 @@ use core::{ slice, str, }; +use library_cache::{LoadedLibrary, Selected}; + /// The constructs the AIR frontend lowers completely (`metal/README.md`). const FEATURES: ShaderFeatures = ShaderFeatures::COMPUTE .union(ShaderFeatures::VERTEX_FRAGMENT) @@ -133,13 +136,15 @@ pub struct Service { *mut c_void, *mut ffi::AirError, ) -> bool, - /// `stela_metal_compile`. + /// `stela_metal_compile_reflected`. Custom callbacks receive the full + /// record. Stela's linked callbacks also accept a compilation projection. pub compile: unsafe extern "C" fn( *const c_void, usize, *const c_char, *const ffi::Target, *const ffi::Specialization, + *const ffi::Reflection, *mut ffi::AirError, ) -> *mut c_void, /// `stela_metal_tessellation_stages`. @@ -219,8 +224,9 @@ impl Drop for InternalKernelCode { pub struct AirCompiler { service: Service, target: ffi::Target, + project_reflection: bool, /// MTLB libraries by id; ids are never reused. - libraries: BTreeMap>, + libraries: BTreeMap, next_library: u64, refusal: Option, } @@ -255,9 +261,17 @@ impl AirCompiler { max_mesh_vertices: mesh.map_or(0, |mesh| mesh.max_mesh_output_vertices), max_mesh_primitives: mesh.map_or(0, |mesh| mesh.max_mesh_output_primitives), }; + // The boot image mounts the linked AIR compiler. Hosted all-feature + // builds also expose `Service::linked`, but only pull in its external + // symbols if the caller constructs that service. + #[cfg(all(feature = "metal-linked", target_os = "uefi"))] + let project_reflection = service.accepts_compilation_projection(); + #[cfg(not(all(feature = "metal-linked", target_os = "uefi")))] + let project_reflection = false; Self { service, target, + project_reflection, libraries: BTreeMap::new(), next_library: 0, refusal: None, @@ -280,10 +294,10 @@ impl Compiler for AirCompiler { } fn add_library(&mut self, data: Vec) -> Result { - Library::parse(&data).map_err(|_| Error::Invalid("Metal library"))?; + let loaded = LoadedLibrary::new(data)?; let id = self.next_library; self.next_library += 1; - self.libraries.insert(id, data); + self.libraries.insert(id, loaded); Ok(id) } @@ -349,8 +363,8 @@ impl Compiler for AirCompiler { let sources: Vec<_> = selected .iter() .map(|selected| ffi::StitchSource { - bitcode: selected.air.bitcode.as_ptr().cast(), - size: selected.air.bitcode.len(), + bitcode: selected.bitcode.as_ptr().cast(), + size: selected.bitcode.len(), name: selected.entry.as_ptr(), }) .collect(); @@ -425,7 +439,7 @@ impl Compiler for AirCompiler { fn library_data(&self, library: u64) -> Result<&[u8]> { self.libraries .get(&library) - .map(Vec::as_slice) + .map(LoadedLibrary::bytes) .ok_or(Error::Invalid("unknown library")) } @@ -448,6 +462,31 @@ impl Compiler for AirCompiler { Ok(reflection) } + fn prepare_function( + &mut self, + library: u64, + entry: &str, + constants: Vec<(u32, Vec)>, + ) -> Result { + let selected = select(&self.libraries, library, entry)?; + let specialization = Specialization { + constants, + ..Specialization::default() + }; + let (reflection, provenance) = + selected.reflect(&self.service, Some(&specialization), &mut self.refusal)?; + Ok(PreparedFunction { + library, + constants: specialization.constants, + reflection, + provenance, + reflection_service: self + .project_reflection + .then_some(self.service.reflect as usize) + .and_then(core::num::NonZeroUsize::new), + }) + } + fn constants(&mut self, library: u64, entry: &str) -> Result> { let selected = select(&self.libraries, library, entry)?; let (reflection, _) = selected.reflect(&self.service, None, &mut self.refusal)?; @@ -463,7 +502,7 @@ impl Compiler for AirCompiler { let selected = select(&self.libraries, library, entry)?; let mut bindings = ffi::Bindings::zeroed(); let mut error = ffi::AirError::NONE; - let air = selected.air.bitcode; + let air = selected.bitcode; let values = constant_values(&specialization.constants); let count = u32::try_from(values.len()).map_err(|_| MALFORMED)?; // SAFETY: the AIR, entry and values outlive the call, which writes @@ -496,7 +535,7 @@ impl Compiler for AirCompiler { let linked = linked_modules(&self.libraries, &specialization.linking, own)?; let mut states = Vec::new(); for bitcode in - core::iter::once(selected.air.bitcode).chain(linked.iter().map(|module| module.bitcode)) + core::iter::once(selected.bitcode).chain(linked.iter().map(|module| module.bitcode)) { let mut listed = [0; ffi::SAMPLER_STATES]; let mut count = 0; @@ -528,12 +567,7 @@ impl Compiler for AirCompiler { entry: &str, specialization: &Specialization, ) -> Result { - let stage_in = specialization - .stage_in - .as_ref() - .map(ffi::StageIn::kernel) - .transpose()?; - self.compile_function(library, entry, specialization, None, stage_in.as_deref()) + self.compile_entry(library, entry, specialization, None) } fn compile_tessellation( @@ -542,6 +576,75 @@ impl Compiler for AirCompiler { entry: &str, specialization: &Specialization, tessellation: &Tessellation, + ) -> Result { + self.compile_patch(library, entry, specialization, tessellation, None) + } + + fn compile_prepared( + &mut self, + function: &PreparedFunction, + specialization: &Specialization, + ) -> Result { + self.compile_entry( + function.library, + function.entry(), + specialization, + Some(function), + ) + } + + fn compile_prepared_tessellation( + &mut self, + function: &PreparedFunction, + specialization: &Specialization, + tessellation: &Tessellation, + ) -> Result { + self.compile_patch( + function.library, + function.entry(), + specialization, + tessellation, + Some(function), + ) + } + + fn release(&mut self, code: ShaderCode) { + // SAFETY: the code is NIR this compiler's service compiled, which the + // device releases once. + unsafe { (self.service.release)(code.0 as usize as *mut c_void) } + } +} + +impl AirCompiler { + fn compile_entry( + &mut self, + library: u64, + entry: &str, + specialization: &Specialization, + prepared: Option<&PreparedFunction>, + ) -> Result { + let stage_in = specialization + .stage_in + .as_ref() + .map(ffi::StageIn::kernel) + .transpose()?; + self.compile_function( + library, + entry, + specialization, + None, + stage_in.as_deref(), + prepared, + ) + } + + fn compile_patch( + &mut self, + library: u64, + entry: &str, + specialization: &Specialization, + tessellation: &Tessellation, + prepared: Option<&PreparedFunction>, ) -> Result { if specialization.stage_in.is_some() { return Err(Error::Invalid("kernel stage-in of a vertex function")); @@ -558,6 +661,7 @@ impl Compiler for AirCompiler { specialization, Some(&properties), stage_in.as_deref(), + prepared, )?; let mut stages = [ptr::null_mut(); 2]; // SAFETY: the target and tessellation outlive the call, which writes @@ -573,14 +677,6 @@ impl Compiler for AirCompiler { }) } - fn release(&mut self, code: ShaderCode) { - // SAFETY: the code is NIR this compiler's service compiled, which the - // device releases once. - unsafe { (self.service.release)(code.0 as usize as *mut c_void) } - } -} - -impl AirCompiler { /// Compiles `entry` of `library`: a post-tessellation vertex function /// with its pipeline's tessellation, and a kernel or post-tessellation /// vertex function with the stage-in layout it fetches by. @@ -591,12 +687,39 @@ impl AirCompiler { specialization: &Specialization, tessellation: Option<&ffi::Tessellation>, stage_in: Option<&ffi::StageIn>, + prepared: Option<&PreparedFunction>, ) -> Result { let selected = select(&self.libraries, library, entry)?; - let (reflection, provenance) = - selected.reflect(&self.service, Some(specialization), &mut self.refusal)?; - let Reflection::Stage(interface) = reflection else { - return Err(Error::Invalid("a visible function is not a pipeline stage")); + let constants = constant_values(&specialization.constants); + // Reflection uses only the module, entry and function constant values. + // Linkage, layouts and dispatch sizes enter later at compilation. + let prepared = prepared.filter(|function| { + self.project_reflection + && function.library == library + && function.entry() == entry + && function.provenance.slice_hash == selected.slice_hash + && function.constants == specialization.constants + && function + .reflection_service + .is_some_and(|service| service.get() == self.service.reflect as usize) + }); + let (reflected, interface, provenance) = if let Some(function) = prepared { + let Reflection::Stage(interface) = &function.reflection else { + return Err(Error::Invalid("a visible function is not a pipeline stage")); + }; + ( + compilation_reflection(interface)?, + interface.as_ref().clone(), + function.provenance.clone(), + ) + } else { + let reflected = + selected.reflect_raw(&self.service, Some(&constants), &mut self.refusal)?; + let (reflection, provenance) = selected.decode_reflection(&reflected)?; + let Reflection::Stage(interface) = reflection else { + return Err(Error::Invalid("a visible function is not a pipeline stage")); + }; + (reflected, *interface, provenance) }; let linking = &specialization.linking; let own = (selected.slice_hash, specialization.constants.as_slice()); @@ -647,7 +770,6 @@ impl AirCompiler { per_primitive: varying.per_primitive.into(), }) .collect(); - let constants = constant_values(&specialization.constants); let samplers: Vec<_> = specialization .samplers .iter() @@ -676,10 +798,11 @@ impl AirCompiler { samplers: samplers.as_ptr(), }; let mut error = ffi::AirError::NONE; - let air = selected.air.bitcode; + let air = selected.bitcode; // SAFETY: the AIR, entry, target and specialization, with the arrays, // identifiers, values, layouts, modules and names it points to, - // outlive the call, which writes only the error. + // outlive the call, which writes only the error. The compilation + // fields come from this service's reflection of the same input and constants. let shader = unsafe { (self.service.compile)( air.as_ptr().cast(), @@ -687,6 +810,7 @@ impl AirCompiler { selected.entry.as_ptr(), &self.target, &raw, + &*reflected, &mut error, ) }; @@ -695,7 +819,7 @@ impl AirCompiler { } Ok(CompiledShader { code: ShaderCode(shader as usize as u64), - interface: *interface, + interface, provenance, }) } @@ -822,12 +946,12 @@ fn same_values(a: Option<&[(u32, Vec)]>, b: Option<&[(u32, Vec)]>) -> bo /// digest and values: each once, by digest. A module links with one set of /// values; a dynamic library's takes those of a function linked from it. fn linked_modules<'a>( - libraries: &'a BTreeMap>, + libraries: &'a BTreeMap, linking: &'a Linking, own: ([u8; 32], &'a [(u32, Vec)]), ) -> Result>> { let mut modules: Vec> = Vec::new(); - let mut add = |digest: [u8; 32], air: Air<'a>, constants| { + let mut add = |digest: [u8; 32], bitcode: &'a [u8], constants| { if digest == own.0 { return require( same_values(Some(own.1), constants), @@ -844,7 +968,7 @@ fn linked_modules<'a>( } None => modules.push(LinkedModule { digest, - bitcode: air.bitcode, + bitcode, constants, }), } @@ -853,55 +977,31 @@ fn linked_modules<'a>( for function in linking.functions.iter().chain(&linking.private_functions) { let selected = select(libraries, function.library, &function.entry)?; let constants = Some(function.constants.as_slice()); - add(selected.slice_hash, selected.air, constants)?; + add(selected.slice_hash, selected.bitcode, constants)?; } - let invalid = |_| Error::Invalid("Metal library"); for library in &linking.libraries { - let data = libraries + let library = libraries .get(library) .ok_or(Error::Invalid("unknown library"))?; - let parsed = Library::parse(data).map_err(invalid)?; - ensure( - parsed.header.kind == Header::DYNAMIC, - "a preloaded library that is not dynamic", - )?; - for function in parsed.functions() { - add(*function.digest, function.air().map_err(invalid)?, None)?; + ensure(library.dynamic, "a preloaded library that is not dynamic")?; + for module in library.modules() { + let (digest, bitcode) = module?; + add(digest, bitcode, None)?; } } Ok(modules) } -/// A library function selected for the service. -struct Selected<'a> { - air: Air<'a>, - name: &'a str, - entry: CString, - slice_hash: [u8; 32], -} - /// Selects `entry` of `library`. fn select<'a>( - libraries: &'a BTreeMap>, + libraries: &'a BTreeMap, library: u64, entry: &str, ) -> Result> { - let data = libraries + libraries .get(&library) - .ok_or(Error::Invalid("unknown library"))?; - let invalid = |_| Error::Invalid("Metal library"); - let parsed = Library::parse(data).map_err(invalid)?; - let function = parsed - .functions() - .iter() - .find(|function| function.name == entry) - .ok_or(Error::Invalid("no function of that name"))?; - Ok(Selected { - air: function.air().map_err(invalid)?, - name: function.name, - entry: CString::new(function.name).map_err(|_| Error::Invalid("function name"))?, - slice_hash: *function.digest, - }) + .ok_or(Error::Invalid("unknown library"))? + .select(entry) } impl Selected<'_> { @@ -914,11 +1014,21 @@ impl Selected<'_> { specialization: Option<&Specialization>, refusal: &mut Option, ) -> Result<(Reflection, Provenance)> { - let mut reflection = Box::new(ffi::Reflection::ZERO); - let mut error = ffi::AirError::NONE; - let air = self.air.bitcode; let values = specialization.map(|known| constant_values(&known.constants)); - let (values, count) = match &values { + let reflection = self.reflect_raw(service, values.as_deref(), refusal)?; + self.decode_reflection(&reflection) + } + + fn reflect_raw( + &self, + service: &Service, + values: Option<&[ffi::ConstantValue]>, + refusal: &mut Option, + ) -> Result> { + let mut reflection = ffi::Reflection::zeroed(); + let mut error = ffi::AirError::NONE; + let air = self.bitcode; + let (values, count) = match values { Some(values) => ( values.as_ptr(), u32::try_from(values.len()).map_err(|_| MALFORMED)?, @@ -941,19 +1051,23 @@ impl Selected<'_> { if !reflected { return Err(refuse(refusal, self.name, &error)); } + Ok(reflection) + } + + fn decode_reflection(&self, reflection: &ffi::Reflection) -> Result<(Reflection, Provenance)> { let provenance = Provenance { - build_id: name(&reflection, reflection.ident, reflection.ident_bytes)?.to_vec(), + build_id: name(reflection, reflection.ident, reflection.ident_bytes)?.to_vec(), slice_hash: self.slice_hash, source_map: None, entry: self.name.to_string(), }; let reflection = if u64::from(reflection.stage) == FunctionType::Visible.raw() { Reflection::Visible { - constants: constants(&reflection)?, + constants: constants(reflection)?, command_barriers: reflection.command_barriers != 0, } } else { - Reflection::Stage(Box::new(interface(&reflection)?)) + Reflection::Stage(Box::new(interface(reflection)?)) }; Ok((reflection, provenance)) } @@ -1026,6 +1140,48 @@ fn scalar(primitive: u32) -> Result { }) } +/// The compilation ABI reads only these fields. Rebuild them from the +/// validated interface to avoid retaining a full ABI record for each function. +fn compilation_reflection(interface: &Interface) -> Result> { + let mut reflection = ffi::Reflection::zeroed(); + reflection.stage = interface.stage.raw() as u32; + reflection.patch = match interface.patch.map(|patch| patch.domain) { + None => 0, + Some(PatchDomain::Triangle) => 1, + Some(PatchDomain::Quad) => 2, + }; + reflection.threadgroup_bytes = interface.static_threadgroup_bytes; + for (index, varying) in interface.varyings.iter().enumerate() { + let identifier = varying.identifier.as_bytes(); + let offset = reflection.names_bytes as usize; + let end = offset.checked_add(identifier.len()).ok_or(MALFORMED)?; + reflection + .names + .get_mut(offset..end) + .ok_or(MALFORMED)? + .copy_from_slice(identifier); + *reflection.varyings.get_mut(index).ok_or(MALFORMED)? = ffi::Varying { + identifier: offset as u32, + identifier_bytes: identifier.len() as u32, + primitive: match varying.scalar { + Scalar::Char => ffi::primitive::CHAR, + Scalar::Uchar => ffi::primitive::UCHAR, + Scalar::Short => ffi::primitive::SHORT, + Scalar::Ushort => ffi::primitive::USHORT, + Scalar::Int => ffi::primitive::INT, + Scalar::Uint => ffi::primitive::UINT, + Scalar::Float => ffi::primitive::FLOAT, + Scalar::Half => ffi::primitive::HALF, + }, + components: varying.components.into(), + per_primitive: varying.per_primitive.into(), + }; + reflection.names_bytes = end as u32; + } + reflection.varying_count = interface.varyings.len() as u32; + Ok(reflection) +} + fn numeric(primitive: u32) -> Result { Ok(match scalar(primitive)? { Scalar::Float | Scalar::Half => NumericClass::Float, diff --git a/crates/stela-driver-gpu/src/metal/compiler/ffi.rs b/crates/stela-driver-gpu/src/metal/compiler/ffi.rs index 306ab2fe3c..6df02b870f 100644 --- a/crates/stela-driver-gpu/src/metal/compiler/ffi.rs +++ b/crates/stela-driver-gpu/src/metal/compiler/ffi.rs @@ -179,8 +179,14 @@ pub struct Reflection { } impl Reflection { + #[cfg(test)] // SAFETY: every member is an integer or an array of integers. pub(super) const ZERO: Self = unsafe { core::mem::zeroed() }; + + pub(super) fn zeroed() -> alloc::boxed::Box { + // SAFETY: every member is an integer or an array of integers. + unsafe { alloc::boxed::Box::new_zeroed().assume_init() } + } } /// `enum stela_metal_binding_kind`. diff --git a/crates/stela-driver-gpu/src/metal/compiler/library_cache.rs b/crates/stela-driver-gpu/src/metal/compiler/library_cache.rs new file mode 100644 index 0000000000..4b59164100 --- /dev/null +++ b/crates/stela-driver-gpu/src/metal/compiler/library_cache.rs @@ -0,0 +1,160 @@ +//! Selection from immutable MTLB bytes. The index holds offsets into the +//! original library, and checks each module's digest and AIR framing once +//! when it is first needed. +use super::{ + super::library::{Air, Header, Library}, + Error, Result, +}; +use alloc::{collections::BTreeMap, vec::Vec}; +use core::{cell::OnceCell, ffi::CStr, ops::Range}; + +const INVALID: Error = Error::Invalid("Metal library"); + +pub(super) struct LoadedLibrary { + bytes: Vec, + functions: Vec, + modules: Vec, + pub(super) dynamic: bool, +} + +struct Entry { + name: Range, + module: usize, +} + +struct Module { + wrapped: Range, + digest: [u8; 32], + /// The original bitcode range, or a failed digest/framing check. + checked: OnceCell>>, +} + +pub(super) struct Selected<'a> { + pub(super) bitcode: &'a [u8], + pub(super) name: &'a str, + pub(super) entry: &'a CStr, + pub(super) slice_hash: [u8; 32], +} + +impl LoadedLibrary { + pub(super) fn new(bytes: Vec) -> Result { + let parsed = Library::parse(&bytes).map_err(|_| INVALID)?; + let dynamic = parsed.header.kind == Header::DYNAMIC; + let mut modules = Vec::new(); + let mut index = BTreeMap::new(); + let mut functions = Vec::new(); + functions + .try_reserve_exact(parsed.functions().len()) + .map_err(|_| Error::OutOfMemory)?; + for function in parsed.functions() { + let wrapped = function.module_range(); + let digest = *function.digest; + let module = *index + .entry((wrapped.start, wrapped.end, digest)) + .or_insert_with(|| { + let index = modules.len(); + modules.push(Module { + wrapped, + digest, + checked: OnceCell::new(), + }); + index + }); + // The parser borrowed NAME from these bytes and verified its + // terminator. Keep the terminator for the compiler service. + let start = function.name.as_ptr().addr() - bytes.as_ptr().addr(); + let name = start..start + function.name.len() + 1; + functions.push(Entry { name, module }); + } + Ok(Self { + bytes, + functions, + modules, + dynamic, + }) + } + + pub(super) fn bytes(&self) -> &[u8] { + &self.bytes + } + + pub(super) fn select(&self, name: &str) -> Result> { + let entry = self + .functions + .iter() + .find(|entry| &self.bytes[entry.name.start..entry.name.end - 1] == name.as_bytes()) + .ok_or(Error::Invalid("no function of that name"))?; + let module = &self.modules[entry.module]; + let entry = + CStr::from_bytes_with_nul(&self.bytes[entry.name.clone()]).map_err(|_| INVALID)?; + Ok(Selected { + bitcode: module.bitcode(&self.bytes)?, + name: entry.to_str().map_err(|_| INVALID)?, + entry, + slice_hash: module.digest, + }) + } + + pub(super) fn modules(&self) -> impl Iterator> { + self.modules + .iter() + .map(|module| Ok((module.digest, module.bitcode(&self.bytes)?))) + } +} + +impl Module { + fn bitcode<'a>(&self, data: &'a [u8]) -> Result<&'a [u8]> { + let range = self.checked.get_or_init(|| { + let wrapped = &data[self.wrapped.clone()]; + let bitcode = Air::verified(wrapped, &self.digest).ok()?.bitcode; + let start = bitcode.as_ptr().addr() - data.as_ptr().addr(); + Some(start..start + bitcode.len()) + }); + range + .as_ref() + .map(|range| &data[range.clone()]) + .ok_or(INVALID) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::metal::library; + + #[test] + fn selection_caches_one_checked_module_for_entries_sharing_an_extent_and_digest() { + let data = library::assemble( + b"BC\xc0\xdepayload", + &[("first", 2), ("second", 2)], + 0, + None, + ); + let loaded = LoadedLibrary::new(data.clone()).unwrap(); + assert_eq!(loaded.bytes(), &data); + assert_eq!(loaded.modules.len(), 1); + assert!(loaded.modules[0].checked.get().is_none()); + let first = loaded.select("first").unwrap(); + let second = loaded.select("second").unwrap(); + assert_eq!(first.entry.to_bytes(), b"first"); + assert_eq!(second.entry.to_bytes(), b"second"); + assert_eq!(first.bitcode, b"BC\xc0\xdepayload"); + assert_eq!(first.bitcode.as_ptr(), second.bitcode.as_ptr()); + assert_eq!(first.slice_hash, second.slice_hash); + assert!(matches!(loaded.modules[0].checked.get(), Some(Some(_)))); + } + + #[test] + fn mismatched_digests_do_not_share_an_air_check() { + let mut data = library::assemble(b"BC\xc0\xdepayload", &[("good", 2), ("bad", 2)], 0, None); + let parsed = Library::parse(&data).unwrap(); + let digest = parsed.functions()[1].digest.as_ptr().addr() - data.as_ptr().addr(); + data[digest] ^= 1; + let loaded = LoadedLibrary::new(data).unwrap(); + assert_eq!(loaded.modules.len(), 2); + assert!(loaded.select("good").is_ok()); + assert!(matches!(loaded.select("bad"), Err(INVALID))); + assert!(matches!(loaded.select("bad"), Err(INVALID))); + assert_eq!(loaded.modules[1].checked.get(), Some(&None)); + } +} diff --git a/crates/stela-driver-gpu/src/metal/compiler/linked.rs b/crates/stela-driver-gpu/src/metal/compiler/linked.rs index 5596b473b7..528b17158b 100644 --- a/crates/stela-driver-gpu/src/metal/compiler/linked.rs +++ b/crates/stela-driver-gpu/src/metal/compiler/linked.rs @@ -47,12 +47,13 @@ unsafe extern "C" { data: *mut c_void, error: *mut ffi::AirError, ) -> bool; - fn stela_metal_compile( + fn stela_metal_compile_reflected( air: *const c_void, size: usize, entry: *const c_char, target: *const ffi::Target, specialization: *const ffi::Specialization, + reflection: *const ffi::Reflection, error: *mut ffi::AirError, ) -> *mut c_void; fn stela_metal_tessellation_stages( @@ -68,6 +69,13 @@ unsafe extern "C" { } impl Service { + #[cfg(target_os = "uefi")] + pub(super) fn accepts_compilation_projection(&self) -> bool { + let linked = Self::linked(self.nir_options); + core::ptr::fn_addr_eq(self.reflect, linked.reflect) + && core::ptr::fn_addr_eq(self.compile, linked.compile) + } + /// The linked service, compiling with the driver's `nir_options`. pub fn linked(nir_options: NonNull) -> Self { Self { @@ -76,7 +84,7 @@ impl Service { sampler_states: stela_metal_sampler_states, functions: stela_metal_functions, stitch: stela_metal_stitch, - compile: stela_metal_compile, + compile: stela_metal_compile_reflected, tessellation_stages: stela_metal_tessellation_stages, accumulate_kernel: stela_metal_accumulate_kernel, select_kernel: stela_metal_select_kernel, diff --git a/crates/stela-driver-gpu/src/metal/compiler/tests.rs b/crates/stela-driver-gpu/src/metal/compiler/tests.rs index 1d3aafdd26..e8d1af8eb3 100644 --- a/crates/stela-driver-gpu/src/metal/compiler/tests.rs +++ b/crates/stela-driver-gpu/src/metal/compiler/tests.rs @@ -6,7 +6,10 @@ use crate::metal::{ IndexType, TessellationControlPointIndexType, TessellationFactorStepFunction, TessellationPartitionMode, Winding, }, - library::tests::{container, fixture}, + library::{ + Header, Library, + tests::{container, fixture}, + }, nvidia::{CHIPS, fixture::nvk}, shader::{LinkedFunction, Linking, Patch, PatchDomain}, vertex::{STRIDE_DYNAMIC, StageInputDescriptor, VertexDescriptor}, @@ -66,6 +69,8 @@ struct Fake { reflection: ffi::Reflection, /// The function constant values of each reflection. reflected: Vec, + reflected_record: usize, + expect_projected: bool, refuse_reflection: Option, refuse_compilation: Option, compiled: Vec, @@ -83,6 +88,8 @@ std::thread_local! { RefCell::new(Fake { reflection: ffi::Reflection::ZERO, reflected: Vec::new(), + reflected_record: 0, + expect_projected: false, refuse_reflection: None, refuse_compilation: None, compiled: Vec::new(), @@ -140,6 +147,7 @@ unsafe extern "C" fn reflect( } // SAFETY: the compiler passes its reflection record. unsafe { *reflection = fake.reflection }; + fake.reflected_record = reflection.addr(); true }) } @@ -207,6 +215,7 @@ unsafe extern "C" fn compile( entry: *const c_char, target: *const ffi::Target, specialization: *const ffi::Specialization, + reflection: *const ffi::Reflection, error: *mut ffi::AirError, ) -> *mut c_void { check_input(air, size, entry); @@ -320,6 +329,40 @@ unsafe extern "C" fn compile( if refused(fake.refuse_compilation, error) { return ptr::null_mut(); } + if fake.expect_projected { + // SAFETY: the compiler keeps the projected reflection alive for the call. + let projection = unsafe { &*reflection }; + let original = &fake.reflection; + assert_eq!(projection.stage, original.stage); + assert_eq!(projection.patch, original.patch); + assert_eq!(projection.threadgroup_bytes, original.threadgroup_bytes); + assert_eq!(projection.varying_count, original.varying_count); + for (projected, original_varying) in projection + .varyings + .iter() + .zip(&original.varyings) + .take(original.varying_count as usize) + { + assert_eq!(projected.primitive, original_varying.primitive); + assert_eq!(projected.components, original_varying.components); + assert_eq!(projected.per_primitive, original_varying.per_primitive); + assert_eq!( + name(projection, projected.identifier, projected.identifier_bytes), + name( + original, + original_varying.identifier, + original_varying.identifier_bytes + ) + ); + } + } else { + assert_eq!(reflection.addr(), fake.reflected_record); + // SAFETY: this is the live reflection record the service filled. + let actual = unsafe { &*reflection }; + assert_eq!(actual.ident_bytes, fake.reflection.ident_bytes); + assert_eq!(actual.names, fake.reflection.names); + } + assert_eq!(fake.reflected.last(), Some(&constants)); fake.compiled.push(Compiled { workgroup_size: specialization.workgroup_size, lengths: lengths @@ -663,6 +706,92 @@ fn reflections_become_interfaces_with_their_provenance() { ); } +#[test] +fn custom_compilation_receives_the_full_reflection_of_a_prepared_function() { + reflecting(|r| { + r.stage = 3; + r.ident = add_name(r, IDENT); + r.ident_bytes = IDENT.len() as u32; + }); + let (mut compiler, library) = with_library(); + let function = compiler + .prepare_function(library, "kernel", Vec::new()) + .unwrap(); + assert!(function.reflection_service.is_none()); + assert_eq!(function.entry(), "kernel"); + let shader = compiler + .compile_prepared(&function, &Specialization::default()) + .unwrap(); + assert_eq!(shader.provenance.build_id, IDENT); + compiler.release(shader.code); + FAKE.with_borrow(|fake| assert_eq!(fake.reflected.len(), 2)); +} + +#[test] +fn prepared_compilation_reuses_only_the_same_specialization() { + reflecting(|r| { + r.stage = 1; + r.ident = add_name(r, IDENT); + r.ident_bytes = IDENT.len() as u32; + add_varying(r, "user(uv)", ffi::primitive::HALF, 2); + add_varying(r, "user(index)", ffi::primitive::UINT, 1); + }); + let (mut compiler, library) = with_library(); + compiler.project_reflection = true; + let mut specialization = Specialization { + constants: vec![(4, vec![1])], + ..Specialization::default() + }; + let prepared = compiler + .prepare_function(library, "kernel", specialization.constants.clone()) + .unwrap(); + let reflections = FAKE.with_borrow(|fake| fake.reflected.len()); + FAKE.with_borrow_mut(|fake| fake.expect_projected = true); + let shader = compiler + .compile_prepared(&prepared, &specialization) + .unwrap(); + assert_eq!(shader.provenance, prepared.provenance); + assert_eq!(shader.provenance.build_id, IDENT); + assert_eq!( + Reflection::Stage(Box::new(shader.interface)), + prepared.reflection + ); + compiler.release(shader.code); + FAKE.with_borrow(|fake| assert_eq!(fake.reflected.len(), reflections)); + + FAKE.with_borrow_mut(|fake| { + fake.refuse_compilation = Some((ffi::kind::INSTRUCTION, 17, "unsupported call")) + }); + assert_eq!( + compiler.compile_prepared(&prepared, &specialization), + Err(Error::Unsupported("AIR instructions")) + ); + let refusal = compiler.take_refusal().unwrap(); + assert_eq!( + ( + refusal.entry.as_str(), + refusal.instruction, + refusal.detail.as_str() + ), + ("kernel", 17, "unsupported call") + ); + FAKE.with_borrow_mut(|fake| { + assert_eq!(fake.reflected.len(), reflections); + fake.expect_projected = false; + fake.refuse_compilation = None; + }); + + specialization.constants[0].1[0] = 2; + let shader = compiler + .compile_prepared(&prepared, &specialization) + .unwrap(); + compiler.release(shader.code); + FAKE.with_borrow(|fake| { + assert_eq!(fake.reflected.len(), reflections + 1); + assert_eq!(fake.reflected.last(), Some(&specialization.constants)); + }); +} + #[test] fn fragment_interpolation_is_a_feature_of_its_function() { reflecting(|r| { @@ -1165,6 +1294,7 @@ fn post_tessellation_vertex_functions_compile_with_their_stage_in() { r.attribute_count = 1; }); let (mut compiler, library) = with_library(); + compiler.project_reflection = true; let patch = Patch { domain: PatchDomain::Quad, control_points: Some(4), @@ -1196,9 +1326,14 @@ fn post_tessellation_vertex_functions_compile_with_their_stage_in() { }], }), }; - let stages = compiler - .compile_tessellation(library, "kernel", &Specialization::default(), &tessellation) + let prepared = compiler + .prepare_function(library, "kernel", Vec::new()) .unwrap(); + FAKE.with_borrow_mut(|fake| fake.expect_projected = true); + let stages = compiler + .compile_prepared_tessellation(&prepared, &Specialization::default(), &tessellation) + .unwrap(); + FAKE.with_borrow_mut(|fake| fake.expect_projected = false); assert_eq!( (stages.vertex, stages.control), (ShaderCode(0x10), ShaderCode(0x20)) diff --git a/crates/stela-driver-gpu/src/metal/device.rs b/crates/stela-driver-gpu/src/metal/device.rs index 4f4557cc9f..94179aeedc 100644 --- a/crates/stela-driver-gpu/src/metal/device.rs +++ b/crates/stela-driver-gpu/src/metal/device.rs @@ -16,7 +16,7 @@ use super::{ object::{Memory, Semaphore}, }, }; -use alloc::vec::Vec; +use alloc::{collections::VecDeque, vec::Vec}; mod execution_sets; #[cfg(test)] @@ -116,8 +116,9 @@ pub struct Device { lost: bool, quiesce: Option, /// Objects waiting for a serial to complete, with the allocation bytes - /// charged until their backend memory is destroyed. - deferred: Vec<(u64, Object, u64)>, + /// charged until their backend memory is destroyed. Entries follow + /// submission order. + deferred: VecDeque<(u64, Object, u64)>, allocated: u64, resources: resources::Resources, pipelines: pipelines::Pipelines, @@ -163,7 +164,7 @@ impl Device { completed: 0, lost: false, quiesce: None, - deferred: Vec::new(), + deferred: VecDeque::new(), allocated: 0, resources: resources::Resources::default(), pipelines: pipelines::Pipelines::default(), @@ -215,7 +216,7 @@ impl Device { self.backend.destroy(object); self.allocated -= allocated; } else { - self.deferred.push((self.submitted, object, allocated)); + self.deferred.push_back((self.submitted, object, allocated)); } } diff --git a/crates/stela-driver-gpu/src/metal/device/fixture.rs b/crates/stela-driver-gpu/src/metal/device/fixture.rs index 1188049715..4bbf24f9e4 100644 --- a/crates/stela-driver-gpu/src/metal/device/fixture.rs +++ b/crates/stela-driver-gpu/src/metal/device/fixture.rs @@ -56,12 +56,17 @@ pub(crate) struct MockBackend { pub(crate) caches: BTreeMap, pub(crate) submissions: Vec>, pub(crate) writes: Vec<(Memory, u64, Vec)>, + pub(crate) write_error: Option, pub(crate) invalidated: Vec<(Memory, u64, u64)>, /// Host memory each imported memory is, by memory. pub(crate) imports: BTreeMap, NonZeroU64)>, pub(crate) retired: VecDeque, pub(crate) semaphores: BTreeMap, pub(crate) queries_ready: bool, + pub(crate) query_pool_error: Option, + pub(crate) query_pools: Vec<(QueryPool, QueryPoolInfo)>, + pub(crate) query_resets: Vec<(QueryPool, u32, u32)>, + pub(crate) query_reads: Vec<(QueryPool, u32, usize)>, pub(crate) layouts: Vec, /// Each execution set's pipelines by index. pub(crate) execution_sets: BTreeMap>, @@ -212,8 +217,13 @@ impl Backend for MockBackend { self.compute.push(*info); Ok(Pipeline(self.id())) } - fn create_query_pool(&mut self, _: &QueryPoolInfo) -> Result { - Ok(QueryPool(self.id())) + fn create_query_pool(&mut self, info: &QueryPoolInfo) -> Result { + if let Some(error) = self.query_pool_error.take() { + return Err(error); + } + let pool = QueryPool(self.id()); + self.query_pools.push((pool, *info)); + Ok(pool) } fn create_semaphore(&mut self, initial: u64) -> Result { let id = self.id(); @@ -264,6 +274,9 @@ impl Backend for MockBackend { self.descriptors.push((index, descriptor)); } fn write_memory(&mut self, memory: Memory, offset: u64, bytes: &[u8]) -> Result<()> { + if let Some(error) = self.write_error.take() { + return Err(error); + } self.writes.push((memory, offset, bytes.to_vec())); Ok(()) } @@ -292,8 +305,11 @@ impl Backend for MockBackend { fn copy_from_image(&mut self, _: Image, _: &BufferImageCopy, _: &mut [u8]) -> Result<()> { Ok(()) } - fn reset_queries(&mut self, _: QueryPool, _: u32, _: u32) {} - fn query_results(&mut self, _: QueryPool, _: u32, results: &mut [u64]) -> Result { + fn reset_queries(&mut self, pool: QueryPool, first: u32, count: u32) { + self.query_resets.push((pool, first, count)); + } + fn query_results(&mut self, pool: QueryPool, first: u32, results: &mut [u64]) -> Result { + self.query_reads.push((pool, first, results.len())); results .iter_mut() .enumerate() diff --git a/crates/stela-driver-gpu/src/metal/device/pipelines.rs b/crates/stela-driver-gpu/src/metal/device/pipelines.rs index 8b62d0233d..f209548335 100644 --- a/crates/stela-driver-gpu/src/metal/device/pipelines.rs +++ b/crates/stela-driver-gpu/src/metal/device/pipelines.rs @@ -22,8 +22,8 @@ use crate::metal::{ }, reflection::Binding, shader::{ - CompiledShader, Compiler, Interface, LinkedFunction, Linking, Reflection, Specialization, - Stage, Tessellation, TessellationStages, Varying, + CompiledShader, Compiler, Interface, LinkedFunction, Linking, PreparedFunction, Reflection, + Specialization, Stage, Tessellation, TessellationStages, Varying, }, stitching::StitchedGraph, vertex::{StageInputDescriptor, VertexDescriptor}, @@ -141,16 +141,14 @@ impl Sources { #[derive(Debug)] struct FunctionObject { library: LibraryId, - entry: String, - constants: Vec<(u32, Vec)>, - reflection: Reflection, + prepared: PreparedFunction, users: Users, } impl FunctionObject { /// The interface of a function that becomes a pipeline stage. fn interface(&self) -> Result<&Interface> { - match &self.reflection { + match &self.prepared.reflection { Reflection::Stage(interface) => Ok(interface.as_ref()), Reflection::Visible { .. } => Err(Error::Invalid("a visible function is not a stage")), } @@ -463,14 +461,14 @@ impl Device { for &id in functions { let function = self.pipelines.functions.get(id.0)?; ensure( - matches!(function.reflection, Reflection::Visible { .. }), + matches!(function.prepared.reflection, Reflection::Visible { .. }), "stitched functions are visible functions", )?; - let mut constants = function.constants.clone(); + let mut constants = function.prepared.constants.clone(); constants.sort_unstable_by_key(|&(index, _)| index); stitched.push(LinkedFunction { library: self.pipelines.library(function.library)?, - entry: function.entry.clone(), + entry: String::from(function.prepared.entry()), constants, }); libraries.push(function.library); @@ -646,11 +644,8 @@ impl Device { .iter() .map(|&(index, value)| (index, value.value.clone())) .collect(); - let specialization = Specialization { - constants: constants.clone(), - ..Specialization::default() - }; - let reflection = self.compiler.reflect(compiled, entry, &specialization)?; + let prepared = self.compiler.prepare_function(compiled, entry, constants)?; + let reflection = &prepared.reflection; reflection.validate()?; for constant in reflection.constants() { match indexed.iter().find(|(index, _)| *index == constant.index) { @@ -669,9 +664,7 @@ impl Device { } let function = FunctionObject { library, - entry: String::from(entry), - constants, - reflection, + prepared, users: Users::CREATED, }; self.keep(&kept)?; @@ -685,7 +678,7 @@ impl Device { /// What the compiler reflects of a function. pub fn function_reflection(&self, id: FunctionId) -> Result<&Reflection> { - Ok(&self.pipelines.functions.get(id.0)?.reflection) + Ok(&self.pipelines.functions.get(id.0)?.prepared.reflection) } /// The bindings of a function specialized with its function constant @@ -694,11 +687,11 @@ impl Device { let function = self.pipelines.functions.get(id.0)?; let library = self.pipelines.library(function.library)?; let specialization = Specialization { - constants: function.constants.clone(), + constants: function.prepared.constants.clone(), ..Specialization::default() }; self.compiler - .bindings(library, &function.entry, &specialization) + .bindings(library, function.prepared.entry(), &specialization) } pub fn function_type(&self, id: FunctionId) -> Result { @@ -706,6 +699,7 @@ impl Device { .pipelines .functions .get(id.0)? + .prepared .reflection .function_type()) } @@ -765,10 +759,9 @@ impl Device { &mut self, id: FunctionId, specialization: Specialization, - ) -> Result<(u64, String, Specialization)> { + ) -> Result { let function = self.pipelines.functions.get(id.0)?; let library = self.pipelines.library(function.library)?; - let entry = function.entry.clone(); let mut linking = specialization.linking; for &dependency in &self .pipelines @@ -782,24 +775,20 @@ impl Device { } } let specialization = Specialization { - constants: function.constants.clone(), + constants: function.prepared.constants.clone(), linking, ..specialization }; let samplers = self .compiler - .sampler_states(library, &entry, &specialization)? + .sampler_states(library, function.prepared.entry(), &specialization)? .into_iter() .map(|state| Ok((state, self.constexpr_sampler(state)?.0))) .collect::>()?; - Ok(( - library, - entry, - Specialization { - samplers, - ..specialization - }, - )) + Ok(Specialization { + samplers, + ..specialization + }) } fn compile( @@ -808,8 +797,9 @@ impl Device { specialization: Specialization, ) -> Result { let stage = self.pipelines.interface(id)?.stage; - let (library, entry, specialization) = self.specialize(id, specialization)?; - let compiled = self.compiler.compile(library, &entry, &specialization)?; + let specialization = self.specialize(id, specialization)?; + let function = &self.pipelines.functions.get(id.0)?.prepared; + let compiled = self.compiler.compile_prepared(function, &specialization)?; if compiled.interface.stage != stage { self.compiler.release(compiled.code); return Err(Error::Invalid("the compiler changed the function's stage")); @@ -827,10 +817,11 @@ impl Device { .pipelines .interface(id) .map(|interface| (interface.stage, interface.patch))?; - let (library, entry, specialization) = self.specialize(id, specialization)?; + let specialization = self.specialize(id, specialization)?; + let function = &self.pipelines.functions.get(id.0)?.prepared; let stages = self.compiler - .compile_tessellation(library, &entry, &specialization, tessellation)?; + .compile_prepared_tessellation(function, &specialization, tessellation)?; let interface = &stages.evaluation.interface; if (interface.stage, interface.patch) != expected { for code in [stages.vertex, stages.control, stages.evaluation.code] { @@ -1440,7 +1431,7 @@ impl Device { for &id in functions() { let function = self.pipelines.functions.get(id.0)?; ensure( - matches!(function.reflection, Reflection::Visible { .. }), + matches!(function.prepared.reflection, Reflection::Visible { .. }), "linked functions are visible functions", )?; } @@ -1448,11 +1439,11 @@ impl Device { ids.iter() .map(|id| { let function = self.pipelines.functions.get(id.0)?; - let mut constants = function.constants.clone(); + let mut constants = function.prepared.constants.clone(); constants.sort_unstable_by_key(|&(index, _)| index); Ok(LinkedFunction { library: self.pipelines.library(function.library)?, - entry: function.entry.clone(), + entry: String::from(function.prepared.entry()), constants, }) }) diff --git a/crates/stela-driver-gpu/src/metal/device/queue.rs b/crates/stela-driver-gpu/src/metal/device/queue.rs index 0294f85bdb..58c186ede6 100644 --- a/crates/stela-driver-gpu/src/metal/device/queue.rs +++ b/crates/stela-driver-gpu/src/metal/device/queue.rs @@ -22,7 +22,7 @@ use crate::metal::{ }, binding::ResourceId, command_buffer::{ - BufferRef, CommandBuffer, ComputePipelineState, DynamicFeatures, MappedRange, Recording, + BufferRef, CommandBuffer, ComputePipelineState, DynamicFeatures, MappedRange, RenderPipelineState, Resolver, Segment, counters::{self, CounterRange, CounterSample, STATISTIC_SAMPLE_BYTES}, generated::{GeneratedLayoutKey, IndirectRenderClass}, @@ -51,9 +51,12 @@ use crate::metal::{ }; use alloc::{collections::VecDeque, sync::Arc, vec::Vec}; -/// Queries per occlusion, statistics or timestamp pool. +/// Queries per encoder attachment pool. const POOL_QUERIES: u32 = 256; +/// Start and end timestamps for one command buffer. +const COMPLETION_QUERIES: u32 = 2; + /// Completed command buffers whose GPU times are kept. const TIMES_KEPT: usize = 1024; @@ -86,11 +89,17 @@ struct InFlight { chunks: Vec, pools: Vec<(QueryType, QueryPool)>, invalidations: Vec, - /// The pool, among `pools`, whose first two queries time the command - /// buffer. + /// The dedicated pool that times the command buffer. times: Option, } +#[derive(Debug)] +struct FreeQueryPool { + query_type: QueryType, + count: u32, + pool: QueryPool, +} + /// Segments of a committed command buffer that the host submits: either all /// of them, or those from an indirect mapping update's on. #[derive(Debug)] @@ -109,8 +118,8 @@ pub(super) struct Queue { /// Upload chunks with their memory; free ones are reused. chunks: Vec<(Chunk, Memory)>, free_chunks: Vec, - free_pools: Vec<(QueryType, QueryPool)>, - in_flight: Vec, + free_pools: Vec, + in_flight: VecDeque, events: Slab, counters: Slab, /// Committed work not yet submitted, in commit order. @@ -377,28 +386,50 @@ impl Device { .and_then(|()| commands.finish(&mut self.resolver(), completion)); let recording = commands.into_recording(); if let Err(error) = finished.and_then(|()| self.check_mappings(&recording.mappings)) { - self.recycle(recording); + self.recycle(recording.uploads, recording.query_pools); return Err(error); } - let mut held = self.hold(serial, recording.segments, recording.mappings)?; - let mut pools = recording.query_pools; - let times = self.time(&mut held)?; - pools.extend(times.map(|pool| (QueryType::Timestamp, pool))); + let mut times = None; + let prepared = (|| { + let mut held = self.hold(serial, recording.segments, recording.mappings)?; + times = self.time(&mut held)?; + let mut chunks = Vec::with_capacity(recording.uploads.len()); + for (chunk, bytes) in &recording.uploads { + let memory = self.chunk_memory(chunk.buffer)?; + self.backend.write_memory(memory, 0, bytes)?; + chunks.push(*chunk); + } + Ok((held, chunks)) + })(); + let (mut held, chunks) = match prepared { + Ok(prepared) => prepared, + Err(error) => { + self.recycle(recording.uploads, recording.query_pools); + if let Some(pool) = times { + // The recording never reached the queue, so the pool + // remains reset and can be returned without a GPU call. + self.queue.free_pools.push(FreeQueryPool { + query_type: QueryType::Timestamp, + count: COMPLETION_QUERIES, + pool, + }); + } + if error == Error::DeviceLost { + self.mark_lost(); + } + return Err(error); + } + }; // CPU-copy writes reach the images first, after the opening barrier - // and outside the command buffer's GPU times. + // and outside the command buffer's GPU times. Keep pending copies + // available for the next commit until preparation succeeds. let uploads = self.take_cpu_copy_uploads(); held[0].segments[0].commands.splice(1..1, uploads); - let mut chunks = Vec::with_capacity(recording.uploads.len()); - for (chunk, bytes) in &recording.uploads { - let memory = self.chunk_memory(chunk.buffer)?; - self.backend.write_memory(memory, 0, bytes)?; - chunks.push(*chunk); - } self.submitted = serial; - self.queue.in_flight.push(InFlight { + self.queue.in_flight.push_back(InFlight { serial, chunks, - pools, + pools: recording.query_pools, invalidations: recording.invalidations, times, }); @@ -413,7 +444,7 @@ impl Device { if self.capabilities.timestamp_frequency == 0 { return Ok(None); } - let (pool, _) = self.resolver().query_pool(QueryType::Timestamp)?; + let pool = self.take_query_pool(QueryType::Timestamp, COMPLETION_QUERIES)?; held[0].segments[0].commands.insert( 1, Command::WriteTimestamp { @@ -433,6 +464,38 @@ impl Device { Ok(Some(pool)) } + fn take_query_pool(&mut self, query_type: QueryType, count: u32) -> Result { + let free = &mut self.queue.free_pools; + if let Some(index) = free + .iter() + .position(|entry| entry.query_type == query_type && entry.count == count) + { + return Ok(free.swap_remove(index).pool); + } + let statistics = if query_type == QueryType::PipelineStatistics { + counters::STATISTICS + } else { + PipelineStatistics::EMPTY + }; + let info = QueryPoolInfo { + query_type, + count, + statistics, + }; + let pool = self.backend.create_query_pool(&info)?; + self.backend.reset_queries(pool, 0, count); + Ok(pool) + } + + fn retire_query_pool(&mut self, pool: QueryPool, query_type: QueryType, count: u32) { + self.backend.reset_queries(pool, 0, count); + self.queue.free_pools.push(FreeQueryPool { + query_type, + count, + pool, + }); + } + /// `GPUStartTime` and `GPUEndTime` of the completed command buffer with /// `serial`, in timestamp ticks; the latest [`TIMES_KEPT`] are kept. pub fn command_buffer_times(&self, serial: u64) -> Result<[u64; 2]> { @@ -450,15 +513,22 @@ impl Device { /// Drops a command buffer that will not be committed. pub fn discard(&mut self, commands: CommandBuffer) { - self.recycle(commands.into_recording()); + let recording = commands.into_recording(); + self.recycle(recording.uploads, recording.query_pools); } /// Takes back the upload chunks and query pools of a recording that was /// never submitted, so its queries are still reset. - fn recycle(&mut self, recording: Recording) { - let chunks = recording.uploads.into_iter().map(|(chunk, _)| chunk); + fn recycle(&mut self, uploads: Vec<(Chunk, Vec)>, pools: Vec<(QueryType, QueryPool)>) { + let chunks = uploads.into_iter().map(|(chunk, _)| chunk); self.queue.free_chunks.extend(chunks); - self.queue.free_pools.extend(recording.query_pools); + self.queue + .free_pools + .extend(pools.into_iter().map(|(query_type, pool)| FreeQueryPool { + query_type, + count: POOL_QUERIES, + pool, + })); } fn check_mappings(&self, mappings: &[(usize, Mapping)]) -> Result<()> { @@ -635,12 +705,12 @@ impl Device { return Ok(()); } self.completed = completed; - let (done, pending): (Vec<_>, Vec<_>) = core::mem::take(&mut self.queue.in_flight) - .into_iter() - .partition(|flight| flight.serial <= completed); - self.queue.in_flight = pending; let mut outcome = Ok(()); - for flight in done { + while let Some(flight) = self + .queue + .in_flight + .pop_front_if(|flight| flight.serial <= completed) + { // Before deferred destruction, which may free the memory. for range in flight.invalidations { outcome = outcome.and(self.backend.invalidate_memory( @@ -657,18 +727,17 @@ impl Device { Ok(false) => {} Err(error) => outcome = outcome.and(Err(error)), } + self.retire_query_pool(pool, QueryType::Timestamp, COMPLETION_QUERIES); } self.queue.free_chunks.extend(flight.chunks); for (query_type, pool) in flight.pools { - self.backend.reset_queries(pool, 0, POOL_QUERIES); - self.queue.free_pools.push((query_type, pool)); + self.retire_query_pool(pool, query_type, POOL_QUERIES); } } - let (ready, waiting): (Vec<_>, Vec<_>) = core::mem::take(&mut self.deferred) - .into_iter() - .partition(|(serial, _, _)| *serial <= completed); - self.deferred = waiting; - for (_, object, allocated) in ready { + while let Some((_, object, allocated)) = self + .deferred + .pop_front_if(|(serial, _, _)| *serial <= completed) + { self.backend.destroy(object); self.allocated -= allocated; } @@ -979,22 +1048,7 @@ impl Resolver for DeviceResolver<'_, B, C> { } fn query_pool(&mut self, query_type: QueryType) -> Result<(QueryPool, u32)> { - let free = &mut self.device.queue.free_pools; - if let Some(index) = free.iter().position(|&(free, _)| free == query_type) { - return Ok((free.swap_remove(index).1, POOL_QUERIES)); - } - let statistics = if query_type == QueryType::PipelineStatistics { - counters::STATISTICS - } else { - PipelineStatistics::EMPTY - }; - let info = QueryPoolInfo { - query_type, - count: POOL_QUERIES, - statistics, - }; - let pool = self.device.backend.create_query_pool(&info)?; - self.device.backend.reset_queries(pool, 0, POOL_QUERIES); + let pool = self.device.take_query_pool(query_type, POOL_QUERIES)?; Ok((pool, POOL_QUERIES)) } diff --git a/crates/stela-driver-gpu/src/metal/device/resources.rs b/crates/stela-driver-gpu/src/metal/device/resources.rs index 4bfdc096df..85b9d6fcbc 100644 --- a/crates/stela-driver-gpu/src/metal/device/resources.rs +++ b/crates/stela-driver-gpu/src/metal/device/resources.rs @@ -708,11 +708,13 @@ impl Device { strides: Strides, ) -> Result<()> { let (copy, rows) = self.cpu_region(id, region, strides, bytes.len())?; - let packed: Vec = rows - .into_iter() - .flat_map(|row| &bytes[row]) - .copied() - .collect(); + if rows.tight() { + return self.write_region(id, ©, &bytes[..rows.packed_bytes]); + } + let mut packed = Vec::with_capacity(rows.packed_bytes); + for row in rows.ranges() { + packed.extend_from_slice(&bytes[row]); + } self.write_region(id, ©, &packed) } @@ -725,10 +727,14 @@ impl Device { strides: Strides, ) -> Result<()> { let (copy, rows) = self.cpu_region(id, region, strides, bytes.len())?; - let mut packed = alloc::vec![0; rows.iter().map(ExactSizeIterator::len).sum()]; + let mut packed = alloc::vec![0; rows.packed_bytes]; self.read_region(id, ©, &mut packed)?; + if rows.tight() { + bytes[..rows.packed_bytes].copy_from_slice(&packed); + return Ok(()); + } let mut packed = packed.as_slice(); - for row in rows { + for row in rows.ranges() { let (head, rest) = packed.split_at(row.len()); bytes[row].copy_from_slice(head); packed = rest; @@ -744,7 +750,7 @@ impl Device { region: &Region, strides: Strides, length: usize, - ) -> Result<(BufferImageCopy, Vec>)> { + ) -> Result<(BufferImageCopy, CpuRows)> { let descriptor = &self.resources.textures.get(id.0)?.descriptor; let description = descriptor.pixel_format.describe(); ensure( @@ -761,19 +767,34 @@ impl Device { "bytesPerRow is smaller than a row", )?; ensure( - images <= 1 || strides.bytes_per_image >= strides.bytes_per_row * rows, + images <= 1 + || strides + .bytes_per_row + .checked_mul(rows) + .is_some_and(|bytes| strides.bytes_per_image >= bytes), "bytesPerImage is smaller than an image", )?; - let starts = (0..images).flat_map(|image| { - (0..rows).map(move |row| image * strides.bytes_per_image + row * strides.bytes_per_row) - }); - let rows = starts - .map(|start| { - let end = start + row_bytes; - ensure(end <= length as u64, "the bytes end before the region")?; - Ok(start as usize..end as usize) - }) - .collect::>>()?; + let end = if images == 0 || rows == 0 { + Some(0) + } else { + (images - 1) + .checked_mul(strides.bytes_per_image) + .zip((rows - 1).checked_mul(strides.bytes_per_row)) + .and_then(|(image, row)| image.checked_add(row)) + .and_then(|start| start.checked_add(row_bytes)) + }; + ensure( + end.is_some_and(|end| end <= length as u64), + "the bytes end before the region", + )?; + // The validated non-overlapping layout contains all the packed bytes. + let rows = CpuRows { + strides, + row_bytes, + rows, + images, + packed_bytes: (row_bytes * rows * images) as usize, + }; let copy = BufferImageCopy { buffer_offset: 0, buffer_row_length: 0, @@ -804,11 +825,12 @@ impl Device { copy.memory, cpu_copy_rows(&texture.descriptor, region, bytes.len())?, ); - for (offset, packed) in rows.clone() { + let first = rows.first; + for (offset, packed) in rows { self.backend.write_memory(memory, offset, &bytes[packed])?; } let upload = BufferImageCopy { - buffer_offset: rows.first, + buffer_offset: first, ..*region }; let upload = cpu_copy_region(&texture.descriptor, upload); @@ -1181,6 +1203,10 @@ impl Device { descriptor: &TextureDescriptor, ) -> Result { let plan = resource::texture(&self.capabilities, descriptor)?; + self.heap_texture_requirements(&plan) + } + + fn heap_texture_requirements(&mut self, plan: &TexturePlan) -> Result { let requirements = self.backend.image_requirements(&plan.image)?; SizeAndAlign::from_requirements(requirements.size, requirements.alignment) .ok_or(Error::Invalid("requirements")) @@ -1272,7 +1298,8 @@ impl Device { ensure(offset.is_none(), "sparse heaps place textures themselves")?; return self.new_sparse_texture(id, descriptor); } - let requirement = self.heap_texture_size_and_align(descriptor)?; + let plan = resource::texture(&self.capabilities, descriptor)?; + let requirement = self.heap_texture_requirements(&plan)?; let (memory, offset) = self.place(id, descriptor.options, requirement, offset)?; let backing = Backing::Heap { heap: id, @@ -1280,7 +1307,6 @@ impl Device { size: requirement.size, aliasable: false, }; - let plan = resource::texture(&self.capabilities, descriptor)?; let image = match self .backend .create_placed_image(&plan.image, memory, offset) @@ -1492,18 +1518,45 @@ fn make_aliasable(backing: &mut Backing) -> Result<(HeapId, u64, u64)> { } } -/// The rows `region` covers in a texture's CPU copy, as (copy offset, +/// Validated row layout in the caller's bytes. +struct CpuRows { + strides: Strides, + row_bytes: u64, + rows: u64, + images: u64, + packed_bytes: usize, +} + +impl CpuRows { + fn tight(&self) -> bool { + self.packed_bytes == 0 + || (self.rows <= 1 || self.strides.bytes_per_row == self.row_bytes) + && (self.images <= 1 || self.strides.bytes_per_image == self.row_bytes * self.rows) + } + + fn ranges(&self) -> impl Iterator> + '_ { + (0..self.images).flat_map(move |image| { + (0..self.rows).map(move |row| { + let start = image * self.strides.bytes_per_image + row * self.strides.bytes_per_row; + start as usize..(start + self.row_bytes) as usize + }) + }) + } +} + +/// Contiguous spans `region` covers in a texture's CPU copy, as (copy offset, /// range in tightly packed bytes of `length`); `first` is the region's /// first byte in the copy. -#[derive(Clone, Debug)] +#[derive(Debug)] struct CopyRows { first: u64, bytes_per_row: u64, bytes_per_image: u64, row_bytes: usize, - rows: u32, - images: u32, - next: u32, + rows: u64, + images: u64, + rows_per_copy: u64, + next: u64, } impl Iterator for CopyRows { @@ -1514,12 +1567,13 @@ impl Iterator for CopyRows { return None; } let (image, row) = (self.next / self.rows, self.next % self.rows); - let offset = self.first - + u64::from(image) * self.bytes_per_image - + u64::from(row) * self.bytes_per_row; + let offset = self.first + image * self.bytes_per_image + row * self.bytes_per_row; let start = self.next as usize * self.row_bytes; - self.next += 1; - Some((offset, start..start + self.row_bytes)) + self.next += self.rows_per_copy; + Some(( + offset, + start..start + self.rows_per_copy as usize * self.row_bytes, + )) } } @@ -1566,6 +1620,13 @@ fn cpu_copy_rows( row_bytes * rows * size[2] == length as u64, "the bytes are the region, tightly packed", )?; + let rows_per_copy = if bytes_per_row != row_bytes { + 1 + } else if bytes_per_image != bytes_per_row * rows { + rows + } else { + rows * size[2] + }; Ok(CopyRows { first: offset + origin[2] * bytes_per_image @@ -1574,8 +1635,9 @@ fn cpu_copy_rows( bytes_per_row, bytes_per_image, row_bytes: row_bytes as usize, - rows: rows as u32, - images: size[2] as u32, + rows, + images: size[2], + rows_per_copy, next: 0, }) } diff --git a/crates/stela-driver-gpu/src/metal/device/tests.rs b/crates/stela-driver-gpu/src/metal/device/tests.rs index a7c2ece996..b9afc720d8 100644 --- a/crates/stela-driver-gpu/src/metal/device/tests.rs +++ b/crates/stela-driver-gpu/src/metal/device/tests.rs @@ -39,7 +39,7 @@ use crate::metal::{ MemoryProperties, PipelineStages, PrimitiveTopology, ShaderStages, backend::{Descriptor, Object}, command::Command, - object::{Buffer, MemoryRequest, Pipeline, PipelineSource}, + object::{Buffer, MemoryRequest, Pipeline, PipelineSource, QueryType}, }, }; use alloc::{string::String, vec::Vec}; @@ -1430,6 +1430,69 @@ fn managed_textures_keep_a_cpu_copy_without_host_image_copy() { ); } +#[test] +fn texture_transfers_keep_strided_padding_and_coalesce_contiguous_rows() { + let mut backend = MockBackend::new(); + backend.physical.as_mut().unwrap().features.host_image_copy = false; + let mut device = device_on(backend); + let descriptor = TextureDescriptor { + texture_type: TextureType::D3, + width: 2, + height: 2, + depth: 2, + options: options(StorageMode::Managed), + ..texture(PixelFormat::Rgba8Unorm, TextureUsage::SHADER_READ) + }; + let texture = device.new_texture(&descriptor).unwrap(); + let region = Region { + slice: 0, + level: 0, + origin: [0; 3], + size: [2; 3], + }; + let strides = Strides { + bytes_per_row: 12, + bytes_per_image: 28, + }; + let ranges = [0..8, 12..20, 28..36, 40..48]; + let pixels = core::array::from_fn::<_, 32, _>(|index| index as u8); + let (rows, _) = pixels.as_chunks::<8>(); + let mut upload = [0xaa; 48]; + for (range, row) in ranges.iter().zip(rows) { + upload[range.clone()].copy_from_slice(row); + } + let previous = device.backend().writes.len(); + device + .replace_region(texture, ®ion, &upload, strides) + .unwrap(); + let [(_, _, written)] = &device.backend().writes[previous..] else { + panic!("contiguous texture data should reach the backend in one write"); + }; + assert_eq!(written, &pixels); + + let mut read = [0xee; 49]; + device + .get_bytes(texture, ®ion, &mut read, strides) + .unwrap(); + let mut expected = [0xee; 49]; + for (range, row) in ranges.into_iter().zip(rows) { + expected[range].copy_from_slice(row); + } + assert_eq!(read, expected); + assert_eq!( + device.replace_region( + texture, + ®ion, + &upload, + Strides { + bytes_per_row: u64::MAX, + bytes_per_image: u64::MAX, + }, + ), + Err(Error::Invalid("bytesPerImage is smaller than an image")) + ); +} + #[test] fn post_tessellation_functions_compile_with_their_feeding_stages() { let mut device = device(); @@ -2278,6 +2341,136 @@ fn command_buffers_are_timed_from_their_first_command_to_their_last() { assert_eq!(device.command_buffer_times(serial), Ok([0, 10])); } +#[test] +fn completion_query_pools_reuse_two_slots_after_retirement() { + let mut device = device(); + device + .new_counter_sample_buffer(CounterSet::Timestamp, 17) + .unwrap(); + let first = submit(&mut device); + let second = submit(&mut device); + let backend = device.backend(); + let [ + (public_pool, public_info), + (first_pool, first_info), + (second_pool, second_info), + ] = backend.query_pools.as_slice() + else { + panic!("expected one public pool and two in-flight completion pools"); + }; + assert_eq!(public_info.count, 17); + assert_eq!(first_info.query_type, QueryType::Timestamp); + assert_eq!(first_info.count, 2); + assert_eq!(second_info, first_info); + let (public_pool, first_pool, second_pool) = (*public_pool, *first_pool, *second_pool); + assert_ne!(first_pool, second_pool); + assert_eq!( + backend.query_resets, + [ + (public_pool, 0, 17), + (first_pool, 0, 2), + (second_pool, 0, 2) + ] + ); + assert!(backend.query_reads.is_empty()); + + backend.queries_ready = true; + complete(&mut device, first); + assert_eq!(device.command_buffer_times(first), Ok([0, 10])); + assert_eq!(device.backend().query_reads, [(first_pool, 0, 2)]); + assert_eq!(device.backend().query_resets[3..], [(first_pool, 0, 2)]); + + let third = submit(&mut device); + let backend = device.backend(); + assert_eq!(backend.query_pools.len(), 3); + assert_eq!(backend.query_resets.len(), 4); + let submission = backend.submissions.last().unwrap(); + assert!(matches!( + submission[0].commands[1], + Command::WriteTimestamp { pool, query: 0, .. } if pool == first_pool + )); + + complete(&mut device, third); + assert_eq!(device.command_buffer_times(second), Ok([0, 10])); + assert_eq!(device.command_buffer_times(third), Ok([0, 10])); + assert_eq!( + device.backend().query_reads, + [(first_pool, 0, 2), (second_pool, 0, 2), (first_pool, 0, 2)] + ); + assert_eq!( + device.backend().query_resets[3..], + [(first_pool, 0, 2), (second_pool, 0, 2), (first_pool, 0, 2)] + ); +} + +#[test] +fn failed_completion_preparation_preserves_pending_texture_uploads() { + let mut backend = MockBackend::new(); + backend.physical.as_mut().unwrap().features.host_image_copy = false; + let mut device = device_on(backend); + let texture = device + .new_texture(&TextureDescriptor { + options: options(StorageMode::Managed), + ..texture(PixelFormat::Rgba8Unorm, TextureUsage::SHADER_READ) + }) + .unwrap(); + device + .replace_region( + texture, + &Region { + slice: 0, + level: 0, + origin: [0; 3], + size: [1; 3], + }, + &[1, 2, 3, 4], + Strides { + bytes_per_row: 4, + bytes_per_image: 0, + }, + ) + .unwrap(); + let encode = |device: &mut TestDevice| { + let mut commands = device.new_command_buffer(); + commands.begin_compute(DispatchType::Serial).unwrap(); + commands + .set_compute_bytes(&mut device.resolver(), &[7; 64], 0) + .unwrap(); + commands.end_encoding(&mut device.resolver()).unwrap(); + commands + }; + + let commands = encode(&mut device); + let writes = device.backend().writes.len(); + let created = device.backend().next; + device.backend().query_pool_error = Some(Error::OutOfMemory); + assert_eq!(device.commit(commands), Err(Error::OutOfMemory)); + assert_eq!(device.backend().writes.len(), writes); + assert!(device.backend().submissions.is_empty()); + + let commands = encode(&mut device); + device.backend().write_error = Some(Error::OutOfMemory); + assert_eq!(device.commit(commands), Err(Error::OutOfMemory)); + assert_eq!(device.backend().next, created + 1); + let pool = device.backend().query_pools[0].0; + assert_eq!(device.backend().query_resets, [(pool, 0, 2)]); + assert!(device.backend().submissions.is_empty()); + + let commands = encode(&mut device); + let serial = device.commit(commands).unwrap(); + assert_eq!(serial, 1); + assert_eq!(device.backend().next, created + 1); + assert_eq!(device.backend().query_resets, [(pool, 0, 2)]); + let submitted = &device.backend().submissions[0][0].commands; + assert!(matches!(submitted[1], Command::CopyBufferToImage { .. })); + assert!(matches!( + submitted[3], + Command::WriteTimestamp { query: 0, .. } + )); + complete(&mut device, serial); + assert_eq!(device.backend().query_resets, [(pool, 0, 2), (pool, 0, 2)]); +} + #[test] fn uncommitted_command_buffers_return_their_upload_memory() { let mut device = device(); @@ -2394,6 +2587,7 @@ fn device_loss_keeps_in_flight_imports_pinned_and_charged() { .import_memory(&ranges, core::num::NonZeroU64::new(12).unwrap()) .unwrap(); let serial = submit(&mut device); + let query_resets = device.backend().query_resets.len(); device.destroy_buffer(buffer).unwrap(); device.backend().semaphore_error = Some(Error::DeviceLost); assert_eq!(device.poll(), Err(Error::DeviceLost)); @@ -2407,5 +2601,7 @@ fn device_loss_keeps_in_flight_imports_pinned_and_charged() { assert_eq!(device.current_allocated_size(), 16384); assert_eq!(device.backend().imports.len(), 2); assert!(device.backend().destroyed.is_empty()); + assert_eq!(device.backend().query_resets.len(), query_resets); + assert!(device.backend().query_reads.is_empty()); assert_eq!(device.retired(), None); } diff --git a/crates/stela-driver-gpu/src/metal/kms.rs b/crates/stela-driver-gpu/src/metal/kms.rs index 06de2c6c60..4e39ebe972 100644 --- a/crates/stela-driver-gpu/src/metal/kms.rs +++ b/crates/stela-driver-gpu/src/metal/kms.rs @@ -14,6 +14,7 @@ use alloc::vec::Vec; use core::ffi::c_void; use core::ptr::{self, NonNull}; +use stela_contracts::{Refusal, refuse}; /// `_IOWR('d', number, T)`. const fn request(number: u32) -> u32 { @@ -225,6 +226,17 @@ pub struct Display { // time through the board's lock. unsafe impl Send for Display {} +/// A complete frame in the hidden buffer. Dropping it leaves the display +/// unchanged. No other frame can be prepared before this one is released. +pub struct PreparedFrame<'a, D>(&'a mut Display); + +impl PreparedFrame<'_, D> { + /// Queue the prepared frame for the next vertical blank. + pub fn present(self) -> Result<(), Error> { + self.0.flip() + } +} + fn call(drm: &mut D, request: u32, argument: &mut T) -> Result<(), Error> { match drm.control(request, ptr::from_mut(argument).cast()) { 0 => Ok(()), @@ -450,20 +462,46 @@ impl Display { actual: rows.len(), }); } - let target = self.buffers[2].pixels.as_ptr(); - let pitch = self.buffers[2].pitch; - for (y, line) in rows - .chunks_exact(row) - .take(self.height as usize) - .enumerate() - { - // SAFETY: `y` is a row of the mapped buffer, whose rows are - // `pitch` apart and hold `row` bytes, and the engine reads - // another buffer. - unsafe { - ptr::copy_nonoverlapping(line.as_ptr(), target.add(y * pitch), row); - } + for (y, line) in rows.chunks_exact(row).enumerate() { + self.copy_hidden_row(y, line); } + self.flip() + } + + /// Fill the hidden buffer one row at a time. The producer works in + /// ordinary RAM so inspecting or changing pixels never reads VRAM. + /// A failed row leaves the current scanout and buffer order unchanged. + pub fn prepare_rows( + &mut self, + mut fill: impl FnMut(usize, &mut [u8]) -> Result<(), Refusal>, + ) -> Result, Refusal> { + let bytes = self.width as usize * BYTES_PER_PIXEL as usize; + let mut row = Vec::new(); + row.try_reserve_exact(bytes) + .map_err(|_| refuse!("could not allocate a scanout row"))?; + row.resize(bytes, 0); + for y in 0..self.height as usize { + fill(y, &mut row)?; + self.copy_hidden_row(y, &row); + } + Ok(PreparedFrame(self)) + } + + fn copy_hidden_row(&mut self, y: usize, row: &[u8]) { + let target = &self.buffers[2]; + // SAFETY: callers give one full row and a valid row index. The + // mapping's pitch holds that row, and the engine reads a different + // buffer. + unsafe { + ptr::copy_nonoverlapping( + row.as_ptr(), + target.pixels.as_ptr().add(y * target.pitch), + row.len(), + ); + } + } + + fn flip(&mut self) -> Result<(), Error> { let mut flip = PageFlip { crtc: self.crtc, framebuffer: self.buffers[2].framebuffer, diff --git a/crates/stela-driver-gpu/src/metal/kms/tests/scanout.rs b/crates/stela-driver-gpu/src/metal/kms/tests/scanout.rs index de3ce1908f..e0d6003cdc 100644 --- a/crates/stela-driver-gpu/src/metal/kms/tests/scanout.rs +++ b/crates/stela-driver-gpu/src/metal/kms/tests/scanout.rs @@ -1,5 +1,54 @@ use super::*; +#[test] +fn row_fill_failure_keeps_the_front_and_retries_the_hidden_buffer() { + let mut card = Card::new(vec![mode(2, 2, PREFERRED)]); + card.busy = 2; + card.pitches = vec![8, 16, 32]; + let hidden; + { + let mut display = Display::take(&mut card, (2, 2)).unwrap(); + let front = display.front(); + hidden = display.buffers[2].framebuffer; + let failure = display + .prepare_rows(|y, row| { + row.fill(1); + if y == 1 { + return Err(refuse!("second row failed")); + } + Ok(()) + }) + .err(); + assert_eq!(failure, Some(refuse!("second row failed"))); + assert_eq!(display.front(), front); + assert!(display.drm.flips.is_empty()); + assert_eq!(display.drm.busy, 2); + assert!(display.drm.memory[..2].iter().flatten().all(|&b| b == 0)); + assert_eq!(&display.drm.memory[2][..8], &[1; 8]); + assert!(display.drm.memory[2][8..].iter().all(|&b| b == 0)); + + let mut scratch = None; + display + .prepare_rows(|y, row| { + assert_eq!(row.len(), 8); + assert_eq!(*scratch.get_or_insert(row.as_ptr()), row.as_ptr()); + row.fill(if y == 0 { 2 } else { 3 }); + Ok(()) + }) + .unwrap() + .present() + .unwrap(); + assert_eq!(display.buffers[0].framebuffer, hidden); + } + assert_eq!(card.flips, [hidden]); + assert_eq!(card.relaxed, 2); + let filled = &card.memory[2]; + assert_eq!(&filled[..8], &[2; 8]); + assert_eq!(&filled[32..40], &[3; 8]); + assert!(filled[8..32].iter().all(|&b| b == 0)); + assert!(filled[40..].iter().all(|&b| b == 0)); +} + #[test] fn a_failed_flip_keeps_the_front_and_retries_the_hidden_buffer() { let mut card = Card::new(vec![mode(2, 2, PREFERRED)]); diff --git a/crates/stela-driver-gpu/src/metal/library.rs b/crates/stela-driver-gpu/src/metal/library.rs index 8181a1004d..7684f6baca 100644 --- a/crates/stela-driver-gpu/src/metal/library.rs +++ b/crates/stela-driver-gpu/src/metal/library.rs @@ -509,10 +509,7 @@ impl<'a> Function<'a> { /// Verify the archive's digest before returning the LLVM reader's input. pub fn air(&self) -> Result> { - if Sha256::digest(self.module).as_slice() != self.digest { - return Err(error(self.module_offset, ErrorKind::Hash)); - } - Air::parse(self.module).map_err(|mut failure| { + Air::verified(self.module, self.digest).map_err(|mut failure| { failure.offset += self.module_offset; failure }) @@ -551,6 +548,13 @@ pub struct Air<'a> { } impl<'a> Air<'a> { + pub(super) fn verified(data: &'a [u8], digest: &[u8; 32]) -> Result { + if Sha256::digest(data).as_slice() != digest { + return Err(error(0, ErrorKind::Hash)); + } + Self::parse(data) + } + pub fn parse(data: &'a [u8]) -> Result { if data.starts_with(LLVM_MAGIC) { return Ok(Self { diff --git a/crates/stela-driver-gpu/src/metal/macros.rs b/crates/stela-driver-gpu/src/metal/macros.rs index 4dcd682616..a9b8c768ec 100644 --- a/crates/stela-driver-gpu/src/metal/macros.rs +++ b/crates/stela-driver-gpu/src/metal/macros.rs @@ -7,12 +7,14 @@ /// A closed enumeration with fixed raw values. Decoding refuses any value the /// list does not name; `ALL` lists the variants in declaration order. +/// `decode with` can select an enum's own lookup method. macro_rules! raw_enum { ( $(#[$meta:meta])* $vis:vis enum $name:ident: $raw:ty { $($(#[$variant_meta:meta])* $variant:ident = $value:expr,)+ } + $(decode with $decode:ident;)? ) => { $(#[$meta])* #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] @@ -29,10 +31,16 @@ macro_rules! raw_enum { } pub fn from_raw(raw: $raw) -> Option { - Self::ALL.iter().copied().find(|value| value.raw() == raw) + raw_enum!(@decode raw $(, $decode)?) } } }; + (@decode $raw:ident, $decode:ident) => { + Self::$decode($raw) + }; + (@decode $raw:ident) => { + Self::ALL.iter().copied().find(|value| value.raw() == $raw) + }; } /// A bit set with named flags. `from_bits` refuses bits outside `KNOWN`; diff --git a/crates/stela-driver-gpu/src/metal/native.rs b/crates/stela-driver-gpu/src/metal/native.rs index 4fc3881645..5add4c6050 100644 --- a/crates/stela-driver-gpu/src/metal/native.rs +++ b/crates/stela-driver-gpu/src/metal/native.rs @@ -134,15 +134,80 @@ struct Mapping { coherent: bool, } +#[derive(Debug)] +enum CommandBuffers { + One(vk::CommandBuffer), + Many(Vec), +} + +impl CommandBuffers { + /// The pool belongs to this device and is used only by the caller. + fn allocate(device: &ash::Device, pool: vk::CommandPool, count: u32) -> Result { + let info = vk::CommandBufferAllocateInfo::default() + .command_pool(pool) + .level(vk::CommandBufferLevel::PRIMARY) + .command_buffer_count(count); + if count == 1 { + let mut buffer = vk::CommandBuffer::null(); + // SAFETY: one writable handle is sufficient for the requested count. + unsafe { + (device.fp_v1_0().allocate_command_buffers)(device.handle(), &info, &mut buffer) + } + .result() + .map_err(failure)?; + return Ok(Self::One(buffer)); + } + // SAFETY: ash provides output space for the requested count. + unsafe { device.allocate_command_buffers(&info) } + .map(Self::Many) + .map_err(failure) + } + + fn as_slice(&self) -> &[vk::CommandBuffer] { + match self { + Self::One(buffer) => core::slice::from_ref(buffer), + Self::Many(buffers) => buffers, + } + } +} + /// Command buffers of one submission, freed once the queue's timeline /// passes `value`. #[derive(Debug)] struct InFlight { - buffers: Vec, + buffers: CommandBuffers, timeline: vk::Semaphore, value: u64, } +impl InFlight { + /// Counts finished submissions from the front of the queue. Timeline + /// values only increase, so one observation covers consecutive + /// submissions that signal the same semaphore. + fn completed_prefix( + flights: &VecDeque, + mut observe: impl FnMut(vk::Semaphore) -> Result, + ) -> Result { + let mut observed = None; + let mut ready = 0; + for entry in flights { + let value = match observed { + Some((timeline, value)) if timeline == entry.timeline => value, + _ => { + let value = observe(entry.timeline)?; + observed = Some((entry.timeline, value)); + value + } + }; + if value < entry.value { + break; + } + ready += 1; + } + Ok(ready) + } +} + /// The bindless descriptor heap: set 0 of every pipeline. #[derive(Clone, Copy, Debug)] struct Heap { @@ -204,7 +269,7 @@ pub struct NativeBackend { null_sampler: vk::Sampler, layout: vk::PipelineLayout, command_pool: vk::CommandPool, - in_flight: Vec, + in_flight: VecDeque, mappings: BTreeMap, exporter: ManuallyDrop>, /// What each imported memory came from, and its token. @@ -381,7 +446,7 @@ impl NativeBackend { null_sampler: vk::Sampler::null(), layout: vk::PipelineLayout::null(), command_pool: vk::CommandPool::null(), - in_flight: Vec::new(), + in_flight: VecDeque::new(), mappings: BTreeMap::new(), exporter: ManuallyDrop::new(exporter), imports: BTreeMap::new(), @@ -676,28 +741,46 @@ impl NativeBackend { /// Frees the command buffers of submissions the queue has finished. fn reclaim(&mut self) -> Result<()> { - let mut finished = Vec::new(); - let mut index = 0; - while index < self.in_flight.len() { - let entry = &self.in_flight[index]; + // Leave the queue intact if observing a completion fails. + let ready = InFlight::completed_prefix(&self.in_flight, |timeline| { // SAFETY: the timeline semaphore is alive while submissions use it. - let value = unsafe { self.device.get_semaphore_counter_value(entry.timeline) } - .map_err(failure)?; - if value >= entry.value { - finished.extend(self.in_flight.swap_remove(index).buffers); - } else { - index += 1; - } - } - if !finished.is_empty() { - // SAFETY: the queue finished every command buffer in `finished`. - unsafe { - self.device - .free_command_buffers(self.command_pool, &finished) - }; - } + unsafe { self.device.get_semaphore_counter_value(timeline) }.map_err(failure) + })?; + self.free_completed(ready); Ok(()) } + + fn free_completed(&mut self, ready: usize) { + if ready == 0 { + return; + } + let buffers = if ready == 1 { + self.in_flight + .pop_front() + .expect("a ready submission") + .buffers + } else { + let mut completed = self.in_flight.drain(..ready); + let first = completed.next().expect("a ready submission").buffers; + let mut buffers = match first { + CommandBuffers::One(buffer) => { + let mut buffers = Vec::with_capacity(ready); + buffers.push(buffer); + buffers + } + CommandBuffers::Many(buffers) => buffers, + }; + for entry in completed { + buffers.extend_from_slice(entry.buffers.as_slice()); + } + CommandBuffers::Many(buffers) + }; + // SAFETY: the queue finished every command buffer in `buffers`. + unsafe { + self.device + .free_command_buffers(self.command_pool, buffers.as_slice()) + }; + } } impl Drop for NativeBackend { @@ -1360,8 +1443,20 @@ impl Backend for NativeBackend { } fn semaphore_value(&mut self, semaphore: Semaphore) -> Result { + let timeline = handle(semaphore.0); // SAFETY: the semaphore is alive. - unsafe { self.device.get_semaphore_counter_value(handle(semaphore.0)) }.map_err(failure) + let value = + unsafe { self.device.get_semaphore_counter_value(timeline) }.map_err(failure)?; + // The Metal completion poll already observed this timeline. Free the + // prefix it proves complete so the next submission need not query it + // again just to free these command buffers. + let ready = self + .in_flight + .iter() + .take_while(|entry| entry.timeline == timeline && entry.value <= value) + .count(); + self.free_completed(ready); + Ok(value) } fn signal_semaphore(&mut self, semaphore: Semaphore, value: u64) -> Result<()> { @@ -1391,15 +1486,12 @@ impl Backend for NativeBackend { if segments.is_empty() { return Ok(()); } - let info = vk::CommandBufferAllocateInfo::default() - .command_pool(self.command_pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(segments.len() as u32); - // SAFETY: the pool belongs to this device and is used only here. - let buffers = unsafe { self.device.allocate_command_buffers(&info) }.map_err(failure)?; + let buffers = + CommandBuffers::allocate(&self.device, self.command_pool, segments.len() as u32)?; + let handles = buffers.as_slice(); let new_images = core::mem::take(&mut self.new_images); let recorded = - buffers + handles .iter() .zip(segments) .enumerate() @@ -1407,19 +1499,19 @@ impl Backend for NativeBackend { let adopt = if index == 0 { &new_images[..] } else { &[] }; record::segment(self, buffer, adopt, segment) }); - let submitted = recorded.and_then(|()| self.queue_segments(segments, &buffers)); + let submitted = recorded.and_then(|()| self.queue_segments(segments, handles)); if let Err(error) = submitted { // Some segments may have reached the queue. A failed idle query // leaves their buffers owned by the command pool until device // teardown can prove idleness. - let _ = free_after_idle(&self.device, self.queue, self.command_pool, &buffers); + let _ = free_after_idle(&self.device, self.queue, self.command_pool, handles); self.new_images = new_images; return Err(error); } // A commit appends the queue's completion signal last. let completion = segments.last().and_then(|segment| segment.signals.last()); match completion { - Some(&(timeline, value)) => self.in_flight.push(InFlight { + Some(&(timeline, value)) => self.in_flight.push_back(InFlight { buffers, timeline: handle(timeline.0), value, @@ -1427,7 +1519,7 @@ impl Backend for NativeBackend { // Without a completion signal the buffers are free only once the // queue idles. None => { - free_after_idle(&self.device, self.queue, self.command_pool, &buffers)?; + free_after_idle(&self.device, self.queue, self.command_pool, handles)?; } } Ok(()) @@ -1481,6 +1573,31 @@ fn flush( submitted.map_err(failure) } +/// Keep the Vulkan packet for a single ordinary segment on the stack. +fn submit_single_segment( + device: &ash::Device, + queue: vk::Queue, + segments: &[Segment], + buffers: &[vk::CommandBuffer], +) -> Option> { + let ([segment], [buffer]) = (segments, buffers) else { + return None; + }; + if !segment.binds.is_empty() || segment.waits.len() > 1 || segment.signals.len() > 1 { + return None; + } + let wait = segment.waits.first().copied().map(objects::semaphore); + let signal = segment.signals.first().copied().map(objects::semaphore); + let commands = [vk::CommandBufferSubmitInfo::default().command_buffer(*buffer)]; + let submits = [vk::SubmitInfo2::default() + .wait_semaphore_infos(wait.as_slice()) + .command_buffer_infos(&commands) + .signal_semaphore_infos(signal.as_slice())]; + // SAFETY: the backend owns the queue and recorded buffer. All packet + // arrays stay alive for the call, which consumes their contents. + Some(unsafe { device.queue_submit2(queue, &submits, vk::Fence::null()) }.map_err(failure)) +} + impl NativeBackend { /// Submits the recorded segments in order. A segment with sparse binds /// splits the submission: the queue signals the bind timeline once @@ -1491,6 +1608,10 @@ impl NativeBackend { segments: &[Segment], buffers: &[vk::CommandBuffer], ) -> Result<()> { + if let Some(submitted) = submit_single_segment(&self.device, self.queue, segments, buffers) + { + return submitted; + } let bound: Vec> = segments .iter() .map(|segment| { diff --git a/crates/stela-driver-gpu/src/metal/native/objects.rs b/crates/stela-driver-gpu/src/metal/native/objects.rs index fbb74b5e88..615131d900 100644 --- a/crates/stela-driver-gpu/src/metal/native/objects.rs +++ b/crates/stela-driver-gpu/src/metal/native/objects.rs @@ -508,15 +508,14 @@ pub(super) fn image_to_memory( .image_extent(extent(region.extent)) } -/// Timeline waits or signals of a submission, at every stage. +/// A timeline wait or signal of a submission, at every stage. +pub(super) fn semaphore((semaphore, value): (Semaphore, u64)) -> vk::SemaphoreSubmitInfo<'static> { + vk::SemaphoreSubmitInfo::default() + .semaphore(handle(semaphore.0)) + .value(value) + .stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) +} + pub(super) fn semaphores(values: &[(Semaphore, u64)]) -> Vec> { - values - .iter() - .map(|&(semaphore, value)| { - vk::SemaphoreSubmitInfo::default() - .semaphore(handle(semaphore.0)) - .value(value) - .stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - }) - .collect() + values.iter().copied().map(semaphore).collect() } diff --git a/crates/stela-driver-gpu/src/metal/native/record.rs b/crates/stela-driver-gpu/src/metal/native/record.rs index 143da993ee..ba2e487c62 100644 --- a/crates/stela-driver-gpu/src/metal/native/record.rs +++ b/crates/stela-driver-gpu/src/metal/native/record.rs @@ -233,6 +233,24 @@ impl Recorder<'_> { /// Binds runs of buffers that all set, or all keep, their strides: /// `pStrides` covers every buffer of a call or none. fn bind_vertex_buffers(&self, first: u32, buffers: &[VertexBuffer]) { + if let [vertex] = buffers { + let handles = [handle(vertex.buffer.0)]; + let offsets = [vertex.offset]; + let sizes = [vertex.size]; + let strides = vertex.stride.as_ref().map(core::slice::from_ref); + // SAFETY: the buffer is alive with vertex-buffer usage. + unsafe { + self.device().cmd_bind_vertex_buffers2( + self.buffer, + first, + &handles, + &offsets, + Some(&sizes), + strides, + ); + } + return; + } let mut binding = first; for run in buffers.chunk_by(|a, b| a.stride.is_some() == b.stride.is_some()) { let handles: Vec = diff --git a/crates/stela-driver-gpu/src/metal/native/tests.rs b/crates/stela-driver-gpu/src/metal/native/tests.rs index 6c096d7772..fc3a8593e9 100644 --- a/crates/stela-driver-gpu/src/metal/native/tests.rs +++ b/crates/stela-driver-gpu/src/metal/native/tests.rs @@ -1,4 +1,4 @@ -use super::{failure, objects}; +use super::{CommandBuffers, InFlight, failure, objects}; use crate::metal::{ binding::HeapArray, error::Error, @@ -13,10 +13,48 @@ use crate::metal::{ }, }, }; -use alloc::vec; -use ash::vk; +use alloc::{collections::VecDeque, vec, vec::Vec}; +use ash::vk::{self, Handle}; mod lifecycle; +mod submission; + +#[test] +fn in_flight_retirement_observes_a_timeline_once_per_ready_run() { + let main = vk::Semaphore::from_raw(1); + let sparse_step = vk::Semaphore::from_raw(2); + let mut flights: VecDeque<_> = (1..=64) + .map(|value| InFlight { + timeline: main, + value, + buffers: CommandBuffers::One(vk::CommandBuffer::null()), + }) + .collect(); + flights.push_back(InFlight { + timeline: sparse_step, + value: 1, + buffers: CommandBuffers::One(vk::CommandBuffer::null()), + }); + let mut queries = Vec::new(); + assert_eq!( + InFlight::completed_prefix(&flights, |timeline| { + queries.push(timeline); + Ok(32) + }), + Ok(32), + ); + assert_eq!(queries, [main], "stop at the first unfinished submission"); + + queries.clear(); + assert_eq!( + InFlight::completed_prefix(&flights, |timeline| { + queries.push(timeline); + Ok(if timeline == main { 64 } else { 0 }) + }), + Ok(64), + ); + assert_eq!(queries, [main, sparse_step]); +} fn memory() -> crate::metal::vulkan::physical::Memory { nvk(Chip::find(0x1b3).unwrap(), 16 << 30).memory diff --git a/crates/stela-driver-gpu/src/metal/native/tests/lifecycle.rs b/crates/stela-driver-gpu/src/metal/native/tests/lifecycle.rs index 909ee15d24..44ef7d0fbf 100644 --- a/crates/stela-driver-gpu/src/metal/native/tests/lifecycle.rs +++ b/crates/stela-driver-gpu/src/metal/native/tests/lifecycle.rs @@ -3,6 +3,7 @@ use super::super::*; use crate::metal::nvidia::{Chip, fixture::nvk}; use alloc::sync::Arc; use core::{ + cell::Cell, ffi::c_void, sync::atomic::{AtomicUsize, Ordering}, }; @@ -117,7 +118,7 @@ unsafe extern "system" fn device_proc( None } -fn backend(calls: &Calls, drops: &Arc) -> NativeBackend { +fn backend(device: ash::Device, drops: &Arc) -> NativeBackend { // SAFETY: these tables have no GPU; only wait_device runs during Drop. // Missing destruction callbacks fail the test if Drop tries to free state. let (entry, instance) = unsafe { @@ -137,7 +138,6 @@ fn backend(calls: &Calls, drops: &Arc) -> NativeBackend { ), ) }; - let device = device(calls); let conditional = ext::conditional_rendering::Device::new(&instance, &device); NativeBackend { _entry: ManuallyDrop::new(entry), @@ -165,7 +165,7 @@ fn backend(calls: &Calls, drops: &Arc) -> NativeBackend { null_sampler: vk::Sampler::null(), layout: vk::PipelineLayout::null(), command_pool: vk::CommandPool::null(), - in_flight: Vec::new(), + in_flight: VecDeque::new(), mappings: BTreeMap::new(), exporter: ManuallyDrop::new(Box::new(Exporter(drops.clone()))), imports: BTreeMap::new(), @@ -188,7 +188,7 @@ fn failed_device_idle_keeps_the_export_owner() { frees: AtomicUsize::new(0), }; let drops = Arc::new(AtomicUsize::new(0)); - let backend = backend(&calls, &drops); + let backend = backend(device(&calls), &drops); drop(backend); assert_eq!(calls.waits.load(Ordering::Relaxed), 1); assert_eq!(calls.frees.load(Ordering::Relaxed), 0); @@ -211,7 +211,7 @@ fn idle_acknowledgement_requires_native_success_and_keeps_roots_owned() { frees: AtomicUsize::new(0), }; let drops = Arc::new(AtomicUsize::new(0)); - let mut backend = ManuallyDrop::new(backend(&calls, &drops)); + let mut backend = ManuallyDrop::new(backend(device(&calls), &drops)); assert_eq!(backend.acknowledge_idle(), expected); assert_eq!(calls.waits.load(Ordering::Relaxed), 1); assert_eq!(calls.frees.load(Ordering::Relaxed), 0); @@ -224,3 +224,144 @@ fn idle_acknowledgement_requires_native_success_and_keeps_roots_owned() { } } } + +struct BufferCalls { + status: Cell, + value: Cell, + allocated: Cell, + queries: Cell, + freed: Cell>, +} + +unsafe extern "system" fn allocate( + device: vk::Device, + info: *const vk::CommandBufferAllocateInfo<'_>, + output: *mut vk::CommandBuffer, +) -> vk::Result { + // SAFETY: the fixture owns the kept BufferCalls and Vulkan arguments. + let (calls, info) = unsafe { (&*(device.as_raw() as *const BufferCalls), &*info) }; + assert!(info.level == vk::CommandBufferLevel::PRIMARY); + assert_eq!(info.command_pool.as_raw(), 2); + if calls.status.get() == vk::Result::SUCCESS { + for index in 0..info.command_buffer_count { + let next = calls.allocated.get() + 1; + // SAFETY: the caller provides one writable handle per requested buffer. + unsafe { + output + .add(index as usize) + .write(vk::CommandBuffer::from_raw(next)) + }; + calls.allocated.set(next); + } + } + calls.status.get() +} + +unsafe extern "system" fn counter( + device: vk::Device, + _: vk::Semaphore, + value: *mut u64, +) -> vk::Result { + // SAFETY: the fixture owns the kept BufferCalls. + let calls = unsafe { &*(device.as_raw() as *const BufferCalls) }; + calls.queries.set(calls.queries.get() + 1); + // SAFETY: the caller provides a writable counter. + unsafe { value.write(calls.value.get()) }; + calls.status.get() +} + +unsafe extern "system" fn free_completed( + device: vk::Device, + pool: vk::CommandPool, + count: u32, + buffers: *const vk::CommandBuffer, +) { + // SAFETY: the fixture owns the kept BufferCalls and submitted handle array. + let (calls, buffers) = unsafe { + ( + &*(device.as_raw() as *const BufferCalls), + core::slice::from_raw_parts(buffers, count as usize), + ) + }; + assert_eq!(pool.as_raw(), 2); + let ordered = buffers + .iter() + .fold(0, |sum, buffer| sum * 10 + buffer.as_raw()); + assert!(calls.freed.replace(Some((count, ordered))).is_none()); +} + +#[test] +fn inline_and_owned_buffers_retire_once_in_queue_order() { + let calls = BufferCalls { + status: Cell::new(vk::Result::SUCCESS), + value: Cell::new(0), + allocated: Cell::new(0), + queries: Cell::new(0), + freed: Cell::new(None), + }; + // SAFETY: only these typed test callbacks are invoked and Calls stays live. + let device = unsafe { + ash::Device::load_with( + |name| match name.to_bytes() { + b"vkAllocateCommandBuffers" => allocate as *const c_void, + b"vkGetSemaphoreCounterValue" => counter as *const c_void, + b"vkFreeCommandBuffers" => free_completed as *const c_void, + _ => core::ptr::null(), + }, + vk::Device::from_raw(&calls as *const BufferCalls as u64), + ) + }; + let drops = Arc::new(AtomicUsize::new(0)); + let mut backend = ManuallyDrop::new(backend(device, &drops)); + backend.command_pool = vk::CommandPool::from_raw(2); + for (timeline, value, count) in [(7, 1, 1), (7, 2, 1), (7, 3, 2), (8, 4, 1)] { + let buffers = + CommandBuffers::allocate(&backend.device, backend.command_pool, count).unwrap(); + assert_eq!(buffers.as_slice().len(), count as usize); + backend.in_flight.push_back(InFlight { + buffers, + timeline: vk::Semaphore::from_raw(timeline), + value, + }); + } + calls.status.set(vk::Result::ERROR_DEVICE_LOST); + for count in [1, 2] { + assert!(matches!( + CommandBuffers::allocate(&backend.device, backend.command_pool, count), + Err(Error::DeviceLost), + )); + } + assert_eq!(backend.reclaim(), Err(Error::DeviceLost)); + assert_eq!( + backend.semaphore_value(Semaphore(7)), + Err(Error::DeviceLost) + ); + assert_eq!(backend.in_flight.len(), 4); + assert_eq!(calls.allocated.get(), 5); + assert_eq!(calls.freed.get(), None); + + calls.status.set(vk::Result::SUCCESS); + backend.reclaim().unwrap(); + assert_eq!(calls.freed.get(), None); + calls.value.set(4); + assert_eq!(backend.semaphore_value(Semaphore(8)), Ok(4)); + assert_eq!(calls.freed.get(), None); + assert_eq!(backend.in_flight.len(), 4); + calls.value.set(1); + backend.reclaim().unwrap(); + assert_eq!(calls.freed.replace(None), Some((1, 1))); + assert_eq!(backend.in_flight.len(), 3); + + calls.value.set(4); + assert_eq!(backend.semaphore_value(Semaphore(7)), Ok(4)); + assert_eq!(calls.freed.replace(None), Some((3, 234))); + assert_eq!(backend.in_flight.len(), 1); + assert_eq!(backend.semaphore_value(Semaphore(8)), Ok(4)); + assert_eq!(calls.freed.replace(None), Some((1, 5))); + assert!(backend.in_flight.is_empty()); + let queries = calls.queries.get(); + backend.reclaim().unwrap(); + assert_eq!(calls.queries.get(), queries); + // SAFETY: the fixture has no Vulkan resources and the list is empty. + unsafe { ManuallyDrop::drop(&mut backend.exporter) }; +} diff --git a/crates/stela-driver-gpu/src/metal/native/tests/submission.rs b/crates/stela-driver-gpu/src/metal/native/tests/submission.rs new file mode 100644 index 0000000000..f5b1252ade --- /dev/null +++ b/crates/stela-driver-gpu/src/metal/native/tests/submission.rs @@ -0,0 +1,166 @@ +use super::super::{Error, Segment, Semaphore, submit_single_segment}; +use crate::metal::vulkan::{command::SparseBind, object::Image}; +use alloc::vec; +use ash::vk::{self, Handle}; +use core::{cell::Cell, ffi::c_void}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Packet { + wait: Option<(u64, u64)>, + signal: Option<(u64, u64)>, + buffer: u64, +} + +struct Calls { + packet: Cell>, + result: vk::Result, +} + +unsafe extern "system" fn submit( + queue: vk::Queue, + count: u32, + infos: *const vk::SubmitInfo2<'_>, + fence: vk::Fence, +) -> vk::Result { + assert_eq!(count, 1); + assert_eq!(fence, vk::Fence::null()); + // SAFETY: the test uses its own kept Calls allocation for this queue. + let calls = unsafe { &*(queue.as_raw() as *const Calls) }; + // SAFETY: the one submitted packet stays live throughout this call. + let info = unsafe { &*infos }; + assert_eq!(info.command_buffer_info_count, 1); + assert!(info.flags.is_empty() && info.p_next.is_null()); + // SAFETY: the packet contains one live command-buffer record. + let buffer = unsafe { &*info.p_command_buffer_infos }; + assert_eq!(buffer.device_mask, 0); + let semaphore = |count: u32, info: *const vk::SemaphoreSubmitInfo<'_>| { + assert!(count <= 1); + (count == 1).then(|| { + // SAFETY: the nonempty record stays live throughout this call. + let info = unsafe { &*info }; + assert!(info.stage_mask == vk::PipelineStageFlags2::ALL_COMMANDS); + assert_eq!(info.device_index, 0); + (info.semaphore.as_raw(), info.value) + }) + }; + let previous = calls.packet.replace(Some(Packet { + wait: semaphore(info.wait_semaphore_info_count, info.p_wait_semaphore_infos), + signal: semaphore( + info.signal_semaphore_info_count, + info.p_signal_semaphore_infos, + ), + buffer: buffer.command_buffer.as_raw(), + })); + assert!(previous.is_none()); + calls.result +} + +fn device() -> ash::Device { + // SAFETY: the tests invoke only the typed submit callback. + unsafe { + ash::Device::load_with( + |name| match name.to_bytes() { + b"vkQueueSubmit2" => submit as *const c_void, + _ => core::ptr::null(), + }, + vk::Device::null(), + ) + } +} + +#[test] +fn single_segment_keeps_the_exact_vulkan_packet_and_error() { + let device = device(); + for wait in [None, Some((7, 20))] { + for signal in [None, Some((8, 50))] { + let segment = Segment { + waits: wait + .map(|(id, value)| (Semaphore(id), value)) + .into_iter() + .collect(), + signals: signal + .map(|(id, value)| (Semaphore(id), value)) + .into_iter() + .collect(), + ..Segment::default() + }; + for (result, outcome) in [ + (vk::Result::SUCCESS, Ok(())), + (vk::Result::ERROR_DEVICE_LOST, Err(Error::DeviceLost)), + ( + vk::Result::ERROR_OUT_OF_HOST_MEMORY, + Err(Error::OutOfMemory), + ), + ] { + let calls = Calls { + packet: Cell::new(None), + result, + }; + let queue = vk::Queue::from_raw(&calls as *const Calls as u64); + assert_eq!( + submit_single_segment( + &device, + queue, + core::slice::from_ref(&segment), + &[vk::CommandBuffer::from_raw(9)], + ), + Some(outcome), + ); + assert_eq!( + calls.packet.get(), + Some(Packet { + wait, + signal, + buffer: 9 + }) + ); + } + } + } +} + +#[test] +fn single_segment_leaves_complex_packets_to_batch_submission() { + let device = device(); + let calls = Calls { + packet: Cell::new(None), + result: vk::Result::SUCCESS, + }; + let queue = vk::Queue::from_raw(&calls as *const Calls as u64); + let buffer = vk::CommandBuffer::from_raw(9); + assert_eq!(submit_single_segment(&device, queue, &[], &[]), None); + assert_eq!( + submit_single_segment( + &device, + queue, + &[Segment::default(), Segment::default()], + &[buffer; 2], + ), + None, + ); + for segment in [ + Segment { + waits: vec![(Semaphore(7), 20), (Semaphore(8), 40)], + ..Segment::default() + }, + Segment { + signals: vec![(Semaphore(7), 20), (Semaphore(8), 40)], + ..Segment::default() + }, + Segment { + binds: vec![SparseBind::Opaque { + image: Image(10), + offset: 0, + size: 4096, + memory: None, + }], + ..Segment::default() + }, + ] { + assert_eq!( + submit_single_segment(&device, queue, &[segment], &[buffer]), + None + ); + } + assert!(calls.packet.get().is_none()); +} diff --git a/crates/stela-driver-gpu/src/metal/pixel_format.rs b/crates/stela-driver-gpu/src/metal/pixel_format.rs index fe0a0954aa..9f92fe6bf5 100644 --- a/crates/stela-driver-gpu/src/metal/pixel_format.rs +++ b/crates/stela-driver-gpu/src/metal/pixel_format.rs @@ -162,8 +162,33 @@ raw_enum! { Bgr10Xr = 554, Bgr10XrSrgb = 555, } + decode with decode_indexed; } +const RAW_COUNT: usize = { + let mut index = 0; + let mut max = 0; + while index < PixelFormat::ALL.len() { + let raw = PixelFormat::ALL[index].raw() as usize; + if raw > max { + max = raw; + } + index += 1; + } + max + 1 +}; + +static INDICES: [u8; RAW_COUNT] = { + assert!(PixelFormat::ALL.len() <= u8::MAX as usize + 1); + let mut indices = [0; RAW_COUNT]; + let mut index = 0; + while index < PixelFormat::ALL.len() { + indices[PixelFormat::ALL[index].raw() as usize] = index as u8; + index += 1; + } + indices +}; + /// How shaders read a color format's components. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Numeric { @@ -352,10 +377,18 @@ impl PixelFormat { } pub fn describe(self) -> &'static Description { - DESCRIPTIONS - .iter() - .find(|description| description.format == self) - .expect("every pixel format has a description") + &DESCRIPTIONS[self.index()] + } + + pub(super) fn index(self) -> usize { + usize::from(INDICES[self.raw() as usize]) + } + + fn decode_indexed(raw: u64) -> Option { + let index = *INDICES.get(usize::try_from(raw).ok()?)?; + let format = Self::ALL[usize::from(index)]; + // Holes contain the first format's index, so check its raw value. + (format.raw() == raw).then_some(format) } } @@ -813,6 +846,15 @@ static DESCRIPTIONS: &[Description] = &[ unrealized(P::Bgr10XrSrgb, true, 4, Unrealized::ExtendedRange), ]; +const _: () = { + assert!(DESCRIPTIONS.len() == PixelFormat::ALL.len()); + let mut index = 0; + while index < DESCRIPTIONS.len() { + assert!(DESCRIPTIONS[index].format.raw() == PixelFormat::ALL[index].raw()); + index += 1; + } +}; + #[cfg(test)] mod tests { use super::*; @@ -827,11 +869,12 @@ mod tests { #[test] fn raw_values_round_trip_and_placeholders_are_refused() { - for format in PixelFormat::ALL { - assert_eq!(PixelFormat::from_raw(format.raw()), Some(*format)); - } - for raw in [0, 2, 21, 44, 191, 263, 556] { - assert_eq!(PixelFormat::from_raw(raw), None, "{raw}"); + for raw in (0..=RAW_COUNT as u64).chain([(1 << 32) + 1, u64::MAX]) { + let listed = PixelFormat::ALL + .iter() + .copied() + .find(|format| format.raw() == raw); + assert_eq!(PixelFormat::from_raw(raw), listed, "{raw}"); } } diff --git a/crates/stela-driver-gpu/src/metal/shader.rs b/crates/stela-driver-gpu/src/metal/shader.rs index 28894f7c23..6e3ae363c4 100644 --- a/crates/stela-driver-gpu/src/metal/shader.rs +++ b/crates/stela-driver-gpu/src/metal/shader.rs @@ -452,6 +452,22 @@ pub struct Provenance { pub entry: String, } +/// A specialized function and the reflection of its exact AIR input. +#[derive(Debug)] +pub struct PreparedFunction { + pub(crate) library: u64, + pub(crate) constants: Vec<(u32, Vec)>, + pub(crate) reflection: Reflection, + pub(crate) provenance: Provenance, + pub(crate) reflection_service: Option, +} + +impl PreparedFunction { + pub(crate) fn entry(&self) -> &str { + &self.provenance.entry + } +} + /// A function compiled for a pipeline stage. #[derive(Clone, Debug, Eq, PartialEq)] pub struct CompiledShader { @@ -631,6 +647,30 @@ pub trait Compiler { specialization: &Specialization, ) -> Result; + /// Reflects a specialized function for later pipeline compilation. + fn prepare_function( + &mut self, + library: u64, + entry: &str, + constants: Vec<(u32, Vec)>, + ) -> Result { + let specialization = Specialization { + constants, + ..Specialization::default() + }; + let reflection = self.reflect(library, entry, &specialization)?; + Ok(PreparedFunction { + library, + constants: specialization.constants, + reflection, + provenance: Provenance { + entry: String::from(entry), + ..Provenance::default() + }, + reflection_service: None, + }) + } + /// The function constants `entry` of `library` declares, before any has /// a value. fn constants(&mut self, library: u64, entry: &str) -> Result>; @@ -681,6 +721,30 @@ pub trait Compiler { tessellation: &Tessellation, ) -> Result; + /// Compiles a function whose specialized reflection is already available. + fn compile_prepared( + &mut self, + function: &PreparedFunction, + specialization: &Specialization, + ) -> Result { + self.compile(function.library, function.entry(), specialization) + } + + /// Compiles a prepared patch function with its preceding stages. + fn compile_prepared_tessellation( + &mut self, + function: &PreparedFunction, + specialization: &Specialization, + tessellation: &Tessellation, + ) -> Result { + self.compile_tessellation( + function.library, + function.entry(), + specialization, + tessellation, + ) + } + /// Releases a compiled function's NIR. fn release(&mut self, code: ShaderCode); } diff --git a/crates/stela-driver-gpu/src/metal/upload.rs b/crates/stela-driver-gpu/src/metal/upload.rs index 26736c27a5..379e6bee2e 100644 --- a/crates/stela-driver-gpu/src/metal/upload.rs +++ b/crates/stela-driver-gpu/src/metal/upload.rs @@ -51,8 +51,32 @@ impl UploadArena { bytes: &[u8], alignment: u64, ) -> Result { + let (upload, data) = self.reserve(source, bytes.len(), alignment)?; + data.extend_from_slice(bytes); + Ok(upload) + } + + /// Appends storage for a payload encoded directly into the arena. + pub(super) fn zeroed( + &mut self, + source: &mut dyn ChunkSource, + length: usize, + alignment: u64, + ) -> Result<(Upload, &mut [u8])> { + let (upload, data) = self.reserve(source, length, alignment)?; + let start = data.len(); + data.resize(start + length, 0); + Ok((upload, &mut data[start..])) + } + + fn reserve( + &mut self, + source: &mut dyn ChunkSource, + length: usize, + alignment: u64, + ) -> Result<(Upload, &mut Vec)> { debug_assert!(alignment.is_power_of_two()); - let length = bytes.len() as u64; + let length = length as u64; let fits = |(chunk, data): &(Chunk, Vec)| { let offset = (data.len() as u64).next_multiple_of(alignment); (offset + length <= chunk.size).then_some(offset) @@ -70,12 +94,14 @@ impl UploadArena { }; let (chunk, data) = self.chunks.last_mut().expect("a chunk was just ensured"); data.resize(offset as usize, 0); - data.extend_from_slice(bytes); - Ok(Upload { - buffer: chunk.buffer, - offset, - address: chunk.address + offset, - }) + Ok(( + Upload { + buffer: chunk.buffer, + offset, + address: chunk.address + offset, + }, + data, + )) } /// The chunks and the bytes to copy into each before submission. @@ -109,7 +135,9 @@ mod tests { let mut pool = Pool::default(); let mut arena = UploadArena::default(); let first = arena.write(&mut pool, &[1; 10], 16).unwrap(); - let second = arena.write(&mut pool, &[2; 4], 16).unwrap(); + let (second, payload) = arena.zeroed(&mut pool, 4, 16).unwrap(); + assert_eq!(payload, &[0; 4]); + payload.fill(2); assert_eq!((first.offset, second.offset), (0, 16)); assert_eq!(second.address, (1 << 32) + 16); let big = arena diff --git a/crates/stela-driver-storage/src/nvme.rs b/crates/stela-driver-storage/src/nvme.rs index c6d1e3c359..55c4755174 100644 --- a/crates/stela-driver-storage/src/nvme.rs +++ b/crates/stela-driver-storage/src/nvme.rs @@ -374,6 +374,12 @@ impl Queue { self.consumed = 0; } + /// The next position after an already validated index. + fn next(&self, slot: u16) -> u16 { + let next = slot + 1; + if next == self.entries { 0 } else { next } + } + /// Whether a reported submission head lies no earlier than the last /// one and no further than the tail, in ring order: commands fetched /// together may complete reporting the same head. @@ -391,7 +397,11 @@ impl Queue { /// How many entries `to` lies after `from`, in ring order. fn ahead(&self, from: u16, to: u16) -> u16 { - (to + self.entries - from) % self.entries + if to >= from { + to - from + } else { + self.entries - (from - to) + } } } @@ -574,6 +584,10 @@ struct Controller { prp_list: Buffer, /// Tags 1 and up's bounce memory. slots: Vec, + /// Initialized PRP list prefix per tag, counted in bounce pages including + /// the first page that travels in the command. The bounce mappings stay + /// fixed and the controller only reads the lists, including across reset. + prp_pages: [usize; DEPTH], tags: Vec, recovery: Option, /// The I/O completion queue raises MSI-X vector 0, which the host @@ -749,6 +763,7 @@ pub fn attach( bounce: Buffer::Legacy(dma.allocate(BOUNCE_BYTES, PAGE)?), prp_list: Buffer::Legacy(dma.allocate(PAGE, PAGE)?), slots, + prp_pages: [1; DEPTH], tags: (0..DEPTH).map(|_| Tag::Free).collect(), recovery: None, signalled, diff --git a/crates/stela-driver-storage/src/nvme/io.rs b/crates/stela-driver-storage/src/nvme/io.rs index f3c9497884..5e9b0ac783 100644 --- a/crates/stela-driver-storage/src/nvme/io.rs +++ b/crates/stela-driver-storage/src/nvme/io.rs @@ -47,7 +47,7 @@ impl Controller { pub(super) fn publish( &mut self, io: bool, - command: [u32; 16], + mut command: [u32; 16], tag: Option, ) -> Result { let stride = self.doorbell_stride; @@ -70,18 +70,10 @@ impl Controller { // than the queue holds. unsafe { queue.submissions.resume_writes() }; let base = usize::from(queue.tail) * 64; - for (index, word) in command.iter().enumerate() { - queue.submissions.write( - base + 4 * index, - if index == 0 { - word | u32::from(id) << 16 - } else { - *word - }, - ); - } + command[0] |= u32::from(id) << 16; + queue.submissions.write_submission(base, command); queue.submissions.give()?; - queue.tail = (queue.tail + 1) % queue.entries; + queue.tail = queue.next(queue.tail); fence(Ordering::SeqCst); registers.write32( DOORBELLS + 2 * usize::from(queue.id) * stride, @@ -113,7 +105,7 @@ impl Controller { return Err(BlockError::Device { status: 0xffff }); } queue.consumed = head; - queue.head = (queue.head + 1) % queue.entries; + queue.head = queue.next(queue.head); if queue.head == 0 { queue.phase = !queue.phase; } @@ -518,7 +510,11 @@ impl Controller { /// Tag `tag`'s result once its command completed; never waits. pub(super) fn finish(&mut self, tag: usize) -> Option { - self.advance(); + // An earlier poll can reap several completions. Only a tag whose + // result is still pending needs another pass over the queues. + if !matches!(self.tags.get(tag), Some(Tag::Done(_))) { + self.advance(); + } if !matches!(self.tags.get(tag)?, Tag::Done(_)) { return None; } @@ -534,16 +530,19 @@ impl Controller { tag: usize, bytes: usize, ) -> Result<(u64, u64), BlockError> { + let initialized = self.prp_pages[tag]; let (bounce, prp_list) = self.slot(tag); let first = bounce.address()?; match bytes.div_ceil(PAGE) { 0 | 1 => Ok((first, 0)), 2 => Ok((first, first + PAGE as u64)), pages => { - for page in 1..pages { + let second = prp_list.address()?; + for page in initialized..pages { prp_list.write(8 * (page - 1), first + (page * PAGE) as u64); } - Ok((first, prp_list.address()?)) + self.prp_pages[tag] = initialized.max(pages); + Ok((first, second)) } } } diff --git a/crates/stela-driver-storage/src/nvme/owned.rs b/crates/stela-driver-storage/src/nvme/owned.rs index a688358e22..020f02434f 100644 --- a/crates/stela-driver-storage/src/nvme/owned.rs +++ b/crates/stela-driver-storage/src/nvme/owned.rs @@ -283,6 +283,16 @@ impl Buffer { // SAFETY: complete aligned span in uniquely CPU-owned memory. unsafe { ptr::write_volatile(p, value) }; } + /// Write a whole submission entry through one checked CPU view. The + /// caller publishes it only after all words are written. + pub(super) fn write_submission(&mut self, offset: usize, words: [u32; 16]) { + let entry = &mut self.bytes_mut()[offset..][..size_of_val(&words)]; + let pointer = entry.as_mut_ptr().cast::<[u32; 16]>(); + assert!(pointer.is_aligned()); + // SAFETY: bounds and alignment were checked for the complete array. + // The queue granted CPU ownership of this entry until publication. + unsafe { pointer.write_volatile(words) }; + } pub(super) fn coherent(&self, offset: usize) -> Result { match self { Self::Legacy(b) => Ok(b.read(offset)), @@ -443,6 +453,7 @@ unsafe fn attach_with_timeout( prp_list: Buffer::Empty, // The DMA domain's buffers change hands whole: one command at a time. slots: alloc::vec::Vec::new(), + prp_pages: [1; DEPTH], tags: alloc::vec![Tag::Free], recovery: None, signalled: false, diff --git a/crates/stela-driver-storage/src/nvme/owned/tests.rs b/crates/stela-driver-storage/src/nvme/owned/tests.rs index 198935462e..46fd6e35c9 100644 --- a/crates/stela-driver-storage/src/nvme/owned/tests.rs +++ b/crates/stela-driver-storage/src/nvme/owned/tests.rs @@ -860,7 +860,7 @@ impl Fixture { } #[test] -fn owned_protocol_initializes_identifies_transfers_prps_wraps_and_retires() { +fn owned_protocol_reuses_prps_across_reset_then_wraps_and_retires() { let f = Fixture::new(); let mut attached = f.attach().unwrap(); assert!(attached.failures.is_empty()); @@ -875,10 +875,23 @@ fn owned_protocol_initializes_identifies_transfers_prps_wraps_and_retires() { let mut read = vec![0; pattern.len()]; disk.read(8, &mut read).unwrap(); assert_eq!(read, pattern); + let (before, mappings) = { + let mut m = f.model.lock().unwrap(); + m.fatal = true; + ( + m.events.len(), + m.maps.values().map(|lease| lease.token).collect::>(), + ) + }; let replacement: Vec = pattern.iter().map(|byte| byte ^ 0xa5).collect(); disk.write(8, &replacement).unwrap(); disk.read(8, &mut read).unwrap(); assert_eq!(read, replacement); + { + let m = f.model.lock().unwrap(); + assert!(m.events[before..].contains(&"drain")); + assert!(m.maps.values().map(|lease| lease.token).eq(mappings)); + } for _ in 0..35 { disk.flush().unwrap(); } diff --git a/crates/stela-driver-storage/src/nvme/tests.rs b/crates/stela-driver-storage/src/nvme/tests.rs index a17a893ae0..6d50569d77 100644 --- a/crates/stela-driver-storage/src/nvme/tests.rs +++ b/crates/stela-driver-storage/src/nvme/tests.rs @@ -26,7 +26,7 @@ impl Fixture { }; let slots = (1..DEPTH) .map(|_| Slot { - bounce: Buffer::Legacy(dma.allocate(PAGE, PAGE).unwrap()), + bounce: Buffer::Legacy(dma.allocate(4 * PAGE, PAGE).unwrap()), prp_list: Buffer::Legacy(dma.allocate(PAGE, PAGE).unwrap()), }) .collect(); @@ -38,6 +38,7 @@ impl Fixture { bounce: Buffer::Legacy(dma.allocate(BOUNCE_BYTES, PAGE).unwrap()), prp_list: Buffer::Legacy(dma.allocate(PAGE, PAGE).unwrap()), slots, + prp_pages: [1; DEPTH], tags: (0..DEPTH).map(|_| Tag::Free).collect(), recovery: None, signalled: false, @@ -350,6 +351,79 @@ fn running_id(controller: &Controller, tag: u32) -> u16 { } } +#[test] +fn submission_publication_keeps_the_whole_wire_entry_and_rings_its_queue() { + let fixture = Fixture::new(); + let mut controller = fixture.disk.controller.borrow_mut(); + for io in [false, true] { + let mut words = core::array::from_fn(|index| 0x1020_3040 + index as u32 * 0x0101_0101); + words[0] &= 0xffff; + let id = controller.publish(io, words, None).unwrap(); + words[0] |= u32::from(id) << 16; + let queue = if io { + &controller.io + } else { + &controller.admin + }; + let expected = words.map(u32::to_le_bytes).concat(); + assert_eq!(&queue.submissions.bytes()[..64], &expected); + assert_eq!(&queue.submissions.bytes()[64..128], &[0; 64]); + let doorbell = DOORBELLS + 2 * usize::from(queue.id) * controller.doorbell_stride; + assert_eq!(controller.registers.read32(doorbell), Ok(1)); + } +} + +#[test] +fn prp_list_prefixes_follow_each_bounce_mapping_and_only_grow() { + let mut fixture = Fixture::new(); + let disk = &mut fixture.disk; + let submit = |disk: &mut Namespace, pages| { + disk.start(Command::Read { + lba: 0, + bytes: pages * PAGE, + }) + .unwrap() + }; + let check = |disk: &Namespace, tag: u32, pages| { + let mut controller = disk.controller.borrow_mut(); + let tag = tag as usize; + assert_eq!(controller.prp_pages[tag], pages); + let (bounce, list) = controller.slot(tag); + let base = bounce.address().unwrap(); + for page in 1..=pages { + let start = (page - 1) * 8; + let entry = u64::from_le_bytes(list.bytes()[start..start + 8].try_into().unwrap()); + let expected = if page < pages { + base + (page * PAGE) as u64 + } else { + 0 + }; + assert_eq!(entry, expected); + } + base + }; + let complete = |disk: &mut Namespace, tag| { + { + let mut controller = disk.controller.borrow_mut(); + let id = running_id(&controller, tag); + post(&mut controller, id, 0); + } + assert!(matches!(disk.finish(tag), Some(Ok(Some(_))))); + }; + let first = submit(disk, 3); + let second = submit(disk, 4); + let base = check(disk, first, 3); + assert_ne!(check(disk, second, 4), base); + complete(disk, first); + assert_eq!(submit(disk, 2), first); + assert_eq!(check(disk, first, 3), base); + complete(disk, first); + assert_eq!(submit(disk, 5), first); + assert_eq!(check(disk, first, 5), base); + complete(disk, second); + complete(disk, first); +} + #[test] fn queued_commands_run_together_and_complete_in_any_order() { let mut fixture = Fixture::new(); @@ -401,6 +475,28 @@ fn queued_commands_run_together_and_complete_in_any_order() { assert!(disk.start(Command::Flush).is_err()); } +#[test] +fn taking_a_ready_result_leaves_live_deadlines_to_their_poll() { + let _clock = crate::test_clock::virtualize(); + let mut fixture = Fixture::new(); + let disk = &mut fixture.disk; + let done = disk.start(Command::Flush).unwrap(); + let live = disk.start(Command::Flush).unwrap(); + let clock = { + let mut controller = disk.controller.borrow_mut(); + let id = running_id(&controller, done); + post(&mut controller, id, 0); + controller.advance(); + controller.clock + }; + crate::test_clock::advance(clock, 1000); + + assert_eq!(disk.finish(done), Some(Ok(None))); + assert!(disk.controller.borrow().aborts.is_empty()); + assert_eq!(disk.finish(live), None); + assert_eq!(disk.controller.borrow().aborts.len(), 1); +} + #[test] fn delayed_read_completes_after_submission_ring_wraps() { let _clock = crate::test_clock::virtualize(); diff --git a/crates/stela-drivers/src/minimum_model.rs b/crates/stela-drivers/src/minimum_model.rs index cd52a448f2..ff1e3dcf84 100644 --- a/crates/stela-drivers/src/minimum_model.rs +++ b/crates/stela-drivers/src/minimum_model.rs @@ -2,11 +2,11 @@ //! This module is compiled only for tests and creates no native timing permit. extern crate std; use crate::{ - Clock, - bus::pci::power::{Error, Timer}, + Clock, Deadline, + bus::pci::power::{Error, Interval, Timer}, test_clock, }; -use alloc::rc::Rc; +use alloc::{boxed::Box, rc::Rc}; use std::thread::{self, ThreadId}; struct Minimum { _clock: test_clock::Guard, @@ -14,6 +14,19 @@ struct Minimum { scale: Clock, refused: bool, } +struct ModelInterval { + _clock: test_clock::Guard, + owner: ThreadId, + deadline: Deadline, +} +impl Interval for ModelInterval { + fn elapsed(&self) -> Result { + if thread::current().id() != self.owner { + return Err(Error::Clock); + } + Ok(self.deadline.passed()) + } +} // SAFETY: this test-only producer owns its actual thread-local virtual clock // guard. Waits advance that same fixture clock; no physical device is admitted. unsafe impl Timer for Minimum { @@ -31,6 +44,18 @@ unsafe impl Timer for Minimum { test_clock::advance(self.scale, microseconds); Ok(()) } + fn begin_interval(&self, microseconds: u64) -> Result>, Error> { + self.check()?; + let deadline = self + .scale + .try_deadline(microseconds) + .map_err(|_| Error::Clock)?; + Ok(Some(Box::new(ModelInterval { + _clock: test_clock::virtualize(), + owner: self.owner, + deadline, + }))) + } } pub(crate) fn owned(scale: Clock) -> Rc { Rc::new(Minimum { diff --git a/crates/stela-drivers/src/usb/storage.rs b/crates/stela-drivers/src/usb/storage.rs index 98828f6b90..d296444e7c 100644 --- a/crates/stela-drivers/src/usb/storage.rs +++ b/crates/stela-drivers/src/usb/storage.rs @@ -14,7 +14,9 @@ use crate::{ }, bus::dma::DmaAllocator, }; -use alloc::{format, rc::Rc, string::String, vec, vec::Vec}; +#[cfg(test)] +use alloc::vec; +use alloc::{format, rc::Rc, string::String, vec::Vec}; use core::cell::{Cell, RefCell}; mod media; pub use media::UsbStorage; @@ -964,7 +966,10 @@ impl Disk { Command::Write { fua, .. } => (true, *fua), _ => (false, false), }; - (self.cdb(write, fua, at, (length / size) as u32), length) + ( + scsi::read_write(write, fua, at, (length / size) as u32), + length, + ) } Command::Read { .. } | Command::Write { .. } => { let running = self.running.as_mut().unwrap(); @@ -973,7 +978,7 @@ impl Disk { running.result = Some(Ok(read.then_some(data))); return; } - Command::Flush if running.done == 0 => (scsi::synchronize_cache().to_vec(), 0), + Command::Flush if running.done == 0 => (scsi::Cdb::Ten(scsi::synchronize_cache()), 0), Command::Flush => { self.running.as_mut().unwrap().result = Some(Ok(None)); return; @@ -987,13 +992,14 @@ impl Disk { let begun = { let running = self.running.as_ref().unwrap(); let mut bot = self.bot.borrow_mut(); + let cdb = cdb.as_ref(); match &running.command { Command::Write { data, .. } => { let part = &data[running.done..running.done + length]; - bot.begin(self.lun, &cdb, Data::Out(part)) + bot.begin(self.lun, cdb, Data::Out(part)) } - Command::Read { .. } => bot.begin(self.lun, &cdb, Data::In(length)), - _ => bot.begin(self.lun, &cdb, Data::None), + Command::Read { .. } => bot.begin(self.lun, cdb, Data::In(length)), + _ => bot.begin(self.lun, cdb, Data::None), } }; let running = self.running.as_mut().unwrap(); @@ -1028,36 +1034,12 @@ impl Disk { let (chunk, rest) = remaining.split_at(length); remaining = rest; let blocks = (chunk.len() / size) as u32; - let cdb = self.cdb(true, fua, lba, blocks); - self.io(&cdb, Data::Out(chunk))?; + let cdb = scsi::read_write(true, fua, lba, blocks); + self.io(cdb.as_ref(), Data::Out(chunk))?; lba += u64::from(blocks); } Ok(()) } - - /// READ or WRITE of `blocks` at `lba`, (10) when it fits, else (16), - /// with Force Unit Access when `fua`. - fn cdb(&self, write: bool, fua: bool, lba: u64, blocks: u32) -> Vec { - let flags = if fua { scsi::FUA } else { 0 }; - if lba - .checked_add(u64::from(blocks)) - .is_some_and(|end| end <= u64::from(u32::MAX) + 1) - && blocks <= u32::from(u16::MAX) - { - let mut cdb = vec![if write { scsi::WRITE_10 } else { scsi::READ_10 }, flags]; - cdb.extend_from_slice(&(lba as u32).to_be_bytes()); - cdb.push(0); - cdb.extend_from_slice(&(blocks as u16).to_be_bytes()); - cdb.push(0); - cdb - } else { - let mut cdb = vec![if write { scsi::WRITE_16 } else { scsi::READ_16 }, flags]; - cdb.extend_from_slice(&lba.to_be_bytes()); - cdb.extend_from_slice(&blocks.to_be_bytes()); - cdb.extend_from_slice(&[0, 0]); - cdb - } - } } impl BlockDevice for Disk { fn identity(&self) -> &Identity { @@ -1086,8 +1068,8 @@ impl BlockDevice for Disk { let (chunk, rest) = remaining.split_at_mut(length); remaining = rest; let blocks = (chunk.len() / size) as u32; - let cdb = self.cdb(false, false, lba, blocks); - let data = self.io(&cdb, Data::In(chunk.len()))?; + let cdb = scsi::read_write(false, false, lba, blocks); + let data = self.io(cdb.as_ref(), Data::In(chunk.len()))?; if data.len() != chunk.len() { return Err(BlockError::Protocol("short USB storage read")); } diff --git a/crates/stela-drivers/src/usb/storage/bot.rs b/crates/stela-drivers/src/usb/storage/bot.rs index f05b48c478..7ad4f52216 100644 --- a/crates/stela-drivers/src/usb/storage/bot.rs +++ b/crates/stela-drivers/src/usb/storage/bot.rs @@ -151,12 +151,10 @@ impl Io for Native { .is_ok_and(|controller| controller.posted_for(self.id)) } fn ready(&mut self) -> Result<(), BlockError> { - let mut controller = self.controller.borrow_mut(); - let mut device = controller.device(self.id)?; - for dci in [1, self.endpoints[0].dci(), self.endpoints[1].dci()] { - device.endpoint_ready(dci)?; - } - Ok(()) + self.controller + .borrow_mut() + .device(self.id)? + .endpoints_ready(&[1, self.endpoints[0].dci(), self.endpoints[1].dci()]) } fn control(&mut self, request: [u8; 8]) -> Result, BlockError> { self.controller @@ -351,7 +349,7 @@ pub(super) struct Bot { /// none waited for ([`Bot::begin`]). struct Begun { lun: u8, - cdb: Vec, + opcode: u8, is_in: bool, length: usize, out: Option>, @@ -764,7 +762,7 @@ impl Bot { }; self.begun = Some(Begun { lun, - cdb: cdb.to_vec(), + opcode: cdb[0], is_in, length, out, @@ -819,14 +817,14 @@ impl Bot { } None => {} } - let (lun, cdb) = (begun.lun, &begun.cdb); + let (lun, opcode) = (begun.lun, begun.opcode); // SCSI auto-sense must use the failing command's LUN, and cannot race // a different unit's command while the interface is borrowed. let sensing = if result == Err(BlockError::CheckCondition) { - (cdb[0] != scsi::REQUEST_SENSE).then_some(Sensing::Failed) + (opcode != scsi::REQUEST_SENSE).then_some(Sensing::Failed) } else { (result.is_ok() - && cdb.first() == Some(&scsi::SYNCHRONIZE_CACHE_10) + && opcode == scsi::SYNCHRONIZE_CACHE_10 && self.flags.sense_after_sync()) .then_some(Sensing::Synchronized) }; @@ -975,7 +973,7 @@ impl Bot { /// The command's result from its CSW. fn conclude(&mut self, begun: &mut Begun) -> Result, BlockError> { - let (cdb, is_in, length, moved) = (&begun.cdb, begun.is_in, begun.length, begun.moved); + let (opcode, is_in, length, moved) = (begun.opcode, begun.is_in, begun.length, begun.moved); let mut received = core::mem::take(&mut begun.received); let bytes = &self.wrapper.bytes()[..13]; let residue = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize; @@ -998,8 +996,8 @@ impl Bot { if is_in && moved == length && residue != 0 - && ((cdb[0] == scsi::INQUIRY && length == 36) - || (cdb[0] == scsi::READ_CAPACITY_10 && length == 8)) + && ((opcode == scsi::INQUIRY && length == 36) + || (opcode == scsi::READ_CAPACITY_10 && length == 8)) { self.flags.learn_residue(); } diff --git a/crates/stela-drivers/src/usb/storage/bot/tests.rs b/crates/stela-drivers/src/usb/storage/bot/tests.rs index e79e47c886..e93188a0c5 100644 --- a/crates/stela-drivers/src/usb/storage/bot/tests.rs +++ b/crates/stela-drivers/src/usb/storage/bot/tests.rs @@ -1235,9 +1235,18 @@ fn real_block_api_chunks_units_checks_bounds_and_never_copies_short_reads() { let mut untouched = [0xa5; 512]; assert!(disks[0].read(0, &mut untouched).is_err()); assert_eq!(untouched, [0xa5; 512]); - assert_eq!(disks[0].cdb(false, false, u32::MAX as u64, 1)[0], 0x28); - assert_eq!(disks[0].cdb(false, false, u32::MAX as u64, 2)[0], 0x88); - assert_eq!(disks[0].cdb(true, false, 1u64 << 32, 1)[0], 0x8a); + assert_eq!( + scsi::read_write(false, false, u32::MAX as u64, 1).as_ref()[0], + 0x28 + ); + assert_eq!( + scsi::read_write(false, false, u32::MAX as u64, 2).as_ref()[0], + 0x88 + ); + assert_eq!( + scsi::read_write(true, false, 1u64 << 32, 1).as_ref()[0], + 0x8a + ); } #[test] diff --git a/crates/stela-drivers/src/usb/storage/scsi.rs b/crates/stela-drivers/src/usb/storage/scsi.rs index 8e89ad9dff..65ef5e5e00 100644 --- a/crates/stela-drivers/src/usb/storage/scsi.rs +++ b/crates/stela-drivers/src/usb/storage/scsi.rs @@ -39,6 +39,45 @@ const DPOFUA: u8 = 0x10; /// READ/WRITE (10) and (16) byte 1: Force Unit Access. pub(super) const FUA: u8 = 0x08; +pub(super) enum Cdb { + Ten([u8; 10]), + Sixteen([u8; 16]), +} + +impl AsRef<[u8]> for Cdb { + fn as_ref(&self) -> &[u8] { + match self { + Self::Ten(bytes) => bytes, + Self::Sixteen(bytes) => bytes, + } + } +} + +/// READ or WRITE of `blocks` at `lba`, (10) when it fits, else (16), +/// with Force Unit Access when `fua`. +pub(super) fn read_write(write: bool, fua: bool, lba: u64, blocks: u32) -> Cdb { + let flags = if fua { FUA } else { 0 }; + if lba + .checked_add(u64::from(blocks)) + .is_some_and(|end| end <= u64::from(u32::MAX) + 1) + && blocks <= u32::from(u16::MAX) + { + let mut cdb = [0; 10]; + cdb[0] = if write { WRITE_10 } else { READ_10 }; + cdb[1] = flags; + cdb[2..6].copy_from_slice(&(lba as u32).to_be_bytes()); + cdb[7..9].copy_from_slice(&(blocks as u16).to_be_bytes()); + Cdb::Ten(cdb) + } else { + let mut cdb = [0; 16]; + cdb[0] = if write { WRITE_16 } else { READ_16 }; + cdb[1] = flags; + cdb[2..10].copy_from_slice(&lba.to_be_bytes()); + cdb[10..14].copy_from_slice(&blocks.to_be_bytes()); + Cdb::Sixteen(cdb) + } +} + pub(super) fn request_sense() -> [u8; 6] { [REQUEST_SENSE, 0, 0, 0, SENSE_BYTES as u8, 0] } @@ -87,6 +126,25 @@ pub(super) fn write_cache_enabled(mode: &[u8]) -> Option { mod tests { use super::*; + #[test] + fn read_write_commands_keep_wire_width_lba_count_and_fua() { + let last = u64::from(u32::MAX); + assert_eq!( + read_write(false, false, last, 1).as_ref(), + &[READ_10, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 1, 0] + ); + assert_eq!( + read_write(true, true, last, 2).as_ref(), + &[ + WRITE_16, FUA, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 2, 0, 0 + ] + ); + assert_eq!( + read_write(true, false, 17, 0x1_0000).as_ref(), + &[WRITE_16, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 1, 0, 0, 0, 0] + ); + } + #[test] fn mode_data_yields_write_protection_and_the_write_cache() { assert_eq!(write_protected(&[3, 0, 0x80, 0]), Some(true)); diff --git a/crates/stela-drivers/src/usb/storage/uas.rs b/crates/stela-drivers/src/usb/storage/uas.rs index c2e555c740..ff74a62e46 100644 --- a/crates/stela-drivers/src/usb/storage/uas.rs +++ b/crates/stela-drivers/src/usb/storage/uas.rs @@ -522,13 +522,11 @@ impl Io for Native { .is_ok_and(|controller| controller.posted_for(self.id)) } fn ready(&mut self) -> Result<(), BlockError> { - let mut controller = self.controller.borrow_mut(); - let mut device = controller.device(self.id)?; - device.endpoint_ready(1)?; - for endpoint in self.endpoints { - device.endpoint_ready(endpoint.dci())?; - } - Ok(()) + let [command, status, input, output] = self.endpoints; + self.controller + .borrow_mut() + .device(self.id)? + .endpoints_ready(&[1, command.dci(), status.dci(), input.dci(), output.dci()]) } fn streams(&self) -> Option { self.streams diff --git a/crates/stela-drivers/src/usb/xhci/enumerate.rs b/crates/stela-drivers/src/usb/xhci/enumerate.rs index ba6d768f40..8a4a40b621 100644 --- a/crates/stela-drivers/src/usb/xhci/enumerate.rs +++ b/crates/stela-drivers/src/usb/xhci/enumerate.rs @@ -17,19 +17,12 @@ fn debounce_with_delay( mut sample: impl FnMut() -> Result<(bool, bool), BlockError>, mut delay: impl FnMut() -> Result<(), BlockError>, ) -> Result { - let mut connection = None; - let mut stable = 0; + let mut debounce = Debounce::default(); let mut total = 0; loop { let (connected, changed) = sample()?; - if !changed && connection == Some(connected) { - stable += DEBOUNCE_STEP_US; - if stable >= DEBOUNCE_STABLE_US { - return Ok(connected); - } - } else { - stable = 0; - connection = Some(connected); + if let Some(connected) = debounce.observe(connected, changed) { + return Ok(connected); } if total >= DEBOUNCE_TIMEOUT_US { return Err(BlockError::Unsupported("USB port connection never settled")); @@ -39,6 +32,34 @@ fn debounce_with_delay( } } +#[derive(Default)] +pub(super) struct Debounce { + connection: Option, + stable: u64, +} + +impl Debounce { + /// A notification between timed samples can invalidate stability, but + /// cannot contribute a sample to the interval. + pub(super) fn restart_on_change(&mut self, connected: bool, changed: bool) -> bool { + if !changed && self.connection == Some(connected) { + return false; + } + self.stable = 0; + self.connection = Some(connected); + true + } + + /// Timed observations are at least one debounce step apart. + pub(super) fn observe(&mut self, connected: bool, changed: bool) -> Option { + if self.restart_on_change(connected, changed) { + return None; + } + self.stable += DEBOUNCE_STEP_US; + (self.stable >= DEBOUNCE_STABLE_US).then_some(connected) + } +} + /// The status change endpoint of a hub's interface in `alternate`. pub(super) fn hub_status_endpoint(configuration: &[u8], alternate: u8) -> Option { interfaces(configuration) diff --git a/crates/stela-drivers/src/usb/xhci/hub/tests.rs b/crates/stela-drivers/src/usb/xhci/hub/tests.rs index bac04a0ea3..aad1e92d53 100644 --- a/crates/stela-drivers/src/usb/xhci/hub/tests.rs +++ b/crates/stela-drivers/src/usb/xhci/hub/tests.rs @@ -7,6 +7,22 @@ pub(in super::super) fn controller( dma: &mut dyn DmaAllocator, context: usize, nodes: BTreeMap, +) -> (Controller, Rc>) { + controller_with_minimum( + dma, + context, + nodes, + Clock { + ticks_per_microsecond: 1, + }, + ) +} + +fn controller_with_minimum( + dma: &mut dyn DmaAllocator, + context: usize, + nodes: BTreeMap, + physical: Clock, ) -> (Controller, Rc>) { let model = Rc::new(RefCell::new(Hardware::new(context, nodes))); let controller = Controller::new( @@ -16,9 +32,7 @@ pub(in super::super) fn controller( }, dma, "hub model".into(), - crate::minimum_model::owned(Clock { - ticks_per_microsecond: 1, - }), + crate::minimum_model::owned(physical), ) .unwrap(); (controller, model) diff --git a/crates/stela-drivers/src/usb/xhci/hub/tests/runtime.rs b/crates/stela-drivers/src/usb/xhci/hub/tests/runtime.rs index dc3f31ea61..5ee5d48a6c 100644 --- a/crates/stela-drivers/src/usb/xhci/hub/tests/runtime.rs +++ b/crates/stela-drivers/src/usb/xhci/hub/tests/runtime.rs @@ -1,5 +1,9 @@ //! Ring/context/interrupt model coverage of runtime topology ownership. -use super::super::{model::*, tests::controller, *}; +use super::super::{ + model::*, + tests::{controller, controller_with_minimum}, + *, +}; use crate::bus::dma::TestRegion; use alloc::collections::BTreeMap; @@ -15,6 +19,7 @@ fn runtime_poll(host: &mut Host, dma: &mut dyn DmaAllocator) -> Changes { #[test] fn runtime_hub_bitmap_disconnect_reconnect_retires_old_alias_before_fresh_binding() { + let _clock = crate::test_clock::virtualize(); for speed in [HIGH_SPEED, SUPER_SPEED] { for context in [32, 64] { let nodes = BTreeMap::from([(0, Node::hub(speed, 1)), (1, unbound_leaf(speed))]); @@ -66,7 +71,15 @@ fn runtime_hub_bitmap_disconnect_reconnect_retires_old_alias_before_fresh_bindin port.status |= 3; port.change |= 1; } - let added = runtime_poll(&mut host, &mut dma); + let mut added = runtime_poll(&mut host, &mut dma); + if speed == HIGH_SPEED { + assert!(added.added.devices.is_empty()); + for _ in 0..4 { + crate::test_clock::advance(shared.borrow().clock, DEBOUNCE_STEP_US); + added = runtime_poll(&mut host, &mut dma); + assert!(added.added.failures.is_empty()); + } + } assert!(added.removed.is_empty()); assert!( added.added.failures.is_empty(), @@ -100,6 +113,98 @@ fn runtime_hub_bitmap_disconnect_reconnect_retires_old_alias_before_fresh_bindin } } +#[test] +fn runtime_usb2_hub_debounce_yields_between_samples_and_restarts_on_a_bounce() { + let _clock = crate::test_clock::virtualize(); + let speed = HIGH_SPEED; + let mut hub = Node::hub(speed, 1); + hub.ports.as_mut().unwrap()[0].status &= !3; + let nodes = BTreeMap::from([(0, hub), (1, unbound_leaf(speed))]); + let mut dma = TestRegion::new(512 * 1024 * 8); + let physical = Clock { + ticks_per_microsecond: 2, + }; + let (mut c, model) = controller_with_minimum(&mut dma, 64, nodes, physical); + let clock = c.clock; + let mut failures = Vec::new(); + let devices = c.enumerate(&mut dma, &mut failures); + assert!(failures.is_empty()); + assert_eq!(devices.len(), 1); + let shared = Rc::new(RefCell::new(c)); + let mut host = Host::new(shared.clone(), &devices, &mut dma, &mut failures); + runtime_poll(&mut host, &mut dma); + + let arm = || { + let mut m = model.borrow_mut(); + let port = &mut m.nodes.get_mut(&0).unwrap().ports.as_mut().unwrap()[0]; + port.status |= 1; + port.change |= 1; + }; + let reset = setup(0x23, SET_FEATURE, PORT_RESET, 1, 0); + let start_requests = model.borrow().requests.len(); + let assert_no_reset = || { + assert!( + !model.borrow().requests[start_requests..] + .iter() + .any(|&(_, _, setup)| setup == reset) + ); + }; + arm(); + let mut service_start = Clock::ticks(); + let first = runtime_poll(&mut host, &mut dma); + assert!(first.added.devices.is_empty() && first.added.failures.is_empty()); + assert!(Clock::ticks().wrapping_sub(service_start) < DEBOUNCE_STEP_US); + assert!(!host.attachment_due()); + assert_no_reset(); + // The nominal clock schedules the callback halfway through the physical + // minimum. This callback must neither sample the port nor credit time. + let requests = model.borrow().requests.len(); + crate::test_clock::advance(clock, DEBOUNCE_STEP_US); + assert!(host.attachment_due()); + let early = runtime_poll(&mut host, &mut dma); + assert!(early.added.devices.is_empty() && early.added.failures.is_empty()); + assert_eq!(model.borrow().requests.len(), requests); + for _ in 0..3 { + crate::test_clock::advance(physical, DEBOUNCE_STEP_US); + assert!(host.attachment_due()); + service_start = Clock::ticks(); + let changes = runtime_poll(&mut host, &mut dma); + assert!(changes.added.devices.is_empty() && changes.added.failures.is_empty()); + assert!(Clock::ticks().wrapping_sub(service_start) < DEBOUNCE_STEP_US); + assert_no_reset(); + } + // A reconnect with the same final level still invalidates all three + // observed steps, including when it arrives before the next timer poll. + arm(); + let bounced = runtime_poll(&mut host, &mut dma); + assert!(bounced.added.devices.is_empty() && bounced.added.failures.is_empty()); + let bounced_at = Clock::ticks(); + assert_no_reset(); + for _ in 0..3 { + crate::test_clock::advance(physical, DEBOUNCE_STEP_US); + assert!(runtime_poll(&mut host, &mut dma).added.devices.is_empty()); + assert_no_reset(); + } + crate::test_clock::advance(physical, DEBOUNCE_STEP_US); + let completed = runtime_poll(&mut host, &mut dma); + assert!( + completed.added.failures.is_empty(), + "{:?}", + completed.added.failures + ); + assert_eq!(completed.added.devices.len(), 1); + let m = model.borrow(); + let reset_at = (start_requests..m.requests.len()) + .find(|&i| m.requests[i].2 == reset) + .unwrap(); + assert!( + physical + .elapsed_at(bounced_at, m.request_times[reset_at]) + .unwrap() + >= DEBOUNCE_STABLE_US + ); +} + #[test] fn runtime_hub_chain_disconnect_stops_queued_bitmaps_and_children_before_parent_disable() { let nodes = BTreeMap::from([ diff --git a/crates/stela-drivers/src/usb/xhci/hub/usb2.rs b/crates/stela-drivers/src/usb/xhci/hub/usb2.rs index 43e7b1e15d..4f60899f59 100644 --- a/crates/stela-drivers/src/usb/xhci/hub/usb2.rs +++ b/crates/stela-drivers/src/usb/xhci/hub/usb2.rs @@ -46,30 +46,62 @@ impl Controller { fn hub_port_owned(&mut self, id: SlotId, port: u8) -> Result, BlockError> { self.check_minimum()?; let slot = self.validate_topology_id(id)?; - let index = u16::from(port); self.observe_current_ancestors(slot, true)?; let minimum = self.minimum.clone(); - let connected = enumerate::debounce(minimum, || { - let (status, change) = self.hub_port_status_owned(slot, port)?; - powered(status, change)?; - let changed = change & HUB_PORT_CONNECTION != 0; - for (bit, selector) in [ - (HUB_PORT_CONNECTION, C_PORT_CONNECTION), - (2, 17), - (4, 18), - (16, 20), - (32, 23), - ] { - if change & bit != 0 { - self.control_owned(slot, setup(0x23, CLEAR_FEATURE, selector, index, 0), &[])?; - } - } - Ok((status & HUB_PORT_CONNECTION != 0, changed)) - }); - let connected = self.minimum_status(connected)?; - if !connected { + let connected = + enumerate::debounce(minimum, || self.sample_usb2_hub_port_owned(slot, port)); + if !self.minimum_status(connected)? { return Ok(None); } + self.reset_debounced_usb2_hub_port(id, port) + } + + pub(in super::super) fn sample_usb2_hub_port( + &mut self, + id: SlotId, + port: u8, + ) -> Result<(bool, bool), BlockError> { + let slot = self.validate_topology_id(id)?; + self.sample_usb2_hub_port_owned(slot, port) + } + + fn sample_usb2_hub_port_owned( + &mut self, + slot: u8, + port: u8, + ) -> Result<(bool, bool), BlockError> { + let (status, change) = self.hub_port_status_owned(slot, port)?; + powered(status, change)?; + for (bit, selector) in [ + (HUB_PORT_CONNECTION, C_PORT_CONNECTION), + (2, 17), + (4, 18), + (16, 20), + (32, 23), + ] { + if change & bit != 0 { + self.control_owned( + slot, + setup(0x23, CLEAR_FEATURE, selector, u16::from(port), 0), + &[], + )?; + } + } + Ok(( + status & HUB_PORT_CONNECTION != 0, + change & HUB_PORT_CONNECTION != 0, + )) + } + + /// The caller owns a completed stability interval for this exact port. + pub(in super::super) fn reset_debounced_usb2_hub_port( + &mut self, + id: SlotId, + port: u8, + ) -> Result, BlockError> { + self.check_minimum()?; + let slot = self.validate_topology_id(id)?; + let index = u16::from(port); for _ in 0..RESET_ATTEMPTS { self.control_owned(slot, setup(0x23, SET_FEATURE, PORT_RESET, index, 0), &[])?; let deadline = self.clock.deadline(PORT_RESET_US); diff --git a/crates/stela-drivers/src/usb/xhci/identity.rs b/crates/stela-drivers/src/usb/xhci/identity.rs index 141d8337d3..44d5c84be0 100644 --- a/crates/stela-drivers/src/usb/xhci/identity.rs +++ b/crates/stela-drivers/src/usb/xhci/identity.rs @@ -372,6 +372,13 @@ impl DeviceAccess<'_> { self.controller.endpoint_ready_owned(slot, dci) } + /// Check all the endpoints a class operation may use before changing its + /// buffers, with one controller readiness check. + pub(crate) fn endpoints_ready(&mut self, dcis: &[u8]) -> Result<(), BlockError> { + let slot = self.slot()?; + self.controller.endpoints_ready_owned(slot, dcis) + } + pub fn current_configuration(&mut self) -> Result, BlockError> { let slot = self.slot()?; self.controller.current_configuration_owned(slot) diff --git a/crates/stela-drivers/src/usb/xhci/lifecycle.rs b/crates/stela-drivers/src/usb/xhci/lifecycle.rs index 2e6fe82af2..d4875fd62f 100644 --- a/crates/stela-drivers/src/usb/xhci/lifecycle.rs +++ b/crates/stela-drivers/src/usb/xhci/lifecycle.rs @@ -5,6 +5,7 @@ //! identity of the old generation then fails. use super::*; +mod attach; mod recovery; mod suspend; @@ -43,6 +44,7 @@ struct Hub { pending: Option, retired: bool, recovery: Option, + attachments: Vec, } /// Keeps the controller even when no leaf class currently owns it. Call @@ -163,6 +165,7 @@ impl Host { pending: None, retired: false, recovery: None, + attachments: Vec::new(), }) })(); match result { @@ -186,7 +189,8 @@ impl Host { /// Whether [`Self::poll`] has work, as `xhci_irq` and `hub_irq` find it: /// an event on the ring, a root port's status change or a hub's status /// transfer that completed, a queued reset, a hub to recover, a dead - /// controller or a device whose slot changed. A look at memory alone. + /// controller, a device whose slot changed, or an attachment timer due. + /// This does not access controller registers. pub fn due(&self) -> bool { let Ok(c) = self.controller.try_borrow() else { return true; @@ -206,15 +210,19 @@ impl Host { event.kind() == reset::PORT_STATUS_CHANGE || (event.kind() == super::TRANSFER_EVENT && hub(event.slot())) }) - || self.hubs.iter().any(|hub| hub.recovery.is_some()); - drop(c); - changed || { - let current = self.current(); - current.len() != self.devices.len() - || current - .iter() - .any(|device| !self.devices.iter().any(|old| old.id == device.id)) + || self.hubs.iter().any(|hub| hub.recovery.is_some()) + || self.attachment_due(); + if changed { + return true; } + let mut count = 0; + for device in Self::current(&c) { + if !self.devices.iter().any(|old| old.id == device.id) { + return true; + } + count += 1; + } + count != self.devices.len() } /// Poll root notifications/PORTSC and queued hub interrupt bitmaps. @@ -269,6 +277,7 @@ impl Host { .failures .push((format!("{location} hub lifecycle"), error)); } + self.poll_hub_attachments(index, dma, &mut changes); } let queued = self.controller.borrow_mut().take_queued_resets(); for id in queued { @@ -318,37 +327,34 @@ impl Host { /// polls. Follow the controller's fresh descriptor inventory without /// attempting a second native bind of that already-owned replacement. /// The enabled devices the controller's slots hold now. - fn current(&self) -> Vec { - let c = self.controller.borrow(); - c.slots - .iter() - .enumerate() - .filter_map(|(id, state)| { - state - .as_ref() - .filter(|state| { - !state.retiring - && !state.suspended - && c.slot_ownership[id] == reset::Ownership::Enabled - }) - .and_then(|state| state.inventory.clone()) - }) - .collect() + fn current(c: &Controller) -> impl Iterator { + (0..c.slots.len()).filter_map(move |slot| Self::current_slot(c, slot)) + } + + fn current_slot(c: &Controller, slot: usize) -> Option<&Device> { + let state = c.slots.get(slot)?.as_ref()?; + if state.retiring || state.suspended || c.slot_ownership[slot] != reset::Ownership::Enabled + { + return None; + } + state.inventory.as_ref() } fn reconcile(&mut self, changes: &mut Changes) { - let current = self.current(); + let c = self.controller.borrow(); self.devices.retain(|old| { - if current.iter().any(|device| device.id == old.id) { + if Self::current_slot(&c, usize::from(old.slot)) + .is_some_and(|device| device.id == old.id) + { true } else { changes.removed.push(old.clone()); false } }); - for device in current { + for device in Self::current(&c) { if !self.devices.iter().any(|old| old.id == device.id) { - self.devices.push(device); + self.devices.push(device.clone()); } } } @@ -599,7 +605,6 @@ impl Host { changes: &mut Changes, ) -> Result<(), BlockError> { let id = self.hubs[index].device.id; - let slot = id.hardware_slot(); let attachment = self.hubs[index].attachment; let ss = attachment.speed >= SUPER_SPEED; let (status, change, owner) = { @@ -652,12 +657,49 @@ impl Host { if !reconnect { return Ok(()); } - let location = format!("{}.{port}", self.hubs[index].device.location); - let ssp = self.hubs[index].ssp.as_ref(); + if !ss && owner.is_none() { + if let Some(pending) = self.hubs[index] + .attachments + .iter_mut() + .find(|pending| pending.port == port) + { + // The change latch was consumed above. A bounce reported + // between timer samples must still restart the interval. + return pending.notice(&mut c, status & 1 != 0, change & 1 != 0); + } + if status & 1 != 0 + && let Some(pending) = attach::Pending::start(&mut c, id, port)? + { + self.hubs[index].attachments.push(pending); + return Ok(()); + } + } + drop(c); + self.connect_hub_port(index, port, false, dma, changes); + Ok(()) + } + + fn connect_hub_port( + &mut self, + index: usize, + port: u8, + mut debounced: bool, + dma: &mut dyn DmaAllocator, + changes: &mut Changes, + ) { + let hub = &self.hubs[index]; + let id = hub.device.id; + let slot = id.hardware_slot(); + let attachment = hub.attachment; + let ss = attachment.speed >= SUPER_SPEED; + let location = format!("{}.{port}", hub.device.location); + let ssp = hub.ssp.as_ref(); let reset = |c: &mut Controller| { c.observe_current_ancestors_for(id, true)?; let speed = if ss { c.superspeed_port_for(id, port, ssp) + } else if core::mem::take(&mut debounced) { + c.reset_debounced_usb2_hub_port(id, port) } else { c.hub_port_for(id, port) }; @@ -674,15 +716,14 @@ impl Host { }, })) }; - c.connect( + self.controller.borrow_mut().connect( location, - Some(self.hubs[index].device.id), + Some(id), reset, dma, &mut changes.added.devices, &mut changes.added.failures, ); - Ok(()) } /// Linux usb_hc_died: every device below a dead host controller is @@ -699,6 +740,7 @@ impl Host { for hub in &mut self.hubs { hub.retired = true; hub.recovery = None; + hub.attachments.clear(); } changes.removed.append(&mut self.devices); } @@ -771,6 +813,7 @@ impl Host { for hub in &mut self.hubs { if slots.contains(&hub.device.slot) && c.known_id(hub.device.id) { hub.retired = true; + hub.attachments.clear(); if Some(hub.device.id) != keep { hub.recovery = None; } diff --git a/crates/stela-drivers/src/usb/xhci/lifecycle/attach.rs b/crates/stela-drivers/src/usb/xhci/lifecycle/attach.rs new file mode 100644 index 0000000000..d31c2fe648 --- /dev/null +++ b/crates/stela-drivers/src/usb/xhci/lifecycle/attach.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! USB2 downstream attachment waits across host service calls. Port reset +//! and enumeration still require the same stable, observed connection. +use super::*; +use crate::bus::pci::power::{Error as ClockError, Interval}; + +pub(super) struct Pending { + pub(super) port: u8, + debounce: enumerate::Debounce, + next: Deadline, + end: Deadline, + interval: Box, +} + +impl Pending { + pub(super) fn start( + c: &mut Controller, + id: SlotId, + port: u8, + ) -> Result, BlockError> { + c.check_minimum()?; + let end = c + .clock + .try_deadline(DEBOUNCE_TIMEOUT_US) + .map_err(|_| BlockError::Unsupported("xHCI debounce clock unavailable"))?; + c.observe_current_ancestors_for(id, true)?; + let (connected, changed) = c.sample_usb2_hub_port(id, port)?; + let mut debounce = enumerate::Debounce::default(); + debounce.observe(connected, changed); + let interval = c.minimum.begin_interval(DEBOUNCE_STEP_US); + let Some(interval) = c.minimum_status(interval)? else { + return Ok(None); + }; + Ok(Some(Self { + port, + debounce, + next: c.clock.deadline(DEBOUNCE_STEP_US), + end, + interval, + })) + } + + fn restart_interval(&mut self, c: &mut Controller) -> Result<(), BlockError> { + let interval = c.minimum.begin_interval(DEBOUNCE_STEP_US); + let Some(interval) = c.minimum_status(interval)? else { + let failure = c.minimum.source_result(Err(ClockError::Clock)); + return c.minimum_status(failure); + }; + self.interval = interval; + self.next = c.clock.deadline(DEBOUNCE_STEP_US); + Ok(()) + } + + pub(super) fn notice( + &mut self, + c: &mut Controller, + connected: bool, + changed: bool, + ) -> Result<(), BlockError> { + if self.debounce.restart_on_change(connected, changed) { + self.restart_interval(c)?; + } + Ok(()) + } + + fn due(&self, now: u64) -> bool { + self.next.passed_at(now) || self.end.passed_at(now) + } + + fn sample(&mut self, c: &mut Controller, id: SlotId) -> Result, BlockError> { + let sampled = if self.next.passed() { + let elapsed = c.minimum.interval_elapsed(self.interval.as_ref()); + if c.minimum_status(elapsed)? { + let (connected, changed) = c.sample_usb2_hub_port(id, self.port)?; + if let Some(stable) = self.debounce.observe(connected, changed) { + return Ok(Some(stable)); + } + true + } else { + false + } + } else { + false + }; + if self.end.passed() { + return Err(BlockError::Unsupported("USB port connection never settled")); + } + if sampled { + self.restart_interval(c)?; + } else { + self.next = c.clock.deadline(DEBOUNCE_STEP_US); + } + Ok(None) + } +} + +impl Host { + /// Work due even without a controller event or the fallback hub poll. + pub fn attachment_due(&self) -> bool { + if !self.sleep.awake() { + return false; + } + self.hubs.iter().filter(|hub| !hub.retired).any(|hub| { + !hub.attachments.is_empty() && { + let now = Clock::ticks(); + hub.attachments.iter().any(|pending| pending.due(now)) + } + }) + } + + pub(super) fn poll_hub_attachments( + &mut self, + index: usize, + dma: &mut dyn DmaAllocator, + changes: &mut Changes, + ) { + let hub = &self.hubs[index]; + if hub.retired || hub.attachments.is_empty() { + return; + } + let id = hub.device.id; + let now = Clock::ticks(); + let mut at = 0; + while let Some(pending) = self.hubs[index].attachments.get_mut(at) { + if !pending.due(now) { + at += 1; + continue; + } + let result = pending.sample(&mut self.controller.borrow_mut(), id); + if matches!(result, Ok(None)) { + at += 1; + continue; + } + let port = self.hubs[index].attachments.remove(at).port; + match result { + Ok(Some(true)) => self.connect_hub_port(index, port, true, dma, changes), + Ok(_) => {} + Err(error) => changes.added.failures.push(( + format!("{}.{port} port lifecycle", self.hubs[index].device.location), + error, + )), + } + } + } +} diff --git a/crates/stela-drivers/src/usb/xhci/lifecycle/suspend.rs b/crates/stela-drivers/src/usb/xhci/lifecycle/suspend.rs index 1ff7c5064a..587314dc75 100644 --- a/crates/stela-drivers/src/usb/xhci/lifecycle/suspend.rs +++ b/crates/stela-drivers/src/usb/xhci/lifecycle/suspend.rs @@ -153,6 +153,7 @@ impl Host { c.suspend_controller()?; for hub in &mut self.hubs { hub.pending = None; + hub.attachments.clear(); } Ok(Snapshot { topology, roots }) } diff --git a/crates/stela-drivers/src/usb/xhci/memory/tests.rs b/crates/stela-drivers/src/usb/xhci/memory/tests.rs index 15768ee527..26795a45a9 100644 --- a/crates/stela-drivers/src/usb/xhci/memory/tests.rs +++ b/crates/stela-drivers/src/usb/xhci/memory/tests.rs @@ -317,7 +317,7 @@ fn native_ring_publishes_real_iova_td_before_first_cycle_and_keeps_failed_visibi ); assert!(memory.ready().is_err()); } else { - assert_eq!(result.unwrap(), vec![address]); + assert_eq!(result.unwrap(), [address]); let td = peer.device(address, TRB); assert_eq!(u64::from_le_bytes(td[..8].try_into().unwrap()), 0x1234_5000); assert_eq!(u32::from_le_bytes(td[8..12].try_into().unwrap()), 32); diff --git a/crates/stela-drivers/src/usb/xhci/minimum.rs b/crates/stela-drivers/src/usb/xhci/minimum.rs index f70afb2cbf..26a3b553b8 100644 --- a/crates/stela-drivers/src/usb/xhci/minimum.rs +++ b/crates/stela-drivers/src/usb/xhci/minimum.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT //! Owned minimum intervals, distinct from nominal polling deadlines. use super::*; -use crate::bus::pci::power::{Error, Timer}; +use crate::bus::pci::power::{Error, Interval, Timer}; use core::{cell::Cell, mem::ManuallyDrop, sync::atomic::AtomicU64}; static RETAINED: AtomicU64 = AtomicU64::new(0); @@ -52,6 +52,19 @@ impl Minimum { self.source_result(self.0.timer.wait_us(microseconds))?; self.check() } + pub fn begin_interval( + &self, + microseconds: u64, + ) -> Result>, BlockError> { + self.check()?; + self.source_result(self.0.timer.begin_interval(microseconds)) + } + pub fn interval_elapsed(&self, interval: &dyn Interval) -> Result { + if let Some(error) = self.error() { + return Err(BlockError::PciPower(error)); + } + self.source_result(interval.elapsed()) + } pub fn timer(&self) -> &Rc { &self.0.timer } diff --git a/crates/stela-drivers/src/usb/xhci/ring.rs b/crates/stela-drivers/src/usb/xhci/ring.rs index 3c1008b574..993e93e7f9 100644 --- a/crates/stela-drivers/src/usb/xhci/ring.rs +++ b/crates/stela-drivers/src/usb/xhci/ring.rs @@ -103,12 +103,15 @@ impl Ring { /// Writes one TD, its first TRB owned last, and returns each TRB's /// address. - pub(super) fn push(&mut self, trbs: &[(u64, u32, u32)]) -> Result, BlockError> { - let mut addresses = Vec::with_capacity(trbs.len()); + pub(super) fn push( + &mut self, + trbs: &[(u64, u32, u32); N], + ) -> Result<[u64; N], BlockError> { + let mut addresses = [0; N]; let mut first = None; for (n, &(parameter, status, control)) in trbs.iter().enumerate() { let at = self.index * TRB; - addresses.push(self.address()); + addresses[n] = self.address(); self.buffer.write(at, parameter); self.buffer.write(at + 8, status); let cycle = u32::from(self.cycle); diff --git a/crates/stela-drivers/src/usb/xhci/transfer.rs b/crates/stela-drivers/src/usb/xhci/transfer.rs index 917ce8a6e2..ec96c2eb3a 100644 --- a/crates/stela-drivers/src/usb/xhci/transfer.rs +++ b/crates/stela-drivers/src/usb/xhci/transfer.rs @@ -80,7 +80,24 @@ impl Controller { } pub(super) fn endpoint_ready_owned(&mut self, slot: u8, dci: u8) -> Result<(), BlockError> { - self.completion_ready(slot, dci)?; + self.endpoints_ready_owned(slot, &[dci]) + } + + pub(super) fn endpoints_ready_owned( + &mut self, + slot: u8, + dcis: &[u8], + ) -> Result<(), BlockError> { + self.live_slot(slot)?; + self.ready()?; + for &dci in dcis { + self.endpoint_enabled(slot, dci)?; + self.endpoint_can_submit(slot, dci)?; + } + Ok(()) + } + + fn endpoint_can_submit(&mut self, slot: u8, dci: u8) -> Result<(), BlockError> { // Incompatible Device may be transferless; its pointer need not name // any ticket. It requires slot retirement before new DMA publication. let incompatible = self.pending.iter().any(|event| { @@ -130,6 +147,10 @@ impl Controller { fn endpoint_ready_inner(&mut self, slot: u8, dci: u8) -> Result<(), BlockError> { self.ready()?; + self.endpoint_enabled(slot, dci) + } + + fn endpoint_enabled(&mut self, slot: u8, dci: u8) -> Result<(), BlockError> { let state = self.slot(slot)?; if dci != 1 && !state.current_configuration.is_some_and(|value| value != 0) { return Err(BlockError::Unsupported( diff --git a/crates/stela-drivers/src/usb/xhci/transfer/operation.rs b/crates/stela-drivers/src/usb/xhci/transfer/operation.rs index af60ebe320..cdfde5dc9f 100644 --- a/crates/stela-drivers/src/usb/xhci/transfer/operation.rs +++ b/crates/stela-drivers/src/usb/xhci/transfer/operation.rs @@ -9,7 +9,9 @@ pub(in super::super) struct Control { slot: u8, length: usize, is_in: bool, - addresses: Vec, + setup_address: u64, + data_address: Option, + status_address: u64, deadline: Deadline, received: usize, short_seen: bool, @@ -101,20 +103,24 @@ impl Controller { (_, false) => 2, (_, true) => 3, }; - let mut trbs = vec![( + let setup = ( u64::from_le_bytes(request), 8, SETUP << 10 | IDT | transfer_type << 16, - )]; - let direction = if is_in { DIRECTION_IN } else { 0 }; - if length > 0 { - trbs.push((buffer, length as u32, DATA << 10 | ISP | direction)); - } + ); let status_direction = if length > 0 && is_in { 0 } else { DIRECTION_IN }; - trbs.push((0, 0, STATUS << 10 | IOC | status_direction)); - let addresses = { + let status = (0, 0, STATUS << 10 | IOC | status_direction); + let (setup_address, data_address, status_address) = { let endpoint = self.slot(slot)?.endpoints[1].as_mut().unwrap(); - let addresses = endpoint.ring.push(&trbs)?; + let addresses = if length > 0 { + let direction = if is_in { DIRECTION_IN } else { 0 }; + let data = (buffer, length as u32, DATA << 10 | ISP | direction); + let [setup, data, status] = endpoint.ring.push(&[setup, data, status])?; + (setup, Some(data), status) + } else { + let [setup, status] = endpoint.ring.push(&[setup, status])?; + (setup, None, status) + }; endpoint.in_flight = 1; addresses }; @@ -123,7 +129,9 @@ impl Controller { slot, length, is_in, - addresses, + setup_address, + data_address, + status_address, deadline, received: length, short_seen: false, @@ -143,7 +151,7 @@ impl Controller { return Some(result.and(Err(error.clone()))); } let slot = control.slot; - let status_address = *control.addresses.last().unwrap(); + let status_address = control.status_address; loop { let event = match self.poll_event(control.deadline, |e| { e.kind() == TRANSFER_EVENT && e.slot() == slot && e.endpoint() == 1 @@ -158,13 +166,14 @@ impl Controller { // An event must name this TD's Setup/Data/Status TRB. // Event Data is never submitted by this control path. Only Data // short packets may precede the final zero-length Status ACK. - let data_address = (control.length > 0).then(|| control.addresses[1]); let valid = event.control & EVENT_DATA == 0 - && control.addresses.contains(&event.parameter) + && (event.parameter == control.setup_address + || event.parameter == status_address + || Some(event.parameter) == control.data_address) && match event.code() { SUCCESS => event.parameter == status_address && event.residual() == 0, SHORT_PACKET => { - data_address == Some(event.parameter) + control.data_address == Some(event.parameter) && event.residual() <= control.length && !control.short_seen } diff --git a/crates/stela-drivers/src/usb/xhci/transfer/tests.rs b/crates/stela-drivers/src/usb/xhci/transfer/tests.rs index 795ad9cb18..94f348e335 100644 --- a/crates/stela-drivers/src/usb/xhci/transfer/tests.rs +++ b/crates/stela-drivers/src/usb/xhci/transfer/tests.rs @@ -2,6 +2,35 @@ use super::*; use crate::bus::dma::TestRegion; use crate::usb::xhci::model::*; +#[test] +fn shared_preflight_samples_status_once_and_still_checks_every_endpoint() { + let mut dma = TestRegion::new(64 * 1024 * 8); + let (mut controller, model) = cancellation_controller(&mut dma); + assert!(!controller.event_posted()); + controller.quiet_drains = 0; + let before = model.borrow().status_reads; + controller.endpoints_ready_owned(1, &[1, 3, 5]).unwrap(); + assert_eq!(model.borrow().status_reads - before, 1); + + model + .borrow_mut() + .event(0, INCOMPATIBLE_DEVICE, TRANSFER_EVENT, 5, 0); + assert_eq!( + controller.endpoints_ready_owned(1, &[1, 3, 5]), + Err(BlockError::Device { + status: INCOMPATIBLE_DEVICE, + }) + ); + assert!(controller.endpoint_poisoned(1, 5)); + assert!(controller.endpoint_ready_owned(1, 3).is_ok()); + + model.borrow_mut().fatal_status = HSE; + assert_eq!( + controller.endpoints_ready_owned(1, &[1, 3]), + Err(BlockError::Device { status: HSE }) + ); +} + #[test] fn strings_use_the_first_listed_language_and_default_to_english() { let mut dma = TestRegion::new(32 * 1024 * 8); diff --git a/crates/stela-engine/src/artifact.rs b/crates/stela-engine/src/artifact.rs index ed01d36a14..b4a4882caa 100644 --- a/crates/stela-engine/src/artifact.rs +++ b/crates/stela-engine/src/artifact.rs @@ -41,13 +41,6 @@ pub struct Manifest { pub(crate) struct LoadedArtifact { pub(crate) manifest: Manifest, } -impl LoadedArtifact { - pub(crate) fn bind(manifest: Manifest, native: &[u8]) -> Result { - validate_native_snapshot(&manifest, native)?; - Ok(Self { manifest }) - } -} - pub(crate) fn validate_native_snapshot(manifest: &Manifest, native: &[u8]) -> Result<(), Refusal> { if native.len() != manifest.native_bytes || stela_formats::sha256(native) != manifest.native_sha256 diff --git a/crates/stela-engine/src/blocks.rs b/crates/stela-engine/src/blocks.rs index eaef9924c5..480706e116 100644 --- a/crates/stela-engine/src/blocks.rs +++ b/crates/stela-engine/src/blocks.rs @@ -22,8 +22,6 @@ pub use outcome::{ use stela_contracts::{refuse, require}; use crate::Result; -#[cfg(feature = "std")] -use crate::error::Io; use crate::{execution::platform, floating, memory, pauth, system}; #[cfg(not(feature = "std"))] use alloc::{boxed::Box, string::String, string::ToString, vec::Vec}; @@ -34,7 +32,7 @@ use services::{ RuntimeServices, complete_pauth_with_memory, runtime_pauth_key, serialize_instruction_execution, }; #[cfg(feature = "std")] -use std::{io::Read, path::PathBuf}; +use std::path::PathBuf; use stela_compiler::{ GuestAddress, block::{ @@ -48,8 +46,6 @@ use validate::{ validate_thread_register_exit, validate_trap_exit, }; -#[cfg(feature = "std")] -const MAX_NATIVE_BYTES: usize = 64 * 1024 * 1024; const INSTRUCTION_BYTES: usize = 4; const ZERO_REGISTER_INDEX: u8 = 31; const REGISTER_COUNT: u8 = ZERO_REGISTER_INDEX + 1; @@ -199,69 +195,25 @@ impl BlockRuntime { } fn load(&mut self, pc: GuestAddress, outcome: &mut RunOutcome) -> Result<()> { - let (base, region) = self - .region(pc) - .ok_or_else(|| refuse!("instruction mapping disappeared", pc = pc.0))?; - if let Some(block) = self.loaded.get(&pc.0) { - require!( - block.region_base == base && block.generation == region.generation, - "stale native block generation" - ); - outcome.memory_cache_hits += 1; - return Ok(()); - } - #[cfg(not(feature = "std"))] - { - let discovery = self.prepare(pc)?; - let profile = discovery.artifact_profile; - let generation = discovery.generation; - let source_bytes = discovery.analysis.source_bytes; - let native = discovery.native; - let prepared = - crate::artifact::LoadedArtifact::bind(discovery.prepared.manifest, &native)?; - let block = LoadedBlock::from_artifact( - self.target, - profile, - base, - generation, - source_bytes, - prepared, - &native, - )?; - self.loaded.insert(pc.0, block); + let (block, native) = self.prepare_snapshot(pc)?; + let prepared = block.prepared; + let loaded = LoadedBlock::from_artifact( + self.target, + block.artifact_profile, + block.region_base.0, + block.generation, + block.analysis.source_bytes, + crate::artifact::LoadedArtifact { + manifest: prepared.manifest, + }, + &native, + )?; + if prepared.cache_hit { + outcome.disk_cache_hits += 1; + } else { outcome.compiled_blocks += 1; } - #[cfg(feature = "std")] - { - let prepared = self.prepare(pc)?; - let profile = prepared.artifact_profile; - let generation = prepared.generation; - let source_bytes = prepared.analysis.source_bytes; - let prepared = prepared.prepared; - let mut native = Vec::new(); - std::fs::File::open(prepared.directory.join("native.bin")) - .io("open a cached native block")? - .take((MAX_NATIVE_BYTES + 1) as u64) - .read_to_end(&mut native) - .io("read a cached native block")?; - let loaded_artifact = - crate::artifact::LoadedArtifact::bind(prepared.manifest, &native)?; - let block = LoadedBlock::from_artifact( - self.target, - profile, - base, - generation, - source_bytes, - loaded_artifact, - &native, - )?; - if prepared.cache_hit { - outcome.disk_cache_hits += 1; - } else { - outcome.compiled_blocks += 1; - } - self.loaded.insert(pc.0, block); - } + self.loaded.insert(pc.0, loaded); Ok(()) } @@ -511,9 +463,12 @@ impl BlockRuntime { } else { None }; - // Decode ahead of loading so an unsupported instruction is a typed - // dispatch stop. Disk corruption and allocation errors remain errors. - if !self.loaded.contains_key(&pc.0) { + let (block, current) = if let Some(block) = self.loaded.get(&pc.0) { + outcome.memory_cache_hits += 1; + (block, region) + } else { + // Decode ahead of loading so an unsupported instruction is a typed + // dispatch stop. Disk corruption and allocation errors remain errors. let offset = (pc.0 - base) as usize; let words = ((region.source.len() - offset) / 4).min(MAX_BLOCK_INSTRUCTIONS); if let Err(error) = stela_compiler::block::source_bytes_with_profile( @@ -526,17 +481,20 @@ impl BlockRuntime { }; break; } - } - self.load(pc, &mut outcome)?; - let block = self - .loaded - .get(&pc.0) - .ok_or_else(|| refuse!("loaded block disappeared", pc = pc.0))?; - let (_, current) = self - .region(pc) - .ok_or_else(|| refuse!("loaded block unmapped", pc = pc.0))?; + self.load(pc, &mut outcome)?; + let block = self + .loaded + .get(&pc.0) + .ok_or_else(|| refuse!("loaded block disappeared", pc = pc.0))?; + let (_, current) = self + .region(pc) + .ok_or_else(|| refuse!("loaded block unmapped", pc = pc.0))?; + (block, current) + }; require!( - block.generation == current.generation && block.source_bytes > 0, + block.region_base == base + && block.generation == current.generation + && block.source_bytes > 0, "refusing stale block execution" ); let mut completed_blocks = 1; @@ -563,6 +521,19 @@ impl BlockRuntime { let BlockExit { next_pc, kind } = native_exit; let exit_kind = ExitKind::try_from(kind) .map_err(|_| refuse!("invalid native block exit kind", kind))?; + if matches!( + exit_kind, + ExitKind::Fallthrough + | ExitKind::Direct + | ExitKind::Indirect + | ExitKind::Call + | ExitKind::Return + ) { + state.pc = GuestAddress(next_pc); + outcome.last_exit = Some((next_pc, kind)); + outcome.blocks_executed += completed_blocks; + continue; + } require!( exit_kind != ExitKind::ScalableNumerical, "context-block numerical exit requires owned scalable entry" diff --git a/crates/stela-engine/src/blocks/aot.rs b/crates/stela-engine/src/blocks/aot.rs index 353e32c83e..760243b82d 100644 --- a/crates/stela-engine/src/blocks/aot.rs +++ b/crates/stela-engine/src/blocks/aot.rs @@ -176,7 +176,7 @@ impl BlockRuntime { prepare::validate_preparation_native(&manifest, native)?; prepare::validate_preparation_claim(&manifest)?; validate_source_map(&manifest, pc, source_bytes)?; - let prepared = LoadedArtifact::bind(manifest, native)?; + let prepared = LoadedArtifact { manifest }; let block = LoadedBlock::from_artifact( self.target, profile, @@ -265,7 +265,7 @@ mod tests { } #[test] - fn standard_artifact_enters_original_loaded_hit_path_without_disk_or_execution() -> Result<()> { + fn standard_artifact_dispatches_from_memory_without_disk_or_compilation() -> Result<()> { let source = source(&[MOVZ_X0_42, B_NEXT]); let (manifest, native) = artifact(&source, BlockProfile::ORDINARY)?; let (bytes, checksum) = serialized(&manifest)?; @@ -275,12 +275,22 @@ mod tests { runtime.loaded_manifest(BASE).unwrap().identity, manifest.identity ); - let mut observations = outcome(); - runtime.load(BASE, &mut observations)?; - assert_eq!(observations.memory_cache_hits, 1); - assert_eq!(observations.disk_cache_hits, 0); - assert_eq!(observations.compiled_blocks, 0); - assert_eq!(observations.blocks_executed, 0); + #[cfg(all(target_arch = "x86_64", any(target_os = "linux", target_os = "macos")))] + { + let mut state = ThreadState { + registers: stela_compiler::GuestState::default(), + pc: BASE, + }; + let stop = GuestAddress(BASE.0 + source.len() as u64); + // SAFETY: the block only modifies registers and branches to the stop address. + let observations = unsafe { runtime.run(&mut state, Some(stop), 1)? }; + assert_eq!(observations.reason, StopReason::StopAddress); + assert_eq!(observations.memory_cache_hits, 1); + assert_eq!(observations.disk_cache_hits, 0); + assert_eq!(observations.compiled_blocks, 0); + assert_eq!(observations.blocks_executed, 1); + assert_eq!(state.registers.x[0], 42); + } assert_eq!(runtime.loaded.len(), 1); assert!( runtime diff --git a/crates/stela-engine/src/blocks/discovery.rs b/crates/stela-engine/src/blocks/discovery.rs index c11050fbe3..434f16a8a3 100644 --- a/crates/stela-engine/src/blocks/discovery.rs +++ b/crates/stela-engine/src/blocks/discovery.rs @@ -1,14 +1,10 @@ //! Ahead-of-time preparation and static code discovery. use super::BlockRuntime; -#[cfg(feature = "std")] -use super::MAX_NATIVE_BYTES; #[cfg(not(feature = "std"))] use super::aot::ArtifactPreparation; use super::validate::validate_source_map; use crate::Prepared; use crate::Result; -#[cfg(feature = "std")] -use crate::prepare_runtime_block_for_target; use alloc::collections::{BTreeSet, VecDeque}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; @@ -16,10 +12,12 @@ use serde::Serialize; use stela_compiler::{ CompileErrorKind, GuestAddress, block::{ - BlockAnalysis, BlockProfile, DynamicEdge, MAX_BLOCK_INSTRUCTIONS, analyze_with_profile, + BlockAnalysis, BlockProfile, CompilationPlan, DynamicEdge, Features, + MAX_BLOCK_INSTRUCTIONS, analyze_and_plan, analyze_with_profile, }, }; use stela_contracts::{refuse, require}; +#[cfg(not(feature = "std"))] use stela_formats::sha256; /// Persistent preparation artifact shared by ahead-of-time discovery and JIT. @@ -28,9 +26,6 @@ use stela_formats::sha256; pub struct PreparedDiscoveryBlock { #[serde(skip)] pub(super) artifact_profile: BlockProfile, - #[cfg(not(feature = "std"))] - #[serde(skip)] - pub(super) native: Vec, pub entry: GuestAddress, pub region_base: GuestAddress, pub generation: u64, @@ -82,56 +77,20 @@ pub struct DiscoveryReport { impl BlockRuntime { /// Prepare one known entry into the persistent AOT/JIT cache, without RX /// loading or execution. Source bytes/edges share the compiler's parser. - #[cfg(feature = "std")] pub fn prepare(&mut self, pc: GuestAddress) -> Result { - require!(pc.0.is_multiple_of(4), "unaligned preparation entry"); - let cache_root = self.preparation.cache_root(pc)?; - let (base, region) = self - .region(pc) - .ok_or_else(|| refuse!("unmapped preparation entry", pc = pc.0))?; - require!(region.end - pc.0 >= 4, "truncated preparation instruction"); - let offset = (pc.0 - base) as usize; - let available = ((region.source.len() - offset) / 4).min(MAX_BLOCK_INSTRUCTIONS) * 4; - let generation = region.generation; - let window = ®ion.source[offset..offset + available]; - let analysis = analyze_with_profile(window, pc, self.profile)?; - let (prepared, artifact_profile) = - prepare_runtime_block_for_target(window, pc, cache_root, self.profile, self.target)?; - require!( - prepared.source_bytes == analysis.source_bytes, - "prepared block analysis extent mismatch" - ); - let manifest = &prepared.prepared.manifest; - require!( - manifest.identity.guest_base == pc.0 - && manifest.identity.abi == artifact_profile.abi() - && manifest.identity.target_cpu == self.target.id() - && manifest.identity.schema_version == 1, - "unsupported block translation identity" - ); - require!( - manifest.identity.compiler_source_sha256 == crate::compiler_source_sha256() - && manifest.identity.source_sha256 == sha256(&window[..prepared.source_bytes]), - "block compiler/source identity mismatch" - ); - validate_source_map(&prepared.prepared.manifest, pc, prepared.source_bytes)?; - require!( - manifest.native_bytes > 0 && manifest.native_bytes <= MAX_NATIVE_BYTES, - "invalid block native size" - ); - Ok(PreparedDiscoveryBlock { - artifact_profile, - entry: pc, - region_base: GuestAddress(base), - generation, - analysis, - prepared: prepared.prepared, - }) + self.prepare_snapshot(pc).map(|(prepared, _)| prepared) } - #[cfg(not(feature = "std"))] - pub fn prepare(&mut self, pc: GuestAddress) -> Result { + /// Keep the same native bytes whose checksum the preparation bound to the + /// manifest, so dispatch can map them without reopening the cache file. + pub(super) fn prepare_snapshot( + &mut self, + pc: GuestAddress, + ) -> Result<(PreparedDiscoveryBlock, Vec)> { require!(pc.0.is_multiple_of(4), "unaligned preparation entry"); + #[cfg(feature = "std")] + let cache_root = self.preparation.cache_root(pc)?; + #[cfg(not(feature = "std"))] require!( matches!(self.preparation, ArtifactPreparation::InMemory), "AOT block unavailable; runtime compilation is unsupported", @@ -145,40 +104,56 @@ impl BlockRuntime { let available = ((region.source.len() - offset) / 4).min(MAX_BLOCK_INSTRUCTIONS) * 4; let generation = region.generation; let window = ®ion.source[offset..offset + available]; - let analysis = analyze_with_profile(window, pc, self.profile)?; - let plan = stela_compiler::block::CompilationPlan::new( - window, - pc, - &stela_compiler::Options::new(self.profile, self.target), - )? - .with_resident_loops(); + let options = stela_compiler::Options::new(self.profile, self.target); + // A leaf plan uses a different parser and consumes the entire window. + let (analysis, plan) = if self.profile.has(Features::LEAF) { + ( + analyze_with_profile(window, pc, self.profile)?, + CompilationPlan::new(window, pc, &options), + ) + } else { + analyze_and_plan(window, pc, &options)? + }; + let plan = plan?.with_resident_loops(); let artifact_profile = plan.profile(); let source_bytes = plan.source_bytes(); require!( source_bytes == analysis.source_bytes, "prepared block analysis extent mismatch" ); - let identity = crate::block_plan_identity(window, pc, self.target, &plan)?; - let key = sha256(&serde_json::to_vec(&identity)?); - let requirements = plan.memory_requirements(); - let (manifest, native) = - crate::artifact::prepare::generate(identity, requirements, || { - plan.compile().map(|block| block.native) - })?; - validate_source_map(&manifest, pc, source_bytes)?; - Ok(PreparedDiscoveryBlock { - artifact_profile, - native, - entry: pc, - region_base: GuestAddress(base), - generation, - analysis, - prepared: Prepared { - key, - cache_hit: false, - manifest, + #[cfg(feature = "std")] + let (prepared, native) = + crate::prepare_block_plan(window, pc, cache_root, self.target, plan)?; + #[cfg(not(feature = "std"))] + let (prepared, native) = { + let identity = crate::block_plan_identity(window, pc, self.target, &plan)?; + let key = sha256(&serde_json::to_vec(&identity)?); + let requirements = plan.memory_requirements(); + let (manifest, native) = + crate::artifact::prepare::generate(identity, requirements, || { + plan.compile().map(|block| block.native) + })?; + ( + Prepared { + key, + cache_hit: false, + manifest, + }, + native, + ) + }; + validate_source_map(&prepared.manifest, pc, source_bytes)?; + Ok(( + PreparedDiscoveryBlock { + artifact_profile, + entry: pc, + region_base: GuestAddress(base), + generation, + analysis, + prepared, }, - }) + native, + )) } /// Follow known static successors only. Call continuations are candidates, @@ -288,3 +263,40 @@ impl BlockRuntime { }) } } + +#[cfg(all(test, feature = "std"))] +mod tests { + use super::*; + + #[test] + fn runtime_preparation_returns_the_validated_native_snapshot() -> anyhow::Result<()> { + let cache = tempfile::tempdir()?; + let mut runtime = BlockRuntime::new(1, cache.path().to_owned()); + let entry = GuestAddress(0x1000); + let source = [0x9100_0400u32, 0xd65f_03c0] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + runtime.register_code(entry, source)?; + let (fresh, original) = runtime.prepare_snapshot(entry)?; + assert!(!fresh.prepared.cache_hit); + let (hit, checked) = runtime.prepare_snapshot(entry)?; + assert!(hit.prepared.cache_hit); + assert_eq!(hit.prepared.key, fresh.prepared.key); + assert_eq!(checked, original); + assert_eq!( + hit.prepared.manifest.native_sha256, + stela_formats::sha256(&checked) + ); + + let mut corrupted = original; + corrupted[0] ^= 1; + std::fs::write(hit.prepared.directory.join("native.bin"), &corrupted)?; + assert!(matches!( + runtime.prepare_snapshot(entry), + Err(crate::Error::InvalidCacheEntry { .. }) + )); + assert_ne!(checked, corrupted); + Ok(()) + } +} diff --git a/crates/stela-engine/src/blocks/tests.rs b/crates/stela-engine/src/blocks/tests.rs index 5a6d494b31..cfe4fa5a12 100644 --- a/crates/stela-engine/src/blocks/tests.rs +++ b/crates/stela-engine/src/blocks/tests.rs @@ -648,6 +648,208 @@ mod resident { Ok(runtime) } + #[test] + fn ordinary_address_pair_respects_standalone_entry_and_truncated_source() -> Result<()> { + const ADRP: u32 = 0xb000_0000; // adrp x0, BASE+0x1000 + const ADD: u32 = 0x9100_2000; // add x0, x0, #8 + let cache = tempfile::tempdir()?; + let add_pc = GuestAddress(BASE.0 + 4); + let mut runtime = ordinary(cache.path(), &[ADRP, ADD, RET_X30])?; + for (entry, value) in [(BASE, BASE.0 + 0x1008), (add_pc, 5)] { + let mut state = thread(u64::MAX - 2); + state.pc = entry; + let mut expected = state.registers.clone(); + expected.x[0] = value; + // SAFETY: pure register instructions and RET to STOP. + let outcome = unsafe { runtime.run(&mut state, Some(STOP), 1)? }; + assert_eq!(outcome.blocks_executed, 1); + assert_eq!(state.registers, expected); + assert_eq!(state.pc, STOP); + } + let map = &runtime.loaded_manifest(BASE).unwrap().source_map; + assert_eq!(map[..2], [(BASE, 0), (add_pc, 10)]); + assert_eq!( + runtime.loaded_manifest(add_pc).unwrap().source_map[0], + (add_pc, 0) + ); + + let mut truncated = ordinary(cache.path(), &[ADRP])?; + let mut state = thread(100); + let mut expected = state.registers.clone(); + expected.x[0] = BASE.0 + 0x1000; + // SAFETY: the truncated input contains only ADRP. + let outcome = unsafe { truncated.run(&mut state, Some(add_pc), 1)? }; + assert_eq!(outcome.blocks_executed, 1); + assert_eq!(state.registers, expected); + assert_eq!(state.pc, add_pc); + Ok(()) + } + + #[test] + fn ordinary_wide_constant_respects_standalone_and_truncated_entries() -> Result<()> { + const MOVN: u32 = 0x92c0_0000 | (0xabcd << 5); + const MOVK_LOW: u32 = 0xf2a0_0000 | (0x1234 << 5); + const MOVK_HIGH: u32 = 0xf2e0_0000 | (0x5678 << 5); + const INITIAL: u64 = 0x9876_1357_9abc_def0; + let cache = tempfile::tempdir()?; + let second = GuestAddress(BASE.0 + 4); + let third = GuestAddress(BASE.0 + 8); + let mut runtime = ordinary(cache.path(), &[MOVN, MOVK_LOW, MOVK_HIGH, RET_X30])?; + for (entry, value) in [ + (BASE, 0x5678_5432_1234_ffff), + (second, 0x5678_1357_1234_def0), + (third, 0x5678_1357_9abc_def0), + ] { + let mut state = thread(INITIAL); + state.pc = entry; + let mut expected = state.registers.clone(); + expected.x[0] = value; + // SAFETY: only register instructions and RET to STOP. + let outcome = unsafe { runtime.run(&mut state, Some(STOP), 1)? }; + assert_eq!(outcome.blocks_executed, 1); + assert_eq!(state.registers, expected); + assert_eq!(state.pc, STOP); + } + let map = &runtime.loaded_manifest(BASE).unwrap().source_map; + assert_eq!(map[..3], [(BASE, 0), (second, 1), (third, 11)]); + for (words, stop, value) in [ + (&[MOVN][..], second, 0xffff_5432_ffff_ffff), + (&[MOVN, MOVK_LOW][..], third, 0xffff_5432_1234_ffff), + ] { + let mut truncated = ordinary(cache.path(), words)?; + let mut state = thread(INITIAL); + let mut expected = state.registers.clone(); + expected.x[0] = value; + // SAFETY: the truncated inputs contain only register instructions. + let outcome = unsafe { truncated.run(&mut state, Some(stop), 1)? }; + assert_eq!(outcome.blocks_executed, 1); + assert_eq!(state.registers, expected); + assert_eq!(state.pc, stop); + } + Ok(()) + } + + #[test] + fn ordinary_trailing_zero_pair_respects_truncated_source_and_standalone_entry() -> Result<()> { + const RBIT: u32 = 0xdac0_0000; // rbit x0, x0 + const CLZ: u32 = 0xdac0_1000; // clz x0, x0 + let cache = tempfile::tempdir()?; + let clz_pc = GuestAddress(BASE.0 + 4); + let mut runtime = ordinary(cache.path(), &[RBIT, CLZ, RET_X30])?; + + for (entry, result) in [(BASE, 4), (clz_pc, 59)] { + let mut state = thread(16); + state.pc = entry; + let mut expected = state.registers.clone(); + expected.x[0] = result; + // SAFETY: pure register instructions and RET to STOP. + let outcome = unsafe { runtime.run(&mut state, Some(STOP), 1)? }; + assert_eq!(outcome.blocks_executed, 1); + assert_eq!(state.registers, expected); + assert_eq!(state.pc, STOP); + } + let mut truncated = ordinary(cache.path(), &[RBIT])?; + let mut state = thread(16); + let mut expected = state.registers.clone(); + expected.x[0] = 0x0800_0000_0000_0000; + // SAFETY: the truncated input contains only RBIT. + let outcome = unsafe { truncated.run(&mut state, Some(clz_pc), 1)? }; + assert_eq!(outcome.blocks_executed, 1); + assert_eq!(state.registers, expected); + assert_eq!(state.pc, clz_pc); + Ok(()) + } + + #[test] + fn ordinary_direct_ram_loop_keeps_budget_state_and_cached_source_map() -> Result<()> { + const BODY: [u32; 7] = [ + 0xf940_0022, // ldr x2, [x1] + 0xf940_0423, // ldr x3, [x1, #8] + SUBS_X0_ONE, + 0x9100_4021, // add x1, x1, #16 + 0x8b02_0084, // add x4, x4, x2 + 0x8b03_0084, // add x4, x4, x3 + 0x54ff_ff41, // b.ne BASE + ]; + const BRK: u32 = 0xd420_0120; + const DATA: [u64; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; + let words: Vec<_> = BODY.into_iter().chain([BRK]).collect(); + let next = GuestAddress(BASE.0 + (BODY.len() * size_of::()) as u64); + let mut input = DATA.to_vec(); + let base = input.as_mut_ptr() as u64; + let iterations = DATA.len() / 2; + let initial = || { + let mut state = thread(iterations as u64); + state.registers.x[1] = base; + state + }; + let expected = |completed: usize| { + let mut state = initial().registers; + if completed != 0 { + let last = completed * 2 - 2; + state.x[0] -= completed as u64; + state.x[1] += (completed * 2 * size_of::()) as u64; + state.x[2] = DATA[last]; + state.x[3] = DATA[last + 1]; + state.x[4] = state.x[4].wrapping_add(DATA[..last + 2].iter().sum()); + state.nzcv = ARM_CARRY | if completed == iterations { ARM_ZERO } else { 0 }; + } + state + }; + let cache = tempfile::tempdir()?; + let mut runtime = ordinary(cache.path(), &words)?; + for budget in 0..=iterations { + let mut state = initial(); + // SAFETY: each iteration reads two aligned, live elements of + // input before advancing the pointer. The loop writes no RAM. + let outcome = unsafe { runtime.run(&mut state, Some(next), budget)? }; + assert_eq!(outcome.blocks_executed, budget); + assert_eq!(state.registers, expected(budget)); + if budget == iterations { + assert_eq!(state.pc, next); + assert_eq!(outcome.reason, StopReason::StopAddress); + } else { + assert_eq!(state.pc, BASE); + assert_eq!(outcome.reason, StopReason::BudgetExhausted); + } + } + + let manifest = runtime.loaded_manifest(BASE).unwrap(); + let source: Vec<_> = BODY.into_iter().flat_map(u32::to_le_bytes).collect(); + assert_eq!( + manifest.identity.source_sha256, + stela_formats::sha256(&source) + ); + assert_eq!( + manifest.identity.abi, + BlockProfile::new(Features::RESIDENT_LOOPS).abi() + ); + assert_eq!(manifest.source_map[0], (BASE, 0)); + assert_eq!(manifest.source_map.len(), BODY.len()); + assert!(manifest.source_map.windows(2).all(|pair| { + pair[1].0.0 - pair[0].0.0 == size_of::() as u64 && pair[1].1 > pair[0].1 + })); + let mut reload = ordinary(cache.path(), &words)?; + let mut state = initial(); + // SAFETY: the same immutable array and source, followed by a BRK + // that returns a modeled trap instead of accessing memory. + let outcome = unsafe { reload.run(&mut state, None, iterations + 1)? }; + assert_eq!(outcome.blocks_executed, iterations + 1); + assert_eq!(outcome.disk_cache_hits, 1); + assert_eq!( + reload.loaded_manifest(BASE).unwrap().source_map, + manifest.source_map + ); + assert_eq!(state.registers, expected(iterations)); + assert_eq!(state.pc, next); + assert!( + matches!(outcome.reason, StopReason::SynchronousTrap { trap } + if trap.kind == stela_compiler::block::TrapKind::SoftwareBreakpoint + && trap.instruction_pc == next && trap.immediate == 9) + ); + Ok(()) + } + fn crc_thread() -> (ThreadState, GuestState) { let mut state = thread(0); state.registers.x[8] = 0x1234_5678_0000_0000 | u64::from(CRC_INITIAL); diff --git a/crates/stela-engine/src/floating/tests.rs b/crates/stela-engine/src/floating/tests.rs index aa1c65eabb..2e7c71a6c9 100644 --- a/crates/stela-engine/src/floating/tests.rs +++ b/crates/stela-engine/src/floating/tests.rs @@ -1360,6 +1360,99 @@ fn unsupported_conversion_controls_preserve_every_register_flags_and_status() { } } +#[test] +fn vector_self_comparisons_accept_zeros_and_infinities_without_fp_status() { + use crate::execution::platform::Mapping; + use stela_compiler::{ + GuestAddress, TargetCpu, + aarch64::floating::{FPCR_DN, FPCR_EXCEPTION_ENABLE_MASK, FPCR_FZ, FPCR_FZ16}, + block::{BlockProfile, CompilationPlan, ExitKind, Features}, + }; + + const PC: u64 = 0x1000; + for (word, format, lanes) in [ + (0x0e41_2420u32, Format::Half, 4), + (0x4e41_2420, Format::Half, 8), + (0x0e21_e421, Format::Single, 2), + (0x4e21_e420, Format::Single, 4), + (0x4e61_e420, Format::Double, 2), + ] { + let (infinity, one, quiet) = match format { + Format::Half => (0x7c00, 0x3c00, 0x0200), + Format::Single => (0x7f80_0000, 0x3f80_0000, 0x0040_0000), + Format::Double => ( + 0x7ff0_0000_0000_0000, + 0x3ff0_0000_0000_0000, + 0x0008_0000_0000_0000, + ), + }; + let operation = FloatingPointOperation::decode(word).unwrap().unwrap(); + let block = CompilationPlan::new( + &word.to_le_bytes(), + GuestAddress(PC), + &stela_compiler::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::Baseline, + ), + ) + .unwrap() + .compile() + .unwrap(); + let mapping = Mapping::new(&stela_compiler::x86_64::pinned::entered( + &block.native.x86_64_code, + )) + .unwrap(); + let sign = 1 << (format.bits() - 1); + for (first, ordinary) in [ + (0, true), + (sign, true), + (infinity, true), + (infinity | sign, true), + (one, true), + (1, false), + (infinity | 1, false), + (infinity | quiet, false), + ] { + for fpcr in [ + 0, + FPCR_AH | FPCR_DN | FPCR_FZ | FPCR_FZ16, + FPCR_EXCEPTION_ENABLE_MASK, + ] { + let mut state = GuestState { + fpcr, + fpsr: FPSR_QC, + ..GuestState::default() + }; + // Signaling NaNs in the inactive high half cannot cause a fallback. + for lane in 0..128 / format.bits() { + write_lane( + &mut state.v[1], + format.bits(), + lane, + if lane < lanes { one } else { infinity | 1 }, + ); + } + write_lane(&mut state.v[1], format.bits(), 0, first); + let mut actual = state.clone(); + let mut expected = state.clone(); + let expected_result = complete(&mut expected, &operation); + // SAFETY: baseline non-memory code accesses only the provided frame. + let exit = unsafe { mapping.call_block(&mut actual) }.unwrap(); + if ordinary && expected_result.is_ok() { + assert_eq!(exit.kind, ExitKind::Fallthrough as u64); + assert_eq!(exit.next_pc, PC + 4); + } else { + assert_eq!(exit.kind, ExitKind::FloatingPoint as u64); + assert_eq!(exit.next_pc, PC); + assert_eq!(actual, state); + assert_eq!(complete(&mut actual, &operation), expected_result); + } + assert_eq!(actual, expected); + } + } + } +} + #[cfg(all(feature = "std", target_arch = "x86_64"))] mod fused_native; mod half_conversion_native; diff --git a/crates/stela-engine/src/floating/tests/half_conversion_native.rs b/crates/stela-engine/src/floating/tests/half_conversion_native.rs index 8e8580cfc6..eccb4d65ba 100644 --- a/crates/stela-engine/src/floating/tests/half_conversion_native.rs +++ b/crates/stela-engine/src/floating/tests/half_conversion_native.rs @@ -51,10 +51,11 @@ const FORMS: [u32; 30] = [ ]; fn compile(word: u32, target: TargetCpu) -> Mapping { - let source: Vec<_> = [PREFIX, word, SUFFIX] - .into_iter() - .flat_map(u32::to_le_bytes) - .collect(); + compile_words(&[PREFIX, word, SUFFIX], target) +} + +fn compile_words(words: &[u32], target: TargetCpu) -> Mapping { + let source: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect(); let block = CompilationPlan::new( &source, GuestAddress(PC), @@ -169,3 +170,47 @@ fn half_conversions_match_completion_on_each_host_recipe() { assert_eq!(inline == 0, target == TargetCpu::Baseline, "{target:?}"); } } + +#[test] +fn half_widening_keeps_all_finite_lanes_native_on_sse2() { + for (word, part) in [(0x0e21_7820, 0), (0x4e21_7820, 1)] { + let operation = FloatingPointOperation::decode(word).unwrap().unwrap(); + let mapping = compile_words(&[PREFIX, word], TargetCpu::Baseline); + for first in (0..=u16::MAX).step_by(4) { + let mut state = GuestState { + fpcr: FPCR_AH | FPCR_AHP | FPCR_FZ | FPCR_FIZ | FPCR_FZ16 | FPCR_DN, + fpsr: FPSR_QC, + ..GuestState::default() + }; + // The unused half contains signaling NaNs, including for FCVTL2. + state.v[SOURCE] = [0x7c01_7c01_7c01_7c01; 2]; + state.v[SOURCE][part] = (0..4).fold(0, |bits, lane| { + bits | u64::from(first + lane) << (16 * lane) + }); + let finite = first & 0x7c00 != 0x7c00; + assert_eq!(check(&mapping, &operation, state), finite, "{first:#06x}"); + } + + for special in [0x7c00, 0xfc00, 0x7c01, 0xfe00] { + let mut state = GuestState::default(); + state.v[SOURCE][part] = special; + assert!(!check(&mapping, &operation, state)); + } + + let mut state = GuestState { + fpcr: FPCR_EXCEPTION_ENABLE_MASK, + ..GuestState::default() + }; + state.v[0] = [u64::MAX; 2]; + assert!(complete(&mut state.clone(), &operation).is_err()); + let mut expected = state.clone(); + expected.x[8] += 1; + let before_mxcsr = mxcsr(); + // SAFETY: compiled for the host baseline and only accesses its frame. + let exit = unsafe { mapping.call_block(&mut state) }.unwrap(); + assert_eq!(exit.kind, ExitKind::FloatingPoint as u64); + assert_eq!(exit.next_pc, PC + 4); + assert_eq!(state, expected); + assert_eq!(mxcsr(), before_mxcsr); + } +} diff --git a/crates/stela-engine/src/json.rs b/crates/stela-engine/src/json.rs index 85b6a534e9..f8ac970615 100644 --- a/crates/stela-engine/src/json.rs +++ b/crates/stela-engine/src/json.rs @@ -3,6 +3,12 @@ use crate::{Result, error::Io}; use serde::Serialize; use std::{fs::File, io::Write, path::Path}; +pub(crate) fn pretty_bytes(value: &impl Serialize) -> Result> { + let mut bytes = serde_json::to_vec_pretty(value)?; + bytes.push(b'\n'); + Ok(bytes) +} + /// Write `value` as pretty JSON, replacing `path` atomically. Readers see the /// old or the new file; durability across power loss is not promised. pub fn write_json(path: &Path, value: &impl Serialize) -> Result<()> { @@ -11,8 +17,7 @@ pub fn write_json(path: &Path, value: &impl Serialize) -> Result<()> { .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")); std::fs::create_dir_all(parent).io("create a JSON file's directory")?; - let mut bytes = serde_json::to_vec_pretty(value)?; - bytes.push(b'\n'); + let bytes = pretty_bytes(value)?; let mut tmp = tempfile::NamedTempFile::new_in(parent).io("create a temporary JSON file")?; tmp.write_all(&bytes).io("write a JSON file")?; tmp.persist(path) diff --git a/crates/stela-engine/src/lib.rs b/crates/stela-engine/src/lib.rs index a88419c809..ca2ef13397 100644 --- a/crates/stela-engine/src/lib.rs +++ b/crates/stela-engine/src/lib.rs @@ -77,12 +77,10 @@ use artifact::prepare::{MAX_CACHE_MANIFEST_BYTES, MAX_CACHE_NATIVE_BYTES}; #[cfg(feature = "std")] fn bounded_file(path: &Path, limit: usize) -> Result> { let file = std::fs::File::open(path).io("open a cache file")?; - require!( - file.metadata().io("read a cache file's size")?.len() <= limit as u64, - "cache file exceeds size limit", - limit - ); + let size = file.metadata().io("read a cache file's size")?.len(); + require!(size <= limit as u64, "cache file exceeds size limit", limit); let mut bytes = Vec::new(); + bytes.try_reserve_exact(size as usize)?; file.take(limit as u64 + 1) .read_to_end(&mut bytes) .io("read a cache file")?; @@ -124,7 +122,7 @@ fn validate( identity: &Identity, memory_requirements: Option, profile: stela_compiler::block::BlockProfile, -) -> Result { +) -> Result<(Manifest, Vec)> { let manifest_bytes = bounded_file(&directory.join("manifest.json"), MAX_CACHE_MANIFEST_BYTES)?; let expected: String = serde_json::from_slice(&bounded_file( &directory.join("manifest.sha256.json"), @@ -141,7 +139,7 @@ fn validate( let native = bounded_file(&directory.join("native.bin"), MAX_CACHE_NATIVE_BYTES)?; artifact::prepare::validate_preparation_native(&manifest, &native)?; artifact::prepare::validate_preparation_claim(&manifest)?; - Ok(manifest) + Ok((manifest, native)) } #[cfg(feature = "std")] @@ -170,6 +168,7 @@ pub fn prepare_leaf_for_target( stela_compiler::compile(source, base, &stela_compiler::Options::new(profile, target)) .map(|block| block.native) }) + .map(|(prepared, _)| prepared) } #[derive(Debug, Serialize)] @@ -220,30 +219,12 @@ pub fn prepare_block_for_target( base, &stela_compiler::Options::new(profile, target), )?; - prepare_block_plan(source, base, root, target, plan) -} - -/// Ordinary dispatch may choose the resident ABI; service profiles keep their -/// own call contract. -#[cfg(feature = "std")] -pub(crate) fn prepare_runtime_block_for_target( - source: &[u8], - base: GuestAddress, - root: &Path, - profile: stela_compiler::block::BlockProfile, - target: stela_compiler::TargetCpu, -) -> Result<(PreparedBlock, stela_compiler::block::BlockProfile)> { - let plan = stela_compiler::block::CompilationPlan::new( - source, - base, - &stela_compiler::Options::new(profile, target), - )? - .with_resident_loops(); - let artifact_profile = plan.profile(); - Ok(( - prepare_block_plan(source, base, root, target, plan)?, - artifact_profile, - )) + let source_bytes = plan.source_bytes(); + let (prepared, _) = prepare_block_plan(source, base, root, target, plan)?; + Ok(PreparedBlock { + source_bytes, + prepared, + }) } #[cfg(feature = "std")] @@ -253,17 +234,12 @@ fn prepare_block_plan( root: &Path, target: stela_compiler::TargetCpu, plan: stela_compiler::block::CompilationPlan, -) -> Result { +) -> Result<(Prepared, Vec)> { let profile = plan.profile(); - let source_bytes = plan.source_bytes(); let memory_requirements = plan.memory_requirements(); let identity = block_plan_identity(source, base, target, &plan)?; - let prepared = prepare(identity, root, memory_requirements, profile, || { + prepare(identity, root, memory_requirements, profile, || { plan.compile().map(|b| b.native) - })?; - Ok(PreparedBlock { - source_bytes, - prepared, }) } @@ -298,9 +274,11 @@ fn prepare( memory_requirements: Option, profile: stela_compiler::block::BlockProfile, generate: impl FnOnce() -> Result, -) -> Result { +) -> Result<(Prepared, Vec)> { let key = sha256(&serde_json::to_vec(&identity)?); - std::fs::create_dir_all(root).io("create the translation cache")?; + if !root.is_dir() { + std::fs::create_dir_all(root).io("create the translation cache")?; + } let root = root.canonicalize().io("resolve the translation cache")?; let directory = root.join(&key); let invalid = |cause| Error::InvalidCacheEntry { @@ -308,14 +286,17 @@ fn prepare( cause: alloc::boxed::Box::new(cause), }; if directory.exists() { - let manifest = + let (manifest, native) = validate(&directory, &identity, memory_requirements, profile).map_err(invalid)?; - return Ok(Prepared { - key, - cache_hit: true, - directory, - manifest, - }); + return Ok(( + Prepared { + key, + cache_hit: true, + directory, + manifest, + }, + native, + )); } // Compile before creating an entry. Unsupported code never produces a hit. let (manifest, x86_64_code) = @@ -323,28 +304,44 @@ fn prepare( let pending = tempfile::tempdir_in(&root).io("create a pending cache entry")?; let path = pending.path().join("native.bin"); std::fs::write(&path, &x86_64_code).io("write generated code")?; - write_json(&pending.path().join("manifest.json"), &manifest)?; - let manifest_hash = sha256( - &std::fs::read(pending.path().join("manifest.json")).io("read a generated manifest")?, - ); - write_json(&pending.path().join("manifest.sha256.json"), &manifest_hash)?; + // The pending directory is private until the publication rename, so its + // files can be written directly. Hash the same bytes that go to disk. + let manifest_bytes = json::pretty_bytes(&manifest)?; + let manifest_hash = sha256(&manifest_bytes); + std::fs::write(pending.path().join("manifest.json"), manifest_bytes) + .io("write a generated manifest")?; + std::fs::write( + pending.path().join("manifest.sha256.json"), + json::pretty_bytes(&manifest_hash)?, + ) + .io("write a generated manifest checksum")?; match std::fs::rename(pending.path(), &directory) { - Ok(()) => Ok(Prepared { - key, - cache_hit: false, - directory, - manifest, - }), + Ok(()) => { + // The complete directory moved to its published name. + drop(pending.keep()); + Ok(( + Prepared { + key, + cache_hit: false, + directory, + manifest, + }, + x86_64_code, + )) + } // Another process published the same entry first; it must validate. Err(_) if directory.exists() => { - let manifest = + let (manifest, native) = validate(&directory, &identity, memory_requirements, profile).map_err(invalid)?; - Ok(Prepared { - key, - cache_hit: true, - directory, - manifest, - }) + Ok(( + Prepared { + key, + cache_hit: true, + directory, + manifest, + }, + native, + )) } Err(error) => Err(Error::Io { operation: "publish a cache entry".into(), diff --git a/crates/stela-engine/src/machine/cpu.rs b/crates/stela-engine/src/machine/cpu.rs index b491fda426..43582f81d5 100644 --- a/crates/stela-engine/src/machine/cpu.rs +++ b/crates/stela-engine/src/machine/cpu.rs @@ -677,13 +677,18 @@ impl Cpu { /// the HCR_EL2 bit, or the vGIC CPU interface's signal, which Arm ORs /// with it. A virtual SError (`HCR_VSE`) has only its bit. pub fn virtual_pending(&self, virtual_bit: u32) -> bool { + match virtual_bit { + HCR_VI | HCR_VF | HCR_VSE => self.virtual_pending_bits() & (1 << virtual_bit) != 0, + _ => self.hcr(virtual_bit), + } + } + + /// The virtual pending lines in their HCR_EL2 bit positions. Observe + /// the virtual controller once even when a caller needs all three. + pub(crate) fn virtual_pending_bits(&self) -> u64 { + let pending = self.read(Register::HCR_EL2) & (1 << HCR_VI | 1 << HCR_VF | 1 << HCR_VSE); let signals = self.vgic.signals(); - self.hcr(virtual_bit) - || match virtual_bit { - HCR_VI => signals.irq, - HCR_VF => signals.fiq, - _ => false, - } + pending | (u64::from(signals.irq) << HCR_VI) | (u64::from(signals.fiq) << HCR_VF) } /// Arm `IsPACMEnabled` for the current PSTATE: PACM sets PSTATE.PACM diff --git a/crates/stela-engine/src/machine/engine.rs b/crates/stela-engine/src/machine/engine.rs index 1a4027e887..53820d0bbb 100644 --- a/crates/stela-engine/src/machine/engine.rs +++ b/crates/stela-engine/src/machine/engine.rs @@ -5,7 +5,8 @@ mod mirrors; mod reports; use boundary::*; pub use boundary::{ - ConsumedPair, DeviceError, Devices, Host, LocalRegisters, NoDevices, ScalarRead, Start, + CodePartitions, ConsumedPair, DeviceError, Devices, Host, LocalRegisters, NoDevices, + ScalarRead, Start, }; use mirrors::*; use reports::*; @@ -20,6 +21,7 @@ mod caller; mod chain_control; mod clock; mod code_cache; +mod code_slots; mod compilation; mod compression; mod data_access; @@ -434,8 +436,8 @@ struct Block { /// or BLR form (or that form's PAC thunk) ends with, until a lookup dispatcher /// serves it. dynamic_site: Option, - /// Its first instruction, for the Branch Target check of a branch to it. - first: u32, + /// What its first instruction admits on a guarded page. + landing: fetch::Landing, /// The word of its last instruction, where it exits to the engine. terminal: u32, /// Exits to the engine at `terminal`, up to its limit. @@ -444,18 +446,21 @@ struct Block { /// the other contexts of its page /// ([`Machine::remember_target_page`]). fetched: bool, - /// The guest bytes it was compiled from, for [`Machine::stale_code`]. - source_bytes: u16, source_hash: u64, } // Every PE keeps one per block it ran, millions in all. -const _: () = assert!(size_of::() <= 80); +const _: () = assert!(size_of::() <= 72); impl Block { + /// One source-map entry per four-byte guest instruction. + fn source_bytes(&self) -> usize { + usize::from(self.instructions) * INSTRUCTION as usize + } + /// The PC of its last instruction. fn terminal_pc(&self) -> u64 { - self.pc + u64::from(self.source_bytes) - INSTRUCTION + self.pc + self.source_bytes() as u64 - INSTRUCTION } } @@ -668,6 +673,7 @@ pub struct Machine { preparation_metrics: Option, target: TargetCpu, blocks: table::Table, + code_slots: code_slots::CodeSlots, /// Slots of `blocks` whose code was reclaimed, for new blocks. free_blocks: Vec, /// The blocks this machine held when it last reclaimed code for memory, @@ -681,6 +687,7 @@ pub struct Machine { /// faultable access, which a native fault applies first. Kept apart /// from [`Block`], whose fields every exit reads. fault_recovery: recovery::Owners, + recovery_scratch: Vec, native_failure: Option, /// Every variant a block was compiled for, once: what a [`VariantId`] /// names. @@ -788,6 +795,7 @@ pub struct Machine { mirrors: alloc::boxed::Box, /// The chip's `Chip::admit`, indexed. admit_table: Arc, + system_decode: system_access::DecodeCache, /// The watched pages the host keeps unmapped. watch: Watch, /// The context the host last isolated predictions for. @@ -975,10 +983,12 @@ impl Machine { preparation_metrics: None, target, blocks: table::Table::new(), + code_slots: code_slots::CodeSlots::default(), free_blocks: Vec::new(), reclaimed_at: None, memory_release_blocks: MEMORY_RELEASE_BLOCKS, fault_recovery: recovery::Owners::new(), + recovery_scratch: Vec::new(), native_failure: None, variants: Vec::new(), index: block_index::BlockIndex::new(), @@ -1022,6 +1032,7 @@ impl Machine { pointer: alloc::boxed::Box::new(pointer::PointerService::new()), mirrors: alloc::boxed::Box::default(), admit_table, + system_decode: system_access::DecodeCache::default(), watch: Watch::default(), prediction_context: None, current: boot_processor, @@ -1105,10 +1116,7 @@ struct RamTables<'a, H: Host>(&'a mut H); impl mmu::TableMemory for RamTables<'_, H> { fn read_descriptor(&mut self, physical: u64) -> Option { - let mut bytes = [0; 8]; - self.0 - .read_ram(physical, &mut bytes) - .then(|| u64::from_le_bytes(bytes)) + self.0.read_ram_descriptor(physical) } fn update_descriptor(&mut self, physical: u64, old: u64, new: u64) -> Option { diff --git a/crates/stela-engine/src/machine/engine/block_index.rs b/crates/stela-engine/src/machine/engine/block_index.rs index cabcd0e2eb..59d92b43ae 100644 --- a/crates/stela-engine/src/machine/engine/block_index.rs +++ b/crates/stela-engine/src/machine/engine/block_index.rs @@ -206,11 +206,10 @@ mod tests { variant: VariantId(variant), successors: Box::default(), dynamic_site: None, - first: 0, + landing: super::super::fetch::Landing::None, terminal: 0, taken: 0, fetched: false, - source_bytes: 4, source_hash: 0, } } diff --git a/crates/stela-engine/src/machine/engine/boundary.rs b/crates/stela-engine/src/machine/engine/boundary.rs index 7085e52960..4ea4b15d7f 100644 --- a/crates/stela-engine/src/machine/engine/boundary.rs +++ b/crates/stela-engine/src/machine/engine/boundary.rs @@ -17,6 +17,14 @@ pub trait LocalRegisters: Send + Sync { fn storage(&self, encoding: Encoding) -> Option; } +/// Equal, consecutive native code ranges a host reclaims as whole parts. +#[derive(Clone, Copy)] +pub struct CodePartitions { + pub base: usize, + pub bytes_per_part: usize, + pub parts: usize, +} + /// The x86 machine beneath the engine: guest RAM, native code, shadow /// translation, time and waiting. pub trait Host { @@ -60,6 +68,14 @@ pub trait Host { /// Read guest RAM. False when any byte is not RAM. fn read_ram(&mut self, physical: u64, buffer: &mut [u8]) -> bool; + + /// Read an aligned, little-endian guest page-table descriptor. + fn read_ram_descriptor(&mut self, physical: u64) -> Option { + let mut bytes = [0; 8]; + self.read_ram(physical, &mut bytes) + .then(|| u64::from_le_bytes(bytes)) + } + /// Write guest RAM. False when any byte is not RAM. fn write_ram(&mut self, physical: u64, data: &[u8]) -> bool; /// Store `new` at `physical` if guest RAM there holds `expected`, in one @@ -135,6 +151,12 @@ pub trait Host { } /// Free every installed block. fn discard_code(&mut self); + /// Optional layout for indexing reclaimable block slots. It must + /// stay fixed from the first block installation until discard, and + /// reclamation must return one whole part or an empty range. + fn code_partitions(&self) -> Option { + None + } /// Free the oldest part of the code arena for new code, as a ring /// does, and return the host addresses it held: the engine forgets /// every block and leaf there before installing more. `None` from a diff --git a/crates/stela-engine/src/machine/engine/clock.rs b/crates/stela-engine/src/machine/engine/clock.rs index bd2aa08f43..a7a411a655 100644 --- a/crates/stela-engine/src/machine/engine/clock.rs +++ b/crates/stela-engine/src/machine/engine/clock.rs @@ -164,9 +164,9 @@ impl SharedClock { self.unlock(sequence); } - /// The count now, with the host's counter sampled while one published - /// state holds. - fn read(&self, counter: &mut impl Counter) -> u64 { + /// The count and offset from one publication, with the host's counter + /// sampled while that state holds. + fn read(&self, counter: &mut impl Counter) -> (u64, u64) { loop { let sequence = self.state.sequence.load(Ordering::Acquire); if sequence & 1 != 0 { @@ -178,7 +178,7 @@ impl SharedClock { let host = sampled(counter); fence(Ordering::Acquire); if self.state.sequence.load(Ordering::Relaxed) == sequence { - return host.wrapping_add(offset).min(ceiling); + return (host.wrapping_add(offset).min(ceiling), offset); } } } @@ -256,7 +256,7 @@ impl SharedClock { /// The count now, and the PE whose horizon holds it, if one does. pub fn status(&self, mut counter: impl Counter) -> ClockStatus { - let count = self.read(&mut counter); + let (count, _) = self.read(&mut counter); let ceiling = self.state.ceiling.load(Ordering::Acquire); let holder = (count >= ceiling) .then(|| { @@ -401,8 +401,9 @@ impl Clock { pub(super) fn read(&mut self, mut counter: impl Counter) -> u64 { let count = match &mut self.shared { Some(attachment) => { - attachment.offset = attachment.clock.state.offset.load(Ordering::Relaxed); - attachment.clock.read(&mut counter) + let (count, offset) = attachment.clock.read(&mut counter); + attachment.offset = offset; + count } None => return self.read_at(counter()), }; @@ -485,8 +486,9 @@ impl Clock { if attachment.waiting { attachment.waiting = false; attachment.blocks = blocks; - let (clock, pe) = (Arc::clone(&attachment.clock), attachment.pe); - clock.publish(pe, Progress::Ran(0), &mut counter); + attachment + .clock + .publish(attachment.pe, Progress::Ran(0), &mut counter); } return; } @@ -511,8 +513,9 @@ impl Clock { if !attachment.waiting { let ran = blocks.saturating_sub(attachment.blocks); attachment.blocks = blocks; - let (clock, pe) = (Arc::clone(&attachment.clock), attachment.pe); - clock.publish(pe, Progress::Ran(ran), &mut counter); + attachment + .clock + .publish(attachment.pe, Progress::Ran(ran), &mut counter); } return; } @@ -540,8 +543,9 @@ impl Clock { || attachment.clock.horizons[attachment.pe].load(Ordering::Relaxed) != UNBOUNDED) { attachment.waiting = true; - let (clock, pe) = (Arc::clone(&attachment.clock), attachment.pe); - clock.publish(pe, Progress::Waits, &mut counter); + attachment + .clock + .publish(attachment.pe, Progress::Waits, &mut counter); } } @@ -551,10 +555,11 @@ impl Clock { if let Some(attachment) = &mut self.shared { let host = counter(); if !attachment.waiting && host >= attachment.next_poll { - let (clock, pe) = (Arc::clone(&attachment.clock), attachment.pe); - let period = clock.lookahead.load(Ordering::Relaxed) / 2; + let period = attachment.clock.lookahead.load(Ordering::Relaxed) / 2; attachment.next_poll = host.saturating_add(period); - clock.publish(pe, Progress::Polls, &mut counter); + attachment + .clock + .publish(attachment.pe, Progress::Polls, &mut counter); } } } @@ -776,6 +781,24 @@ mod tests { assert!(!first.below(1140, || 5040)); } + #[test] + fn a_retried_shared_sample_uses_the_accepted_offset() { + let (_, mut first, mut second) = pair(); + first.start_slice(|| 1000, 0, 1); + second.start_slice(|| 1000, 0, 1); + let mut samples = 0; + let count = first.read(|| { + samples += 1; + if samples == 1 { + second.end_slice(|| 5000, 10_000); + } + 5040 + }); + assert_eq!((count, samples), (1100, 2)); + assert!(first.below(1141, || 5040)); + assert!(!first.below(1140, || 5040)); + } + #[test] fn a_stopped_pe_holds_the_count_within_its_lookahead_and_resumes_without_a_jump() { let (shared, mut first, mut second) = pair(); diff --git a/crates/stela-engine/src/machine/engine/code_cache.rs b/crates/stela-engine/src/machine/engine/code_cache.rs index 6b0d4bf01b..451d6b127e 100644 --- a/crates/stela-engine/src/machine/engine/code_cache.rs +++ b/crates/stela-engine/src/machine/engine/code_cache.rs @@ -25,7 +25,7 @@ impl Machine { let mut last = None; for (cursor, index) in self.index.sweep(self.stale_cursor).take(STALE_CHECKS) { let block = &self.blocks[index]; - bytes.resize(block.source_bytes as usize, 0); + bytes.resize(block.source_bytes(), 0); report.blocks += 1; if self.host.read_ram(block.physical, &mut bytes) && source_hash(&bytes) != block.source_hash @@ -388,10 +388,16 @@ impl Machine { if range.is_empty() { return; } - let evicted: Vec = (0..self.blocks.len()) - .filter(|&slot| range.contains(&self.blocks[slot].code.0)) - .collect(); - for &slot in &evicted { + let evicted = self.code_slots.take(&range).unwrap_or_else(|| { + (0..self.blocks.len()) + .filter(|&slot| { + let address = self.blocks[slot].code.0; + address != 0 && range.contains(&address) + }) + .map(|slot| slot as u32) + .collect() + }); + for slot in evicted.iter().map(|&slot| slot as usize) { let block = &self.blocks[slot]; let found = self .index @@ -400,7 +406,7 @@ impl Machine { self.index.forget_page(block.physical & !(FETCH_PAGE - 1)); } } - for &slot in &evicted { + for slot in evicted.iter().map(|&slot| slot as usize) { let block = &mut self.blocks[slot]; if block.taken != 0 { *self.exit_words.entry(block.terminal).or_default() += u64::from(block.taken); @@ -426,9 +432,18 @@ impl Machine { self.exit_words = self.exit_words(); self.host.discard_code(); self.lookup_dispatchers = Default::default(); - self.blocks.clear(); - self.free_blocks.clear(); - self.fault_recovery.clear(); + // A running guest normally fills the chunks again after a discard. + // Return their storage when freeing memory is the reason to discard. + if matches!(cause, Discard::Memory | Discard::Finished) { + self.blocks = table::Table::new(); + self.free_blocks = Vec::new(); + self.fault_recovery = recovery::Owners::new(); + } else { + self.blocks.clear(); + self.free_blocks.clear(); + self.fault_recovery.clear(); + } + self.code_slots = Default::default(); self.index.clear(); self.pages.clear(); self.scalable_leaves.clear(); diff --git a/crates/stela-engine/src/machine/engine/code_slots.rs b/crates/stela-engine/src/machine/engine/code_slots.rs new file mode 100644 index 0000000000..cdb52d5a23 --- /dev/null +++ b/crates/stela-engine/src/machine/engine/code_slots.rs @@ -0,0 +1,115 @@ +//! Block slots grouped by the native arena part that owns their code. + +use super::CodePartitions; +use alloc::vec::Vec; +use core::ops::Range; + +#[derive(Default)] +pub(super) enum CodeSlots { + #[default] + Uninitialized, + Linear, + Partitioned { + layout: CodePartitions, + slots: Vec>, + }, +} + +impl CodePartitions { + fn part_at(self, address: usize) -> Option { + let offset = address.checked_sub(self.base)?; + let part = offset.checked_div(self.bytes_per_part)?; + (part < self.parts).then_some(part) + } + + fn whole_part(self, range: &Range) -> Option { + let part = self.part_at(range.start)?; + let offset = range.start - self.base; + (offset.is_multiple_of(self.bytes_per_part) + && range.end.checked_sub(range.start) == Some(self.bytes_per_part)) + .then_some(part) + } +} + +impl CodeSlots { + pub(super) fn record( + &mut self, + address: usize, + slot: usize, + partitions: impl FnOnce() -> Option, + ) { + if matches!(self, Self::Uninitialized) { + *self = partitions().map_or(Self::Linear, |layout| { + let mut slots = Vec::new(); + if slots.try_reserve_exact(layout.parts).is_err() { + return Self::Linear; + } + slots.resize_with(layout.parts, Vec::new); + Self::Partitioned { layout, slots } + }); + } + let Self::Partitioned { layout, slots } = self else { + return; + }; + if let Some(part) = layout.part_at(address) + && let Ok(slot) = u32::try_from(slot) + && slots[part].try_reserve(1).is_ok() + { + slots[part].push(slot); + } else { + // The index is optional. A missing block would let reclaimed + // code remain reachable, so discard the index and scan instead. + *self = Self::Linear; + } + } + + /// Take the slots of a whole part. A non-partitioned or unexpected + /// reclaim falls back to scanning the authoritative block table. + pub(super) fn take(&mut self, range: &Range) -> Option> { + let Self::Partitioned { layout, slots } = self else { + return None; + }; + if let Some(part) = layout.whole_part(range) { + Some(core::mem::take(&mut slots[part])) + } else { + *self = Self::Linear; + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const LAYOUT: CodePartitions = CodePartitions { + base: 0x1000, + bytes_per_part: 0x80, + parts: 3, + }; + + #[test] + fn reclamation_takes_only_the_requested_part_and_supports_wraparound() { + let mut slots = CodeSlots::default(); + slots.record(0x1000, 5, || Some(LAYOUT)); + slots.record(0x107f, 2, || unreachable!()); + slots.record(0x1080, 4, || unreachable!()); + assert!(slots.take(&(0x1100..0x1180)).unwrap().is_empty()); + assert_eq!(slots.take(&(0x1000..0x1080)).unwrap(), [5, 2]); + slots.record(0x1000, 3, || unreachable!()); + assert_eq!(slots.take(&(0x1080..0x1100)).unwrap(), [4]); + assert_eq!(slots.take(&(0x1000..0x1080)).unwrap(), [3]); + } + + #[test] + fn nonconforming_reclamation_or_address_falls_back_to_linear_scan() { + let mut slots = CodeSlots::default(); + slots.record(0x1000, 5, || Some(LAYOUT)); + assert!(slots.take(&(0x1010..0x1080)).is_none()); + assert!(slots.take(&(0x1000..0x1080)).is_none()); + + let mut slots = CodeSlots::default(); + slots.record(0x1180, 5, || Some(LAYOUT)); + assert!(slots.take(&(0x1000..0x1080)).is_none()); + } +} diff --git a/crates/stela-engine/src/machine/engine/compilation.rs b/crates/stela-engine/src/machine/engine/compilation.rs index 39e525357c..d3479d3fae 100644 --- a/crates/stela-engine/src/machine/engine/compilation.rs +++ b/crates/stela-engine/src/machine/engine/compilation.rs @@ -136,14 +136,12 @@ impl Machine { { return; } - let (entry, first) = (block.code.0 as u64, block.first); + let entry = block.code.0 as u64; let page = pc & !(FETCH_PAGE - 1); let guarded = self.fetch[(page / FETCH_PAGE) as usize % FETCH_CACHE] .is_some_and(|fetched| fetched.page == page && fetched.guarded); let targets = match guarded { - true => (0..4u8) - .filter(|&btype| btype == 0 || self.branch_target_accepts(first, btype)) - .fold(0, |targets, btype| targets | 1 << btype), + true => block.landing.targets(&self.cpu) | 1, false => 0b1111, }; let context = self.chain.contexts()[chain::half(pc)]; @@ -460,16 +458,19 @@ impl Machine { "native spill/extended-register invocation capture is not qualified", ))); } + let source_bytes = compiled.source_bytes(); + let instructions = compiled.native().source_map.len(); if !compiled.matches_source(source) - || compiled.source_bytes() < INSTRUCTION as usize - || compiled.source_bytes() > source.len() - || pc.checked_add(compiled.source_bytes() as u64).is_none() + || source_bytes < INSTRUCTION as usize + || source_bytes > source.len() + || pc.checked_add(source_bytes as u64).is_none() + || instructions * INSTRUCTION as usize != source_bytes { return Err(self.unsupported(RequirementKind::Native( "native template has no matching admitted source extent", ))); } - let last = compiled.source_bytes() - INSTRUCTION as usize; + let last = source_bytes - INSTRUCTION as usize; let terminal = u32::from_le_bytes(source[last..last + 4].try_into().expect("a word")); // A heap without room for the block table's next chunk reuses the // oldest code's slots instead, or, when none of this machine's @@ -491,7 +492,7 @@ impl Machine { })? } }; - let terminal_pc = pc + compiled.source_bytes() as u64 - INSTRUCTION; + let terminal_pc = pc + last as u64; let mut successors: Vec = compiled .direct_exits() .iter() @@ -539,16 +540,15 @@ impl Machine { pc, physical, code, - instructions: compiled.native().source_map.len() as u16, + instructions: instructions as u16, variant: id, successors: successors.into_boxed_slice(), dynamic_site: dynamic_site.and_then(NonZeroU64::new), - first, + landing: fetch::Landing::of(first), terminal, taken: 0, fetched: false, - source_bytes: compiled.source_bytes() as u16, - source_hash: source_hash(&source[..compiled.source_bytes()]), + source_hash: source_hash(&source[..source_bytes]), }; let index = match self.free_blocks.pop() { Some(slot) => { @@ -557,6 +557,8 @@ impl Machine { } None => self.blocks.push(block), }; + self.code_slots + .record(code.0, index, || self.host.code_partitions()); self.fault_recovery.insert(index, compiled.installed()); self.index.insert(&self.blocks, index); self.mirrors.close_code_page(); diff --git a/crates/stela-engine/src/machine/engine/fetch.rs b/crates/stela-engine/src/machine/engine/fetch.rs index 256cbc8614..d9b5ca8458 100644 --- a/crates/stela-engine/src/machine/engine/fetch.rs +++ b/crates/stela-engine/src/machine/engine/fetch.rs @@ -3,6 +3,62 @@ use super::*; +/// Which BTYPEs may land on this instruction. PAC signing instructions use +/// the current SCTLR to decide whether they also admit BTYPE 0b11. +#[derive(Clone, Copy)] +#[repr(u8)] +pub(super) enum Landing { + None = 0b0000, + Bti = 0b0001, + Call = 0b0111, + Jump = 0b1011, + Any = 0b1111, + Pac = 0b1_0000, +} + +impl Landing { + pub(super) fn of(word: u32) -> Self { + const PACIASP: u32 = 0xd503_233f; + const PACIBSP: u32 = 0xd503_237f; + if word & 0xffff_ff3f == 0xd503_241f { + return match (word >> 6) & 3 { + 0b00 => Self::Bti, + 0b01 => Self::Call, + 0b10 => Self::Jump, + _ => Self::Any, + }; + } + if word == PACIASP || word == PACIBSP || block::pauth_lr::signs_with_implicit_bti(word) { + return Self::Pac; + } + if matches!(word & 0xffe0_001f, 0xd420_0000 | 0xd440_0000) { + Self::Any // BRK and HLT + } else { + Self::None + } + } + + pub(super) fn targets(self, cpu: &Cpu) -> u32 { + match self { + Self::Pac => { + const SCTLR_BT0: u64 = 1 << 35; + const SCTLR_BT1: u64 = 1 << 36; + let forbid = if cpu.pstate.el == 0 { + SCTLR_BT0 + } else { + SCTLR_BT1 + }; + if cpu.regime_sctlr() & forbid == 0 { + Self::Any as u32 + } else { + Self::Call as u32 + } + } + static_targets => static_targets as u32, + } + } +} + impl Machine { /// Arm `BranchTargetCheck`: the Branch Target exception (EC 0x0D) /// reports BTYPE in ISS and leaves it set for SPSR. @@ -371,29 +427,7 @@ impl Machine { /// [`Self::branch_target_compatible`] for BTYPE `btype`. pub(super) fn branch_target_accepts(&self, word: u32, btype: u8) -> bool { - const PACIASP: u32 = 0xd503_233f; - const PACIBSP: u32 = 0xd503_237f; - const SCTLR_BT0: u64 = 1 << 35; - const SCTLR_BT1: u64 = 1 << 36; - if word & 0xffff_ff3f == 0xd503_241f { - return match (word >> 6) & 3 { - 0b00 => btype == 0, - 0b01 => btype != 0b11, - 0b10 => btype != 0b10, - _ => true, - }; - } - if word == PACIASP || word == PACIBSP || block::pauth_lr::signs_with_implicit_bti(word) { - let sctlr = self.cpu.regime_sctlr(); - let forbid = if self.cpu.pstate.el == 0 { - SCTLR_BT0 - } else { - SCTLR_BT1 - }; - return btype != 0b11 || sctlr & forbid == 0; - } - // BRK and HLT. - matches!(word & 0xffe0_001f, 0xd420_0000 | 0xd440_0000) + Landing::of(word).targets(&self.cpu) & (1 << btype) != 0 } /// The EL an FP/SIMD access traps to, if it traps (Arm diff --git a/crates/stela-engine/src/machine/engine/interrupts.rs b/crates/stela-engine/src/machine/engine/interrupts.rs index b9030100aa..b8343c9bab 100644 --- a/crates/stela-engine/src/machine/engine/interrupts.rs +++ b/crates/stela-engine/src/machine/engine/interrupts.rs @@ -13,33 +13,26 @@ impl Machine { // The count is read only when an answer can change with it alone: a // device answer with a deadline, a timer's or a PMI's. Every exit // asks, and a raw validation PE has none of them. - let timed = !matches!(self.device_lines, Some((_, u64::MAX, _))) - || self.timer_deadline().is_some() - || self - .cpu - .pmu - .as_ref() - .is_some_and(|monitor| monitor.deadline().is_some()); - let now = match timed { - true if self.lines_hold() => self.clock.last(), - true => self.now(), - false => 0, - }; - self.lines_at(now) - } - - /// Whether the count is below every count at which the running PE's - /// cached lines change with the count alone. - fn lines_hold(&mut self) -> bool { let Some((_, devices, pe)) = self.device_lines else { - return false; + let now = self.now(); + return self.lines_at(now); }; + let timer = self.timer_deadline(); let monitor = self.cpu.pmu.as_ref().and_then(|monitor| monitor.deadline()); - let change = [self.timer_deadline(), monitor] - .into_iter() - .flatten() - .fold(devices, u64::min); - pe == self.current && self.clock.below(change, || self.host.counter()) + let now = if devices == u64::MAX && timer.is_none() && monitor.is_none() { + 0 + } else { + let change = devices + .min(timer.unwrap_or(u64::MAX)) + .min(monitor.unwrap_or(u64::MAX)); + if pe == self.current && self.clock.below(change, || self.host.counter()) { + self.clock.last() + } else { + self.now() + } + }; + let device = self.device_lines_of(self.current, now); + self.merge_lines(device, now, timer) } /// The lines the devices drive into PE `pe` at count `now`: the cached @@ -84,12 +77,16 @@ impl Machine { let device = self.device_lines_of(self.current, now); // A timer signals exactly when the count reaches its deadline, which // only System register writes change. - let deadline = self.timer_deadline(); + let timer = self.timer_deadline(); + self.merge_lines(device, now, timer) + } + + fn merge_lines(&self, device: Lines, now: u64, timer: Option) -> Lines { self.cpu.core_lines(Lines { irq: device.irq, // Apple cores signal the generic timers and the PMI as FIQ. fiq: device.fiq - || deadline.is_some_and(|deadline| now >= deadline) + || timer.is_some_and(|deadline| now >= deadline) || monitor_asserted(&self.cpu, now), }) } @@ -155,16 +152,17 @@ impl Machine { /// SError that HCR_EL2.{VI,VF,VSE} hold for EL1 and EL0 outside the host. pub(super) fn deliver_interrupts(&mut self) -> bool { let lines = self.lines(); - let virtual_pending = self.cpu.pstate.el != 2 - && [HCR_VI, HCR_VF, HCR_VSE] - .into_iter() - .any(|bit| self.cpu.virtual_pending(bit)); - self.cpu.state.pending = if virtual_pending { + let virtual_pending = if self.cpu.pstate.el == 2 { + 0 + } else { + self.cpu.virtual_pending_bits() + }; + self.cpu.state.pending = if virtual_pending != 0 { u32::from(DAIF_A | DAIF_I | DAIF_F) } else { u32::from(if lines.irq { DAIF_I } else { 0 } | if lines.fiq { DAIF_F } else { 0 }) }; - if !lines.irq && !lines.fiq && !virtual_pending { + if !lines.irq && !lines.fiq && virtual_pending == 0 { return false; } let mut exception = None; @@ -178,15 +176,14 @@ impl Machine { break; } } - let guest = self.cpu.pstate.el != 2 && !self.cpu.in_host(); - if exception.is_none() && guest { + if exception.is_none() && virtual_pending != 0 && !self.cpu.in_host() { for (vector, routing, virtual_bit, mask) in [ (Vector::Fiq, HCR_FMO, HCR_VF, DAIF_F), (Vector::Irq, HCR_IMO, HCR_VI, DAIF_I), (Vector::SError, HCR_AMO, HCR_VSE, DAIF_A), ] { if self.cpu.hcr(routing) - && self.cpu.virtual_pending(virtual_bit) + && virtual_pending & (1 << virtual_bit) != 0 && self.cpu.pstate.daif & mask == 0 { let syndrome = if vector == Vector::SError { @@ -226,12 +223,15 @@ impl Machine { /// the last sample. Sampling before the event register is read and before /// every write that changes a stream gives each tick the controls it had. pub(crate) fn sample_events(&mut self, now: u64) { - if let Some(previous) = self.event_sample + // An already pending event absorbs every stream edge through this + // sample. The running PE is the sole consumer, but the sample still + // advances so the next WFE cannot see one of those edges again. + if let Some(previous) = self.event_sample.replace(now) + && !self.cpu.event_is_set() && timer::event(&self.cpu, previous, now) { self.cpu.signal_event(); } - self.event_sample = Some(now); } pub(super) fn timer_deadline(&mut self) -> Option { @@ -289,29 +289,36 @@ impl Machine { Timeout { limit, offset } } }); + let event_sample = match kind { + WaitKind::Event => { + let now = self.now(); + self.sample_events(now); + if self.cpu.consume_event() { + // The WFE of a spin-wait ends the PE's time slice: the PE + // it waits for runs next instead of after the slice. + self.slice_end = self.statistics.blocks; + return self.next(); + } + Some(now) + } + WaitKind::Interrupt => { + if self.interrupt_pending() { + return self.next(); + } + None + } + }; + if timeout + .is_some_and(|timeout| timeout.expired(event_sample.unwrap_or_else(|| self.now()))) + { + return self.next(); + } let el = self.cpu.pstate.el; let sctlr = self.cpu.regime_sctlr(); let (enable_bit, hcr_trap, form) = match kind { WaitKind::Interrupt => (1u64 << 16, HCR_TWI, 0b00), WaitKind::Event => (1u64 << 18, HCR_TWE, 0b01), }; - let now = self.now(); - if kind == WaitKind::Event { - self.sample_events(now); - } - match kind { - WaitKind::Event if self.cpu.consume_event() => { - // The WFE of a spin-wait ends the PE's time slice: the PE - // it waits for runs next instead of after the slice. - self.slice_end = self.statistics.blocks; - return self.next(); - } - WaitKind::Interrupt if self.interrupt_pending() => return self.next(), - _ => {} - } - if timeout.is_some_and(|timeout| timeout.expired(now)) { - return self.next(); - } // ISS.TI: 0b00 WFI, 0b01 WFE, 0b10 WFIT, 0b11 WFET; RV and the // register for the timeout forms. let iss = TRAPPED_AARCH64 diff --git a/crates/stela-engine/src/machine/engine/mirrors.rs b/crates/stela-engine/src/machine/engine/mirrors.rs index d1dd0be9f5..1b5c7baf1d 100644 --- a/crates/stela-engine/src/machine/engine/mirrors.rs +++ b/crates/stela-engine/src/machine/engine/mirrors.rs @@ -269,28 +269,11 @@ pub(super) fn stored(register: SystemRegister) -> bool { /// System registers no read of a System register follows: not its value, /// which only a read of the register itself takes, nor whether it traps. A -/// kernel writes them at each thread switch and timer. What derives from +/// kernel writes them at each thread switch. What derives from /// them goes as ever ([`Machine::forget_derived`]). pub(super) fn keeps_reads(register: SystemRegister) -> bool { use SystemRegister::*; - pointer_key(register) - || matches!( - register, - CONTEXTIDR_EL1 - | CONTEXTIDR_EL2 - | CNTP_CTL_EL0 - | CNTP_CVAL_EL0 - | CNTP_TVAL_EL0 - | CNTV_CTL_EL0 - | CNTV_CVAL_EL0 - | CNTV_TVAL_EL0 - | CNTHP_CTL_EL2 - | CNTHP_CVAL_EL2 - | CNTHP_TVAL_EL2 - | CNTHV_CTL_EL2 - | CNTHV_CVAL_EL2 - | CNTHV_TVAL_EL2 - ) + pointer_key(register) || matches!(register, CONTEXTIDR_EL1 | CONTEXTIDR_EL2) } /// Whether `register` is half of a PAC key. diff --git a/crates/stela-engine/src/machine/engine/native_failure.rs b/crates/stela-engine/src/machine/engine/native_failure.rs index 9094b90ae0..a9dc3e8d6f 100644 --- a/crates/stela-engine/src/machine/engine/native_failure.rs +++ b/crates/stela-engine/src/machine/engine/native_failure.rs @@ -82,8 +82,7 @@ impl Machine { let Some(block) = (index < self.blocks.len()).then(|| &self.blocks[index]) else { return Err(self.fail_native(index, fault, NativeFailureReason::UnknownCode)); }; - let (entry_pc, physical, source_bytes) = - (block.pc, block.physical, block.source_bytes as usize); + let (entry_pc, physical, source_bytes) = (block.pc, block.physical, block.source_bytes()); let Some(owner) = self.fault_recovery.get(&index) else { return Err(self.fail_native(index, fault, NativeFailureReason::UnknownCode)); }; @@ -96,7 +95,7 @@ impl Machine { let owner = self.fault_recovery.get_mut(&index).expect("found above"); let qualified = owner.qualify(entry_pc, record.as_deref()); let table = match qualified { - Ok(table) => table, + Ok(rows) => rows.rows_at_reusing(fault.offset, &mut self.recovery_scratch), Err(reason) => return Err(self.fail_native(index, fault, reason)), }; let recovery_site = match FaultRecovery::site_at(&table, fault.offset) { diff --git a/crates/stela-engine/src/machine/engine/parallel/shared_devices.rs b/crates/stela-engine/src/machine/engine/parallel/shared_devices.rs index 9004bfb017..597094009a 100644 --- a/crates/stela-engine/src/machine/engine/parallel/shared_devices.rs +++ b/crates/stela-engine/src/machine/engine/parallel/shared_devices.rs @@ -5,15 +5,13 @@ use super::super::{GateCall, GateOutcome, LocalRegisters}; use super::*; pub(super) struct Board { - pub(super) devices: Mutex, + pub(super) devices: Mutex>, pub(super) hub: Arc, /// Calls that found the devices' lock held, by [`Call`]. pub(super) waits: [AtomicU64; Call::ALL.len()], /// The latest count any machine passed, which every later call sees at /// least: the PEs' counters agree only to within their reads. pub(super) now: AtomicU64, - /// Each PE's device lines as last seen. - pub(super) lines: Mutex>, /// Each PE's latched pins as every call left them ([`pack`]), which /// another PE's machine reads without the lock: only the home machine /// advances the devices with time. @@ -37,6 +35,12 @@ pub(super) struct Board { pub(super) registers: [u64; 16], } +pub(super) struct BoardState { + devices: D, + /// Each PE's device lines as last seen, under the same lock as the devices. + lines: Vec, +} + /// Pins as [`Board::pins`] holds them: IRQ and FIQ, or [`UNLATCHED`] for /// devices whose lines need an advance to read. pub(super) fn pack(pins: Option) -> u8 { @@ -65,17 +69,14 @@ pub(super) fn register_bit(encoding: Encoding) -> Option { impl Board { pub(super) fn lock(&self, call: Call) -> Held<'_, D> { - let devices = match self.devices.try_lock() { - Ok(devices) => devices, + let state = match self.devices.try_lock() { + Ok(state) => state, Err(_) => { self.waits[call as usize].fetch_add(1, Ordering::Relaxed); self.devices.lock().unwrap_or_else(|e| e.into_inner()) } }; - Held { - board: self, - devices, - } + Held { board: self, state } } /// Record what the machines ask of `devices` at every step: the home @@ -143,26 +144,69 @@ impl Board { /// The devices while a call holds their lock; its release publishes what /// the call left for the home machine ([`Board::publish`]). pub(super) struct Held<'a, D: Devices> { - pub(super) board: &'a Board, - pub(super) devices: crate::platform::sync::MutexGuard<'a, D>, + board: &'a Board, + state: crate::platform::sync::MutexGuard<'a, BoardState>, +} + +impl Held<'_, D> { + /// The count the devices see for a call at `now`, at least as high as + /// every earlier call's. Only this guard can advance the count. + fn now(&self, now: u64) -> u64 { + let previous = self.board.now.load(Ordering::Relaxed); + if now > previous { + self.board.now.store(now, Ordering::Release); + } + previous.max(now) + } + + /// Tell every PE but `cpu` whose lines changed since it last saw them. + /// Every change reaches the devices under their lock, so a PE learns of + /// each from the call that made it, and needs no device deadline of its + /// own: only the home machine advances the devices with time. + fn notify(&mut self, cpu: usize, now: u64) { + let BoardState { + devices, + lines: seen, + } = &mut *self.state; + if let Some(own) = seen.get_mut(cpu) + && let Some(lines) = devices.pins(cpu) + { + // The caller reads its own lines after the call. + *own = lines; + } + for pe in self.board.hub.others(cpu) { + let pins = devices.pins(pe); + let lines = match pins { + Some(lines) => lines, + None => devices.lines(pe, now), + }; + // The receiver may read its pins as soon as the epoch changes, + // before this call releases the devices' lock. + self.board.publish_pins(pe, pins); + if lines != seen[pe] { + seen[pe] = lines; + self.board.hub.lines_changed(pe, now); + } + } + } } impl core::ops::Deref for Held<'_, D> { type Target = D; fn deref(&self) -> &D { - &self.devices + &self.state.devices } } impl core::ops::DerefMut for Held<'_, D> { fn deref_mut(&mut self) -> &mut D { - &mut self.devices + &mut self.state.devices } } impl Drop for Held<'_, D> { fn drop(&mut self) { - self.board.publish(&mut self.devices); + self.board.publish(&mut self.state.devices); } } @@ -194,11 +238,13 @@ impl SharedDevices { } } let board = Board { - devices: Mutex::new(devices), + devices: Mutex::new(BoardState { + devices, + lines: alloc::vec![Lines::default(); pes], + }), hub, waits: Default::default(), now: AtomicU64::new(0), - lines: Mutex::new(alloc::vec![Lines::default(); pes]), pins: (0..pes).map(|_| AtomicU8::new(UNLATCHED)).collect(), dma: AtomicU64::new(u64::MAX), reset: Mutex::new(None), @@ -253,17 +299,10 @@ impl SharedDevices { self.changing(Call::Home, usize::MAX, now, |devices, _| f(devices)) } - /// The count the devices see for a call at `now`, which no earlier - /// call's passes. Taken under the devices' lock, so calls see counts in - /// the order they reach the devices. - pub(super) fn now(&self, now: u64) -> u64 { - self.board.now.fetch_max(now, Ordering::AcqRel).max(now) - } - - /// Run `f` on the devices at `now`, as [`Self::now`] gives it. + /// Run `f` on the devices at `now`, as [`Held::now`] gives it. pub(super) fn at(&self, call: Call, now: u64, f: impl FnOnce(&mut D, u64) -> R) -> R { let mut devices = self.board.lock(call); - let now = self.now(now); + let now = devices.now(now); f(&mut devices, now) } @@ -289,39 +328,11 @@ impl SharedDevices { f: impl FnOnce(&mut D, u64) -> R, ) -> R { let mut devices = self.board.lock(call); - let now = self.now(now); + let now = devices.now(now); let result = f(&mut devices, now); - self.notify(&mut devices, cpu, now); + devices.notify(cpu, now); result } - - /// Tell every PE but `cpu` whose lines changed since it last saw them. - /// Every change reaches the devices under their lock, so a PE learns of - /// each from the call that made it, and needs no device deadline of its - /// own: only the home machine advances the devices with time. - pub(super) fn notify(&self, devices: &mut D, cpu: usize, now: u64) { - let mut seen = self.board.lines.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(own) = seen.get_mut(cpu) - && let Some(lines) = devices.pins(cpu) - { - // The caller reads its own lines after the call. - *own = lines; - } - for pe in self.board.hub.others(cpu) { - let pins = devices.pins(pe); - let lines = match pins { - Some(lines) => lines, - None => devices.lines(pe, now), - }; - // The receiver may read its pins as soon as the epoch changes, - // before this call releases the devices' lock. - self.board.publish_pins(pe, pins); - if lines != seen[pe] { - seen[pe] = lines; - self.board.hub.lines_changed(pe, now); - } - } - } } impl Devices for SharedDevices { @@ -455,10 +466,10 @@ impl Devices for SharedDevices { return lines; } let mut devices = self.board.lock(Call::Lines); - let now = self.now(now); + let now = devices.now(now); let lines = devices.lines(cpu, now); - self.board.lines.lock().unwrap_or_else(|e| e.into_inner())[cpu] = lines; - self.notify(&mut devices, cpu, now); + devices.state.lines[cpu] = lines; + devices.notify(cpu, now); lines } fn pins(&mut self, cpu: usize) -> Option { @@ -482,10 +493,10 @@ impl Devices for SharedDevices { return (self.lines(cpu, now), None); } let mut devices = self.board.lock(Call::Lines); - let now = self.now(now); + let now = devices.now(now); let (lines, deadline) = devices.lines_and_deadline(cpu, now); - self.board.lines.lock().unwrap_or_else(|e| e.into_inner())[cpu] = lines; - self.notify(&mut devices, cpu, now); + devices.state.lines[cpu] = lines; + devices.notify(cpu, now); (lines, deadline) } fn system_register( @@ -517,7 +528,11 @@ impl Devices for SharedDevices { } /// Only the home machine takes a reset, which stops every PE. fn take_reset(&mut self) -> Option { - if !self.home || !self.board.resetting.swap(false, Ordering::Acquire) { + let resetting = &self.board.resetting; + if !self.home + || !resetting.load(Ordering::Relaxed) + || !resetting.swap(false, Ordering::Acquire) + { return None; } self.board diff --git a/crates/stela-engine/src/machine/engine/parallel/tests.rs b/crates/stela-engine/src/machine/engine/parallel/tests.rs index b100e5e392..f800236d2e 100644 --- a/crates/stela-engine/src/machine/engine/parallel/tests.rs +++ b/crates/stela-engine/src/machine/engine/parallel/tests.rs @@ -974,6 +974,10 @@ fn only_the_home_machine_advances_the_devices_with_time_and_tells_the_others() { // Asking again changes nothing. home.deadline(30); assert_eq!(hub.lines_epoch(1), epoch + 1); + // A call from a PE whose counter read lagged cannot undo that advance. + assert!(!home.lines_and_deadline(0, 10).0.irq); + assert_eq!(hub.lines_epoch(1), epoch + 1); + assert!(worker.lines(1, 10).irq); } #[test] diff --git a/crates/stela-engine/src/machine/engine/processors.rs b/crates/stela-engine/src/machine/engine/processors.rs index ddc6577a7d..11a6983cef 100644 --- a/crates/stela-engine/src/machine/engine/processors.rs +++ b/crates/stela-engine/src/machine/engine/processors.rs @@ -598,35 +598,38 @@ impl Machine { } }) }; - let mut deadlines = Vec::new(); + let mut earliest = None; + let mut consider = |deadline| { + if let Some(deadline) = deadline { + earliest = Some(earliest.map_or(deadline, |prior: u64| prior.min(deadline))); + } + }; if !self.processor_paused(self.current) && !down(self.waiting) { - deadlines.extend([ - self.timer_deadline(), - self.cpu.pmu.as_ref().and_then(|monitor| monitor.deadline()), - streams(&self.cpu, self.waiting), - timeout(self.waiting), - ]); + consider(self.timer_deadline()); + consider(self.cpu.pmu.as_ref().and_then(|monitor| monitor.deadline())); + consider(streams(&self.cpu, self.waiting)); + consider(timeout(self.waiting)); } for (pe, peer) in self.peers.iter().enumerate() { if let Peer::Parked(parked) = peer && !self.processor_paused(pe) && !down(parked.waiting) { - deadlines.push(timer::deadline(&parked.cpu)); - deadlines.push( + consider(timer::deadline(&parked.cpu)); + consider( parked .cpu .pmu .as_ref() .and_then(|monitor| monitor.deadline()), ); - deadlines.push(streams(&parked.cpu, parked.waiting)); - deadlines.push(timeout(parked.waiting)); + consider(streams(&parked.cpu, parked.waiting)); + consider(timeout(parked.waiting)); } } - deadlines.push(self.devices.deadline(now)); - deadlines.push(self.devices.dma_deadline()); - deadlines.into_iter().flatten().min() + consider(self.devices.deadline(now)); + consider(self.devices.dma_deadline()); + earliest } /// Run PE `next` in place of the running one, which parks with its state. diff --git a/crates/stela-engine/src/machine/engine/recovery.rs b/crates/stela-engine/src/machine/engine/recovery.rs index 2467904f1a..814ba2e9eb 100644 --- a/crates/stela-engine/src/machine/engine/recovery.rs +++ b/crates/stela-engine/src/machine/engine/recovery.rs @@ -4,8 +4,10 @@ use super::{NativeCode, NativeFault, Preparation, table::Table}; use crate::translations::{Digest, Record, StoredBlock}; use alloc::{boxed::Box, sync::Arc, vec::Vec}; use stela_compiler::NativeBlock; +#[cfg(test)] +use stela_compiler::block::FaultRecovery; use stela_compiler::block::{ - CompiledBlock, FaultRecovery, PackedRecovery, RecoveryQualificationError, RecoveryTemplate, + CompiledBlock, PackedRecovery, RecoveryQualificationError, RecoveryTemplate, UnqualifiedFaultRecovery, }; use stela_compiler::x86_64::chain::DirectExit; @@ -34,18 +36,21 @@ pub(super) struct StoredOrigin { /// An installed block's recovery owner: its code's length and the rows that /// locate guest state at each faultable site of it. pub(super) struct CodeRecovery { - code_bytes: u32, rows: Rows, #[cfg(test)] qualification_attempts: usize, } enum Rows { - Qualified(PackedRecovery), + Qualified { + code_bytes: u32, + rows: PackedRecovery, + }, /// A stored record's entry, whose template and portable rows its first /// fault reads and emits again to qualify: replaced by the minted rows. Stored { origin: Arc, + code_bytes: u32, offset: u16, }, /// A template and portable rows in hand, as a record's entry gives them. @@ -53,9 +58,15 @@ enum Rows { Pending { template: Arc, rows: Box<[UnqualifiedFaultRecovery]>, + code_bytes: u32, }, } +// The code length shares the per-variant space of the row storage. Every +// installed block uses one slot, including those with no guest fault sites. +#[cfg(not(test))] +const _: () = assert!(core::mem::size_of::>() <= 24); + /// The installed blocks' recovery owners, by block slot. pub(super) struct Owners { slots: Table>, @@ -101,6 +112,11 @@ impl Owners { pub(super) fn len(&self) -> usize { self.slots.iter().flatten().count() } + + #[cfg(test)] + pub(super) fn capacity(&self) -> usize { + self.slots.capacity() + } } /// A terminal native implementation failure. Captured data and code owners stay @@ -223,16 +239,23 @@ impl Template { pub(super) fn installed(self) -> CodeRecovery { let code_bytes = self.emission.block.native.x86_64_code.len() as u32; let rows = match (self.origin, self.pending) { - (Some((origin, offset)), _) => Rows::Stored { origin, offset }, + (Some((origin, offset)), _) => Rows::Stored { + origin, + code_bytes, + offset, + }, #[cfg(test)] (None, Some(rows)) => Rows::Pending { template: self.emission, rows, + code_bytes, + }, + _ => Rows::Qualified { + code_bytes, + rows: PackedRecovery::new(&self.emission.block.fault_recovery), }, - _ => Rows::Qualified(PackedRecovery::new(&self.emission.block.fault_recovery)), }; CodeRecovery { - code_bytes, rows, #[cfg(test)] qualification_attempts: 0, @@ -243,7 +266,7 @@ impl Template { impl CodeRecovery { /// The installed code's length. pub(super) fn code_bytes(&self) -> usize { - self.code_bytes as usize + self.rows.code_bytes() as usize } /// Make the owner a stored record's: `template`'s, whose rows are this @@ -251,20 +274,24 @@ impl CodeRecovery { #[cfg(test)] pub(super) fn test_make_pending(&mut self, template: Arc) { let rows = self.test_portable_rows().into_boxed_slice(); - self.rows = Rows::Pending { template, rows }; + self.rows = Rows::Pending { + template, + rows, + code_bytes: self.rows.code_bytes(), + }; } /// The rows of an actual emitted plan. #[cfg(test)] pub(super) fn test_rows(&self) -> Vec { match &self.rows { - Rows::Qualified(rows) => rows.rows(), + Rows::Qualified { rows, .. } => rows.rows(), _ => panic!("actual emitted plan"), } } /// Change the rows of an actual emitted plan. #[cfg(test)] pub(super) fn test_edit_rows(&mut self, edit: impl FnOnce(&mut [FaultRecovery]) -> T) -> T { - let Rows::Qualified(packed) = &mut self.rows else { + let Rows::Qualified { rows: packed, .. } = &mut self.rows else { panic!("actual emitted plan"); }; let mut rows = packed.rows(); @@ -275,7 +302,7 @@ impl CodeRecovery { #[cfg(test)] pub(super) fn test_packed_bytes(&self) -> usize { match &self.rows { - Rows::Qualified(packed) => packed.bytes(), + Rows::Qualified { rows, .. } => rows.bytes(), _ => panic!("actual emitted plan"), } } @@ -284,7 +311,7 @@ impl CodeRecovery { match &self.rows { Rows::Pending { rows, .. } => rows.to_vec(), Rows::Stored { .. } => panic!("explicitly pending fixture"), - Rows::Qualified(rows) => rows + Rows::Qualified { rows, .. } => rows .rows() .iter() .map(UnqualifiedFaultRecovery::from) @@ -323,39 +350,35 @@ impl CodeRecovery { &mut self, pc: u64, record: Option<&Record>, - ) -> Result, NativeFailureReason> { - #[cfg(test)] - if !matches!(self.rows, Rows::Qualified(_)) { - self.qualification_attempts += 1; - } - if let Rows::Stored { origin, offset } = &self.rows { - let entry = record - .and_then(|record| record.find(*offset, &origin.context)) - .ok_or(NativeFailureReason::StoredRecord)?; - let stored = entry - .rebase(origin.page, &entry.input) - .ok_or(NativeFailureReason::StoredRecord)?; - let block = origin - .preparation - .qualify_recovery( - &entry.input, - pc, - RecoveryTemplate { - code: &stored.native.x86_64_code, - source_map: &stored.native.source_map, - source_bytes: stored.source_bytes, - direct_exits: &stored.direct_exits, - recovery: &stored.fault_recovery, - }, - ) - .map_err(NativeFailureReason::Qualification)?; - self.rows = Rows::Qualified(PackedRecovery::new(&block.fault_recovery)); - } - #[cfg(test)] - if let Rows::Pending { template, rows } = &self.rows { - let block = template - .preparation - .qualify_recovery( + ) -> Result<&PackedRecovery, NativeFailureReason> { + if !matches!(self.rows, Rows::Qualified { .. }) { + #[cfg(test)] + { + self.qualification_attempts += 1; + } + let block = match &self.rows { + Rows::Qualified { .. } => unreachable!("unqualified above"), + Rows::Stored { origin, offset, .. } => { + let entry = record + .and_then(|record| record.find(*offset, &origin.context)) + .ok_or(NativeFailureReason::StoredRecord)?; + let stored = entry + .rebase(origin.page, &entry.input) + .ok_or(NativeFailureReason::StoredRecord)?; + origin.preparation.qualify_recovery( + &entry.input, + pc, + RecoveryTemplate { + code: &stored.native.x86_64_code, + source_map: &stored.native.source_map, + source_bytes: stored.source_bytes, + direct_exits: &stored.direct_exits, + recovery: &stored.fault_recovery, + }, + ) + } + #[cfg(test)] + Rows::Pending { template, rows, .. } => template.preparation.qualify_recovery( &template.input, pc, RecoveryTemplate { @@ -365,14 +388,28 @@ impl CodeRecovery { direct_exits: &template.block.direct_exits, recovery: rows, }, - ) - .map_err(NativeFailureReason::Qualification)?; - self.rows = Rows::Qualified(PackedRecovery::new(&block.fault_recovery)); + ), + } + .map_err(NativeFailureReason::Qualification)?; + self.rows = Rows::Qualified { + code_bytes: self.rows.code_bytes(), + rows: PackedRecovery::new(&block.fault_recovery), + }; } - let Rows::Qualified(rows) = &self.rows else { + let Rows::Qualified { rows, .. } = &self.rows else { unreachable!("qualified above"); }; - Ok(rows.rows()) + Ok(rows) + } +} + +impl Rows { + fn code_bytes(&self) -> u32 { + match *self { + Self::Qualified { code_bytes, .. } | Self::Stored { code_bytes, .. } => code_bytes, + #[cfg(test)] + Self::Pending { code_bytes, .. } => code_bytes, + } } } diff --git a/crates/stela-engine/src/machine/engine/recovery/tests.rs b/crates/stela-engine/src/machine/engine/recovery/tests.rs index 5ace8907f7..c17518da96 100644 --- a/crates/stela-engine/src/machine/engine/recovery/tests.rs +++ b/crates/stela-engine/src/machine/engine/recovery/tests.rs @@ -12,7 +12,7 @@ fn legacy_first_fault_qualification_is_cached_and_reports_dispatcher_cost() { make_pending(&mut machine, index, &input); let mut owner = machine.fault_recovery.remove(&index).unwrap(); let started = std::time::Instant::now(); - let first = owner.qualify(BASE, None).unwrap(); + let first = owner.qualify(BASE, None).unwrap().rows(); let cold = started.elapsed(); assert!( first @@ -21,7 +21,7 @@ fn legacy_first_fault_qualification_is_cached_and_reports_dispatcher_cost() { ); let started = std::time::Instant::now(); for _ in 0..32 { - assert_eq!(owner.qualify(BASE, None).unwrap(), first); + assert_eq!(owner.qualify(BASE, None).unwrap().rows(), first); } let cached = started.elapsed(); assert_eq!( @@ -80,7 +80,7 @@ fn a_compiled_owner_keeps_only_its_packed_rows() { native_bytes, "the code's image, not a copy" ); - assert_eq!(owner.qualify(BASE, None).unwrap(), expected); + assert_eq!(owner.qualify(BASE, None).unwrap().rows(), expected); assert!( owner.test_packed_bytes() * 3 < unpacked, "{} packed bytes of {unpacked}", @@ -92,6 +92,7 @@ fn a_compiled_owner_keeps_only_its_packed_rows() { fn exact_lazy_qualification_replaces_portable_bank_with_only_minted_rows() { let (preparation, source, compiled) = store_window(); let expected = compiled.fault_recovery.clone(); + let code_bytes = compiled.native.x86_64_code.len(); let template = crate::translations::StoredBlock { native: compiled.native, source_bytes: compiled.source_bytes, @@ -103,9 +104,11 @@ fn exact_lazy_qualification_replaces_portable_bank_with_only_minted_rows() { .collect(), }; let mut owner = Template::stored(template, source, preparation, None).installed(); - assert_eq!(owner.qualify(BASE, None).unwrap(), expected); + assert_eq!(owner.code_bytes(), code_bytes); + assert_eq!(owner.qualify(BASE, None).unwrap().rows(), expected); + assert_eq!(owner.code_bytes(), code_bytes); assert_eq!(owner.qualification_attempts, 1); - assert_eq!(owner.qualify(BASE, None).unwrap(), expected); + assert_eq!(owner.qualify(BASE, None).unwrap().rows(), expected); assert_eq!(owner.qualification_attempts, 1); } @@ -127,5 +130,5 @@ fn fault_rows_survive_packing() { let expected = compiled.fault_recovery.clone(); let mut owner = Template::compiled(Arc::new(Emission::new(source, compiled, preparation))).installed(); - assert_eq!(owner.qualify(BASE, None).unwrap(), expected); + assert_eq!(owner.qualify(BASE, None).unwrap().rows(), expected); } diff --git a/crates/stela-engine/src/machine/engine/regime_state.rs b/crates/stela-engine/src/machine/engine/regime_state.rs index 9610007082..37dfdbafe8 100644 --- a/crates/stela-engine/src/machine/engine/regime_state.rs +++ b/crates/stela-engine/src/machine/engine/regime_state.rs @@ -5,9 +5,13 @@ use super::*; impl Machine { /// A write of `register`: a [`stored`] one reaches only its own cells, - /// one that [`keeps_reads`] all that derives from it but the cells, and - /// any other everything derived. + /// a timer channel's changes only its deadline, one that [`keeps_reads`] + /// all that derives from it but the cells, and any other everything derived. pub(super) fn register_written(&mut self, register: SystemRegister) { + if timer::channel_register(register) { + self.timers = None; + return; + } if keeps_reads(register) { return self.forget_derived(); } diff --git a/crates/stela-engine/src/machine/engine/scheduler.rs b/crates/stela-engine/src/machine/engine/scheduler.rs index 25e50ac3aa..e1a9030d47 100644 --- a/crates/stela-engine/src/machine/engine/scheduler.rs +++ b/crates/stela-engine/src/machine/engine/scheduler.rs @@ -354,12 +354,13 @@ impl Machine { if self.variants[block.variant.0 as usize].single { return None; } + if unlinked { + return Some(0); + } let context = self.chain.contexts()[chain::half(next_pc)]; let slot = chain::lookup_slot(next_pc, context); let entry = self.targets.find(slot, next_pc, context); - Some(if unlinked { - 0 - } else if entry.pc != next_pc { + Some(if entry.pc != next_pc { 1 } else if entry.context != context { 2 @@ -380,7 +381,8 @@ impl Machine { pub(super) fn link(&mut self, index: usize, next_pc: u64, word: impl Into) { let word = word.into(); let block = &self.blocks[index]; - if self.variants[block.variant.0 as usize].single + if block.successors.is_empty() + || self.variants[block.variant.0 as usize].single || self.traces.binary_search(&next_pc).is_ok() { return; diff --git a/crates/stela-engine/src/machine/engine/stored.rs b/crates/stela-engine/src/machine/engine/stored.rs index 827e7bf91e..030450fab1 100644 --- a/crates/stela-engine/src/machine/engine/stored.rs +++ b/crates/stela-engine/src/machine/engine/stored.rs @@ -156,6 +156,7 @@ impl Offer { } /// Off-path preparation from canonical immutable input. No native template /// or copied site can be supplied; this owner emits the block itself. + #[cfg(test)] pub(crate) fn compile( key: Digest, page: u64, @@ -224,23 +225,50 @@ impl Offer { /// addresses of its page, proven to move only by them /// ([`translations::prove`](crate::translations::prove)). pub fn prove(&self) -> Option { - let probes = crate::translations::probe_displacements(self.page).map(|displacement| { - self.preparation() - .compile_input(self.input(), self.pc.wrapping_add(displacement)) - .ok() - }); - let [Some(first), Some(second)] = &probes else { - return None; - }; - crate::translations::prove( + Self::prove_block( self.block(), self.input(), self.page, self.pc, self.context, - [first, second], + self.preparation(), ) } + + /// A pending source window owns no installed emission. Compile it for + /// proof without building an owned offer for other PEs. + pub(crate) fn prove_input( + input: &[u8], + page: u64, + pc: u64, + context: Digest, + preparation: &Preparation, + ) -> Option { + if page != pc & !(PAGE_BYTES as u64 - 1) || preparation.context(page) != context { + return None; + } + let block = preparation.compile_input(input, pc).ok()?; + Self::prove_block(&block, input, page, pc, context, preparation) + } + + fn prove_block( + block: &CompiledBlock, + input: &[u8], + page: u64, + pc: u64, + context: Digest, + preparation: &Preparation, + ) -> Option { + let probes = crate::translations::probe_displacements(page).map(|displacement| { + preparation + .compile_input(input, pc.wrapping_add(displacement)) + .ok() + }); + let [Some(first), Some(second)] = &probes else { + return None; + }; + crate::translations::prove(block, input, page, pc, context, [first, second]) + } } /// The fetch pages kept for their blocks at most; when full, the least diff --git a/crates/stela-engine/src/machine/engine/stored/tests.rs b/crates/stela-engine/src/machine/engine/stored/tests.rs index 037ca5920d..cf3d68d595 100644 --- a/crates/stela-engine/src/machine/engine/stored/tests.rs +++ b/crates/stela-engine/src/machine/engine/stored/tests.rs @@ -316,7 +316,7 @@ fn a_block_longer_than_the_first_window_compiles_and_is_stored_whole() { let Ok(Fetched::Block(index)) = first.fetch_block(BASE, false) else { panic!("block") }; - assert_eq!(first.blocks[index].source_bytes as usize, block_bytes); + assert_eq!(first.blocks[index].source_bytes(), block_bytes); let offer = first.host.store.as_mut().unwrap().offers.pop().unwrap(); assert_eq!(offer.input().len(), block_bytes); let mut record = Record::new(translations::translator_id(), offer.key); @@ -332,7 +332,7 @@ fn a_block_longer_than_the_first_window_compiles_and_is_stored_whole() { (second.statistics.compiled, second.statistics.stored), (0, 1) ); - assert_eq!(second.blocks[stored].source_bytes as usize, block_bytes); + assert_eq!(second.blocks[stored].source_bytes(), block_bytes); // A changed word past the first window, inside the block: the stored // block's bytes no longer match, and it is compiled. words[ADDS - 1] = 0x9100_0800; diff --git a/crates/stela-engine/src/machine/engine/system.rs b/crates/stela-engine/src/machine/engine/system.rs index 01d2bcd3c7..c390074e73 100644 --- a/crates/stela-engine/src/machine/engine/system.rs +++ b/crates/stela-engine/src/machine/engine/system.rs @@ -31,7 +31,7 @@ use { crate::machine::exception, crate::machine::exception::Class, crate::machine::exception::DAIF_A, crate::machine::exception::DAIF_D, crate::machine::exception::DAIF_F, crate::machine::exception::DAIF_I, crate::machine::exception::Pstate as PstateBits, - crate::machine::pmu::Pmu, crate::machine::registers::Lines, crate::machine::registers::Refusal, + crate::machine::pmu::Pmu, crate::machine::registers::Refusal, crate::machine::registers::trap_iss, crate::machine::system::ACCESSORS, crate::machine::system::AtAccess, crate::machine::system::CacheOp, crate::machine::system::CacheScope, crate::machine::system::CacheType, @@ -394,9 +394,8 @@ const ISR_F: u64 = 1 << 6; pub(super) struct Access<'a, H: Host, D: Devices> { machine: &'a mut Machine, rt: u8, - /// The interrupt lines and the system counter when the access started. - lines: Lines, - now: u64, + /// One counter sample for all timing calculations of this access. + now: Option, result: Option, translation: Translation, regime: bool, @@ -467,6 +466,10 @@ enum Code { } impl Access<'_, H, D> { + fn now(&mut self) -> u64 { + *self.now.get_or_insert_with(|| self.machine.now()) + } + fn refuse(&self, reason: &'static str) { if self.refusal.get().is_none() { self.refusal.set(Some(reason)); @@ -547,7 +550,12 @@ impl Access<'_, H, D> { /// counter read at EL0 or EL1 outside the host returns the physical /// count less its virtual offset: AMEVCNTVOFF0_EL2, or CNTVOFF_EL2 /// for the constant frequency counter, which has no offset register. - fn read_activity_monitor(&self, register: Register, index: u64) -> u64 { + fn read_activity_monitor(&mut self, register: Register, index: u64) -> u64 { + let now = if register == Register::AMEVCNTR0_EL0 { + self.now() + } else { + 0 + }; let cpu = &self.machine.cpu; let Some(monitors) = cpu.amu.as_ref() else { self.refuse("activity monitors without their model"); @@ -556,7 +564,7 @@ impl Access<'_, H, D> { if register != Register::AMEVCNTR0_EL0 { return monitors.enabled(); } - let count = monitors.count(index as usize, self.now, cpu.retired); + let count = monitors.count(index as usize, now, cpu.retired); let virtual_view = cpu.registers.has(Feature::FEAT_AMUv1p1) && cpu.pstate.el < 2 && !cpu.in_host() @@ -588,7 +596,7 @@ impl Access<'_, H, D> { Register::AMEVCNTR0_EL0 => None, _ => return None, }; - let (now, retired) = (self.now, self.machine.cpu.retired); + let (now, retired) = (self.now(), self.machine.cpu.retired); let Some(monitors) = self.machine.cpu.amu.as_mut() else { return Some(Err(Effect::Refused( "activity monitors without their model", @@ -603,9 +611,9 @@ impl Access<'_, H, D> { /// ISR_EL1: virtual interrupts while routed to EL2 from EL1 or EL0 /// outside the host, physical lines otherwise. - fn pending(&self) -> u64 { + fn pending(&mut self) -> u64 { + let lines = self.machine.lines(); let cpu = &self.machine.cpu; - let lines = self.lines; let guest = cpu.pstate.el != 2 && !cpu.in_host(); let line = |routing: u32, virtual_bit: u32, physical: bool| { if guest && cpu.hcr(routing) { @@ -826,13 +834,10 @@ impl Machine { let read = access.direction() == stela_compiler::aarch64::system::registers::Direction::Read; let (accessor, index) = self.lookup.find(encoding, read)?; - let lines = self.lines(); - let now = self.now(); let mut context = Access { machine: self, rt: access.rt(), - lines, - now, + now: None, result: None, translation: Translation::Unchanged, regime: false, diff --git a/crates/stela-engine/src/machine/engine/system/register_context.rs b/crates/stela-engine/src/machine/engine/system/register_context.rs index 287ce8a4b2..9dbdac51b4 100644 --- a/crates/stela-engine/src/machine/engine/system/register_context.rs +++ b/crates/stela-engine/src/machine/engine/system/register_context.rs @@ -123,7 +123,7 @@ impl Context for Access<'_, H, D> { self.result = Some(value); } - fn read(&self, register: Register, index: u64) -> u64 { + fn read(&mut self, register: Register, index: u64) -> u64 { let machine = &*self.machine; let cpu = &machine.cpu; // The reset address, where the board holds it (Apple's @@ -191,7 +191,10 @@ impl Context for Access<'_, H, D> { Register::OSDTRRX_EL1 => u64::from(cpu.dcc.rx), Register::OSDTRTX_EL1 => u64::from(cpu.dcc.tx), _ => match Channel::by_control(register) { - Some(channel) => channel.read_control(cpu, self.bank, self.now), + Some(channel) => { + let now = self.now(); + channel.read_control(&self.machine.cpu, self.bank, now) + } None => match (self.bank, cpu.apple.generic_timer.get(register)) { (Bank::Apple, Some(value)) => value, _ => { @@ -329,10 +332,12 @@ impl Context for Access<'_, H, D> { | Register::CNTVOFF_EL2 | Register::HCR_EL2 ) { - self.machine.sample_events(self.now); + let now = self.now(); + self.machine.sample_events(now); } if register == Register::TPIDR_EL1 { - self.machine.switch_thread(value, self.now); + let now = self.now(); + self.machine.switch_thread(value, now); } let cpu = &mut self.machine.cpu; let sctlr = matches!(register, Register::SCTLR_EL1 | Register::SCTLR_EL2); @@ -403,8 +408,9 @@ impl Context for Access<'_, H, D> { Ok(()) } - fn physical_count(&self) -> u64 { - timer::count(&self.machine.cpu, self.bank, self.now) + fn physical_count(&mut self) -> u64 { + let now = self.now(); + timer::count(&self.machine.cpu, self.bank, now) } fn nv_mem(&mut self, offset: u64) -> Result { diff --git a/crates/stela-engine/src/machine/engine/system/tests.rs b/crates/stela-engine/src/machine/engine/system/tests.rs index 51f9569215..6e75c4cb8b 100644 --- a/crates/stela-engine/src/machine/engine/system/tests.rs +++ b/crates/stela-engine/src/machine/engine/system/tests.rs @@ -302,6 +302,46 @@ const HCR_TWI: u64 = 1 << 13; type TestMachine = super::super::Machine; +#[test] +fn system_access_samples_the_counter_and_interrupts_only_when_needed() { + const ISR_EL1: Encoding = Encoding::new(3, 0, 12, 1, 0); + const CNTV_TVAL_EL0: Encoding = Encoding::new(3, 3, 14, 3, 0); + const CNTV_CTL_EL0: Encoding = Encoding::new(3, 3, 14, 3, 1); + use crate::machine::timer::ENABLE; + + let mut machine = machine_on(Chip::AppleM2, &[]); + machine.cpu.pstate = Pstate::reset(1); + let reads = machine.host.counter_reads; + let queries = machine.statistics.line_queries; + + machine + .system_instruction(access(true, MIDR_EL1, 0)) + .unwrap(); + machine.system_instruction(TLBI_VMALLE1).unwrap(); + assert_eq!(machine.host.counter_reads, reads); + assert_eq!(machine.statistics.line_queries, queries); + + machine.host.now = 1000; + machine.cpu.state.x[1] = 10; + machine + .system_instruction(access(false, CNTV_TVAL_EL0, 1)) + .unwrap(); + assert_eq!(machine.cpu.read(Register::CNTV_CVAL_EL0), 1010); + assert_eq!(machine.host.counter_reads, reads + 1); + assert_eq!(machine.statistics.line_queries, queries); + + machine.cpu.state.x[1] = ENABLE; + machine + .system_instruction(access(false, CNTV_CTL_EL0, 1)) + .unwrap(); + machine.host.now = 1010; + machine + .system_instruction(access(true, ISR_EL1, 0)) + .unwrap(); + assert_eq!(machine.cpu.state.x[0] & (1 << 6), 1 << 6); + assert_eq!(machine.statistics.line_queries, queries + 1); +} + fn el2_trap(machine: &mut TestMachine, word: u32) -> u64 { machine.cpu.pc = BASE; machine.cpu.pstate = Pstate::reset(1); @@ -2082,13 +2122,10 @@ fn el1_traps_to_el2( .iter() .flat_map(|accessor| (0..1u64 << accessor.index.len()).map(move |m| (accessor, m))) .map(|(accessor, m)| { - let lines = machine.lines(); - let now = machine.now(); let mut context = Access { machine: &mut machine, rt: 0, - lines, - now, + now: None, result: None, translation: Translation::Unchanged, regime: false, diff --git a/crates/stela-engine/src/machine/engine/system_access.rs b/crates/stela-engine/src/machine/engine/system_access.rs index 4dc9e7a095..b5b01952a2 100644 --- a/crates/stela-engine/src/machine/engine/system_access.rs +++ b/crates/stela-engine/src/machine/engine/system_access.rs @@ -3,16 +3,52 @@ use super::*; +/// A PE often completes the same architectural instruction words through +/// many different compiled blocks. Cache decoding only; the operation still +/// runs with the current registers, privilege and feature checks. +pub(super) struct DecodeCache([Option<(u32, SystemOperation)>; Self::SLOTS]); + +impl Default for DecodeCache { + fn default() -> Self { + Self([None; Self::SLOTS]) + } +} + +impl DecodeCache { + const SLOTS: usize = 64; + + fn operation(&mut self, pc: u64, word: u32) -> Option { + let slot = (word.wrapping_mul(0x9e37_79b9) >> (u32::BITS - Self::SLOTS.ilog2())) as usize; + let entry = &mut self.0[slot]; + if let Some((cached_word, operation)) = *entry + && cached_word == word + // The compiler includes a checked fallthrough address in its + // decoded instruction. A cached word must keep that refusal. + && pc <= u64::MAX - INSTRUCTION + { + return Some(operation); + } + let decoded = block::decode_system_mode_instruction(GuestAddress(pc), word) + .ok() + .flatten()? + .operation; + *entry = Some((word, decoded)); + Some(decoded) + } +} + impl Machine { pub(super) fn system_instruction(&mut self, word: u32) -> Step { - let pc = self.cpu.pc; - let instruction = match block::decode_system_mode_instruction(GuestAddress(pc), word) { - Ok(Some(instruction)) => instruction, - _ => return Err(self.refuse_system(word, "System exit at a word that is not System")), + let Some(operation) = self.system_decode.operation(self.cpu.pc, word) else { + return Err(self.refuse_system(word, "System exit at a word that is not System")); }; + self.complete_system_instruction(word, operation) + } + + fn complete_system_instruction(&mut self, word: u32, operation: SystemOperation) -> Step { // Apple's SDSB (`0x00201460` plus the domain), WKDMC and WKDMD; // `guarded` checks the GXF instructions. - let apple = match instruction.operation { + let apple = match operation { SystemOperation::Synchronization(_) if word & !3 == 0x0020_1460 => { Some(hacr::Operation::SynchronizationBarrier) } @@ -24,7 +60,7 @@ impl Machine { { return step; } - match instruction.operation { + match operation { SystemOperation::Exception(operation) => self.exception_instruction(operation), SystemOperation::Register(access) => self.register_instruction(word, access), SystemOperation::PstateImmediate(encoding) => { @@ -108,9 +144,7 @@ impl Machine { let enters_guest = !guarded && !self.cpu.in_host() && super::super::exception::spsr_target(spsr).is_ok_and(|(el, _)| el < 2); - if let Some(entry) = self.cpu.apple.impdef.guest_state() - && enters_guest - { + if enters_guest && let Some(entry) = self.cpu.apple.impdef.guest_state() { self.degrade(self.requirement(RequirementKind::VmState(entry.name))); } } @@ -498,13 +532,15 @@ impl Machine { // Apple's vGIC CPU interface answers the ICH_* and ICC_* encodings // before the generated accessors, which follow the profile's absent // FEAT_GICv3. - let write = (access.direction() == Direction::Write).then(|| match access.rt() { - 31 => 0, - rt => self.cpu.state.x[usize::from(rt)], - }); - let context = self.cpu.vgic_context(write.is_some()); - if let Some(outcome) = self.cpu.vgic.access(encoding, write, &context) { - return self.register_outcome(word, Some(access), outcome); + if super::super::vgic::CpuInterface::may_access(encoding) { + let write = (access.direction() == Direction::Write).then(|| match access.rt() { + 31 => 0, + rt => self.cpu.state.x[usize::from(rt)], + }); + let context = self.cpu.vgic_context(write.is_some()); + if let Some(outcome) = self.cpu.vgic.access(encoding, write, &context) { + return self.register_outcome(word, Some(access), outcome); + } } if self.hacr_reaches(access) && let Some(step) = self.hacr_guest(word, hacr::Operation::Register(encoding)) @@ -907,3 +943,22 @@ impl Machine { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decoded_operation_reuses_words_across_pcs_and_still_checks_fallthrough() { + let mut cache = DecodeCache::default(); + let word = 0xd503_205f; // WFE + let expected = SystemOperation::Wait { + kind: WaitKind::Event, + timeout_register: None, + }; + assert_eq!(cache.operation(0x1000, word), Some(expected)); + assert_eq!(cache.operation(0x2000, word), Some(expected)); + assert_eq!(cache.operation(u64::MAX - 3, word), None); + assert_eq!(cache.operation(0x3000, word), Some(expected)); + } +} diff --git a/crates/stela-engine/src/machine/engine/table.rs b/crates/stela-engine/src/machine/engine/table.rs index c4caa2854f..9c5f7d0ba6 100644 --- a/crates/stela-engine/src/machine/engine/table.rs +++ b/crates/stela-engine/src/machine/engine/table.rs @@ -30,6 +30,11 @@ impl Table { self.len == 0 } + #[cfg(test)] + pub(super) fn capacity(&self) -> usize { + self.chunks.len() * CHUNK + } + /// Drop every entry, keeping the chunks for the next ones. pub(super) fn clear(&mut self) { self.chunks.iter_mut().for_each(Vec::clear); diff --git a/crates/stela-engine/src/machine/engine/tests.rs b/crates/stela-engine/src/machine/engine/tests.rs index bcdce2c1e2..3524659c8e 100644 --- a/crates/stela-engine/src/machine/engine/tests.rs +++ b/crates/stela-engine/src/machine/engine/tests.rs @@ -152,6 +152,7 @@ pub(super) struct FakeHost { /// turn, and its parts' code addresses, oldest first; `None` for an /// arena of one part. pub(super) ring: Option, + code_partitions: Option, parts: Vec>, } @@ -207,6 +208,9 @@ impl Host for FakeHost { assert!(code.len() < NATIVE_CODE_STRIDE); Ok(NativeCode(self.installed.len() * NATIVE_CODE_STRIDE)) } + fn code_partitions(&self) -> Option { + self.code_partitions + } fn reclaim_code(&mut self) -> Option> { self.ring?; let next = self.installed.len() + 1; @@ -520,6 +524,7 @@ pub(super) fn board_on( memory_low: false, require_empty_code_on_read: false, ring: None, + code_partitions: None, parts: Vec::new(), }; let profile = CpuProfile { @@ -1198,6 +1203,34 @@ fn host_breakpoints_end_blocks_and_stop_before_their_instruction() { assert_eq!(machine.cpu.state.x[0], 0); } +#[test] +fn system_address_pair_keeps_an_independent_add_entry_and_breakpoint() { + let words = [0xb000_0000, 0x9100_2000, 0x17ff_ffff]; // adrp; add; b to ADD + let mut grouped = machine(&words); + let Ok(Fetched::Block(head)) = grouped.fetch_block(BASE, false) else { + panic!("address pair block"); + }; + let Ok(Fetched::Block(add)) = grouped.fetch_block(BASE + 4, false) else { + panic!("independent ADD block"); + }; + assert_ne!(grouped.blocks[head].code, grouped.blocks[add].code); + assert_eq!(grouped.blocks[head].instructions, 3); + assert_eq!(grouped.blocks[add].instructions, 2); + assert_eq!(installed_code(&mut grouped, head, 0, 1), [0x90]); + assert_ne!(installed_code(&mut grouped, add, 0, 1), [0x90]); + + let mut split = machine(&words); + split.set_breakpoints(&[BASE + 4]); + let Ok(Fetched::Block(head)) = split.fetch_block(BASE, false) else { + panic!("breakpoint-bounded ADRP"); + }; + assert_eq!(split.blocks[head].instructions, 1); + assert_eq!( + installed_code(&mut split, head, 2, 8), + (BASE + 0x1000).to_le_bytes() + ); +} + #[test] fn trace_points_end_blocks_and_record_each_entry_without_stopping() { // add x0, x0, #1 (twice); fmov d0, d0, which traps with FP access @@ -2026,9 +2059,20 @@ fn all_chip_performance_monitors_count_retirement_and_signal_their_overflow_fiq( #[test] fn a_full_arena_reclaims_its_oldest_part_and_forgets_those_pages() { + for indexed in [false, true] { + check_code_arena_reclamation(indexed); + } +} + +fn check_code_arena_reclamation(indexed: bool) { const RET: u32 = 0xd65f_03c0; let mut machine = machine(&vec![RET; 4 * FETCH_PAGE as usize / 4]); machine.host.ring = Some(2); + machine.host.code_partitions = indexed.then_some(CodePartitions { + base: NATIVE_CODE_STRIDE, + bytes_per_part: 2 * NATIVE_CODE_STRIDE, + parts: 8, + }); let base = machine.cpu.pc; let page = |n: u64| base + n * FETCH_PAGE; let pcs = [page(0), page(1), page(0) + 4, page(2), page(3), page(1) + 8]; @@ -2051,6 +2095,13 @@ fn a_full_arena_reclaims_its_oldest_part_and_forgets_those_pages() { assert_eq!(machine.statistics.code_discards.iter().sum::(), 0); assert_eq!(machine.blocks.len(), 4); assert_eq!(&slots[4..], [1, 0]); + assert_eq!( + matches!( + machine.code_slots, + code_slots::CodeSlots::Partitioned { .. } + ), + indexed + ); } #[test] @@ -2075,6 +2126,37 @@ fn a_fetch_that_reclaims_code_looks_up_in_a_new_context() { ); } +#[test] +fn finishing_and_pressure_return_block_table_storage() { + const RET: u32 = 0xd65f_03c0; + for cause in [Discard::Finished, Discard::Memory] { + let mut machine = machine(&[RET]); + let base = machine.cpu.pc; + assert!(matches!( + machine.fetch_block(base, false), + Ok(Fetched::Block(0)) + )); + let capacities = (machine.blocks.capacity(), machine.fault_recovery.capacity()); + assert!(capacities.0 > 0 && capacities.1 > 0); + machine.discard_code(Discard::Maintenance); + assert_eq!( + (machine.blocks.capacity(), machine.fault_recovery.capacity()), + capacities, + ); + assert!(matches!( + machine.fetch_block(base, false), + Ok(Fetched::Block(0)) + )); + machine.discard_code(cause); + assert_eq!(machine.blocks.capacity(), 0); + assert_eq!(machine.fault_recovery.capacity(), 0); + assert!(matches!( + machine.fetch_block(base, false), + Ok(Fetched::Block(0)) + )); + } +} + #[test] fn pressure_reclaims_before_reading_new_compile_input() { const RET: u32 = 0xd65f_03c0; @@ -3128,11 +3210,16 @@ fn tlbi_invalidates_and_wfi_waits_for_the_virtual_timer() { let mut machine = machine_on(one_timer_bank(), &[]); machine.system_instruction(0xd508_871f).unwrap(); // tlbi vmalle1 assert_eq!(machine.host.invalidations, 1); + machine.native_system(); + machine.memory_checks(); + assert_eq!(machine.timer_deadline(), None); // Arm the virtual timer 1500 ticks ahead and wait. machine.cpu.state.x[0] = 1500; machine.system_instruction(0xd51b_e300).unwrap(); // msr cntv_tval_el0, x0 machine.cpu.state.x[0] = 1; machine.system_instruction(0xd51b_e320).unwrap(); // msr cntv_ctl_el0, x0 + assert_eq!(machine.timer_deadline(), Some(1500)); + assert!(machine.native_system.is_some() && machine.memory_checks.is_some()); wait(&mut machine, 0xd503_207f).unwrap(); // wfi assert_eq!(machine.host.now, 2000); // The FIQ is masked by DAIF until it is cleared. @@ -3151,6 +3238,16 @@ fn tlbi_invalidates_and_wfi_waits_for_the_virtual_timer() { assert_eq!(wait(&mut machine, 0xd503_207f), Err(Stop::Idle)); } +#[test] +fn untimed_wfi_uses_cached_lines_without_reading_the_counter() { + let mut machine = machine_on(one_timer_bank(), &[]); + machine.lines(); + let reads = machine.host.counter_reads; + machine.system_instruction(0xd503_207f).unwrap(); // wfi + assert!(machine.waiting.is_some()); + assert_eq!(machine.host.counter_reads, reads); +} + #[test] fn timer_snapshot_tracks_guest_reads_and_wfi_when_the_clock_lags() { let mut machine = machine_on(one_timer_bank(), &[]); @@ -3499,6 +3596,30 @@ fn branch_target_compatibility_follows_bti_paciasp_brk_and_hlt() { assert!(!machine.branch_target_compatible(PACIASP)); } +#[test] +fn a_compiled_pac_landing_uses_the_current_sctlr_for_lookup_entries() { + const PACIASP: u32 = 0xd503_233f; + const RET: u32 = 0xd65f_03c0; + const SCTLR_BT1: u64 = 1 << 36; + let mut machine = machine(&[PACIASP, RET]); + let pc = machine.cpu.pc; + let Ok(Fetched::Block(index)) = machine.fetch_block(pc, false) else { + panic!("compiled PAC landing"); + }; + let slot = (pc / FETCH_PAGE) as usize % FETCH_CACHE; + machine.fetch[slot].as_mut().unwrap().guarded = true; + let sctlr = machine.cpu.regime_sctlr(); + for (bits, targets) in [(0, 0b1111), (SCTLR_BT1, 0b0111)] { + machine + .cpu + .registers + .set(SystemRegister::SCTLR_EL1, 0, sctlr & !SCTLR_BT1 | bits); + machine.derived_changed(); + machine.remember_target(pc, index); + assert_eq!(machine.targets[target_slot(&machine, pc)].targets, targets); + } +} + /// SCTLR_EL2 bit 36 is BT with HCR_EL2.TGE clear and BT1 with it set /// (E2H is RES1); either way it decides PACIASP at EL2. #[test] @@ -3606,6 +3727,23 @@ fn wfe_wakes_on_an_event_stream_edge() { assert_eq!(wait(&mut machine, WFE), Err(Stop::Idle)); } +#[test] +fn pending_event_coalesces_sampled_edges_without_replaying_them() { + let mut machine = machine(&[]); + machine + .cpu + .registers + .set(SystemRegister::CNTHCTL_EL2, 0, 1 << 2); + machine.sample_events(0); + machine.cpu.signal_event(); + machine.sample_events(1); + assert!(machine.cpu.consume_event()); + machine.sample_events(1); + assert!(!machine.cpu.consume_event()); + machine.sample_events(3); + assert!(machine.cpu.consume_event()); +} + #[test] fn dc_zva_zeroes_one_profile_block_and_at_reports_par() { let mut machine = machine(&[]); @@ -6054,11 +6192,13 @@ fn eret_traps_and_eretaa_authenticates_elr_with_sp() { /// nonzero value enters it without the state, reported once; the host's /// own returns are unaffected. #[test] -fn entering_a_guest_with_unapplied_vm_state_reports_it_once() { +fn only_eligible_guest_entries_report_unapplied_vm_state() { const ERET: u32 = 0xd69f_03e0; const GEXIT: u32 = 0x0020_1400; const EL1H: u64 = 0x3c5; const EL0T: u64 = 0x3c0; + const EL2H: u64 = 0x3c9; + const RESERVED_MODE: u64 = 0x3c2; const HCR_E2H: u64 = 1 << 34; let guest = super::super::impdef::TABLE .iter() @@ -6092,6 +6232,14 @@ fn entering_a_guest_with_unapplied_vm_state_reports_it_once() { .cpu .registers .set(SystemRegister::HCR_EL2, 0, HCR_E2H); + // A pending register must stay silent on a guarded return, an illegal + // saved mode, and a return to the hypervisor itself. + machine.guest_entry(EL1H, true); + machine.guest_entry(RESERVED_MODE, false); + enter(&mut machine, ERET, EL2H).unwrap(); + assert_eq!((machine.cpu.pstate.el, machine.cpu.pc), (2, 0x8000)); + assert!(machine.take_unmodeled().is_empty()); + assert_eq!(machine.statistics.degraded, 0); for _ in 0..2 { enter(&mut machine, ERET, EL1H).unwrap(); assert_eq!((machine.cpu.pstate.el, machine.cpu.pc), (1, 0x8000)); diff --git a/crates/stela-engine/src/machine/impdef.rs b/crates/stela-engine/src/machine/impdef.rs index dfdb8422ea..8921806418 100644 --- a/crates/stela-engine/src/machine/impdef.rs +++ b/crates/stela-engine/src/machine/impdef.rs @@ -1748,6 +1748,34 @@ pub const TABLE: &[Entry] = &[ ), ]; +const fn guest_count() -> usize { + let mut count = 0; + let mut index = 0; + while index < TABLE.len() { + if matches!(TABLE[index].class, Class::Guest) { + count += 1; + } + index += 1; + } + count +} + +// Retain catalog order so the same register is reported when several hold +// guest state. Only these entries need inspection at exception return. +static GUEST_ENTRIES: [&Entry; guest_count()] = { + let mut entries = [&TABLE[0]; guest_count()]; + let mut next = 0; + let mut index = 0; + while index < TABLE.len() { + if matches!(TABLE[index].class, Class::Guest) { + entries[next] = &TABLE[index]; + next += 1; + } + index += 1; + } + entries +}; + const fn guest(encoding: Encoding, name: &'static str) -> Entry { entry(encoding, name, Class::Guest, GUEST_EVIDENCE).el2() } @@ -1980,9 +2008,10 @@ impl Registers { /// The first `Guest` register holding a nonzero value: state an EL1&0 /// guest would run without. pub fn guest_state(&self) -> Option<&'static Entry> { - TABLE.iter().find(|entry| { - entry.class == Class::Guest && self.stored(entry).is_some_and(|value| value != 0) - }) + GUEST_ENTRIES + .iter() + .copied() + .find(|entry| self.stored(entry).is_some_and(|value| value != 0)) } /// (entry, reads, writes) for every register the guest touched, once diff --git a/crates/stela-engine/src/machine/impdef/tests.rs b/crates/stela-engine/src/machine/impdef/tests.rs index a80909f251..c30656f4e5 100644 --- a/crates/stela-engine/src/machine/impdef/tests.rs +++ b/crates/stela-engine/src/machine/impdef/tests.rs @@ -404,6 +404,23 @@ fn nonzero_guest_state_is_reported() { registers.guest_state().map(|entry| entry.encoding), Some(SPRR_CONFIG_EL12) ); + // Multiple live values report the first catalog entry, independent of + // write order. Clearing it exposes the next one. + let first = TABLE + .iter() + .take_while(|entry| entry.encoding != guest.encoding) + .find(|entry| entry.class == Class::Guest && lookup(entry.encoding).is_some()) + .unwrap(); + registers.write(first, 7).unwrap(); + assert_eq!( + registers.guest_state().map(|entry| entry.encoding), + Some(first.encoding) + ); + registers.write(first, 0).unwrap(); + assert_eq!( + registers.guest_state().map(|entry| entry.encoding), + Some(SPRR_CONFIG_EL12) + ); // The VM keys follow the PAC regime: stored, not guest state. registers.write(lookup(APVMKEYLO_EL2).unwrap(), 5).unwrap(); registers.write(guest, 0).unwrap(); diff --git a/crates/stela-engine/src/machine/mmu.rs b/crates/stela-engine/src/machine/mmu.rs index 4bf9640c0d..0121d4ed68 100644 --- a/crates/stela-engine/src/machine/mmu.rs +++ b/crates/stela-engine/src/machine/mmu.rs @@ -409,6 +409,9 @@ pub struct Translation { pub readable: bool, pub writable: bool, pub executable: bool, + /// PAN masks this requester's data permissions for this translation. + /// The classification is available even while PSTATE.PAN is clear. + pub pan_sensitive: bool, /// FEAT_BTI: the stage-1 leaf's GP bit for a location executable at the /// requesting EL (Arm `InGuardedPage`). pub guarded: bool, @@ -500,12 +503,26 @@ pub fn par(outcome: &Outcome) -> Option { } } -/// Whether `access` is permitted by (readable, writable, executable). -fn permits(rights: (bool, bool, bool), access: Access) -> bool { - match access { - Access::Read => rights.0, - Access::Write => rights.1, - Access::Execute => rights.2, +/// Stage-1 access rights and whether PAN masks the data rights. +struct PagePermissions { + readable: bool, + writable: bool, + executable: bool, + pan_sensitive: bool, +} + +impl PagePermissions { + fn permits(&self, access: Access) -> bool { + match access { + Access::Read => self.readable, + Access::Write => self.writable, + Access::Execute => self.executable, + } + } + + #[cfg(test)] + fn rights(self) -> (bool, bool, bool) { + (self.readable, self.writable, self.executable) } } diff --git a/crates/stela-engine/src/machine/mmu/shadow.rs b/crates/stela-engine/src/machine/mmu/shadow.rs index 96431d3f79..99fd8f109f 100644 --- a/crates/stela-engine/src/machine/mmu/shadow.rs +++ b/crates/stela-engine/src/machine/mmu/shadow.rs @@ -96,38 +96,42 @@ impl Extents { self.private } - /// The ranges, first and last byte within `bounds` (this half's - /// addresses), that hold every page this half maps from an entry - /// `reach` removes; the large leaves among them are forgotten, as the - /// caller unmaps them. `None` when the whole half must go. - pub fn ranges(&mut self, reach: Reach, bounds: (u64, u64)) -> Option> { + /// Visit the ranges within `bounds` (this half's addresses) that hold + /// every page this half maps from an entry `reach` removes. Forget the + /// large leaves among them as the caller unmaps them. Return `false` + /// without visiting a range when the whole half must go. + pub fn visit_ranges( + &mut self, + reach: Reach, + bounds: (u64, u64), + mut visit: impl FnMut(u64, u64), + ) -> bool { let (first, last) = match reach { - Reach::Nothing => return Some(Vec::new()), - Reach::All => return None, + Reach::Nothing => return true, + Reach::All => return false, Reach::Containing(address) => (address, address), Reach::Overlapping { first, last } => (first, last), }; let (low, high) = bounds; if last < low || first > high || first > last { - return Some(Vec::new()); + return true; } if self.overflow { - return None; + return false; } let (first, last) = (first.max(low), last.min(high)); - let mut ranges = Vec::new(); if self.small != 0 { let mask = (1u64 << self.small) - 1; - ranges.push(((first & !mask).max(low), (last | mask).min(high))); + visit((first & !mask).max(low), (last | mask).min(high)); } self.large.retain(|&(start, end)| { let overlaps = start <= last && first <= end; if overlaps { - ranges.push((start.max(low), end.min(high))); + visit(start.max(low), end.min(high)); } !overlaps }); - Some(ranges) + true } } @@ -184,21 +188,32 @@ impl Kept { ) -> Option { self.switches += 1; self.halves.retain(|half| half.key != key); - if !entries.is_empty() { - if self.halves.len() == KEPT - && let Some(oldest) = (0..self.halves.len()).min_by_key(|&i| self.halves[i].used) - { - self.halves.swap_remove(oldest); - } - self.halves.push(KeptHalf { - key, - entries, - extents, - used: self.switches, - }); + // Take the incoming half before making room for the outgoing one: + // the half we need can itself be the least recently kept. + let found = self + .halves + .iter() + .position(|half| half.key == to) + .map(|index| self.halves.swap_remove(index)); + if entries.is_empty() { + return found; } - let index = self.halves.iter().position(|half| half.key == to)?; - Some(self.halves.swap_remove(index)) + let outgoing = KeptHalf { + key, + entries, + extents, + used: self.switches, + }; + if key == to { + return Some(outgoing); + } + if self.halves.len() == KEPT + && let Some(oldest) = (0..self.halves.len()).min_by_key(|&i| self.halves[i].used) + { + self.halves.swap_remove(oldest); + } + self.halves.push(outgoing); + found } /// Drop every kept half, returning how many there were. @@ -231,10 +246,7 @@ impl Kept { }; let before = self.halves.len(); self.halves.retain_mut(|half| { - let Some(ranges) = half.extents.ranges(reach, bounds) else { - return false; - }; - for &(first, last) in &ranges { + half.extents.visit_ranges(reach, bounds, |first, last| { for &(_, entry, value) in &half.entries { let start = (entry as u64) << entry_bits; let end = start | ((1 << entry_bits) - 1); @@ -242,8 +254,7 @@ impl Kept { unmap(value, first.max(start), last.min(end)); } } - } - true + }) }); before - self.halves.len() } @@ -256,6 +267,14 @@ mod tests { const LOWER: (u64, u64) = (0, (1 << 48) - 1); const UPPER: (u64, u64) = (0xffff_0000_0000_0000, u64::MAX); + impl Extents { + fn ranges(&mut self, reach: Reach, bounds: (u64, u64)) -> Option> { + let mut ranges = Vec::new(); + self.visit_ranges(reach, bounds, |first, last| ranges.push((first, last))) + .then_some(ranges) + } + } + #[test] fn leaves_and_windows_are_aligned_extents() { assert_eq!(leaf(0x1_2345, 1 << 14), (0x1_0000, 0x1_3fff)); @@ -453,4 +472,33 @@ mod tests { assert_eq!(kept.clear(), 1); assert!(kept.is_empty()); } + + #[test] + fn switching_to_the_oldest_kept_half_reuses_it_when_full() { + let mut kept = Kept::new(); + let key = |n: u64| (n << 12, 0); + for from in 0..KEPT as u64 { + assert!( + kept.switch( + key(from), + alloc::vec![(0x1000, 0, from + 1)], + Extents::new(), + key(from + 1), + ) + .is_none() + ); + } + for from in (KEPT as u64..).take(50).map(|n| n % (KEPT as u64 + 1)) { + let to = (from + 1) % (KEPT as u64 + 1); + let half = kept + .switch( + key(from), + alloc::vec![(0x1000, 0, from + 1)], + Extents::new(), + key(to), + ) + .unwrap(); + assert_eq!(half.entries, [(0x1000, 0, to + 1)]); + } + } } diff --git a/crates/stela-engine/src/machine/mmu/sprr.rs b/crates/stela-engine/src/machine/mmu/sprr.rs index e7c926c7b7..8f928a28ca 100644 --- a/crates/stela-engine/src/machine/mmu/sprr.rs +++ b/crates/stela-engine/src/machine/mmu/sprr.rs @@ -1,7 +1,7 @@ //! Apple SPRR: page permissions indirected through per-index registers //! (Asahi Linux "SPRR and GXF"; m1n1 `cpu_regs.h`). -use super::{Requester, Unsupported}; +use super::{PagePermissions, Requester, Unsupported}; /// With SPRR enabled the descriptor bits AP[1], AP[0], UXN and PXN form a /// 4-bit index (bit 3 down to bit 0), and nibble `index` of SPRR_PERM_EL1 @@ -99,15 +99,15 @@ pub struct Hierarchy { pub uxn_table: bool, } -/// (readable, writable, executable) of a leaf under SPRR. The two special +/// The rights of a leaf under SPRR. The two special /// GL/EL combinations follow the Asahi table: GL `r-x` with EL `rw-` gives /// EL `---`, and GL `r--` with EL `r-x` gives EL `--x`. -pub fn permissions( +pub(super) fn permissions( sprr: Sprr, requester: Requester, hierarchy: &Hierarchy, descriptor: u64, -) -> Result<(bool, bool, bool), Unsupported> { +) -> Result { if hierarchy.no_el0 || hierarchy.read_only { return Err(Unsupported::Sprr("APTable with SPRR")); } @@ -144,20 +144,22 @@ pub fn permissions( if requester.guarded { rights(guarded) } else { - let (readable, writable, executable) = match (guarded, el) { + match (guarded, el) { (1, 3) => (false, false, false), (2, 1) => (false, false, true), (_, el) => rights(el), - }; - // PAN removes data access to a location EL0 can access. - if requester.pan && user_accessible(sprr, index) { - (false, false, executable) - } else { - (readable, writable, executable) } } }; - Ok((readable, writable, executable && !table_xn)) + // PAN removes data access to a location EL0 can access. + let pan_sensitive = !as_el0 && !requester.guarded && user_accessible(sprr, index); + let pan = requester.pan && pan_sensitive; + Ok(PagePermissions { + readable: readable && !pan, + writable: writable && !pan, + executable: executable && !table_xn, + pan_sensitive, + }) } #[cfg(test)] @@ -204,7 +206,9 @@ mod tests { ..Sprr::default() }; let gl0 = requester(0, false, true); - let at = |index, requester| permissions(sprr, requester, &FLAT, leaf(index)); + let at = |index, requester| { + permissions(sprr, requester, &FLAT, leaf(index)).map(PagePermissions::rights) + }; assert_eq!(at(1, gl0), Ok((true, false, false))); assert_eq!(at(4, gl0), Ok((true, true, false))); assert_eq!(at(8, gl0), Ok((true, false, true))); @@ -227,13 +231,14 @@ mod tests { ..Sprr::default() }; let kernel = requester(2, true, false); - let at = |index| permissions(sprr, kernel, &FLAT, leaf(index)); + let at = |index| permissions(sprr, kernel, &FLAT, leaf(index)).map(PagePermissions::rights); assert_eq!(at(0), Ok((true, true, false))); assert_eq!(at(4), Ok((false, false, false))); assert_eq!(at(1), Ok((false, false, false))); assert_eq!(at(5), Ok((true, true, false))); // Without PAN, and at a guarded level, the kernel keeps its rights. - let unmasked = |requester| permissions(sprr, requester, &FLAT, leaf(4)); + let unmasked = + |requester| permissions(sprr, requester, &FLAT, leaf(4)).map(PagePermissions::rights); assert_eq!( unmasked(requester(2, false, false)), Ok((true, true, false)) diff --git a/crates/stela-engine/src/machine/mmu/stage1.rs b/crates/stela-engine/src/machine/mmu/stage1.rs index df0218dd32..adb113775b 100644 --- a/crates/stela-engine/src/machine/mmu/stage1.rs +++ b/crates/stela-engine/src/machine/mmu/stage1.rs @@ -3,11 +3,11 @@ use super::{ Access, Alignment, Controls, Fault, FaultKind, MemoryType, Outcome, PHYSICAL_ADDRESS_BITS, - Regime, Requester, SCTLR_M, SCTLR_WXN, TableMemory, Translation, Unsupported, + PagePermissions, Regime, Requester, SCTLR_M, SCTLR_WXN, TableMemory, Translation, Unsupported, alignment::MemoryCheck, attributes, geometry::{self, Geometry}, - permits, sprr, + sprr, }; // TCR_EL1, and TCR_EL2 with E2H set. @@ -219,6 +219,7 @@ fn disabled( readable: true, writable: true, executable: true, + pan_sensitive: false, guarded: false, global: true, asid: 0, @@ -387,7 +388,7 @@ fn walk_enabled( } else { rights(controls, requester, &hierarchy, descriptor) }; - if !permits(rights, access) { + if !rights.permits(access) { return fault(FaultKind::Permission, level); } // Caches off (pseudocode AArch64.S1TreatAsNormalNC), after the @@ -405,10 +406,11 @@ fn walk_enabled( memory, attributes, shareability, - readable: rights.0, - writable: rights.1, - executable: rights.2, - guarded: descriptor & GUARDED != 0 && rights.2, + readable: rights.readable, + writable: rights.writable, + executable: rights.executable, + pan_sensitive: rights.pan_sensitive, + guarded: descriptor & GUARDED != 0 && rights.executable, global, asid: if global { 0 } else { asid(controls) }, size, @@ -417,7 +419,7 @@ fn walk_enabled( } } -/// (readable, writable, executable) of a leaf for `requester` (Arm ARM +/// The rights of a leaf for `requester` (Arm ARM /// D8.4, pseudocode AArch64.S1DirectBasePermissions and /// AArch64.S1HasPermissionsFault): data rights after PAN, execution at the /// requesting EL. @@ -426,14 +428,19 @@ fn rights( requester: Requester, hierarchy: &Hierarchy, descriptor: u64, -) -> (bool, bool, bool) { +) -> PagePermissions { let read_only = descriptor & AP_READ_ONLY != 0 || hierarchy.read_only; let wxn = controls.sctlr & SCTLR_WXN != 0; if !two_ranges(controls.regime) { // One privilege level: AP[1] and PXN are ignored, bit 54 is XN. let writable = !read_only; let executable = descriptor & UXN == 0 && !hierarchy.uxn && !(wxn && writable); - return (true, writable, executable); + return PagePermissions { + readable: true, + writable, + executable, + pan_sensitive: false, + }; } let el0_readable = descriptor & AP_EL0 != 0 && !hierarchy.no_el0; let el0_writable = el0_readable && !read_only; @@ -443,19 +450,31 @@ fn rights( let el0_executable = descriptor & UXN == 0 && !hierarchy.uxn && !(wxn && el0_writable); let privileged_executable = descriptor & PXN == 0 && !hierarchy.pxn && !el0_writable && !(wxn && privileged_writable); - if requester.el == 0 { - return (el0_readable, el0_writable, el0_executable); - } - if requester.unprivileged { - return (el0_readable, el0_writable, privileged_executable); + if requester.el == 0 || requester.unprivileged { + return PagePermissions { + readable: el0_readable, + writable: el0_writable, + executable: if requester.el == 0 { + el0_executable + } else { + privileged_executable + }, + pan_sensitive: false, + }; } // PAN removes kernel-level data access to EL0-accessible locations, and // with SCTLR_ELx.EPAN (FEAT_PAN3, RES0 without it) to locations EL0 may // execute, before WXN; it never affects execution. let el0_execute_permitted = descriptor & UXN == 0 && !hierarchy.uxn; let enhanced = controls.sctlr & SCTLR_EPAN != 0; - let pan = requester.pan && (el0_readable || enhanced && el0_execute_permitted); - (!pan, !pan && privileged_writable, privileged_executable) + let pan_sensitive = el0_readable || enhanced && el0_execute_permitted; + let pan = requester.pan && pan_sensitive; + PagePermissions { + readable: !pan, + writable: !pan && privileged_writable, + executable: privileged_executable, + pan_sensitive, + } } #[cfg(test)] diff --git a/crates/stela-engine/src/machine/mmu/stage1/tests.rs b/crates/stela-engine/src/machine/mmu/stage1/tests.rs index f1b4d4e2c8..3c9450779c 100644 --- a/crates/stela-engine/src/machine/mmu/stage1/tests.rs +++ b/crates/stela-engine/src/machine/mmu/stage1/tests.rs @@ -197,7 +197,7 @@ fn access_permissions_follow_ap_xn_wxn_and_pan() { ..KERNEL }; let leaf = |controls: &Controls, requester, descriptor| { - super::rights(controls, requester, &Hierarchy::default(), descriptor) + super::rights(controls, requester, &Hierarchy::default(), descriptor).rights() }; // AP[2:1] 00..11 with UXN=PXN=0: the rights of EL1, EL0, EL1 with // PAN, and an unprivileged EL1 access. @@ -264,7 +264,7 @@ fn epan_extends_pan_to_locations_el0_may_execute() { ..KERNEL }; let leaf = |controls: &Controls, hierarchy: &Hierarchy, descriptor| { - super::rights(controls, pan, hierarchy, descriptor) + super::rights(controls, pan, hierarchy, descriptor).rights() }; let execute_only = ATTRS; // AP[2:1] 00, EL0 execute-only. let read_only_execute_only = ATTRS | AP_READ_ONLY; @@ -295,11 +295,53 @@ fn epan_extends_pan_to_locations_el0_may_execute() { assert_eq!(leaf(&controls, &none, el0_writable), (false, false, false)); // Without PSTATE.PAN, EPAN has no effect. assert_eq!( - super::rights(&controls, KERNEL, &none, execute_only), + super::rights(&controls, KERNEL, &none, execute_only).rights(), (true, true, false) ); } +#[test] +fn pan_classification_matches_a_second_translation() { + let va = 0x1_0000_4000; + let pa = 0x8_0000_0000; + let pan = Requester { + pan: true, + ..KERNEL + }; + for sprr in [ + Sprr::default(), + Sprr { + config: SPRR_CONFIG_EN, + el1: 0x3333_3333_3333_3333, + el0: 0x3030_3030_3030_3030, + ..Sprr::default() + }, + ] { + for epan in [false, true] { + let mut controls = controls(); + controls.sprr = sprr; + controls.sctlr |= if epan { SCTLR_EPAN } else { 0 }; + for index in 0..16u64 { + let descriptor = ATTRS | (index >> 2) << 6 | (index & 3) << 53; + let mut tables = Tables::default(); + map(&mut tables, &controls, va, pa, descriptor); + for access in [Access::Read, Access::Write] { + let Outcome::Mapped(mapped) = + translate(&controls, va, access, KERNEL, &mut tables) + else { + continue; + }; + let masked = translate(&controls, va, Access::Read, pan, &mut tables); + assert_eq!( + !mapped.readable || mapped.pan_sensitive, + !matches!(masked, Outcome::Mapped(same) if same.writable == mapped.writable) + ); + } + } + } + } +} + #[test] fn table_permissions_apply_unless_hierarchical_permissions_are_disabled() { let mut controls = controls(); diff --git a/crates/stela-engine/src/machine/mmu/tests.rs b/crates/stela-engine/src/machine/mmu/tests.rs index d7a6b32f70..6e1bcde237 100644 --- a/crates/stela-engine/src/machine/mmu/tests.rs +++ b/crates/stela-engine/src/machine/mmu/tests.rs @@ -12,6 +12,7 @@ fn par_reports_the_output_attributes_or_the_fault() { readable: true, writable: true, executable: false, + pan_sensitive: false, guarded: false, global: true, asid: 0, @@ -264,6 +265,107 @@ fn stage_one_tables_and_output_translate_through_stage_two() { ); } +#[test] +fn pan_shadow_classification_includes_stage_two_read_permissions() { + let (controls, mut tables) = two_stages(0x8000_0000); + // The table walk still uses the original read/write block. The data + // access uses the next block, writable but unreadable at stage 2. + tables.0.insert(0x10_0010, STAGE2_BLOCK & !(1 << 6)); + let Outcome::Mapped(mapped) = translate(&controls, 0x1234, Access::Write, KERNEL, &mut tables) + else { + panic!("stage 2 must permit the write"); + }; + assert!(!mapped.readable && mapped.writable && !mapped.pan_sensitive); + let pan = Requester { + pan: true, + ..KERNEL + }; + let Outcome::Fault(fault) = translate(&controls, 0x1234, Access::Read, pan, &mut tables) else { + panic!("stage 2 must deny the read"); + }; + assert_eq!(fault.kind, FaultKind::Permission); + assert!(fault.second_stage.is_some()); +} + +#[test] +fn device_tlb_uses_stage_two_permissions_and_rewalks_after_maintenance() { + let (controls, mut tables) = two_stages(0x8000_0000); + let slot = 0x10_0010; + let address = 0x1234; + let mut tlb = translated::Tlb::default(); + // The first-stage walk remains readable. The data output is write-only. + tables.0.insert(slot, STAGE2_BLOCK & !(1 << 6)); + let Outcome::Mapped(mapped) = translate(&controls, address, Access::Write, KERNEL, &mut tables) + else { + panic!("stage 2 must permit the write"); + }; + tlb.record_device(address, KERNEL, mapped); + assert_eq!( + tlb.device_physical(address, KERNEL, true), + Some(mapped.physical) + ); + assert_eq!(tlb.device_physical(address, KERNEL, false), None); + assert!(matches!( + translate(&controls, address, Access::Read, KERNEL, &mut tables), + Outcome::Fault(Fault { + kind: FaultKind::Permission, + second_stage: Some(_), + .. + }) + )); + + // Clearing AF after caching requires maintenance. The next translation + // reports the fault instead of writing AF back or reusing the old entry. + tables.0.insert(slot, STAGE2_BLOCK & !(1 << 10)); + tlb.clear(); + assert_eq!(tlb.device_physical(address, KERNEL, true), None); + assert!(matches!( + translate(&controls, address, Access::Write, KERNEL, &mut tables), + Outcome::Fault(Fault { + kind: FaultKind::AccessFlag, + second_stage: Some(_), + .. + }) + )); + + tables.0.insert(slot, STAGE2_BLOCK); + *tables.0.get_mut(&0x8000_0000).unwrap() &= !(1 << 10); + assert!(matches!( + translate(&controls, address, Access::Write, KERNEL, &mut tables), + Outcome::Fault(Fault { + kind: FaultKind::AccessFlag, + second_stage: None, + .. + }) + )); +} + +#[test] +fn device_tlb_cannot_admit_writes_to_a_ctrr_locked_page() { + let (mut controls, mut tables) = two_stages(0x4000_0000); + controls.ctrr.memory[0] = Some((0x8000_4000, 0x8000_4fff)); + let address = 0x4008; + let Outcome::Mapped(mapped) = translate(&controls, address, Access::Read, KERNEL, &mut tables) + else { + panic!("CTRR must permit the read"); + }; + let mut tlb = translated::Tlb::default(); + tlb.record_device(address, KERNEL, mapped); + assert_eq!( + tlb.device_physical(address, KERNEL, false), + Some(mapped.physical) + ); + assert_eq!(tlb.device_physical(address, KERNEL, true), None); + assert!(matches!( + translate(&controls, address, Access::Write, KERNEL, &mut tables), + Outcome::Fault(Fault { + kind: FaultKind::Permission, + second_stage: None, + .. + }) + )); +} + #[test] fn stage_two_applies_under_vm_or_dc_without_tge_and_is_never_skipped() { let (mut controls, mut tables) = two_stages(0x4000_0000); diff --git a/crates/stela-engine/src/machine/mmu/translated.rs b/crates/stela-engine/src/machine/mmu/translated.rs index 6bb56c4101..849cb343a8 100644 --- a/crates/stela-engine/src/machine/mmu/translated.rs +++ b/crates/stela-engine/src/machine/mmu/translated.rs @@ -1,4 +1,6 @@ -//! The software TLB of the translated variant +//! Software TLBs for translated accesses and device translations. +//! +//! The translated variant //! (`docs/design/system.md#host-placement`): blocks that access guest //! addresses outside the host's native ranges ([`super::placement`]) call a //! host helper for each such access, which looks the page up here and @@ -13,6 +15,11 @@ //! contiguously, runs there; across discontiguous pages the helper maps //! both into its bounce slot, so the returned address is always valid for //! the whole access and writes reach the guest's own frames. +//! +//! A separate cache records successful translations outside RAM. Its hits +//! avoid another walk, while the engine still performs each device access. + +use super::{Requester, Translation, attributes}; /// The page an entry maps. pub const PAGE: u64 = 1 << 12; @@ -22,15 +29,18 @@ pub const ENTRIES: usize = 256; /// entry's tag distinguishes. pub const VIEWS: u8 = 8; +const TAG_SPAN: u64 = PAGE * ENTRIES as u64; +const READ_ONLY: u64 = 1 << u8::BITS; +const GENERATION_STEP: u64 = READ_ONLY << 1; + /// One page's translation for one view. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] struct Entry { - /// The page's virtual address with the view in its low bits; valid - /// while `host` is nonzero. + /// The high virtual address bits, then the generation, read-only bit + /// and view. The slot already distinguishes the low page-number bits. tag: u64, - /// The host address of the page. + /// The aligned host address. host: u64, - writable: bool, } /// Where an access runs. @@ -51,12 +61,16 @@ pub enum Lookup { #[derive(Debug, Clone)] pub struct Tlb { entries: [Entry; ENTRIES], + generation: u64, + devices: DevicePages, } impl Default for Tlb { fn default() -> Self { Self { entries: [Entry::default(); ENTRIES], + generation: GENERATION_STEP, + devices: DevicePages::default(), } } } @@ -65,8 +79,9 @@ const fn slot(page: u64) -> usize { ((page / PAGE) as usize) % ENTRIES } -const fn tag(page: u64, view: u8) -> u64 { - page | view as u64 +const fn tag(page: u64, view: u8, generation: u64) -> u64 { + const { assert!(TAG_SPAN.is_power_of_two() && TAG_SPAN > GENERATION_STEP) }; + (page & !(TAG_SPAN - 1)) | generation | view as u64 } impl Tlb { @@ -75,8 +90,8 @@ impl Tlb { fn page(&self, address: u64, write: bool, view: u8) -> Option { let page = address & !(PAGE - 1); let entry = &self.entries[slot(page)]; - (entry.host != 0 && entry.tag == tag(page, view) && (entry.writable || !write)) - .then_some(entry.host) + let ignored = u64::from(!write) * READ_ONLY; + (entry.tag & !ignored == tag(page, view, self.generation)).then_some(entry.host) } /// Where the `bytes`-byte access at `address` runs for `view`. @@ -102,16 +117,86 @@ impl Tlb { debug_assert!(host != 0 && host.is_multiple_of(PAGE) && view < VIEWS); let page = address & !(PAGE - 1); self.entries[slot(page)] = Entry { - tag: tag(page, view), + tag: tag(page, view, self.generation) | (u64::from(!writable) * READ_ONLY), host, - writable, }; } /// Forget every entry. pub fn clear(&mut self) { - self.entries = [Entry::default(); ENTRIES]; + self.generation += GENERATION_STEP; + if self.generation == TAG_SPAN { + // Scrub before reusing an earlier generation. Zero is reserved + // for the empty entries. + self.entries.fill(Entry::default()); + self.generation = GENERATION_STEP; + } + self.clear_devices(); } + + /// Drop device translations without changing cached RAM translations. + pub fn clear_devices(&mut self) { + self.devices.valid = 0; + } + + /// A positive device translation, for a requester and access it permits. + /// Every access still runs through the engine's device path. + pub fn device_physical(&self, address: u64, requester: Requester, write: bool) -> Option { + let (slot, tag) = device_tag(address, requester); + if self.devices.valid & (1 << slot) == 0 { + return None; + } + let (recorded, physical) = self.devices.entries[slot]; + let access = if write { DEVICE_WRITE } else { DEVICE_READ }; + (recorded == tag && physical & access != 0) + .then_some((physical & !(PAGE - 1)) | (address & (PAGE - 1))) + } + + /// Record a translated page outside RAM. + /// The caller still checks watchpoints. Leave Tagged memory to the walk. + pub fn record_device(&mut self, address: u64, requester: Requester, translation: Translation) { + if translation.attributes == attributes::TAGGED { + return; + } + debug_assert_eq!(translation.physical % PAGE, address % PAGE); + let (slot, tag) = device_tag(address, requester); + let rights = u64::from(translation.readable) | (u64::from(translation.writable) << 1); + let physical = (translation.physical & !(PAGE - 1)) | rights; + self.devices.entries[slot] = (tag, physical); + self.devices.valid |= 1 << slot; + } +} + +const DEVICE_ENTRIES: usize = 64; +const DEVICE_READ: u64 = 1; +const DEVICE_WRITE: u64 = 2; + +#[derive(Debug, Clone)] +struct DevicePages { + /// Full virtual tag, physical page with data permissions in its low bits. + entries: [(u64, u64); DEVICE_ENTRIES], + valid: u64, +} + +impl Default for DevicePages { + fn default() -> Self { + Self { + entries: [(0, 0); DEVICE_ENTRIES], + valid: 0, + } + } +} + +fn device_tag(address: u64, requester: Requester) -> (usize, u64) { + let page = address / PAGE; + let requester = u64::from(requester.el) + | (u64::from(requester.pan) << 8) + | (u64::from(requester.unprivileged) << 9) + | (u64::from(requester.guarded) << 10); + // Registers in separate apertures can start at the same page offset. + let slot = ((page ^ (page >> 6) ^ requester ^ (requester >> 6)) as usize) % DEVICE_ENTRIES; + let tag = (address & !(PAGE - 1)) | requester; + (slot, tag) } #[cfg(test)] @@ -120,6 +205,96 @@ mod tests { const VA: u64 = 0xffff_8000_1234_5000; const HOST: u64 = 0x7000_0000; + const KERNEL: Requester = Requester { + el: 1, + pan: false, + unprivileged: false, + guarded: false, + }; + + fn device(physical: u64, readable: bool, writable: bool) -> Translation { + Translation { + physical, + memory: super::super::MemoryType::Device, + attributes: 0x04, + shareability: 0b10, + readable, + writable, + executable: false, + pan_sensitive: false, + guarded: false, + global: true, + asid: 0, + size: PAGE, + alignment: super::super::Alignment { device: true }, + } + } + + #[test] + fn device_page_hits_require_matching_requester_and_access_permissions() { + let mut tlb = Tlb::default(); + tlb.record_device(VA + 4, KERNEL, device(4, true, false)); + assert_eq!(tlb.device_physical(VA + 12, KERNEL, false), Some(12)); + assert_eq!(tlb.device_physical(VA + 12, KERNEL, true), None); + for requester in [ + Requester { el: 2, ..KERNEL }, + Requester { + pan: true, + ..KERNEL + }, + Requester { + unprivileged: true, + ..KERNEL + }, + Requester { + guarded: true, + ..KERNEL + }, + ] { + assert_eq!(tlb.device_physical(VA, requester, false), None); + } + let with_pan = Requester { + pan: true, + ..KERNEL + }; + tlb.record_device(VA, with_pan, device(HOST, true, true)); + assert_eq!(tlb.device_physical(VA, with_pan, true), Some(HOST)); + assert_eq!(tlb.device_physical(VA, KERNEL, false), Some(0)); + tlb.record_device(VA, KERNEL, device(HOST, false, true)); + assert_eq!(tlb.device_physical(VA + 12, KERNEL, true), Some(HOST + 12)); + assert_eq!(tlb.device_physical(VA + 12, KERNEL, false), None); + assert_eq!(tlb.lookup(VA, 1, true, 1), Lookup::Miss { address: VA }); + tlb.clear(); + assert_eq!(tlb.device_physical(VA, KERNEL, true), None); + } + + #[test] + fn clearing_devices_preserves_ram_entries() { + let mut tlb = Tlb::default(); + let ram = VA + PAGE; + tlb.fill(ram, HOST, true, 1); + tlb.record_device(VA, KERNEL, device(HOST + PAGE, true, true)); + tlb.clear_devices(); + assert_eq!(tlb.device_physical(VA, KERNEL, false), None); + assert_eq!(tlb.lookup(ram, 1, true, 1), Lookup::Direct(HOST)); + } + + #[test] + fn device_cache_refuses_tagged_memory_and_requires_the_full_virtual_page() { + let mut tlb = Tlb::default(); + let tagged = Translation { + attributes: attributes::TAGGED, + ..device(HOST, true, true) + }; + tlb.record_device(VA, KERNEL, tagged); + assert_eq!(tlb.device_physical(VA, KERNEL, false), None); + + let alias = VA ^ (PAGE << 12); + tlb.record_device(VA, KERNEL, device(HOST, true, true)); + tlb.record_device(alias, KERNEL, device(HOST + PAGE, true, true)); + assert_eq!(tlb.device_physical(VA, KERNEL, false), None); + assert_eq!(tlb.device_physical(alias, KERNEL, false), Some(HOST + PAGE)); + } #[test] fn an_access_within_a_filled_page_runs_at_its_host_address() { @@ -152,6 +327,30 @@ mod tests { ); } + #[test] + fn clearing_through_a_generation_wrap_cannot_restore_old_entries() { + let mut tlb = Tlb::default(); + assert_eq!(tlb.lookup(0, 8, false, 0), Lookup::Miss { address: 0 }); + tlb.fill(0, HOST, true, 0); + tlb.fill(VA, HOST + PAGE, false, 1); + assert_eq!(tlb.lookup(0, 8, true, 0), Lookup::Direct(HOST)); + assert_eq!(tlb.lookup(VA, 8, false, 1), Lookup::Direct(HOST + PAGE)); + for _ in 0..TAG_SPAN / GENERATION_STEP - 1 { + tlb.clear(); + assert_eq!(tlb.lookup(0, 8, false, 0), Lookup::Miss { address: 0 }); + assert_eq!(tlb.lookup(VA, 8, false, 1), Lookup::Miss { address: VA }); + } + assert_eq!(tlb.generation, GENERATION_STEP); + tlb.fill(VA, HOST, false, 2); + assert_eq!(tlb.lookup(VA, 8, false, 2), Lookup::Direct(HOST)); + assert_eq!(tlb.lookup(VA, 8, true, 2), Lookup::Miss { address: VA }); + assert_eq!(tlb.lookup(VA, 8, false, 1), Lookup::Miss { address: VA }); + assert_eq!( + tlb.lookup(VA, 8, false, u8::MAX), + Lookup::Miss { address: VA } + ); + } + #[test] fn an_access_across_two_pages_needs_both_and_splits_when_the_host_does() { let mut tlb = Tlb::default(); diff --git a/crates/stela-engine/src/machine/system.rs b/crates/stela-engine/src/machine/system.rs index 73ef2b2207..1dda3e2c86 100644 --- a/crates/stela-engine/src/machine/system.rs +++ b/crates/stela-engine/src/machine/system.rs @@ -63,8 +63,8 @@ pub struct Accessor { impl Accessor { /// MRS and the System instructions with a result read; the rest write. - pub fn reads(&self) -> bool { - matches!(self.kind, "MRS" | "SYSL") + pub const fn reads(&self) -> bool { + matches!(self.kind.as_bytes(), b"MRS" | b"SYSL") } } @@ -77,9 +77,47 @@ pub fn key(encoding: Encoding) -> u16 { | u16::from(encoding.op2()) } -/// Accessors by key and direction: entry `key * 2 + read` holds the -/// accessor's position plus one, or 0 when none matches. -pub struct Lookup(alloc::vec::Vec); +/// Accessors by key and direction, shared by all PEs. +pub struct Lookup; + +const SLOTS: usize = 1 << 17; +const INDEX_SHIFT: u32 = 11; +const POSITION_MASK: u16 = (1 << INDEX_SHIFT) - 1; + +/// Each entry packs the accessor position plus one and its decoded array +/// index. Zero marks a slot with no matching accessor. +const fn accessors_by_encoding() -> [u16; SLOTS] { + assert!(ACCESSORS.len() <= POSITION_MASK as usize); + let mut entries = [0u16; SLOTS]; + let mut position = 0; + while position < ACCESSORS.len() { + let accessor = &ACCESSORS[position]; + let mut combination = 0; + while combination < 1 << accessor.index.len() { + let mut key = accessor.value; + let mut index = 0u64; + let mut bit = 0; + while bit < accessor.index.len() { + let (key_bit, index_bit) = accessor.index[bit]; + if combination >> bit & 1 != 0 { + key |= 1 << key_bit; + } + index |= (((key >> key_bit) & 1) as u64) << index_bit; + bit += 1; + } + let slot = key as usize * 2 + accessor.reads() as usize; + if entries[slot] == 0 { + assert!(index < 1 << (u16::BITS - INDEX_SHIFT)); + entries[slot] = (position as u16 + 1) | (index as u16) << INDEX_SHIFT; + } + combination += 1; + } + position += 1; + } + entries +} + +static LOOKUP: [u16; SLOTS] = accessors_by_encoding(); impl Default for Lookup { fn default() -> Self { @@ -88,39 +126,19 @@ impl Default for Lookup { } impl Lookup { - pub fn new() -> Self { - let mut table = alloc::vec![0u16; 1 << 17]; - for (position, accessor) in ACCESSORS.iter().enumerate() { - // Enumerate the keys the pattern admits through its index bits. - let bits: alloc::vec::Vec = - accessor.index.iter().map(|&(key_bit, _)| key_bit).collect(); - for combination in 0..1u32 << bits.len() { - let mut key = accessor.value; - for (number, bit) in bits.iter().enumerate() { - if combination >> number & 1 != 0 { - key |= 1 << bit; - } - } - let slot = usize::from(key) * 2 + usize::from(accessor.reads()); - if table[slot] == 0 { - table[slot] = position as u16 + 1; - } - } - } - Self(table) + pub const fn new() -> Self { + Self } /// The accessor for an encoding and direction, with its array index. pub fn find(&self, encoding: Encoding, read: bool) -> Option<(&'static Accessor, u64)> { - let key = key(encoding); - let position = self.0[usize::from(key) * 2 + usize::from(read)].checked_sub(1)?; - let accessor = &ACCESSORS[usize::from(position)]; - let index = accessor - .index - .iter() - .map(|&(key_bit, index_bit)| u64::from((key >> key_bit) & 1) << index_bit) - .fold(0, |a, b| a | b); - Some((accessor, index)) + let slot = usize::from(key(encoding)) * 2 + usize::from(read); + let entry = LOOKUP[slot]; + let position = (entry & POSITION_MASK).checked_sub(1)?; + Some(( + &ACCESSORS[usize::from(position)], + u64::from(entry >> INDEX_SHIFT), + )) } } @@ -325,10 +343,11 @@ pub trait Context { fn x(&self) -> u64; /// The MRS or SYSL result. fn set_x(&mut self, value: u64); - fn read(&self, register: Register, index: u64) -> u64; + /// Read a register, sampling live interrupt or timer state if it uses it. + fn read(&mut self, register: Register, index: u64) -> u64; fn write(&mut self, register: Register, index: u64, value: u64) -> Result<(), Effect>; /// `PhysicalCountInt()`: the physical count of the system counter. - fn physical_count(&self) -> u64; + fn physical_count(&mut self) -> u64; /// FEAT_NV2 register access redirected to memory at VNCR_EL2 + offset. fn nv_mem(&mut self, offset: u64) -> Result; fn set_nv_mem(&mut self, offset: u64, value: u64) -> Result<(), Effect>; @@ -354,3 +373,39 @@ pub trait Context { 0 } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lookup_matches_the_accessor_patterns_for_every_encoding() { + let lookup = Lookup::new(); + for key in 0..=u16::MAX { + let encoding = Encoding::new( + (key >> 14) as u8, + (key >> 11 & 7) as u8, + (key >> 7 & 15) as u8, + (key >> 3 & 15) as u8, + (key & 7) as u8, + ); + for read in [false, true] { + let expected = ACCESSORS.iter().find(|accessor| { + key & accessor.mask == accessor.value && accessor.reads() == read + }); + let actual = lookup.find(encoding, read); + match (actual, expected) { + (Some((accessor, index)), Some(expected)) => { + assert!(core::ptr::eq(accessor, expected), "{key:#x}, read={read}"); + let decoded = expected.index.iter().fold(0, |value, &(from, to)| { + value | u64::from(key & (1 << from) != 0) << to + }); + assert_eq!(index, decoded, "{key:#x}, read={read}"); + } + (None, None) => {} + _ => panic!("different accessor match for {key:#x}, read={read}"), + } + } + } + } +} diff --git a/crates/stela-engine/src/machine/system/generated.rs b/crates/stela-engine/src/machine/system/generated.rs index 7ddaa9d855..50a0687596 100644 --- a/crates/stela-engine/src/machine/system/generated.rs +++ b/crates/stela-engine/src/machine/system/generated.rs @@ -40655,20 +40655,20 @@ fn a806(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Addr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Addr, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Addr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Addr, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -40699,22 +40699,16 @@ fn a807(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Addr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Addr, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Addr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Addr, index, value)?; } return Ok(Effect::Done); } @@ -40743,20 +40737,20 @@ fn a808(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Ctlr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Ctlr, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Ctlr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Ctlr, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -40787,22 +40781,16 @@ fn a809(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Ctlr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Ctlr, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Ctlr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Ctlr, index, value)?; } return Ok(Effect::Done); } @@ -40831,20 +40819,20 @@ fn a810(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Fr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Fr, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Fr, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Fr, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -40877,20 +40865,20 @@ fn a811(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Gsr, - bits(bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), 6, 10), - ); + let value = { + let index = bits(bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), 6, 10); + c.error_record(ErrorRecord::Gsr, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Gsr, - bits(bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), 6, 10), - ); + let value = { + let index = bits(bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), 6, 10); + c.error_record(ErrorRecord::Gsr, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -40920,20 +40908,20 @@ fn a812(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Misc0, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Misc0, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Misc0, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Misc0, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -40964,22 +40952,16 @@ fn a813(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Misc0, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Misc0, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Misc0, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Misc0, index, value)?; } return Ok(Effect::Done); } @@ -41008,20 +40990,20 @@ fn a814(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Misc1, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Misc1, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Misc1, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Misc1, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -41052,22 +41034,16 @@ fn a815(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Misc1, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Misc1, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Misc1, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Misc1, index, value)?; } return Ok(Effect::Done); } @@ -41096,20 +41072,20 @@ fn a816(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Misc2, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Misc2, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Misc2, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Misc2, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -41140,22 +41116,16 @@ fn a817(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Misc2, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Misc2, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Misc2, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Misc2, index, value)?; } return Ok(Effect::Done); } @@ -41184,20 +41154,20 @@ fn a818(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Misc3, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Misc3, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Misc3, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Misc3, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -41228,22 +41198,16 @@ fn a819(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Misc3, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Misc3, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Misc3, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Misc3, index, value)?; } return Ok(Effect::Done); } @@ -41272,20 +41236,20 @@ fn a820(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Pfgcdn, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Pfgcdn, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Pfgcdn, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Pfgcdn, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -41316,22 +41280,16 @@ fn a821(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Pfgcdn, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Pfgcdn, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Pfgcdn, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Pfgcdn, index, value)?; } return Ok(Effect::Done); } @@ -41360,20 +41318,20 @@ fn a822(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Pfgctl, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Pfgctl, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Pfgctl, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Pfgctl, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -41404,22 +41362,16 @@ fn a823(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Pfgctl, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Pfgctl, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Pfgctl, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Pfgctl, index, value)?; } return Ok(Effect::Done); } @@ -41448,20 +41400,20 @@ fn a824(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Pfgf, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Pfgf, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Pfgf, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Pfgf, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -41491,20 +41443,20 @@ fn a825(c: &mut dyn Context, m: u64) -> Result { }); } { - let value = c.error_record( - ErrorRecord::Status, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Status, index) + }; c.set_x(value); } return Ok(Effect::Done); } if (c.el()) == (2) { { - let value = c.error_record( - ErrorRecord::Status, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - ); + let value = { + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.error_record(ErrorRecord::Status, index) + }; c.set_x(value); } return Ok(Effect::Done); @@ -41535,22 +41487,16 @@ fn a826(c: &mut dyn Context, m: u64) -> Result { } { let value = c.x(); - c.set_error_record( - ErrorRecord::Status, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Status, index, value)?; } return Ok(Effect::Done); } if (c.el()) == (2) { { let value = c.x(); - c.set_error_record( - ErrorRecord::Status, - bits(c.read(Register::ERRSELR_EL1, 0), 0, 16), - value, - )?; + let index = bits(c.read(Register::ERRSELR_EL1, 0), 0, 16); + c.set_error_record(ErrorRecord::Status, index, value)?; } return Ok(Effect::Done); } diff --git a/crates/stela-engine/src/machine/system/helpers.rs b/crates/stela-engine/src/machine/system/helpers.rs index c26e0e147e..1ba3ff23c5 100644 --- a/crates/stela-engine/src/machine/system/helpers.rs +++ b/crates/stela-engine/src/machine/system/helpers.rs @@ -61,13 +61,13 @@ pub fn hcr_nvx(c: &mut dyn Context) -> Result { Ok(effective_nvx(c.read(Register::HCR_EL2, 0), nv, nv2)) } -fn tge(c: &dyn Context) -> bool { +fn tge(c: &mut dyn Context) -> bool { bits(c.read(Register::HCR_EL2, 0), u64::from(HCR_TGE), 1) == 1 } /// `ELIsInHost(el)`: EL2 is always in host (E2H RES1); EL0 is in host while /// HCR_EL2.TGE is 1; EL1 never is. -pub fn is_in_host(c: &dyn Context, el: u64) -> bool { +pub fn is_in_host(c: &mut dyn Context, el: u64) -> bool { match el { 2 => true, 0 => tge(c), @@ -76,23 +76,23 @@ pub fn is_in_host(c: &dyn Context, el: u64) -> bool { } /// `EffectivelyAtEL0InHost()`. -pub fn at_el0_in_host(c: &dyn Context) -> bool { +pub fn at_el0_in_host(c: &mut dyn Context) -> bool { c.el() == 0 && is_in_host(c, 0) } /// `EffectivelyAtEL0NotInHost()`. -pub fn at_el0_not_in_host(c: &dyn Context) -> bool { +pub fn at_el0_not_in_host(c: &mut dyn Context) -> bool { c.el() == 0 && !is_in_host(c, 0) } /// `EffectiveTGEforEL0Traps()`: HCR_EL2.TGE, EL2 being enabled. -pub fn tge_for_el0_traps(c: &dyn Context) -> u64 { +pub fn tge_for_el0_traps(c: &mut dyn Context) -> u64 { u64::from(tge(c)) } /// `AArch64_SystemAccessTraptoEL1orEL2(ec)`: an EL0 trap goes to EL2 when /// HCR_EL2.TGE is 1, else to EL1. -pub fn trap_el1_or_el2(c: &dyn Context, ec: u64) -> Effect { +pub fn trap_el1_or_el2(c: &mut dyn Context, ec: u64) -> Effect { Effect::Trap { el: if tge(c) { 2 } else { 1 }, ec, @@ -102,7 +102,7 @@ pub fn trap_el1_or_el2(c: &dyn Context, ec: u64) -> Effect { /// `UnimplementedIDRegister()` with FEAT_IDST: an access to an ID register /// encoding the profile does not implement traps with EC 0x18 to the current /// EL, or from EL0 to EL1 or, under HCR_EL2.TGE, EL2. -pub fn unimplemented_id_register(c: &dyn Context) -> Effect { +pub fn unimplemented_id_register(c: &mut dyn Context) -> Effect { match c.el() { 0 => trap_el1_or_el2(c, 0x18), el => Effect::Trap { @@ -113,7 +113,7 @@ pub fn unimplemented_id_register(c: &dyn Context) -> Effect { } /// `VMID()`: 8-bit VMIDs (no FEAT_VMID16), from VTTBR_EL2. -pub fn vmid(c: &dyn Context) -> u64 { +pub fn vmid(c: &mut dyn Context) -> u64 { bits(c.read(Register::VTTBR_EL2, 0), u64::from(VTTBR_VMID), 8) } diff --git a/crates/stela-engine/src/machine/timer.rs b/crates/stela-engine/src/machine/timer.rs index 72367a4a7c..1f2538973e 100644 --- a/crates/stela-engine/src/machine/timer.rs +++ b/crates/stela-engine/src/machine/timer.rs @@ -23,6 +23,26 @@ pub const ENABLE: u64 = 1; pub const IMASK: u64 = 2; pub const ISTATUS: u64 = 4; +/// A channel's comparator or interrupt control, including its relative alias. +pub(super) fn channel_register(register: Register) -> bool { + use Register::*; + matches!( + register, + CNTP_CTL_EL0 + | CNTP_CVAL_EL0 + | CNTP_TVAL_EL0 + | CNTV_CTL_EL0 + | CNTV_CVAL_EL0 + | CNTV_TVAL_EL0 + | CNTHP_CTL_EL2 + | CNTHP_CVAL_EL2 + | CNTHP_TVAL_EL2 + | CNTHV_CTL_EL2 + | CNTHV_CVAL_EL2 + | CNTHV_TVAL_EL2 + ) +} + /// One timer channel. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Channel { diff --git a/crates/stela-engine/src/machine/vgic.rs b/crates/stela-engine/src/machine/vgic.rs index a4e856d997..b6db712cdc 100644 --- a/crates/stela-engine/src/machine/vgic.rs +++ b/crates/stela-engine/src/machine/vgic.rs @@ -375,6 +375,13 @@ impl CpuInterface { }) } + /// Whether an encoding can reach a vGIC accessor. Ordinary System + /// register accesses can skip constructing the live vGIC context. + pub(crate) fn may_access(encoding: Encoding) -> bool { + encoding == icc::PMR + || (encoding.op0() == 3 && encoding.crn() == 12 && matches!(encoding.op1(), 0 | 4)) + } + /// An MRS (`write` `None`) or MSR of `encoding` that this interface /// answers before the generated accessors, which follow the profile's /// absent FEAT_GICv3: the ICH_* space and ICC_SRE_EL2 at EL2, and the @@ -408,6 +415,25 @@ mod tests { fine_grained_trap: false, }; + #[test] + fn the_fast_prefilter_admits_every_accessor() { + let mut interface = CpuInterface::default(); + for op0 in 0..4 { + for op1 in 0..8 { + for crn in 0..16 { + for crm in 0..16 { + for op2 in 0..8 { + let encoding = Encoding::new(op0, op1, crn, crm, op2); + if !CpuInterface::may_access(encoding) { + assert!(interface.access(encoding, None, &EL2).is_none()); + } + } + } + } + } + } + } + fn read(gic: &mut CpuInterface, encoding: Encoding) -> Option { gic.access(encoding, None, &EL2) } diff --git a/crates/stela-engine/src/machine/vgic/icc.rs b/crates/stela-engine/src/machine/vgic/icc.rs index 84fb3d31ac..898b11971d 100644 --- a/crates/stela-engine/src/machine/vgic/icc.rs +++ b/crates/stela-engine/src/machine/vgic/icc.rs @@ -42,6 +42,9 @@ use super::{ use crate::machine::registers::{Changes, Outcome}; use stela_compiler::aarch64::system::registers::Encoding; +/// ICC_PMR_EL1 is outside the CRn=12 CPU interface register space. +pub(super) const PMR: Encoding = Encoding::new(3, 0, 4, 6, 0); + /// ICC_SRE_EL1: SRE, DFB and DIB, each RAO/WI. const SRE_EL1_VALUE: u64 = 0b111; /// ICC_SRE_EL2: SRE, DFB, DIB and Enable, each RAO/WI. @@ -128,7 +131,7 @@ impl Register { encoding.crm(), encoding.op2(), ); - if (op0, op1, crn, crm, op2) == (3, 0, 4, 6, 0) { + if encoding == PMR { return Some(Self::Pmr); } if (op0, op1, crn) != (3, 0, 12) { diff --git a/crates/stela-engine/src/memory/domain/native_target.rs b/crates/stela-engine/src/memory/domain/native_target.rs index fc2b703145..82013c0527 100644 --- a/crates/stela-engine/src/memory/domain/native_target.rs +++ b/crates/stela-engine/src/memory/domain/native_target.rs @@ -16,6 +16,8 @@ pub(in crate::memory) fn restrict(actual: TargetCpu, limit: TargetCpu) -> Target (TargetCpu::Popcnt, TargetCpu::with_popcnt), (TargetCpu::Aes, TargetCpu::with_aes), (TargetCpu::Sha, TargetCpu::with_sha), + (TargetCpu::Gfni, TargetCpu::with_gfni), + (TargetCpu::Lzcnt, TargetCpu::with_lzcnt), (TargetCpu::Cx8, TargetCpu::with_cx8), (TargetCpu::Cx16, TargetCpu::with_cx16), (TargetCpu::AtomicLoad16, TargetCpu::with_atomic_load16), @@ -36,6 +38,8 @@ mod tests { .with_pclmulqdq() .with_aes() .with_sha() + .with_gfni() + .with_lzcnt() .with_atomic_load16(); #[test] @@ -55,6 +59,8 @@ mod tests { TargetCpu::Sse42, TargetCpu::Aes, TargetCpu::Sha, + TargetCpu::Gfni, + TargetCpu::Lzcnt, TargetCpu::AtomicLoad16, LEGACY, ] { @@ -72,6 +78,10 @@ mod tests { let actual = TargetCpu::Sse42.with_aes().with_sha().with_atomic_load16(); let worker = TargetCpu::Sse41.with_aes().with_cx16(); assert_eq!(restrict(actual, worker), TargetCpu::Sse41.with_aes()); + assert_eq!( + restrict(TargetCpu::Lzcnt.with_gfni(), TargetCpu::Gfni), + TargetCpu::Gfni + ); assert_eq!( restrict(TargetCpu::Baseline, TargetCpu::X86_64_V4), TargetCpu::Baseline diff --git a/crates/stela-engine/src/platform/cpu/system.rs b/crates/stela-engine/src/platform/cpu/system.rs index d41e32702a..33263dea49 100644 --- a/crates/stela-engine/src/platform/cpu/system.rs +++ b/crates/stela-engine/src/platform/cpu/system.rs @@ -58,6 +58,7 @@ struct CpuDeclarations { // Only the consumed immutable hardware bits; OSXSAVE is live CR4 state. cpuid1_ecx: u32, cpuid1_edx: u32, + extended_ecx: u32, extended_edx: u32, cpuid7_ebx: u32, cpuid7_ecx: u32, @@ -85,6 +86,8 @@ const CPUID1_ECX_READ: u32 = CPUID_PCLMULQDQ | CPUID_AES | (1 << 28); const CPUID_SHA: u32 = 1 << 29; +const CPUID_GFNI: u32 = 1 << 8; +const CPUID_LZCNT: u32 = 1 << 5; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct NativeControls { @@ -155,6 +158,14 @@ impl Observation { if d.cpuid7_ebx & CPUID_SHA != 0 { target = target.with_sha(); } + // This target selects the legacy XMM forms of GFNI. VEX and EVEX + // forms require additional capabilities that remain unavailable. + if d.cpuid7_ecx & CPUID_GFNI != 0 { + target = target.with_gfni(); + } + if d.extended_ecx & CPUID_LZCNT != 0 { + target = target.with_lzcnt(); + } if d.cpuid1_edx & (1 << 8) != 0 { target = target.with_cx8(); } @@ -460,9 +471,10 @@ fn enumerate(mut cpuid: impl FnMut(u32, u32) -> Cpuid) -> Result<(CpuDeclaration vendor, cpuid1_ecx: basic.ecx & CPUID1_ECX_READ, cpuid1_edx: basic.edx & (CPUID_FLOOR_EDX | (1 << 8)), + extended_ecx: ext.ecx & CPUID_LZCNT, extended_edx: ext.edx & CPUID_LONG_NX, cpuid7_ebx: leaf7.ebx & CPUID_SHA, - cpuid7_ecx: leaf7.ecx & (1 << 16), + cpuid7_ecx: leaf7.ecx & ((1 << 16) | CPUID_GFNI), identity: probe, }, apic_id, diff --git a/crates/stela-engine/src/platform/cpu/system/tests.rs b/crates/stela-engine/src/platform/cpu/system/tests.rs index 477660551b..f284b0ceff 100644 --- a/crates/stela-engine/src/platform/cpu/system/tests.rs +++ b/crates/stela-engine/src/platform/cpu/system/tests.rs @@ -5,6 +5,7 @@ fn baseline() -> Observation { vendor: TargetCpu::INTEL_VENDOR, cpuid1_ecx: 0, cpuid1_edx: CPUID_FLOOR_EDX, + extended_ecx: 0, extended_edx: CPUID_LONG_NX, cpuid7_ebx: 0, cpuid7_ecx: 0, @@ -21,6 +22,29 @@ fn baseline() -> Observation { } } +#[test] +fn optional_legacy_extensions_require_live_declarations_without_osxsave() { + let mut actual = baseline(); + actual.declarations.extended_ecx = CPUID_LZCNT; + assert_eq!(actual.target(), Ok(TargetCpu::Lzcnt)); + actual.declarations.cpuid7_ecx = CPUID_GFNI; + assert_eq!(actual.target(), Ok(TargetCpu::Lzcnt.with_gfni())); + assert_eq!(actual.controls.cr4 & (1 << 18), 0); + let proof = NativeSystemTarget { + observed: actual, + lease: None, + target: actual.target().unwrap(), + }; + actual.declarations.extended_ecx = 0; + assert_eq!(actual.target(), Ok(TargetCpu::Gfni)); + assert_eq!( + proof.revalidate_observation(actual), + Err(Refusal::TargetChanged) + ); + actual.declarations.cpuid7_ecx = 0; + assert_eq!(actual.target(), Ok(TargetCpu::Baseline)); +} + #[test] fn legacy_xmm_floor_never_invents_extended_features() { let mut actual = baseline(); @@ -646,6 +670,7 @@ fn one_owner_enumeration_then_one_live_identity_probe_per_boundary() { ..Cpuid::default() }, 0x8000_0001 => Cpuid { + ecx: CPUID_LZCNT | (1 << 22), edx: CPUID_LONG_NX, ..Cpuid::default() }, @@ -655,12 +680,17 @@ fn one_owner_enumeration_then_one_live_identity_probe_per_boundary() { edx: actual.controls.apic_id, ..Cpuid::default() }, - 7 => Cpuid::default(), + 7 => Cpuid { + ecx: CPUID_GFNI | 1, + ..Cpuid::default() + }, _ => panic!("unexpected leaf"), } }) .unwrap(); assert_eq!(enumerations.get(), 6); + assert_eq!(d.extended_ecx, CPUID_LZCNT); + assert_eq!(d.cpuid7_ecx, CPUID_GFNI); let owner = modeled_owner(Observation { declarations: d, controls: NativeControls { @@ -691,6 +721,7 @@ fn one_owner_enumeration_then_one_live_identity_probe_per_boundary() { live, ) .unwrap(); + assert_eq!(proof.target(), TargetCpu::Lzcnt.with_gfni()); for _ in 1..4 { proof .revalidate_with(|| panic!("no reenumeration"), live) diff --git a/crates/stela-engine/src/tests.rs b/crates/stela-engine/src/tests.rs index 6fc40360cc..144c2497e3 100644 --- a/crates/stela-engine/src/tests.rs +++ b/crates/stela-engine/src/tests.rs @@ -681,3 +681,34 @@ fn concurrent_requests_publish_a_complete_single_entry() -> Result<()> { assert_eq!(std::fs::read_dir(root.path())?.count(), 1); Ok(()) } + +#[cfg(unix)] +#[test] +fn preparation_resolves_the_cache_root_for_each_publication() -> Result<()> { + let root = tempfile::tempdir()?; + let first_root = root.path().join("first"); + let second_root = root.path().join("second"); + let alias = root.path().join("alias"); + std::fs::create_dir(&first_root)?; + std::fs::create_dir(&second_root)?; + std::os::unix::fs::symlink("first", &alias)?; + + let input = source(42); + let pc = GuestAddress(0x1000); + let first = prepare_leaf(&input, pc, &alias)?; + assert!(!first.cache_hit); + assert_eq!(first.directory, first_root.canonicalize()?.join(&first.key)); + assert!(prepare_leaf(&input, pc, &alias)?.cache_hit); + + std::fs::remove_file(&alias)?; + std::os::unix::fs::symlink("second", &alias)?; + let second = prepare_leaf(&input, pc, &alias)?; + assert!(!second.cache_hit); + assert_eq!(first.key, second.key); + assert_eq!( + second.directory, + second_root.canonicalize()?.join(&second.key) + ); + assert!(prepare_leaf(&input, pc, &alias)?.cache_hit); + Ok(()) +} diff --git a/crates/stela-engine/src/translations.rs b/crates/stela-engine/src/translations.rs index e3bc42e4c3..291fa6da30 100644 --- a/crates/stela-engine/src/translations.rs +++ b/crates/stela-engine/src/translations.rs @@ -28,6 +28,14 @@ pub const SCHEMA: u32 = 3; const RECORD_MAGIC: [u8; 8] = *b"STLTPAGE"; const HEADER_BYTES: usize = 88; const TRAILER_BYTES: usize = 32; +/// Context, guest offset, source and input lengths, code length, and four +/// metadata counts. Variable-length payloads follow these fixed fields. +const ENTRY_MIN_BYTES: usize = 32 + 3 * 2 + 5 * 4; +const RELOCATION_BYTES: usize = 4; +const SOURCE_MAP_BYTES: usize = 6; +const EXIT_BYTES: usize = 15; +const RECOVERY_ROW_BYTES: usize = 24; +const RECOVERY_BINDING_BYTES: usize = 4; /// A relocated field: a little-endian u64 in the native code. const FIELD_BYTES: usize = 8; /// The bits of a page's address its translations are bound to (the @@ -293,6 +301,24 @@ impl Record { &self.entries } + /// Heap bytes owned by a shared decoded record, excluding allocator + /// bookkeeping. The per-PE source page cache accounts for its own pages. + fn retained_bytes(&self) -> usize { + let mut bytes = core::mem::size_of::() + 2 * core::mem::size_of::(); + bytes += self.entries.capacity() * core::mem::size_of::(); + for entry in &self.entries { + bytes += entry.input.capacity() + entry.code.capacity(); + bytes += entry.relocations.capacity() * core::mem::size_of::(); + bytes += entry.source_map.capacity() * core::mem::size_of::<(u16, u32)>(); + bytes += entry.exits.capacity() * core::mem::size_of::(); + bytes += entry.recovery.capacity() * core::mem::size_of::(); + for row in &entry.recovery { + bytes += row.bindings.capacity() * core::mem::size_of::(); + } + } + bytes + } + fn entry_index(&self, offset: u16, context: &Digest) -> Result { // Keep the first entry when decoding a legacy record with duplicate // keys, as the previous sequential lookup did. @@ -329,24 +355,48 @@ impl Record { } /// Add the entries of `other` this record lacks. - pub fn merge(&mut self, other: Self) { - for entry in other.entries { - if let Err(index) = self.entry_index(entry.offset, &entry.context) { - self.entries.insert(index, entry); - } + pub fn merge(&mut self, mut other: Self) { + if other.entries.is_empty() { + return; } + let key = |entry: &Entry| (entry.offset, entry.context); + // Legacy packs can contain duplicate keys. The first one wins + // unless this record already holds an entry for that key. + other.entries.dedup_by_key(|entry| key(entry)); + if self.entries.is_empty() { + self.entries = other.entries; + return; + } + let mut merged = Vec::with_capacity(self.entries.len() + other.entries.len()); + let mut incoming = other.entries.into_iter().peekable(); + for entry in self.entries.drain(..) { + let current = key(&entry); + while incoming.peek().is_some_and(|next| key(next) < current) { + merged.extend(incoming.next()); + } + if incoming.peek().is_some_and(|next| key(next) == current) { + incoming.next(); + } + merged.push(entry); + } + merged.extend(incoming); + self.entries = merged; } pub fn encode(&self) -> Vec { - let mut out = Vec::with_capacity( - HEADER_BYTES - + TRAILER_BYTES - + self - .entries - .iter() - .map(|entry| 64 + entry.code.len() + entry.source_map.len() * 6) - .sum::(), - ); + let mut encoded_bytes = HEADER_BYTES + TRAILER_BYTES; + for entry in &self.entries { + encoded_bytes += ENTRY_MIN_BYTES + + entry.input.len() + + entry.code.len() + + entry.relocations.len() * RELOCATION_BYTES + + entry.source_map.len() * SOURCE_MAP_BYTES + + entry.exits.len() * EXIT_BYTES; + for row in &entry.recovery { + encoded_bytes += RECOVERY_ROW_BYTES + row.bindings.len() * RECOVERY_BINDING_BYTES; + } + } + let mut out = Vec::with_capacity(encoded_bytes); out.extend(RECORD_MAGIC); out.extend(SCHEMA.to_le_bytes()); out.extend((self.entries.len() as u32).to_le_bytes()); @@ -404,6 +454,7 @@ impl Record { out[80..88].copy_from_slice(&total.to_le_bytes()); let checksum = Sha256::digest(&out); out.extend(checksum); + debug_assert_eq!(out.len(), encoded_bytes); out } @@ -420,7 +471,7 @@ impl Record { if reader.u32()? != SCHEMA { return Err(FormatError::Schema); } - let count = reader.u32()?; + let count = reader.u32()? as usize; if reader.digest()? != *translator { return Err(FormatError::Translator); } @@ -433,14 +484,16 @@ impl Record { if Sha256::digest(body).as_slice() != trailer { return Err(FormatError::Checksum); } - let mut entries = Vec::new(); - for _ in 0..count { + if count > reader.0.len() / ENTRY_MIN_BYTES { + return Err(FormatError::Truncated); + } + let mut entries = decode_items(count, || { let entry = reader.entry()?; if !entry.consistent() { return Err(FormatError::Entry); } - entries.push(entry); - } + Ok(entry) + })?; if !reader.0.is_empty() { return Err(FormatError::Entry); } @@ -455,6 +508,22 @@ impl Record { } } +/// Reserve for the common case without letting a corrupt count make the +/// decoder allocate a large vector before checking its first item. +fn decode_items( + count: usize, + mut next: impl FnMut() -> Result, +) -> Result, FormatError> { + let mut items = Vec::new(); + items + .try_reserve_exact(count.min(256)) + .map_err(|_| FormatError::Entry)?; + for _ in 0..count { + items.push(next()?); + } + Ok(items) +} + /// Bounded little-endian reads; every count is checked against the bytes /// left before anything is allocated. struct Reader<'a>(&'a [u8]); @@ -512,91 +581,81 @@ impl<'a> Reader<'a> { } let input = self.take(input_bytes)?.to_vec(); let code_bytes = self.u32()? as usize; - let relocations = (0..self.count(4)?) - .map(|_| self.u32()) - .collect::>()?; - let source_map = (0..self.count(6)?) - .map(|_| Ok((self.u16()?, self.u32()?))) - .collect::>()?; - let exits = (0..self.count(15)?) - .map(|_| { - Ok(Exit { - offset: self.u32()?, - target: self.u64()?, - kind: self.u8()?, - skipped: self.u16()?, - }) + let relocations = decode_items(self.count(RELOCATION_BYTES)?, || self.u32())?; + let source_map = decode_items(self.count(SOURCE_MAP_BYTES)?, || { + Ok((self.u16()?, self.u32()?)) + })?; + let exits = decode_items(self.count(EXIT_BYTES)?, || { + Ok(Exit { + offset: self.u32()?, + target: self.u64()?, + kind: self.u8()?, + skipped: self.u16()?, }) - .collect::>()?; - let recovery = (0..self.count(24)?) - .map(|_| { - let start = self.u32()? as usize; - let end = self.u32()? as usize; - let pc = GuestAddress(self.u64()?); - let count = self.u16()?; - let phase = match self.u8()? { - 0 => RetirementPhase::Before, - 1 => RetirementPhase::AfterFallthrough, + })?; + let recovery = decode_items(self.count(RECOVERY_ROW_BYTES)?, || { + let start = self.u32()? as usize; + let end = self.u32()? as usize; + let pc = GuestAddress(self.u64()?); + let count = self.u16()?; + let phase = match self.u8()? { + 0 => RetirementPhase::Before, + 1 => RetirementPhase::AfterFallthrough, + _ => return Err(FormatError::Entry), + }; + let site = RecoverySiteKind::try_from(self.u8()?).map_err(|_| FormatError::Entry)?; + let bindings = decode_items(self.count(RECOVERY_BINDING_BYTES)?, || { + let guest = self.u8()?; + let kind = self.u8()?; + let value = self.u16()?; + let source = match kind { + 0 => RecoverySource::HostRegister( + u8::try_from(value).map_err(|_| FormatError::Entry)?, + ), + 1 => RecoverySource::NativeSpill( + SpillOffset::new(value).map_err(|_| FormatError::Entry)?, + ), _ => return Err(FormatError::Entry), }; - let site = - RecoverySiteKind::try_from(self.u8()?).map_err(|_| FormatError::Entry)?; - let bindings = (0..self.count(4)?) - .map(|_| { - let guest = self.u8()?; - let kind = self.u8()?; - let value = self.u16()?; - let source = match kind { - 0 => RecoverySource::HostRegister( - u8::try_from(value).map_err(|_| FormatError::Entry)?, - ), - 1 => RecoverySource::NativeSpill( - SpillOffset::new(value).map_err(|_| FormatError::Entry)?, - ), - _ => return Err(FormatError::Entry), - }; - Ok(RecoveryBinding { guest, source }) - }) - .collect::>()?; - // Build a structurally valid source-backed shape using an - // entry view below; no raw After constructor is exposed. - let before = RetirementPoint::before(pc, count).map_err(|_| FormatError::Entry)?; - let retirement = match phase { - RetirementPhase::Before => before, - RetirementPhase::AfterFallthrough => { - use stela_compiler::Lifter as _; - let at = usize::try_from( - pc.0.checked_sub(u64::from(offset)) - .ok_or(FormatError::Entry)?, - ) - .map_err(|_| FormatError::Entry)?; - if at.checked_add(4).ok_or(FormatError::Entry)? > usize::from(source_bytes) - { - return Err(FormatError::Entry); - } - let word = u32::from_le_bytes( - input - .get(at..at + 4) - .ok_or(FormatError::Entry)? - .try_into() - .map_err(|_| FormatError::Entry)?, - ); - let instruction = stela_compiler::aarch64::Decoder - .lift(pc, word) - .map_err(|_| FormatError::Entry)?; - RetirementPoint::from_instruction(&instruction, count, phase) - .map_err(|_| FormatError::Entry)? + Ok(RecoveryBinding { guest, source }) + })?; + // Build a structurally valid source-backed shape using an + // entry view below; no raw After constructor is exposed. + let before = RetirementPoint::before(pc, count).map_err(|_| FormatError::Entry)?; + let retirement = match phase { + RetirementPhase::Before => before, + RetirementPhase::AfterFallthrough => { + use stela_compiler::Lifter as _; + let at = usize::try_from( + pc.0.checked_sub(u64::from(offset)) + .ok_or(FormatError::Entry)?, + ) + .map_err(|_| FormatError::Entry)?; + if at.checked_add(4).ok_or(FormatError::Entry)? > usize::from(source_bytes) { + return Err(FormatError::Entry); } - }; - Ok(UnqualifiedFaultRecovery { - start, - end, - bindings, - retirement, - site, - }) + let word = u32::from_le_bytes( + input + .get(at..at + 4) + .ok_or(FormatError::Entry)? + .try_into() + .map_err(|_| FormatError::Entry)?, + ); + let instruction = stela_compiler::aarch64::Decoder + .lift(pc, word) + .map_err(|_| FormatError::Entry)?; + RetirementPoint::from_instruction(&instruction, count, phase) + .map_err(|_| FormatError::Entry)? + } + }; + Ok(UnqualifiedFaultRecovery { + start, + end, + bindings, + retirement, + site, }) - .collect::>()?; + })?; let code = self.take(code_bytes)?.to_vec(); Ok(Entry { context, diff --git a/crates/stela-engine/src/translations/pack.rs b/crates/stela-engine/src/translations/pack.rs index 901e645c44..957ca6aabf 100644 --- a/crates/stela-engine/src/translations/pack.rs +++ b/crates/stela-engine/src/translations/pack.rs @@ -40,6 +40,10 @@ pub const MAX_RECORDS: usize = 1 << 22; /// The most memory the blocks waiting for proof take; later blocks are /// counted as dropped. const MAX_PENDING_BYTES: usize = 16 << 20; +/// A direct-mapped cache of decoded pack records shared by all PEs. Each +/// slot has its own bound so one large record cannot evict many small ones. +const DECODED_SLOTS: usize = 128; +const DECODED_SLOT_BYTES: usize = 64 << 10; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PackError { @@ -314,6 +318,67 @@ struct SharedEntry { bytes: usize, } +/// One local producer's shared offer, allocated and charged before the +/// producer acquires the store lock. +pub struct StagedOffer { + key: SharedKey, + entry: Option, +} + +impl StagedOffer { + /// `bound` is the producer's snapshot of the shared cache limit. + /// Admission rechecks the store's limit. + pub fn new(offer: Offer, bound: usize) -> Option { + if bound == 0 { + return None; + } + let bytes = offer + .retained_bytes() + .saturating_add(size_of::<(SharedKey, SharedEntry)>()); + (bytes <= bound).then(|| Self { + key: shared_key(&offer.key(), offer.pc(), &offer.context()), + entry: Some(SharedEntry { + translation: offer.shared(), + bytes, + }), + }) + } +} + +/// At most one displaced owner per producer can outlive the store lock. +/// The cap covers charged cache bytes, with the same exclusions as the +/// shared cache budget. Larger or additional owners are released inside. +const RETIRED_OWNER_BYTES: usize = 64 << 10; + +fn retire(entry: SharedEntry, deferred: &mut Option>) { + if deferred.is_none() && entry.bytes <= RETIRED_OWNER_BYTES { + *deferred = Some(entry.translation); + } +} + +/// A validated record paired with the immutable pack bytes it came from. +pub struct DecodedRecord<'a> { + bytes: &'a [u8], + record: Arc, + retained_bytes: usize, +} + +impl<'a> DecodedRecord<'a> { + pub fn decode(bytes: &'a [u8], translator: &Digest, key: &Digest) -> Option { + let record = Arc::new(Record::decode(bytes, translator, key).ok()?); + let retained_bytes = record.retained_bytes(); + Some(Self { + bytes, + record, + retained_bytes, + }) + } + + pub fn into_record(self) -> Arc { + self.record + } +} + /// One boot's store over the pack it read. #[derive(Debug)] pub struct Store<'a> { @@ -323,6 +388,7 @@ pub struct Store<'a> { /// each. The records themselves are the engine's to keep: decoded, they /// take several times the pack's bytes. loaded: BTreeMap, + decoded: Vec>>, pending: BTreeMap, /// The blocks in `pending`. pending_blocks: usize, @@ -365,6 +431,7 @@ impl<'a> Store<'a> { translator, pack, loaded: BTreeMap::new(), + decoded: Vec::new(), pending: BTreeMap::new(), pending_blocks: 0, pending_bytes: 0, @@ -386,7 +453,7 @@ impl<'a> Store<'a> { pub fn share(&mut self, bound: usize) { self.shared_bound = bound; while self.shared_usage() > bound { - if !self.evict_shared() { + if self.evict_shared().is_none() { self.shared_order = VecDeque::new(); break; } @@ -398,70 +465,63 @@ impl<'a> Store<'a> { .saturating_add(self.shared_order.capacity() * size_of::()) } - fn evict_shared(&mut self) -> bool { - let Some(oldest) = self.shared_order.pop_front() else { - return false; - }; - if let Some(evicted) = self.shared.remove(&oldest) { - self.shared_bytes -= evicted.bytes; + fn evict_shared(&mut self) -> Option { + while let Some(oldest) = self.shared_order.pop_front() { + if let Some(evicted) = self.shared.remove(&oldest) { + self.shared_bytes -= evicted.bytes; + return Some(evicted); + } } - true + None } - fn shared_room(&mut self, key: &SharedKey, incoming: usize) -> bool { + /// Admit a preallocated shared block. The producer can drop a displaced + /// owner after releasing the lock. The producer still owns a declined + /// block, so declining it does not drop its buffers while locked. + pub fn accept_shared(&mut self, staged: &mut StagedOffer) -> Option> { + use alloc::collections::btree_map::Entry; + + let key = staged.key; + let bytes = staged.entry.as_ref()?.bytes; + if bytes > self.shared_bound { + return None; + } + let mut deferred = None; loop { - let replaced = self.shared.get(key).map_or(0, |old| old.bytes); - if self - .shared_usage() - .saturating_sub(replaced) - .saturating_add(incoming) - <= self.shared_bound - { - return true; + let usage = self.shared_usage(); + match self.shared.entry(key) { + Entry::Occupied(mut slot) + if usage.saturating_sub(slot.get().bytes).saturating_add(bytes) + <= self.shared_bound => + { + self.shared_bytes = self.shared_bytes - slot.get().bytes + bytes; + let old = slot.insert(staged.entry.take().expect("staged entry")); + retire(old, &mut deferred); + return deferred; + } + Entry::Vacant(slot) + if usage.saturating_add(bytes) <= self.shared_bound + && self.shared_order.try_reserve(1).is_ok() => + { + // A FIFO allocation can itself exceed the budget. + let fifo = self.shared_order.capacity() * size_of::(); + if self.shared_bytes.saturating_add(fifo).saturating_add(bytes) + <= self.shared_bound + { + slot.insert(staged.entry.take().expect("staged entry")); + self.shared_order.push_back(key); + self.shared_bytes += bytes; + return deferred; + } + } + _ => {} } - if !self.evict_shared() { + let Some(evicted) = self.evict_shared() else { self.shared_order = VecDeque::new(); - return false; - } - } - } - - fn keep_shared(&mut self, offer: Offer) { - let key = shared_key(&offer.key(), offer.pc(), &offer.context()); - let bytes = offer - .retained_bytes() - .saturating_add(size_of::<(SharedKey, SharedEntry)>()); - if bytes > self.shared_bound || !self.shared_room(&key, bytes) { - return; - } - if !self.shared.contains_key(&key) { - // Reuse an oldest slot if bulk FIFO growth cannot be allocated. - // An empty cache simply declines the optional entry. - if self.shared_order.try_reserve(1).is_err() && !self.evict_shared() { - return; - } - if !self.shared_room(&key, bytes) { - return; - } - } - let shared = offer.shared(); - if let Some(present) = self.shared.get_mut(&key) { - self.shared_bytes -= present.bytes; - *present = SharedEntry { - translation: shared, - bytes, + return deferred; }; - } else { - self.shared.insert( - key, - SharedEntry { - translation: shared, - bytes, - }, - ); - self.shared_order.push_back(key); + retire(evicted, &mut deferred); } - self.shared_bytes += bytes; } fn keep_pending(&mut self, offer: &Offer) { @@ -534,28 +594,62 @@ impl<'a> Store<'a> { &self.translator } + fn decoded_slot(key: &Digest) -> usize { + usize::from(key.0[0]) % DECODED_SLOTS + } + + /// A record already decoded and checked against this pack. + pub fn cached_record(&self, key: &Digest) -> Option> { + let record = self.decoded.get(Self::decoded_slot(key))?.as_ref()?; + (record.key == *key).then(|| Arc::clone(record)) + } + + /// Remember a decoded record from this pack. The caller can drop an + /// evicted record after releasing the shared store lock. + pub fn remember_record(&mut self, decoded: &DecodedRecord<'a>) -> Option> { + let record = &decoded.record; + if record.translator != self.translator + || decoded.retained_bytes > DECODED_SLOT_BYTES + || !self + .stored(&record.key) + .is_some_and(|bytes| core::ptr::eq(bytes, decoded.bytes)) + { + return None; + } + if self.decoded.is_empty() { + self.decoded.try_reserve_exact(DECODED_SLOTS).ok()?; + self.decoded.resize_with(DECODED_SLOTS, || None); + } + let slot = &mut self.decoded[Self::decoded_slot(&record.key)]; + if slot.as_ref().is_some_and(|held| held.key == record.key) { + return None; + } + slot.replace(Arc::clone(record)) + } + /// The pack's bytes for `key`, unless an earlier lookup found them /// invalid: for a caller to decode ([`Record::decode`]) without holding /// the store, then report with [`Self::looked_up`]. pub fn stored(&self, key: &Digest) -> Option<&'a [u8]> { + let pack = self.pack?; if self.loaded.get(key) == Some(&false) { return None; } - self.pack.and_then(|pack| pack.get(key)) + pack.get(key) } /// Count `key`'s first lookup: whether the pack held bytes for it, and /// whether they decoded. pub fn looked_up(&mut self, key: &Digest, found: bool, valid: bool) { - if self.loaded.contains_key(key) { + let alloc::collections::btree_map::Entry::Vacant(slot) = self.loaded.entry(*key) else { return; - } + }; match (found, valid) { (true, true) => self.counters.loaded += 1, (true, false) => self.counters.invalid += 1, (false, _) => self.counters.absent += 1, } - self.loaded.insert(*key, valid); + slot.insert(valid); } /// The pack read, if valid. @@ -582,11 +676,9 @@ impl<'a> Store<'a> { } unproven -= 1; let start = block.start as usize; - let input = held.inputs[start..start + usize::from(block.length)].to_vec(); + let input = &held.inputs[start..start + usize::from(block.length)]; let pc = page + u64::from(block.offset); - let preparation = Arc::clone(&held.preparation); - let entry = Offer::compile(key, page, pc, context, input, preparation) - .and_then(|offer| offer.prove()); + let entry = Offer::prove_input(input, page, pc, context, &held.preparation); match entry { Some(entry) => { count += 1; @@ -652,10 +744,16 @@ impl<'a> Store<'a> { impl Translations for Store<'_> { fn record(&mut self, key: &Digest) -> Option> { + if let Some(record) = self.cached_record(key) { + return Some(record); + } let bytes = self.stored(key); - let record = bytes.and_then(|bytes| Record::decode(bytes, &self.translator, key).ok()); - self.looked_up(key, bytes.is_some(), record.is_some()); - record.map(Arc::new) + let decoded = bytes.and_then(|bytes| DecodedRecord::decode(bytes, &self.translator, key)); + self.looked_up(key, bytes.is_some(), decoded.is_some()); + decoded.map(|decoded| { + self.remember_record(&decoded); + decoded.into_record() + }) } fn prepared( @@ -671,11 +769,13 @@ impl Translations for Store<'_> { fn offer(&mut self, offer: Offer) { self.keep_pending(&offer); - self.keep_shared(offer); + self.lend(offer); } fn lend(&mut self, offer: Offer) { - self.keep_shared(offer); + if let Some(mut staged) = StagedOffer::new(offer, self.shared_bound) { + drop(self.accept_shared(&mut staged)); + } } } @@ -698,6 +798,56 @@ mod tests { Offer::compile(key, page, pc, preparation.context(page), input, preparation).unwrap() } + #[test] + fn decoded_pack_records_share_an_owner_and_check_the_full_key() { + let translator = translator_id(); + let first = Digest([1; 32]); + let mut second = first; + second.0[1] = 2; + let bytes = Layout::new( + &translator, + [first, second] + .map(|key| (key, Piece::New(Record::new(translator, key).encode()))) + .into(), + ) + .to_vec(); + let mut store = Store::new(translator, Some(&bytes)).0; + let held = store.record(&first).unwrap(); + assert!(Arc::ptr_eq(&held, &store.record(&first).unwrap())); + assert_eq!(store.record(&second).unwrap().key, second); + assert!(!Arc::ptr_eq(&held, &store.record(&first).unwrap())); + assert_eq!(store.counters.loaded, 2); + } + + #[test] + fn decoded_cache_declines_oversized_and_foreign_records() { + let translator = translator_id(); + let key = Digest::of(b"page"); + let mut large = Record::new(translator, key); + let mut entry = offer(0x1000, key).prove().unwrap(); + entry.code.resize(DECODED_SLOT_BYTES, 0); + large.insert(entry); + let bytes = Layout::new(&translator, vec![(key, Piece::New(large.encode()))]).to_vec(); + let mut store = Store::new(translator, Some(&bytes)).0; + assert!(store.record(&key).is_some()); + assert!(store.cached_record(&key).is_none()); + + let bytes = Layout::new( + &translator, + vec![(key, Piece::New(Record::new(translator, key).encode()))], + ) + .to_vec(); + let foreign = bytes.clone(); + let mut store = Store::new(translator, Some(&bytes)).0; + let foreign = Pack::parse(&foreign, &translator) + .unwrap() + .get(&key) + .unwrap(); + let decoded = DecodedRecord::decode(foreign, &translator, &key).unwrap(); + assert!(store.remember_record(&decoded).is_none()); + assert!(store.cached_record(&key).is_none()); + } + #[test] fn shared_cache_budget_includes_source_and_recovery_owners() { let translator = Digest::of(b"translator"); @@ -768,6 +918,42 @@ mod tests { assert_eq!(store.shared_order.capacity(), 0); } + #[test] + fn staged_admission_defers_eviction_and_keeps_a_declined_owner() { + let translator = Digest::of(b"translator"); + let key = Digest::of(b"page"); + let first = offer(0x1000, key); + let second = offer(0x1008, key); + let context = first.context(); + let charge = first.retained_bytes() + size_of::<(SharedKey, SharedEntry)>(); + let mut queue = VecDeque::::new(); + queue.try_reserve(1).unwrap(); + let bound = charge + queue.capacity() * size_of::(); + + let (mut store, _) = Store::new(translator, None); + store.share(bound); + let mut staged = StagedOffer::new(first, bound).unwrap(); + assert!(store.accept_shared(&mut staged).is_none()); + assert!(staged.entry.is_none()); + let old = Arc::downgrade(&store.prepared(&key, 0x1000, &context).unwrap()); + + let mut staged = StagedOffer::new(second, bound).unwrap(); + let retired = store.accept_shared(&mut staged).unwrap(); + assert!(store.prepared(&key, 0x1000, &context).is_none()); + assert!(Arc::ptr_eq(&retired, &old.upgrade().unwrap())); + assert!(store.prepared(&key, 0x1008, &context).is_some()); + assert!(store.shared_usage() <= bound); + assert_eq!(store.pending(), 0); + drop(retired); + assert!(old.upgrade().is_none()); + + let mut staged = StagedOffer::new(offer(0x1000, key), bound).unwrap(); + store.share(0); + assert!(store.accept_shared(&mut staged).is_none()); + assert!(staged.entry.is_some()); + assert!(store.prepared(&key, 0x1000, &context).is_none()); + } + #[test] fn a_shared_store_hands_offered_blocks_to_other_machines_and_forgets_the_oldest_when_full() { let translator = Digest::of(b"translator"); diff --git a/crates/stela-engine/src/translations/tests.rs b/crates/stela-engine/src/translations/tests.rs index 7697611ed3..06685eed82 100644 --- a/crates/stela-engine/src/translations/tests.rs +++ b/crates/stela-engine/src/translations/tests.rs @@ -61,6 +61,87 @@ fn address_dependent_blocks_rebase_to_what_the_compiler_emits_at_another_page() } } +#[test] +fn system_address_pair_rebases_one_fixed_address_and_both_source_rows() { + // Both PC-relative encodings retain an eight-byte relocation under + // page displacement, including when ADRP wraps to zero. + for first in [0x1000_0000, 0xb000_0000] { + let source = words(&[first, 0x9100_2000]); + let entry = proved(&source, 0x40).expect("pinned address pair is relocatable"); + assert_eq!(entry.source_map, [(0x40, 0), (0x44, 1)]); + assert!(entry.relocations.contains(&3)); + for page in [0x4000, 0x2_3456_8000, 0xffff_ffff_ffff_f000] { + let expected = compile(&source, page + 0x40); + let rebased = entry.rebase(page, &source).unwrap(); + assert_eq!(rebased.native.x86_64_code, expected.native.x86_64_code); + assert_eq!(rebased.native.source_map, expected.native.source_map); + assert_eq!(rebased.direct_exits, expected.direct_exits); + assert!(rebased.fault_recovery.is_empty()); + assert_eq!(rebased.source_bytes, source.len()); + } + assert!(entry.rebase(PAGE, &source[..4]).is_none()); + } +} + +#[test] +fn hosted_fused_address_pair_rebases_one_literal_and_both_source_rows() { + let source = words(&[0x9000_0020, 0x9100_2000, 0xd65f_03c0]); // adrp; add #8; ret + let options = stela_compiler::Options::new(BlockProfile::ORDINARY, TargetCpu::Baseline); + let pc = PAGE + 0x40; + let compile = |pc| stela_compiler::compile(&source, GuestAddress(pc), &options).unwrap(); + let block = compile(pc); + let probes = probe_displacements(PAGE).map(|delta| compile(pc.wrapping_add(delta))); + let entry = prove( + &block, + &source, + PAGE, + pc, + Digest::of(b"hosted"), + [&probes[0], &probes[1]], + ) + .expect("fused address is relocatable"); + assert_eq!(entry.relocations, [2]); + assert_eq!(entry.source_map[..2], [(0x40, 0), (0x44, 10)]); + for page in [0x4000, 0x2_3456_8000, 0x7fff_0000_0000] { + let expected = compile(page + 0x40); + let rebased = entry.rebase(page, &source).unwrap(); + assert_eq!(rebased.native.x86_64_code, expected.native.x86_64_code); + assert_eq!(rebased.native.source_map, expected.native.source_map); + assert_eq!(rebased.source_bytes, source.len()); + } +} + +#[test] +fn hosted_fused_wide_constant_rebases_without_numeric_relocations() { + let source = words(&[ + 0x92c0_0000 | (0xabcd << 5), // movn x0, #0xabcd, lsl #32 + 0xf2a0_0000 | (0x1234 << 5), // movk x0, #0x1234, lsl #16 + 0xf2e0_0000 | (0x5678 << 5), // movk x0, #0x5678, lsl #48 + 0xd65f_03c0, // ret + ]); + let options = stela_compiler::Options::new(BlockProfile::ORDINARY, TargetCpu::Baseline); + let pc = PAGE + 0x40; + let compile = |pc| stela_compiler::compile(&source, GuestAddress(pc), &options).unwrap(); + let block = compile(pc); + let probes = probe_displacements(PAGE).map(|delta| compile(pc.wrapping_add(delta))); + let entry = prove( + &block, + &source, + PAGE, + pc, + Digest::of(b"hosted"), + [&probes[0], &probes[1]], + ) + .expect("numeric immediate keeps no address dependency"); + assert!(entry.relocations.is_empty()); + assert_eq!(entry.source_map[..3], [(0x40, 0), (0x44, 1), (0x48, 11)]); + let page = 0x2_3456_8000; + let expected = compile(page + 0x40); + let rebased = entry.rebase(page, &source).unwrap(); + assert_eq!(rebased.native.x86_64_code, expected.native.x86_64_code); + assert_eq!(rebased.native.source_map, expected.native.source_map); +} + #[test] fn stored_source_witness_requires_the_exact_admitted_compiler_prefix() { // The compiler stops at B, but the complete offered analysis input is @@ -230,7 +311,7 @@ fn records_reject_malformed_source_geometry_with_a_valid_checksum() { let entry = proved(&source, 0x40).expect("actual relocatable four-word block"); assert_eq!(entry.source_map.len(), 4); assert!(entry.consistent()); - assert!(entry.source_map[1].1 > 1); + assert!(entry.source_map[2].1 > entry.source_map[1].1 + 1); let (translator, key) = (translator_id(), Digest::of(&[7; PAGE_BYTES])); let mut good = Record::new(translator, key); good.insert(entry.clone()); @@ -251,7 +332,7 @@ fn records_reject_malformed_source_geometry_with_a_valid_checksum() { entry.source_map[1].1 = entry.source_map[0].1 }), ("descending native", |entry| { - entry.source_map[2].1 = entry.source_map[1].1 - 1 + entry.source_map[3].1 = entry.source_map[2].1 - 1 }), ("one-past native", |entry| { entry.source_map[3].1 = u32::try_from(entry.code.len()).unwrap() @@ -303,6 +384,23 @@ fn records_reject_malformed_source_geometry_with_a_valid_checksum() { assert_eq!(Record::decode(&good.encode(), &translator, &key), Ok(good)); } +#[test] +fn checksummed_record_count_must_fit_the_remaining_bytes() { + let translator = translator_id(); + let key = Digest::of(b"bounded entry count"); + let mut record = Record::new(translator, key); + record.insert(proved(&words(&[0x9000_0020, 0x9400_0002]), 0x10).unwrap()); + let mut bytes = record.encode(); + bytes[12..16].copy_from_slice(&u32::MAX.to_le_bytes()); + let end = bytes.len() - TRAILER_BYTES; + let checksum = Sha256::digest(&bytes[..end]); + bytes[end..].copy_from_slice(&checksum); + assert_eq!( + Record::decode(&bytes, &translator, &key), + Err(FormatError::Truncated) + ); +} + #[test] fn records_refuse_any_damaged_framing_byte() { let source = words(&[0x9000_0020, 0x9400_0002]); @@ -379,3 +477,25 @@ fn unordered_legacy_records_find_the_first_entry_for_each_offset_and_context() { ); assert_eq!(decoded.find(low.offset + 4, &low.context), None); } + +#[test] +fn merge_keeps_current_entries_and_the_first_legacy_duplicate() { + let source = words(&[0xd65f_03c0]); + let first = proved(&source, 0x40).unwrap(); + let second = proved(&source, 0x80).unwrap(); + let third = proved(&source, 0xc0).unwrap(); + let mut duplicate = first.clone(); + duplicate.code.push(0); + let mut older_second = second.clone(); + older_second.code.push(0); + let translator = translator_id(); + let key = Digest::of(b"merge fixture"); + let mut record = Record::new(translator, key); + record.insert(second.clone()); + record.merge(Record { + translator, + key, + entries: vec![first.clone(), duplicate, older_second, third.clone()], + }); + assert_eq!(record.entries(), &[first, second, third]); +} diff --git a/crates/stela-engine/tests/blocks.rs b/crates/stela-engine/tests/blocks.rs index 1eadbe9393..594176f970 100644 --- a/crates/stela-engine/tests/blocks.rs +++ b/crates/stela-engine/tests/blocks.rs @@ -76,6 +76,81 @@ mod numerical { expected.v[d] = value; } + #[test] + fn packed_truncation_retires_from_native_status_with_input_flushing_disabled() -> Result<()> { + use stela_compiler::aarch64::floating::{ + FPCR_AH, FPCR_FIZ, FPCR_FZ, Format, + integer::{IntegerFormat, IntegerRounding, IntegerWidth, to_integer}, + }; + + let cache = tempfile::tempdir()?; + let mut runtime = BlockRuntime::new_for_target( + 76, + cache.path().into(), + BlockProfile::ORDINARY, + TargetCpu::Baseline, + ); + // FCVTZS V0.4S,V1.4S and FCVTZS V2.2S,V2.2S. + runtime.register_code( + GuestAddress(BASE), + words(&[ADD_ONE, 0x4ea1_b820, 0x0ea1_b842, ADD_ONE, RET]), + )?; + let pack = |low: u32, high: u32| u64::from(low) | (u64::from(high) << 32); + let integer = IntegerFormat { + width: IntegerWidth::Bits32, + signed: true, + }; + let small = [0, 0x8000_0000, 1, 0x807f_ffff]; + let normals = [0x3fe0_0000, 0xc020_0000, 0x4eff_ffff, 0xcf00_0000]; + for (fpcr, lanes, helpers) in [ + (0, small, 0), + (FPCR_AH, small, 0), + (FPCR_FZ, small, 1), + (FPCR_FIZ, small, 1), + (FPCR_AH | FPCR_FZ, small, 1), + (FPCR_FZ | FPCR_FIZ, normals, 0), + (0, normals, 0), + (0, [0x7f80_0001, 0x7fc0_1234, 0xc020_0000, 0xff80_0000], 1), + (0, [0x4f00_0000, 0xcf00_0001, 1, 0x8000_0000], 1), + ] { + let mut thread = input(false); + thread.registers.fpcr = fpcr; + thread.registers.v[1] = [pack(lanes[0], lanes[1]), pack(lanes[2], lanes[3])]; + let low_lane = if fpcr & (FPCR_FZ | FPCR_FIZ) == 0 { + 0x8000_0000 + } else { + 0x3f80_0000 + }; + thread.registers.v[2] = [pack(low_lane, 0x4080_0000), 0x7f80_0001_7f80_0001]; + let mut expected = thread.registers.clone(); + let converted = lanes.map(|lane| { + let result = to_integer( + Format::Single, + integer, + 0, + IntegerRounding::TowardZero, + fpcr, + u64::from(lane), + ) + .expect("supported FP controls"); + expected.fpsr |= result.exceptions; + result.bits as u32 + }); + expected.x[0] += 2; + expected.v[0] = [ + pack(converted[0], converted[1]), + pack(converted[2], converted[3]), + ]; + expected.v[2] = [pack(u32::from(low_lane == 0x3f80_0000), 4), 0]; + // SAFETY: the program only operates on its own registered code and state. + let report = unsafe { runtime.run(&mut thread, Some(GuestAddress(STOP)), 8)? }; + assert_eq!(report.reason, StopReason::StopAddress); + assert_eq!(report.floating_point_helpers, helpers); + assert_eq!(thread.registers, expected); + } + Ok(()) + } + #[test] fn interior_half_helper_resumes_after_prefix_and_reuses_disk_code() -> Result<()> { let cache = tempfile::tempdir()?; @@ -250,6 +325,95 @@ mod numerical { } Ok(()) } + + #[test] + fn finite_half_widening_stays_native_for_both_source_halves() -> Result<()> { + use stela_compiler::aarch64::floating::{FPCR_AH, FPCR_AHP, FPCR_FZ, FPCR_FZ16}; + + let cache = tempfile::tempdir()?; + let mut runtime = BlockRuntime::new_for_target( + 74, + cache.path().into(), + BlockProfile::ORDINARY, + TargetCpu::Baseline, + ); + // FCVTL V0.4S,V1.4H and FCVTL2 V2.4S,V1.8H. + runtime.register_code( + GuestAddress(BASE), + words(&[ADD_ONE, 0x0e21_7820, 0x4e21_7822, ADD_ONE, RET]), + )?; + let mut initial = input(false); + initial.registers.fpcr = FPCR_AH | FPCR_AHP | FPCR_FZ | FPCR_FZ16; + initial.registers.v[1] = [0x3c00_0001_8000_0000, 0x0000_c000_0400_8001]; + let mut expected = initial.registers.clone(); + expected.x[0] += 2; + expected.v[0] = [0x8000_0000_0000_0000, 0x3f80_0000_3380_0000]; + expected.v[2] = [0x3880_0000_b380_0000, 0x0000_0000_c000_0000]; + let mut thread = initial.clone(); + // SAFETY: the program only operates on its own registered code and state. + let report = unsafe { runtime.run(&mut thread, Some(GuestAddress(STOP)), 1)? }; + assert_eq!(report.reason, StopReason::StopAddress); + assert_eq!(report.floating_point_helpers, 0); + assert_eq!(thread.registers, expected); + + initial.registers.fpcr |= INVALID << EXCEPTION_ENABLE_SHIFT; + let mut prefix = initial.registers.clone(); + prefix.x[0] += 1; + // SAFETY: the program only operates on its own registered code and state. + let report = unsafe { runtime.run(&mut initial, Some(GuestAddress(STOP)), 8)? }; + assert_eq!( + report.reason, + StopReason::FloatingPointUnsupported { + instruction_pc: GuestAddress(BASE + 4), + fpcr: prefix.fpcr, + enabled_exceptions: INVALID, + }, + ); + assert_eq!(initial.pc, GuestAddress(BASE + 4)); + assert_eq!(initial.registers, prefix); + Ok(()) + } + + #[test] + fn vector_self_comparison_exits_only_for_exceptional_lanes() -> Result<()> { + let cache = tempfile::tempdir()?; + let mut runtime = BlockRuntime::new_for_target( + 75, + cache.path().into(), + BlockProfile::ORDINARY, + TargetCpu::Baseline, + ); + // FCMEQ V0.4S,V1.4S,V1.4S and FCMEQ V2.2S,V2.2S,V2.2S. + runtime.register_code( + GuestAddress(BASE), + words(&[ADD_ONE, 0x4e21_e420, 0x0e22_e442, ADD_ONE, RET]), + )?; + for exceptional in [false, true] { + let mut thread = input(false); + thread.registers.v[1] = if exceptional { + [0x8000_0000_7fc0_0001, 0x7f80_0000_7f80_0001] + } else { + [0x8000_0000_0000_0000, 0xff80_0000_7f80_0000] + }; + // The aliased 2S form clears the old signaling NaNs in the high half. + thread.registers.v[2] = [0x3f80_0000_8000_0000, 0x7f80_0001_7f80_0001]; + let mut expected = thread.registers.clone(); + expected.x[0] += 2; + expected.v[2] = [u64::MAX, 0]; + if exceptional { + expected.v[0] = [0xffff_ffff_0000_0000; 2]; + expected.fpsr |= INVALID; + } else { + expected.v[0] = [u64::MAX; 2]; + } + // SAFETY: the program only operates on its own registered code and state. + let report = unsafe { runtime.run(&mut thread, Some(GuestAddress(STOP)), 8)? }; + assert_eq!(report.reason, StopReason::StopAddress); + assert_eq!(report.floating_point_helpers, usize::from(exceptional)); + assert_eq!(thread.registers, expected); + } + Ok(()) + } } #[test] diff --git a/crates/stela-formats/src/apfs.rs b/crates/stela-formats/src/apfs.rs index cf4598dc54..47bcef42a8 100644 --- a/crates/stela-formats/src/apfs.rs +++ b/crates/stela-formats/src/apfs.rs @@ -236,6 +236,7 @@ pub struct Device { base: u64, block_size: u32, nodes: btree::NodeCache, + open_cache: volume::OpenCache, } impl Device { @@ -245,6 +246,7 @@ impl Device { base, block_size, nodes: btree::NodeCache::default(), + open_cache: volume::OpenCache::default(), } } @@ -255,6 +257,7 @@ impl Device { pub(crate) fn set_block_size(&mut self, block_size: u32) { self.block_size = block_size; self.nodes = btree::NodeCache::default(); + self.open_cache = volume::OpenCache::default(); } /// Read bytes at a byte offset inside the container. diff --git a/crates/stela-formats/src/apfs/volume.rs b/crates/stela-formats/src/apfs/volume.rs index d286d7e8d7..65296d5365 100644 --- a/crates/stela-formats/src/apfs/volume.rs +++ b/crates/stela-formats/src/apfs/volume.rs @@ -15,7 +15,7 @@ use super::{ u16_at, u32_at, u64_at, uuid_at, }; use crate::payload::ReadAt; -use alloc::{format, string::String, vec, vec::Vec}; +use alloc::{collections::VecDeque, format, string::String, vec, vec::Vec}; use core::cmp::Ordering; pub const APFS_VOL_ROLE_NONE: u16 = 0x0000; @@ -181,14 +181,45 @@ pub struct Volume { integrity_meta_oid: u64, } +/// Successfully opened volumes and trees for one stable container source. +#[derive(Default)] +pub(super) struct OpenCache { + volumes: VecDeque, + trees: VecDeque<(TreeKey, Tree)>, +} + +const OPEN_CACHE_SLOTS: usize = 8; + +fn remember(cache: &mut VecDeque, item: T) { + if cache.len() == OPEN_CACHE_SLOTS { + cache.pop_front(); + } + cache.push_back(item); +} + +/// Includes the volume's object-map view and distinguishes seal-checked roots. +#[derive(Clone, Copy, PartialEq, Eq)] +struct TreeKey { + omap_root: u64, + xid: u64, + type_field: u32, + oid: u64, + integrity_meta_oid: Option, + seal_root: bool, +} + fn key_id_and_type(key: &[u8]) -> Result<(u64, u8)> { let value = u64_at(key, 0)?; Ok((value & OBJ_ID_MASK, (value >> OBJ_TYPE_SHIFT) as u8)) } -fn c_string(bytes: &[u8]) -> Result { +fn c_str(bytes: &[u8]) -> Result<&str> { let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); - String::from_utf8(bytes[..end].to_vec()).map_err(|_| ApfsError::Malformed("name is not UTF-8")) + core::str::from_utf8(&bytes[..end]).map_err(|_| ApfsError::Malformed("name is not UTF-8")) +} + +fn c_string(bytes: &[u8]) -> Result { + c_str(bytes).map(String::from) } /// The extended fields of an inode or directory entry: `(type, data)`. @@ -218,9 +249,14 @@ fn extended_fields(blob: &[u8]) -> Result> { impl Volume { pub(crate) fn open(device: &mut Device, paddr: u64) -> Result { + if let Some(volume) = device.open_cache.volumes.iter().find(|v| v.paddr == paddr) { + return Ok(volume.clone()); + } let block = Self::superblock(device, paddr)?; let omap = Omap::open(device, u64_at(&block, 128)?)?; - Self::parse(&block, paddr, omap) + let volume = Self::parse(&block, paddr, omap)?; + remember(&mut device.open_cache.volumes, volume.clone()); + Ok(volume) } fn superblock(device: &mut Device, paddr: u64) -> Result> { @@ -309,6 +345,22 @@ impl Volume { oid: u64, seal_root: bool, ) -> Result { + let key = TreeKey { + omap_root: self.omap.tree.root, + xid: self.xid, + type_field, + oid, + integrity_meta_oid: self.sealed.then_some(self.integrity_meta_oid), + seal_root, + }; + if let Some((_, tree)) = device + .open_cache + .trees + .iter() + .find(|(cached, _)| *cached == key) + { + return Ok(tree.clone()); + } let (root, headerless) = match Storage::of(type_field) { Storage::Physical => { // A physical root shows by its zero header whether it has one. @@ -328,6 +380,7 @@ impl Volume { if Storage::of(type_field) == Storage::Virtual { tree.relative_to(oid); } + remember(&mut device.open_cache.trees, (key, tree.clone())); Ok(tree) } @@ -391,10 +444,13 @@ impl Volume { }) } - /// The entries of directory `oid`. - pub fn entries(&self, device: &mut Device, oid: u64) -> Result> { + fn visit_entries( + &self, + device: &mut Device, + oid: u64, + mut visit: impl FnMut(&str, u64, FileKind), + ) -> Result<()> { let hashed = self.hashed_names(); - let mut entries = Vec::new(); self.records(device, oid, APFS_TYPE_DIR_REC, &mut |key, value| { let name = if hashed { let length = (u32_at(key, 8)? & J_DREC_LEN_MASK) as usize; @@ -404,12 +460,24 @@ impl Volume { key.get(10..10 + length) } .ok_or(ApfsError::Malformed("directory entry name"))?; - entries.push(Entry { - name: c_string(name)?, - oid: u64_at(value, 0)?, - kind: FileKind::from_drec(u16_at(value, 16)?), - }); + visit( + c_str(name)?, + u64_at(value, 0)?, + FileKind::from_drec(u16_at(value, 16)?), + ); Ok(Visit::Continue) + }) + } + + /// The entries of directory `oid`. + pub fn entries(&self, device: &mut Device, oid: u64) -> Result> { + let mut entries = Vec::new(); + self.visit_entries(device, oid, |name, oid, kind| { + entries.push(Entry { + name: String::from(name), + oid, + kind, + }); })?; Ok(entries) } @@ -429,10 +497,17 @@ impl Volume { parent: u64, name: &str, ) -> Result { - self.entries(device, parent)? - .into_iter() - .find(|entry| self.names_match(&entry.name, name)) - .ok_or_else(|| ApfsError::NotFound(String::from(name))) + let mut found = None; + self.visit_entries(device, parent, |stored, oid, kind| { + if found.is_none() && self.names_match(stored, name) { + found = Some(Entry { + name: String::from(stored), + oid, + kind, + }); + } + })?; + found.ok_or_else(|| ApfsError::NotFound(String::from(name))) } /// The inode at `path` from the volume root. Symbolic links in @@ -530,7 +605,7 @@ impl Volume { let size = u64_at(&data, 8)?; let mut bytes = vec![0; usize::try_from(size).map_err(|_| ApfsError::Malformed("xattr size"))?]; - self.read_stream(device, stream, size, 0, &mut bytes)?; + self.read_stream(device, stream, size, 0, &mut bytes, true)?; Ok(Some(bytes)) } Some(_) => Err(ApfsError::Malformed( @@ -597,13 +672,17 @@ impl Volume { size: u64, offset: u64, buffer: &mut [u8], + zeroed: bool, ) -> Result<()> { let end = offset .checked_add(buffer.len() as u64) .filter(|&end| end <= size) .ok_or(ApfsError::Malformed("read past the end of the stream"))?; - // Holes and the space past the last extent read as zeros. - buffer.fill(0); + // Holes and the space past the last extent read as zeros. Whole + // files and attributes already have a freshly zeroed buffer. + if !zeroed { + buffer.fill(0); + } let block_size = u64::from(device.block_size()); for extent in self.extents(device, private_id)? { let start = extent.offset.max(offset); @@ -625,6 +704,17 @@ impl Volume { inode: &Inode, offset: u64, buffer: &mut [u8], + ) -> Result<()> { + self.read_regular_at(device, inode, offset, buffer, false) + } + + fn read_regular_at( + &self, + device: &mut Device, + inode: &Inode, + offset: u64, + buffer: &mut [u8], + zeroed: bool, ) -> Result<()> { if inode.kind != FileKind::Regular { return Err(ApfsError::NotFound(format!( @@ -635,7 +725,19 @@ impl Volume { if inode.bsd_flags & UF_COMPRESSED != 0 { return Err(ApfsError::Unsupported("transparently compressed files")); } - self.read_stream(device, inode.private_id, inode.size, offset, buffer) + self.read_stream(device, inode.private_id, inode.size, offset, buffer, zeroed) + } + + /// Read a whole regular file without accepting transparent compression. + pub(crate) fn read_regular( + &self, + device: &mut Device, + inode: &Inode, + ) -> Result> { + let mut bytes = + vec![0; usize::try_from(inode.size).map_err(|_| ApfsError::Malformed("file size"))?]; + self.read_regular_at(device, inode, 0, &mut bytes, true)?; + Ok(bytes) } /// A whole regular file; a transparently compressed one is inflated @@ -654,10 +756,7 @@ impl Volume { }; return super::decmpfs::decode(&header, fork.as_deref()); } - let mut bytes = - vec![0; usize::try_from(inode.size).map_err(|_| ApfsError::Malformed("file size"))?]; - self.read_at(device, inode, 0, &mut bytes)?; - Ok(bytes) + self.read_regular(device, inode) } /// The volume's snapshots, oldest first. @@ -733,6 +832,41 @@ mod tests { const GROUP: &str = "A304C51B-D22F-4CDD-829D-3E30CB5BD87B"; + #[test] + fn caller_buffer_has_zeroed_unread_bytes_after_source_failure() -> Result<()> { + struct PartialRead(crate::apfs::tests::Memory); + + impl ReadAt for PartialRead { + type Error = &'static str; + + fn len(&self) -> u64 { + self.0.len() + } + + fn read_at( + &mut self, + offset: u64, + out: &mut [u8], + ) -> core::result::Result<(), Self::Error> { + if out.len() == 16 { + out[..3].fill(0xa5); + return Err("injected partial source failure"); + } + self.0.read_at(offset, out) + } + } + + let mut container = Container::open(PartialRead(fixture()), 0)?; + let volume = container.volume_with_role(APFS_VOL_ROLE_PREBOOT)?; + let device = &mut container.device; + let inode = volume.lookup(device, "pattern.bin", true)?; + let mut out = [0xff; 16]; + assert!(volume.read_at(device, &inode, 123_456, &mut out).is_err()); + assert_eq!(&out[..3], &[0xa5; 3]); + assert_eq!(&out[3..], &[0; 13]); + Ok(()) + } + fn pattern(length: usize) -> Vec { (0..length) .map(|i| ((i * 7 + i / 251) & 0xff) as u8) @@ -776,6 +910,9 @@ mod tests { assert_eq!(data.len(), 200_004); assert!(data[..200_000].iter().all(|&b| b == 0)); assert_eq!(&data[200_000..], b"tail"); + let mut last = [0xff; 8]; + volume.read_at(device, &sparse, 199_996, &mut last)?; + assert_eq!(&last, b"\0\0\0\0tail"); let empty = volume.lookup(device, "empty", true)?; assert_eq!( volume @@ -824,6 +961,26 @@ mod tests { Ok(()) } + #[test] + fn cached_tree_keeps_the_transaction_and_seal_identity() -> Result<()> { + let mut container = Container::open(sealed_fixture(), 0)?; + let mut volume = container.volumes()?.remove(0); + let device = &mut container.device; + assert_eq!( + volume.inode(device, ROOT_DIR_INO_NUM)?.kind, + FileKind::Directory + ); + + let xid = volume.xid; + volume.xid = 0; + assert!(volume.inode(device, ROOT_DIR_INO_NUM).is_err()); + volume.xid = xid; + + volume.integrity_meta_oid = u64::MAX; + assert!(volume.inode(device, ROOT_DIR_INO_NUM).is_err()); + Ok(()) + } + #[test] fn the_root_seal_is_the_hash_apples_sealer_recorded() -> Result<()> { // The 208-byte record: version 2, 0, hash type, hash length, hash. diff --git a/crates/stela-formats/src/boot_bundle.rs b/crates/stela-formats/src/boot_bundle.rs index 93265dffec..e0e75c1978 100644 --- a/crates/stela-formats/src/boot_bundle.rs +++ b/crates/stela-formats/src/boot_bundle.rs @@ -489,10 +489,20 @@ impl<'a> Verified<'a> { if region.guest_pa < machine.dram_base || end > ram_end { return Err(fail("lies outside backed guest DRAM")); } - let tail = vec![0u8; (region.memory_bytes - region.bytes) as usize]; - if !write(region.guest_pa, bytes) || !write(region.guest_pa + region.bytes, &tail) { + if !write(region.guest_pa, bytes) { return Err(fail("guest RAM write failed")); } + // Reserved and zero-fill regions can be much larger than + // their file bytes. Stream the zeros without allocating a tail. + static ZEROES: [u8; 16 * 1024] = [0; 16 * 1024]; + let mut tail = region.guest_pa + region.bytes; + while tail < end { + let chunk = (end - tail).min(ZEROES.len() as u64) as usize; + if !write(tail, &ZEROES[..chunk]) { + return Err(fail("guest RAM write failed")); + } + tail += chunk as u64; + } regions.push(LoadedRegion { name: region.name.clone(), guest_pa: region.guest_pa, diff --git a/crates/stela-formats/src/boot_bundle/tests.rs b/crates/stela-formats/src/boot_bundle/tests.rs index ac8e3a2537..8674379969 100644 --- a/crates/stela-formats/src/boot_bundle/tests.rs +++ b/crates/stela-formats/src/boot_bundle/tests.rs @@ -244,7 +244,10 @@ fn verifies_loads_and_patches_into_guest_ram() -> Result<(), BundleError> { let kernel = [0xaa; 100]; let tree = [0x11; 20]; let json = manifest_json(&kernel, &tree); - let manifest = Manifest::parse(json.as_bytes())?; + let mut manifest = Manifest::parse(json.as_bytes())?; + // Leave more than two zero chunks after the prepared tree bytes. + manifest.regions[1].memory_bytes = 0x9000; + manifest.top_of_kernel_data = BASE + 0xd000; let files: BTreeMap<&str, &[u8]> = BTreeMap::from([("kernel.img", &kernel[..]), ("devicetree.adt", &tree[..])]); let verified = manifest.verify(&|name| files.get(name).copied())?; @@ -264,6 +267,8 @@ fn verifies_loads_and_patches_into_guest_ram() -> Result<(), BundleError> { assert_eq!(&ram[dt..dt + 8], &FRAME_BYTES.to_le_bytes()); assert_eq!(&ram[dt + 8..dt + 12], &[0x42; 4]); assert_eq!(&ram[dt + 12..dt + 20], &[0x11; 8]); + assert!(ram[dt + 20..0xd000].iter().all(|&b| b == 0)); + assert_eq!(ram[0xd000], 0xff); // With a framebuffer and verbose boot-args, v_display is 0. let screen = Machine { diff --git a/crates/stela-formats/src/lzfse.rs b/crates/stela-formats/src/lzfse.rs index ee3b8e40ec..c4d10f4e37 100644 --- a/crates/stela-formats/src/lzfse.rs +++ b/crates/stela-formats/src/lzfse.rs @@ -181,6 +181,77 @@ impl Output { } } +/// The byte ranges advertised by a block, before entropy validation. +struct Frame { + raw_bytes: u32, + payload: usize, + lmd: usize, + end: usize, +} + +impl Frame { + fn read(src: &[u8], at: usize, magic: u32) -> Result { + let block = &src[at..]; + let (header, literal, lmd_bytes) = match magic { + UNCOMPRESSED => (8, None, 0), + COMPRESSED_LZVN => (12, Some(u32_at(block, 8)?), 0), + COMPRESSED_V1 => ( + V1_HEADER_BYTES, + Some(u32_at(block, 20)?), + u32_at(block, 24)?, + ), + COMPRESSED_V2 => { + let header = field(u64_at(block, 24)?, 0, 32) as usize; + if header < V2_FREQ_OFFSET { + return Err(LzfseError::Malformed("bvx2 header size")); + } + ( + header, + Some(field(u64_at(block, 8)?, 20, 20)), + field(u64_at(block, 16)?, 40, 20), + ) + } + _ => return Err(LzfseError::Malformed("unknown block magic")), + }; + let raw_bytes = u32_at(block, 4)?; + let payload = at.checked_add(header).ok_or(LzfseError::Truncated)?; + let lmd = payload + .checked_add(literal.unwrap_or(raw_bytes) as usize) + .ok_or(LzfseError::Truncated)?; + let end = lmd + .checked_add(lmd_bytes as usize) + .filter(|&end| end <= src.len()) + .ok_or(LzfseError::Truncated)?; + Ok(Self { + raw_bytes, + payload, + lmd, + end, + }) + } +} + +/// Size a multi-block output without inspecting its frequency tables or +/// decoding any data. A failed hint leaves validation to the decoder. +fn framed_output_size(src: &[u8], limit: usize) -> Option { + let mut at = 0; + let mut multiple = false; + let mut total = 0usize; + loop { + let magic = u32_at(src, at).ok()?; + if magic == END_OF_STREAM { + return (at + 4 == src.len() && multiple).then_some(total); + } + let frame = Frame::read(src, at, magic).ok()?; + total = total.checked_add(frame.raw_bytes as usize)?; + if total > limit { + return None; + } + multiple |= at != 0; + at = frame.end; + } +} + /// Decode a whole LZFSE stream, producing at most `limit` bytes. pub fn decode(src: &[u8], limit: usize) -> Result> { let mut out = Output { @@ -188,73 +259,53 @@ pub fn decode(src: &[u8], limit: usize) -> Result> { limit, block_end: 0, }; + // A heap without in-place growth copies all preceding output on each + // resize. Reserve once when all block ranges fit the stream and limit. + if let Some(bytes) = framed_output_size(src, limit) { + let _ = out.bytes.try_reserve_exact(bytes); + } let mut at = 0; loop { let magic = u32_at(src, at)?; - match magic { - END_OF_STREAM => { - if at + 4 != src.len() { - return Err(LzfseError::Malformed("bytes follow the end of stream")); - } - return Ok(out.bytes); + if magic == END_OF_STREAM { + if at + 4 != src.len() { + return Err(LzfseError::Malformed("bytes follow the end of stream")); } + return Ok(out.bytes); + } + let frame = Frame::read(src, at, magic)?; + match magic { UNCOMPRESSED => { - let raw = u32_at(src, at + 4)?; - out.begin_block(raw)?; - let start = at + 8; - let bytes = src - .get(start..start + raw as usize) - .ok_or(LzfseError::Truncated)?; - out.literals(bytes)?; - at = start + raw as usize; + out.begin_block(frame.raw_bytes)?; + out.literals(&src[frame.payload..frame.end])?; } COMPRESSED_LZVN => { - let raw = u32_at(src, at + 4)?; - let payload = u32_at(src, at + 8)? as usize; - let start = at + 12; - let bytes = src - .get(start..start + payload) - .ok_or(LzfseError::Truncated)?; - out.begin_block(raw)?; - lzvn(bytes, &mut out, true)?; - at = start + payload; + out.begin_block(frame.raw_bytes)?; + lzvn(&src[frame.payload..frame.end], &mut out, true)?; } COMPRESSED_V1 | COMPRESSED_V2 => { - let (header, header_bytes) = if magic == COMPRESSED_V1 { - ( - Header::v1(src.get(at..).ok_or(LzfseError::Truncated)?)?, - V1_HEADER_BYTES, - ) + let encoded = &src[at..frame.payload]; + let header = if magic == COMPRESSED_V1 { + Header::v1(encoded)? } else { - Header::v2(src.get(at..).ok_or(LzfseError::Truncated)?)? + Header::v2(encoded)? }; header.check()?; - let payload_end = at - .checked_add(header_bytes) - .and_then(|n| n.checked_add(header.n_literal_payload_bytes as usize)) - .and_then(|n| n.checked_add(header.n_lmd_payload_bytes as usize)) - .ok_or(LzfseError::Truncated)?; - if payload_end > src.len() { - return Err(LzfseError::Truncated); - } - out.begin_block(header.n_raw_bytes)?; - block(src, at + header_bytes, &header, &mut out)?; - at = payload_end; + out.begin_block(frame.raw_bytes)?; + block(src, &frame, &header, &mut out)?; } - _ => return Err(LzfseError::Malformed("unknown block magic")), + _ => unreachable!("validated by Frame::read"), } out.end_block()?; + at = frame.end; } } /// `lzfse_compressed_block_header_v1`, the form both LZFSE block kinds /// decode to. struct Header { - n_raw_bytes: u32, n_literals: u32, n_matches: u32, - n_literal_payload_bytes: u32, - n_lmd_payload_bytes: u32, literal_bits: i32, literal_state: [u16; 4], lmd_bits: i32, @@ -296,11 +347,8 @@ impl Header { return Err(LzfseError::Truncated); } let mut header = Self { - n_raw_bytes: u32_at(block, 4)?, n_literals: u32_at(block, 12)?, n_matches: u32_at(block, 16)?, - n_literal_payload_bytes: u32_at(block, 20)?, - n_lmd_payload_bytes: u32_at(block, 24)?, literal_bits: u32_at(block, 28)? as i32, literal_state: [ u16_at(block, 32)?, @@ -331,22 +379,14 @@ impl Header { Ok(header) } - /// The header of a `bvx2` block and its size. - fn v2(block: &[u8]) -> Result<(Self, usize)> { + /// The header of a `bvx2` block, bounded by its validated frame. + fn v2(block: &[u8]) -> Result { let v0 = u64_at(block, 8)?; let v1 = u64_at(block, 16)?; let v2 = u64_at(block, 24)?; - let header_bytes = field(v2, 0, 32) as usize; - if header_bytes < V2_FREQ_OFFSET { - return Err(LzfseError::Malformed("bvx2 header size")); - } - let tables = block - .get(V2_FREQ_OFFSET..header_bytes) - .ok_or(LzfseError::Truncated)?; + let tables = &block[V2_FREQ_OFFSET..]; let mut header = Self { - n_raw_bytes: u32_at(block, 4)?, n_literals: field(v0, 0, 20), - n_literal_payload_bytes: field(v0, 20, 20), n_matches: field(v0, 40, 20), literal_bits: field(v0, 60, 3) as i32 - 7, literal_state: [ @@ -355,7 +395,6 @@ impl Header { field(v1, 20, 10) as u16, field(v1, 30, 10) as u16, ], - n_lmd_payload_bytes: field(v1, 40, 20), lmd_bits: field(v1, 60, 3) as i32 - 7, l_state: field(v2, 32, 10) as u16, m_state: field(v2, 42, 10) as u16, @@ -394,7 +433,7 @@ impl Header { return Err(LzfseError::Malformed("bvx2 frequency tables")); } } - Ok((header, header_bytes)) + Ok(header) } /// `lzfse_check_block_header_v1`. @@ -487,15 +526,14 @@ impl<'a> BitStream<'a> { Ok(()) } - /// `fse_in_pull64`. - fn pull(&mut self, bits: u32) -> Result { - if bits > self.accum_bits { - return Err(LzfseError::Malformed("FSE stream underflow")); - } + /// `fse_in_pull64`. Each decode group starts with at least 56 bits + /// after refilling. A group of four literals consumes at most 40 bits, + /// and an L, M, D triple at most (6 + 8) + (6 + 11) + (8 + 15) bits. + /// Only the low `accum_bits` bits are live between pulls and refills. + fn pull(&mut self, bits: u32) -> u64 { + debug_assert!(bits <= self.accum_bits); self.accum_bits -= bits; - let value = self.accum >> self.accum_bits; - self.accum &= (1u64 << self.accum_bits) - 1; - Ok(value) + (self.accum >> self.accum_bits) & ((1u64 << bits) - 1) } } @@ -546,9 +584,9 @@ fn literal_table(freq: &[u16; LITERAL_SYMBOLS]) -> Vec { /// `fse_value_decoder_entry`: one L, M or D decoder state. #[derive(Clone, Copy, Default)] struct ValueEntry { - total_bits: u32, - value_bits: u32, - delta: i32, + total_bits: u8, + value_bits: u8, + delta: i16, base: i32, } @@ -561,20 +599,20 @@ fn value_table(states: usize, freq: &[u16], extra_bits: &[u8], base: &[i32]) -> continue; } let (k, j0) = spread(states, f); - let value_bits = u32::from(extra_bits[symbol]); + let value_bits = extra_bits[symbol]; for j in 0..f { table.push(if j < j0 { ValueEntry { - total_bits: k + value_bits, + total_bits: k as u8 + value_bits, value_bits, - delta: (((f + j) << k) as i32) - states as i32, + delta: (((f + j) << k) as i16) - states as i16, base: base[symbol], } } else { ValueEntry { - total_bits: k - 1 + value_bits, + total_bits: (k - 1) as u8 + value_bits, value_bits, - delta: ((j - j0) << (k - 1)) as i32, + delta: ((j - j0) << (k - 1)) as i16, base: base[symbol], } }); @@ -584,7 +622,7 @@ fn value_table(states: usize, freq: &[u16], extra_bits: &[u8], base: &[i32]) -> table } -fn next_state(delta: i32, bits: u64) -> u16 { +fn next_state(delta: i16, bits: u64) -> u16 { (delta as u16).wrapping_add(bits as u16) } @@ -593,7 +631,7 @@ fn decode_literal(state: &mut u16, table: &[LiteralEntry], input: &mut BitStream let entry = table .get(usize::from(*state)) .ok_or(LzfseError::Malformed("FSE state"))?; - *state = next_state(i32::from(entry.delta), input.pull(u32::from(entry.bits))?); + *state = next_state(entry.delta, input.pull(u32::from(entry.bits))); Ok(entry.symbol) } @@ -602,14 +640,14 @@ fn decode_value(state: &mut u16, table: &[ValueEntry], input: &mut BitStream) -> let entry = table .get(usize::from(*state)) .ok_or(LzfseError::Malformed("FSE state"))?; - let bits = input.pull(entry.total_bits)?; + let bits = input.pull(u32::from(entry.total_bits)); *state = next_state(entry.delta, bits >> entry.value_bits); Ok(entry.base + (bits & ((1u64 << entry.value_bits) - 1)) as i32) } -/// Decode the literals and then the L, M, D triples of one LZFSE block whose -/// payload starts at `payload` (`lzfse_decode` and `lzfse_decode_lmd`). -fn block(src: &[u8], payload: usize, header: &Header, out: &mut Output) -> Result<()> { +/// Decode the literals and then the L, M, D triples of one LZFSE block +/// (`lzfse_decode` and `lzfse_decode_lmd`). +fn block(src: &[u8], frame: &Frame, header: &Header, out: &mut Output) -> Result<()> { let literal_table = literal_table(&header.literal_freq); let l_table = value_table(L_STATES, &header.l_freq, &L_EXTRA_BITS, &L_BASE_VALUE); let m_table = value_table(M_STATES, &header.m_freq, &M_EXTRA_BITS, &M_BASE_VALUE); @@ -617,19 +655,21 @@ fn block(src: &[u8], payload: usize, header: &Header, out: &mut Output) -> Resul // The literal stream may refill from any earlier byte of the input, as // the reference allows; a valid stream never consumes those bits. - let lmd_start = payload + header.n_literal_payload_bytes as usize; - let mut input = BitStream::new(src, 0, lmd_start, header.literal_bits)?; + let mut input = BitStream::new(src, 0, frame.lmd, header.literal_bits)?; let mut literals = Vec::with_capacity((header.n_literals as usize).next_multiple_of(4)); let mut states = header.literal_state; for _ in (0..header.n_literals).step_by(4) { input.refill()?; - for state in &mut states { - literals.push(decode_literal(state, &literal_table, &mut input)?); - } + let [a, b, c, d] = &mut states; + literals.extend_from_slice(&[ + decode_literal(a, &literal_table, &mut input)?, + decode_literal(b, &literal_table, &mut input)?, + decode_literal(c, &literal_table, &mut input)?, + decode_literal(d, &literal_table, &mut input)?, + ]); } - let lmd_end = lmd_start + header.n_lmd_payload_bytes as usize; - let mut input = BitStream::new(src, lmd_start, lmd_end, header.lmd_bits)?; + let mut input = BitStream::new(src, frame.lmd, frame.end, header.lmd_bits)?; let (mut l_state, mut m_state, mut d_state) = (header.l_state, header.m_state, header.d_state); let mut literal = 0usize; let mut distance: Option = None; @@ -860,6 +900,19 @@ mod tests { assert!(is_lzfse(b"bvx2....") && !is_lzfse(b"bvx$") && !is_lzfse(b"bv")); } + #[test] + fn sizes_only_a_complete_multiblock_stream_within_the_limit() { + let mut encoded = stored(b"first"); + assert_eq!(framed_output_size(&encoded, 12), None); + encoded.truncate(encoded.len() - 4); + encoded.extend_from_slice(&stored(b"second")); + assert_eq!(framed_output_size(&encoded, 11), Some(11)); + assert_eq!(decode(&encoded, 11).unwrap(), b"firstsecond"); + assert_eq!(framed_output_size(&encoded, 10), None); + assert_eq!(decode(&encoded, 10), Err(LzfseError::Limit)); + assert_eq!(framed_output_size(&encoded[..encoded.len() - 1], 11), None); + } + #[test] fn decodes_each_lzvn_opcode_kind() { let payload = [ diff --git a/crates/stela-formats/src/payload/pieces.rs b/crates/stela-formats/src/payload/pieces.rs index 1ac56e089d..9fa4024d7b 100644 --- a/crates/stela-formats/src/payload/pieces.rs +++ b/crates/stela-formats/src/payload/pieces.rs @@ -11,7 +11,7 @@ //! before the restore starts. A block that differs is refused with its //! piece's name. use super::{Layout, PayloadError, PayloadManifest, ReadAt, piece_name}; -use alloc::{format, vec, vec::Vec}; +use alloc::{format, vec::Vec}; use stela_crypto::Sha256; use stela_crypto::digest::Digest; @@ -33,14 +33,24 @@ struct Part { first_block: usize, } +/// Bound the scratch buffer to the native install reader's request size. +const MAX_BATCH_BYTES: u64 = 1 << 20; + +struct CachedBlock { + piece: usize, + block: u64, + /// Only this suffix of the scratch buffer stays cached. + start: usize, + scratch: Vec, +} + pub struct Joined { device: R, parts: Vec, total: u64, block_bytes: u64, hashes: Vec<[u8; 32]>, - /// The last block read and verified: its piece, block and bytes. - cached: Option<(usize, u64, Vec)>, + cached: Option, } impl Joined { @@ -153,34 +163,64 @@ impl Joined { Ok(()) } - /// Block `block` of piece `index`, read whole and verified. - fn block(&mut self, index: usize, block: u64) -> Result<&[u8], PayloadError> { - if self - .cached - .as_ref() - .is_none_or(|(piece, cached, _)| (*piece, *cached) != (index, block)) + /// Copy a bounded run of requested blocks, verifying each one before + /// copying its bytes. Keep only the last block cached for later reads. + fn copy_blocks( + &mut self, + index: usize, + block: u64, + mut skip: usize, + output: &mut [u8], + ) -> Result { + if let Some(cached) = &self.cached + && (cached.piece, cached.block) == (index, block) { - let part = &self.parts[index]; - let start = block * self.block_bytes; - let bytes = (part.bytes - start).min(self.block_bytes) as usize; - let hash = self.hashes[part.first_block + block as usize]; - let mut data = match self.cached.take() { - Some((_, _, mut data)) => { - data.resize(bytes, 0); - data - } - None => vec![0; bytes], - }; - self.read_part(index, start, &mut data)?; - if <[u8; 32]>::from(Sha256::digest(&data)) != hash { + let data = &cached.scratch[cached.start..]; + let count = (data.len() - skip).min(output.len()); + output[..count].copy_from_slice(&data[skip..skip + count]); + return Ok(count); + } + let part = &self.parts[index]; + let start = block * self.block_bytes; + let requested = (part.bytes - start).min((skip + output.len()) as u64); + let blocks = requested + .div_ceil(self.block_bytes) + .min((MAX_BATCH_BYTES / self.block_bytes).max(1)); + // Two 64 KiB blocks can exceed a high-speed BOT command's 120 KiB + // bound and add a data descriptor without saving a command. + let blocks = if blocks < 3 { 1 } else { blocks }; + let bytes = (part.bytes - start).min(blocks * self.block_bytes) as usize; + let first_hash = part.first_block + block as usize; + let mut data = self + .cached + .take() + .map_or_else(Vec::new, |cached| cached.scratch); + if bytes > data.capacity() { + data.reserve_exact(bytes - data.len()); + } + data.resize(bytes, 0); + self.read_part(index, start, &mut data)?; + + let mut done = 0; + for (relative, bytes) in data.chunks(self.block_bytes as usize).enumerate() { + if <[u8; 32]>::from(Sha256::digest(bytes)) != self.hashes[first_hash + relative] { return Err(PayloadError::Verification { - member: format!("{} block {block}", piece_name(index)), + member: format!("{} block {}", piece_name(index), block + relative as u64), reason: "its bytes differ from the piece's block hash", }); } - self.cached = Some((index, block, data)); + let count = (bytes.len() - skip).min(output.len() - done); + output[done..done + count].copy_from_slice(&bytes[skip..skip + count]); + done += count; + skip = 0; } - Ok(&self.cached.as_ref().expect("cached above").2) + self.cached = Some(CachedBlock { + piece: index, + block: block + blocks - 1, + start: ((blocks - 1) * self.block_bytes) as usize, + scratch: data, + }); + Ok(done) } } @@ -206,9 +246,7 @@ impl ReadAt for Joined { let within = offset - self.parts[index].start; let block = within / self.block_bytes; let skip = (within - block * self.block_bytes) as usize; - let data = self.block(index, block)?; - let count = (data.len() - skip).min(buffer.len()); - buffer[..count].copy_from_slice(&data[skip..skip + count]); + let count = self.copy_blocks(index, block, skip, buffer)?; buffer = &mut buffer[count..]; offset += count as u64; } @@ -222,6 +260,7 @@ mod tests { use crate::payload::{ BlockHashes, PIECE_HASHES_FILE, Piece, piece_sizes, test_support::Memory, }; + use alloc::vec; const BLOCK: u64 = 512; @@ -308,6 +347,63 @@ mod tests { joined.read_at(ipsw.len() as u64, &mut []).unwrap(); } + #[test] + fn reads_one_run_per_extent_and_caches_only_the_last_block() { + struct Traced { + device: Memory, + reads: Vec<(u64, usize)>, + } + impl ReadAt for Traced { + type Error = ::Error; + + fn len(&self) -> u64 { + self.device.len() + } + + fn read_at(&mut self, offset: u64, buffer: &mut [u8]) -> Result<(), Self::Error> { + self.reads.push((offset, buffer.len())); + self.device.read_at(offset, buffer) + } + } + + let ipsw = ipsw(); + let (device, manifest, extents, hashes) = medium(&ipsw, 3072); + let first = extents[0].clone(); + let traced = Traced { + device, + reads: Vec::new(), + }; + let mut joined = Joined::new(traced, &manifest, extents, &hashes).unwrap(); + let mut data = [0; 3000]; + joined.read_at(17, &mut data).unwrap(); + assert_eq!(data, ipsw[17..3017]); + let expected: Vec<_> = first.iter().map(|e| (e.offset, e.bytes as usize)).collect(); + assert_eq!(joined.device.reads, expected); + joined.read_at(3017, &mut data[..55]).unwrap(); + assert_eq!(data[..55], ipsw[3017..3072]); + assert_eq!(joined.device.reads, expected); + joined.device.device.0[first[0].offset as usize] ^= 1; + assert!(joined.read_at(0, &mut data[..10]).is_err()); + } + + #[test] + fn a_corrupt_block_never_reaches_the_output_of_a_batched_read() { + let ipsw = ipsw(); + let (mut device, manifest, extents, hashes) = medium(&ipsw, 3072); + let corrupt = 2 * BLOCK; + device.0[(extents[0][0].offset + corrupt) as usize] ^= 1; + let mut joined = Joined::new(device, &manifest, extents, &hashes).unwrap(); + let mut data = [0xee; 3072]; + let error = joined.read_at(0, &mut data).unwrap_err(); + assert_eq!( + error.to_string(), + "ipsw.000 block 2: its bytes differ from the piece's block hash" + ); + let (before, after) = data.split_at(corrupt as usize); + assert_eq!(before, &ipsw[..before.len()]); + assert!(after.iter().all(|byte| *byte == 0xee)); + } + #[test] fn an_altered_short_or_misplaced_piece_is_refused_by_name() { let ipsw = ipsw(); diff --git a/crates/stela-formats/src/preboot.rs b/crates/stela-formats/src/preboot.rs index 30de47238f..6efe8994b4 100644 --- a/crates/stela-formats/src/preboot.rs +++ b/crates/stela-formats/src/preboot.rs @@ -481,10 +481,7 @@ pub fn read( object: &Object, ) -> Result> { let inode = preboot.inode(&mut container.device, object.oid)?; - let mut bytes = - vec![0u8; usize::try_from(inode.size).map_err(|_| ApfsError::Malformed("object size"))?]; - preboot.read_at(&mut container.device, &inode, 0, &mut bytes)?; - Ok(bytes) + Ok(preboot.read_regular(&mut container.device, &inode)?) } #[cfg(test)] diff --git a/crates/stela-linux/src/compat/kernel/file.c b/crates/stela-linux/src/compat/kernel/file.c index 5599796ad4..2bdafc3525 100644 --- a/crates/stela-linux/src/compat/kernel/file.c +++ b/crates/stela-linux/src/compat/kernel/file.c @@ -366,6 +366,13 @@ static void test_d_release(struct dentry *dentry) static const struct dentry_operations dentry_ops = {.d_release = test_d_release}; +struct pin_interleave { + struct vfsmount *mount; + struct vfsmount *winner; + int count; +}; +static struct pin_interleave *interleave; + static int test_init_fs_context(struct fs_context *context) { struct pseudo_fs_context *pseudo = init_pseudo(context, 0x7e57); @@ -373,6 +380,14 @@ static int test_init_fs_context(struct fs_context *context) if (!pseudo) return -ENOMEM; pseudo->dops = &dentry_ops; + /* Model a second pin publishing while the first is creating a mount. */ + if (interleave) { + struct pin_interleave *overlap = interleave; + + interleave = NULL; + assert(!simple_pin_fs(context->fs_type, &overlap->mount, &overlap->count)); + overlap->winner = overlap->mount; + } return 0; } @@ -555,6 +570,15 @@ int main(void) assert(!IS_ERR(object) && file_inode(object)->i_size == 8192); fput(object); + struct pin_interleave overlap = {}; + interleave = &overlap; + assert(!simple_pin_fs(&test_fs, &overlap.mount, &overlap.count)); + assert(!interleave && overlap.mount == overlap.winner && overlap.count == 2); + simple_release_fs(&overlap.mount, &overlap.count); + assert(overlap.mount == overlap.winner && overlap.count == 1); + simple_release_fs(&overlap.mount, &overlap.count); + assert(!overlap.mount && !overlap.count); + struct vfsmount *mount = NULL; int count = 0; assert(!simple_pin_fs(&test_fs, &mount, &count) && mount && count == 1); diff --git a/crates/stela-loader/src/boot_bundle.rs b/crates/stela-loader/src/boot_bundle.rs index 79bce73a5a..8ac376df35 100644 --- a/crates/stela-loader/src/boot_bundle.rs +++ b/crates/stela-loader/src/boot_bundle.rs @@ -97,9 +97,25 @@ pub struct Input<'a> { pub source: Source, } +/// The original kernel collection and its source, optionally owned so +/// an installed boot can move the decoded buffer into the bundle. +pub struct KernelInput<'a> { + pub bytes: Cow<'a, [u8]>, + pub source: Source, +} + +impl<'a> From> for KernelInput<'a> { + fn from(input: Input<'a>) -> Self { + Self { + bytes: Cow::Borrowed(input.bytes), + source: input.source, + } + } +} + pub struct Inputs<'a> { pub target: Target, - pub kernel_collection: Input<'a>, + pub kernel_collection: KernelInput<'a>, /// Kexts linked against `kernel_collection` (`aux_kc`), which SPTM maps /// beside it. pub auxiliary_collection: Option>, @@ -164,6 +180,31 @@ pub struct Bundle { pub manifest: Manifest, } +impl Bundle { + /// Append firmware named by the prepared board's DeviceTree. These + /// files have source receipts but are not guest memory regions. + pub fn append_board_firmware( + &mut self, + name: String, + bytes: Vec, + source: Source, + ) -> Result<()> { + require!( + name.len() <= MAX_FILE_NAME && !self.files.iter().any(|(file, _)| file == &name), + "board firmware name {name} is too long or already a bundle file", + ?name + ); + self.manifest.files.push(File { + name: name.clone(), + bytes: bytes.len() as u64, + sha256: sha256(&bytes), + }); + self.manifest.sources.push(source); + self.files.push((name, bytes)); + Ok(()) + } +} + /// Where a split region begins or ends within an image. #[derive(Clone, Copy)] enum Mark { @@ -184,7 +225,13 @@ const fn split(suffix: &'static str, start: Mark, end: Mark) -> Split { } use Mark::{ImageEnd, ImageStart, SegmentEnd, SegmentStart}; -use alloc::{borrow::ToOwned, format, string::String, vec, vec::Vec}; +use alloc::{ + borrow::{Cow, ToOwned}, + format, + string::String, + vec, + vec::Vec, +}; /// m1n1 `load_macos_sptm` image splits. const KERNEL_SPLITS: &[Split] = &[ @@ -399,7 +446,7 @@ const BOOT_MANIFEST_FILE: &str = "boot-manifest.im4m"; /// carveout rather than the memory map (`layout::boot_manifest_region`). const BOOT_MANIFEST_REGION: &str = "BootManifest"; const SEP_FILE: &str = "sepfw.im4p"; -const RAMDISK_FILE: &str = "ramdisk.img"; +pub const RAMDISK_FILE: &str = "ramdisk.img"; /// The engine handoff's file-name capacity (`stela-boot` `handoff::MAX_NAME`). const MAX_FILE_NAME: usize = 48; const BOOT_ARGS_FILE: &str = "bootargs.bin"; @@ -410,6 +457,8 @@ struct LoadedImage { file: &'static str, collection: KernelCollection, memory: Vec, + /// The validated file already had this layout and was moved unchanged. + kept_input: bool, /// `(region name, image offset range)` in split order. pieces: Vec<(String, core::ops::Range)>, } @@ -433,10 +482,13 @@ impl LoadedImage { name: &'static str, file: &'static str, collection: KernelCollection, - bytes: &[u8], + bytes: Cow<'_, [u8]>, splits: &[Split], ) -> Result { - let memory = collection.memory_image(bytes)?; + let (memory, kept_input) = match bytes { + Cow::Owned(bytes) if collection.file_is_memory_image(bytes.len()) => (bytes, true), + bytes => (collection.memory_image(&bytes)?, false), + }; let mut pieces = vec![]; for split in splits { let start = resolve(&collection, split.start)?; @@ -472,6 +524,7 @@ impl LoadedImage { file, collection, memory, + kept_input, pieces, }) } @@ -646,7 +699,24 @@ pub struct OwnedRamdisk { } pub fn prepare(inputs: &Inputs, options: &Options) -> Result { - assemble(inputs, options, None) + assemble( + inputs, + options, + Cow::Borrowed(&inputs.kernel_collection.bytes), + None, + ) +} + +/// Build an installed bundle from the decoder's owned kernel and source +/// receipt. When the kernel already has the required layout, move its +/// bytes unchanged and reuse the decoder's SHA-256 for the file receipt. +pub(crate) fn prepare_moving_kernel( + installed: crate::installed::BundleInputs<'_>, + options: &Options, +) -> Result { + let mut inputs = installed.into_inputs(); + let kernel = core::mem::take(&mut inputs.kernel_collection.bytes); + assemble(&inputs, options, kernel, None) } /// [`prepare`], with `ramdisk` moved into the bundle; `inputs` must name no @@ -656,10 +726,20 @@ pub fn prepare_owned(inputs: &Inputs, ramdisk: OwnedRamdisk, options: &Options) inputs.ramdisk.is_none(), "a bundle has one ramdisk, given both borrowed and owned" ); - assemble(inputs, options, Some(ramdisk)) + assemble( + inputs, + options, + Cow::Borrowed(&inputs.kernel_collection.bytes), + Some(ramdisk), + ) } -fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> Result { +fn assemble( + inputs: &Inputs, + options: &Options, + kernel: Cow<'_, [u8]>, + owned: Option, +) -> Result { stela_formats::builds::find(&inputs.target.product_build)?; let ramdisk_bytes = owned .as_ref() @@ -675,7 +755,7 @@ fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> let chip = inputs.target.chip_id.and_then(board::chip); let core_locks_handed_off = chip.is_some_and(|chip| ctrr::generation(chip) == Some(ctrr::Generation::Ctrr3)); - let images = Images::load(inputs)?; + let images = Images::load(inputs, kernel)?; let extra: Vec<&[u8]> = inputs .extra_trust_caches .iter() @@ -789,6 +869,10 @@ fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> let manifest_images = images.manifest_images(®ions)?; let entry = manifest_images[0].entry.clone(); + let kernel_source = &inputs.kernel_collection.source; + let kernel_digest = (images.kernel.kept_input + && images.kernel.memory.len() as u64 == kernel_source.decoded_bytes) + .then_some(&kernel_source.decoded_sha256); let (files, ramdisk_source) = files( inputs, images, @@ -797,7 +881,7 @@ fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> boot_args_bytes, core_locks_handed_off, owned, - )?; + ); hash_regions(&mut regions, &files)?; let manifest = Manifest { schema_version: SCHEMA_VERSION, @@ -809,10 +893,28 @@ fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> sources: sources(inputs, ramdisk_source), files: files .iter() - .map(|(name, bytes)| File { - name: name.clone(), - bytes: bytes.len() as u64, - sha256: sha256(bytes), + .map(|(name, contents)| { + let bytes = contents.len() as u64; + // A whole-file region (such as a restore ramdisk) already + // has the digest of these exact bytes. + let whole = || { + regions + .iter() + .find(|region| { + region.file == *name && region.file_offset == 0 && region.bytes == bytes + }) + .map(|region| ®ion.sha256) + }; + let digest = if name == KERNEL_FILE { + kernel_digest.or_else(whole) + } else { + whole() + }; + File { + name: name.clone(), + bytes, + sha256: digest.cloned().unwrap_or_else(|| sha256(contents)), + } }) .collect(), regions, @@ -831,7 +933,11 @@ fn assemble(inputs: &Inputs, options: &Options, owned: Option) -> security: shaped.security, unresolved: shaped.unresolved, }; - Ok(Bundle { files, manifest }) + let mut bundle = Bundle { files, manifest }; + for (name, image) in &inputs.board_firmware { + bundle.append_board_firmware(name.clone(), image.bytes.to_vec(), source_of(image))?; + } + Ok(bundle) } /// A global manifest must name the selected board. diff --git a/crates/stela-loader/src/boot_bundle/layout.rs b/crates/stela-loader/src/boot_bundle/layout.rs index 3b7b080f1f..6d5773ba74 100644 --- a/crates/stela-loader/src/boot_bundle/layout.rs +++ b/crates/stela-loader/src/boot_bundle/layout.rs @@ -61,13 +61,13 @@ pub(super) struct Images { } impl Images { - pub(super) fn load(inputs: &Inputs) -> Result { + pub(super) fn load(inputs: &Inputs, kernel: Cow<'_, [u8]>) -> Result { Ok(Self { kernel: LoadedImage::new( "BootKC", KERNEL_FILE, - KernelCollection::parse(inputs.kernel_collection.bytes)?, - inputs.kernel_collection.bytes, + KernelCollection::parse(&kernel)?, + kernel, KERNEL_SPLITS, )?, auxiliary: inputs @@ -78,7 +78,7 @@ impl Images { "AuxKC", AUXILIARY_FILE, KernelCollection::parse_auxiliary(input.bytes)?, - input.bytes, + Cow::Borrowed(input.bytes), AUXILIARY_SPLITS, ) }) @@ -87,14 +87,14 @@ impl Images { "SPTM", SPTM_FILE, KernelCollection::parse_executable(inputs.sptm.bytes)?, - inputs.sptm.bytes, + Cow::Borrowed(inputs.sptm.bytes), SPTM_SPLITS, )?, txm: LoadedImage::new( "TXM", TXM_FILE, KernelCollection::parse_executable(inputs.txm.bytes)?, - inputs.txm.bytes, + Cow::Borrowed(inputs.txm.bytes), TXM_SPLITS, )?, }) @@ -687,7 +687,7 @@ pub(super) fn files( boot_args_bytes: Vec, core_locks_handed_off: bool, owned: Option, -) -> Result<(Files, Option)> { +) -> (Files, Option) { let mut files = vec![ (KERNEL_FILE.to_owned(), images.kernel.memory), (SPTM_FILE.to_owned(), images.sptm.memory), @@ -722,17 +722,7 @@ pub(super) fn files( source_of(ramdisk) }), }; - for (name, image) in &inputs.board_firmware { - // The manifest admits only simple names; these checks keep the name - // within the engine handoff and distinct from the bundle's own files. - require!( - name.len() <= MAX_FILE_NAME && !files.iter().any(|(file, _)| file == name), - "board firmware name {name} is too long or already a bundle file", - ?name - ); - files.push((name.clone(), image.bytes.to_vec())); - } - Ok((files, ramdisk_source)) + (files, ramdisk_source) } /// Each region's hash, over the bytes its file supplies. @@ -756,7 +746,7 @@ pub(super) fn hash_regions(regions: &mut [Region], files: &[(String, Vec)]) /// Every input's source, in manifest order. pub(super) fn sources(inputs: &Inputs, ramdisk_source: Option) -> Vec { - let mut sources = vec![source_of(&inputs.kernel_collection)]; + let mut sources = vec![inputs.kernel_collection.source.clone()]; sources.extend(inputs.auxiliary_collection.iter().map(source_of)); sources.extend([ source_of(&inputs.sptm), @@ -780,7 +770,6 @@ pub(super) fn sources(inputs: &Inputs, ramdisk_source: Option) -> Vec Result<()> { chip_id: Some(0x8112), board_id: Some(0x2e), }, - kernel_collection: input(leak(kernel), "KernelCache"), + kernel_collection: input(leak(kernel), "KernelCache").into(), auxiliary_collection: None, sptm: input(leak(sptm), "Ap,SecurePageTableMonitor"), txm: input(leak(txm), "Ap,TrustedExecutionMonitor"), @@ -866,6 +866,20 @@ fn lays_out_sptm_regions_and_patch_slots() -> Result<()> { let firmware = bundle.files.iter().find(|(n, _)| n == "USB-C_HPM,47.bin"); assert_eq!(firmware.map(|(_, b)| b.as_slice()), Some(&[1u8, 2, 3][..])); let supplied = core::mem::take(&mut inputs.board_firmware); + let mut appended = prepare(&inputs, &options)?; + for (name, image) in &supplied { + appended.append_board_firmware(name.clone(), image.bytes.to_vec(), image.source.clone())?; + } + assert_eq!(appended.files, bundle.files); + assert_eq!( + serde_json::to_string(&appended.manifest)?, + serde_json::to_string(&bundle.manifest)? + ); + assert!( + appended + .append_board_firmware(KERNEL_FILE.into(), vec![1], source("BoardFirmware")) + .is_err() + ); inputs.board_firmware = vec![(KERNEL_FILE.into(), input(leak(vec![1]), "BoardFirmware"))]; assert!(prepare(&inputs, &options).is_err()); inputs.board_firmware = supplied; @@ -1072,7 +1086,11 @@ fn lays_out_sptm_regions_and_patch_slots() -> Result<()> { patch.field ); } - // Every region hash covers its file bytes. + // Check both receipts directly, including the whole-file ramdisk and + // files split across multiple regions. + for entry in &manifest.files { + assert_eq!(sha256(file(&entry.name)), entry.sha256, "{}", entry.name); + } for region in &manifest.regions { let at = region.file_offset as usize; assert_eq!( @@ -1340,9 +1358,28 @@ fn lays_out_sptm_regions_and_patch_slots() -> Result<()> { inputs.auxiliary_collection = None; // A manifest for another board is refused. - let mut other = Inputs { ..inputs }; - other.target.board_id = Some(0x24); - assert!(prepare(&other, &options).is_err()); + let board_id = inputs.target.board_id.replace(0x24); + assert!(prepare(&inputs, &options).is_err()); + inputs.target.board_id = board_id; + + let owned_kernel = inputs.kernel_collection.bytes.to_vec(); + let kernel_ptr = owned_kernel.as_ptr(); + inputs.kernel_collection.source.decoded_bytes = owned_kernel.len() as u64; + inputs.kernel_collection.source.decoded_sha256 = sha256(&owned_kernel); + let original = prepare(&inputs, &options)?; + let moved = assemble(&inputs, &options, Cow::Owned(owned_kernel), None)?; + let moved_kernel = &moved + .files + .iter() + .find(|(n, _)| n == KERNEL_FILE) + .unwrap() + .1; + assert_eq!(moved_kernel.as_ptr(), kernel_ptr); + assert_eq!(moved.files, bundle.files); + assert_eq!( + serde_json::to_vec(&moved.manifest)?, + serde_json::to_vec(&original.manifest)? + ); Ok(()) } diff --git a/crates/stela-loader/src/im4p.rs b/crates/stela-loader/src/im4p.rs index 08ca67ecb9..d5961fb378 100644 --- a/crates/stela-loader/src/im4p.rs +++ b/crates/stela-loader/src/im4p.rs @@ -6,7 +6,7 @@ //! firmware ([blacktop/ipsw img4 payload](https://github.com/blacktop/ipsw/blob/master/pkg/img4/payload.go)). //! This is not an IMG4 signature validator and never decrypts keybag payloads. use crate::Result; -use alloc::{string::String, vec, vec::Vec}; +use alloc::{borrow::Cow, string::String, vec, vec::Vec}; use serde::Serialize; use stela_contracts::{refuse, require}; @@ -203,45 +203,85 @@ pub struct DecodeReceipt { pub signature_validated: bool, } +impl<'a> Im4p<'a> { + /// Decode this parsed payload. Boot bundle callers record the enclosing + /// Image4's identity and need only the plaintext and IM4P metadata. + pub(crate) fn decode_payload(&self, maximum: u64) -> Result<(Vec, &'static str)> { + let (decoded, compression) = self.decode_data(maximum)?; + Ok((decoded.into_owned(), compression)) + } + + fn decode_data(&self, maximum: u64) -> Result<(Cow<'a, [u8]>, &'static str)> { + require!( + self.declared_uncompressed_bytes + .is_none_or(|n| n <= maximum), + "declared output exceeds configured limit" + ); + let (decoded, compression) = if stela_formats::lzfse::is_lzfse(self.payload) { + require!( + self.compression_algorithm + .is_none_or(|n| n == COMPRESSION_LZFSE), + "compression record disagrees with LZFSE marker" + ); + let limit = usize::try_from(maximum).unwrap_or(usize::MAX); + ( + Cow::Owned(stela_formats::lzfse::decode(self.payload, limit)?), + "lzfse", + ) + } else { + require!( + self.compression_algorithm.is_none(), + "unrecognized compressed payload format" + ); + require!( + self.payload.len() as u64 <= maximum, + "payload exceeds configured limit" + ); + (Cow::Borrowed(self.payload), "none") + }; + require!(!decoded.is_empty(), "decoded payload is empty"); + require!( + self.declared_uncompressed_bytes + .is_none_or(|n| n == decoded.len() as u64), + "decoded size disagrees with IM4P metadata" + ); + Ok((decoded, compression)) + } +} + /// Decode a plaintext IM4P payload of any type, returning Apple's bytes. /// /// LZFSE streams must be consumed exactly and match the declared size. Other /// payloads are copied unchanged and must not carry compression metadata. pub fn decode(bytes: &[u8], maximum: u64) -> Result<(Vec, DecodeReceipt)> { + let (decoded, receipt) = decode_with_receipt(bytes, maximum)?; + Ok((decoded.into_owned(), receipt)) +} + +/// Decode an owned IM4P, retaining its allocation when it carries plaintext. +pub fn decode_owned(mut bytes: Vec, maximum: u64) -> Result<(Vec, DecodeReceipt)> { + let (decoded, receipt) = decode_with_receipt(&bytes, maximum)?; + match decoded { + Cow::Owned(decoded) => Ok((decoded, receipt)), + Cow::Borrowed(payload) => { + // The plaintext payload is a subslice of the original container. + let start = payload.as_ptr().addr() - bytes.as_ptr().addr(); + let length = payload.len(); + bytes.copy_within(start..start + length, 0); + bytes.truncate(length); + Ok((bytes, receipt)) + } + } +} + +fn decode_with_receipt(bytes: &[u8], maximum: u64) -> Result<(Cow<'_, [u8]>, DecodeReceipt)> { let im4p = parse(bytes)?; - require!( - im4p.declared_uncompressed_bytes - .is_none_or(|n| n <= maximum), - "declared output exceeds configured limit" - ); - let mut decoded = vec![]; - let compression = if stela_formats::lzfse::is_lzfse(im4p.payload) { - require!( - im4p.compression_algorithm - .is_none_or(|n| n == COMPRESSION_LZFSE), - "compression record disagrees with LZFSE marker" - ); - let limit = usize::try_from(maximum).unwrap_or(usize::MAX); - decoded = stela_formats::lzfse::decode(im4p.payload, limit)?; - "lzfse" - } else { - require!( - im4p.compression_algorithm.is_none(), - "unrecognized compressed payload format" - ); - require!( - im4p.payload.len() as u64 <= maximum, - "payload exceeds configured limit" - ); - decoded.extend_from_slice(im4p.payload); - "none" + let (decoded, compression) = im4p.decode_data(maximum)?; + let payload_sha256 = stela_formats::sha256(im4p.payload); + let decoded_sha256 = match &decoded { + Cow::Borrowed(_) => payload_sha256.clone(), + Cow::Owned(decoded) => stela_formats::sha256(decoded), }; - require!(!decoded.is_empty(), "decoded payload is empty"); - require!( - im4p.declared_uncompressed_bytes - .is_none_or(|n| n == decoded.len() as u64), - "decoded size disagrees with IM4P metadata" - ); let receipt = DecodeReceipt { schema_version: 1, container_bytes: bytes.len(), @@ -250,10 +290,10 @@ pub fn decode(bytes: &[u8], maximum: u64) -> Result<(Vec, DecodeReceipt)> { description: im4p.description, compression: compression.into(), payload_bytes: im4p.payload.len(), - payload_sha256: stela_formats::sha256(im4p.payload), + payload_sha256, declared_uncompressed_bytes: im4p.declared_uncompressed_bytes, decoded_bytes: decoded.len(), - decoded_sha256: stela_formats::sha256(&decoded), + decoded_sha256, opaque_extensions: im4p.opaque_extensions, signature_validated: false, }; @@ -312,9 +352,16 @@ mod tests { assert!(!receipt.signature_validated); assert!(decode(&container, 2).is_err()); - let (decoded, receipt) = decode(&fixture(b"trst", b"\x02\0\0\0", &[]), 1024)?; + let plaintext = fixture(b"trst", b"\x02\0\0\0", &[]); + let container_sha256 = stela_formats::sha256(&plaintext); + let address = plaintext.as_ptr(); + let (decoded, receipt) = decode_owned(plaintext, 1024)?; + assert_eq!(decoded.as_ptr(), address); assert_eq!(decoded, b"\x02\0\0\0"); assert_eq!(receipt.compression, "none"); + assert_eq!(receipt.container_sha256, container_sha256); + assert_eq!(receipt.decoded_sha256, stela_formats::sha256(&decoded)); + assert_eq!(receipt.payload_sha256, receipt.decoded_sha256); let mut truncated = stored_lzfse(raw); truncated.pop(); diff --git a/crates/stela-loader/src/installed.rs b/crates/stela-loader/src/installed.rs index d521517327..c72172d4fe 100644 --- a/crates/stela-loader/src/installed.rs +++ b/crates/stela-loader/src/installed.rs @@ -38,7 +38,7 @@ use crate::aux_kc::{self, Kext, Linked}; use crate::{Error, Result, Within}; use crate::{ apple_device_tree::DeviceTree, - boot_bundle::{self, Bundle, Input, Inputs, Options, RootHash, Source, Target}, + boot_bundle::{self, Bundle, Input, Inputs, KernelInput, Options, RootHash, Source, Target}, boot_policy::{KextGrant, SealedVolume}, boot_selection::{BootVolume, VolumeType, uuid_text}, im4m, im4p, @@ -437,6 +437,16 @@ pub struct Installed { pub evidence: Evidence, } +/// The installed loader's inputs. Its constructor stays in this module +/// where the owned kernel and its exact decode receipt originate. +pub(crate) struct BundleInputs<'a>(Inputs<'a>); + +impl<'a> BundleInputs<'a> { + pub(crate) fn into_inputs(self) -> Inputs<'a> { + self.0 + } +} + pub struct Decoded { bytes: Vec, source: Source, @@ -468,14 +478,15 @@ impl Disk<'_, R> { let object = self.set.require(kind)?.clone(); let file = self.read(&object)?; let parts = img4::parse(&file).within(|| refuse!("{path}", path = object.path))?; - let (bytes, receipt) = im4p::decode(parts.payload, limit)?; + let im4p = im4p::parse(parts.payload)?; + let (bytes, _) = im4p.decode_payload(limit)?; let decoded = Decoded { source: Source { component: format!("Preboot {}", String::from_utf8_lossy(kind)), member: object.path.clone(), container_sha256: sha256(&file), - payload_type: receipt.payload_type, - description: receipt.description, + payload_type: im4p.payload_type, + description: im4p.description, decoded_bytes: bytes.len() as u64, decoded_sha256: sha256(&bytes), }, @@ -710,7 +721,10 @@ pub fn prepare( chip_id: manifest_id(manifest.as_ref(), "CHIP")?, board_id: manifest_id(manifest.as_ref(), "BORD")?, }, - kernel_collection: kernel.input(), + kernel_collection: KernelInput { + bytes: kernel.bytes.into(), + source: kernel.source, + }, auxiliary_collection: auxiliary.as_ref().map(Decoded::input), sptm: sptm.input(), txm: txm.input(), @@ -757,7 +771,7 @@ pub fn prepare( volume_group: disk.set.volume_group.clone(), boot_hash: disk.set.boot_hash.clone(), }); - let mut bundle = boot_bundle::prepare(&inputs, &options)?; + let mut bundle = boot_bundle::prepare_moving_kernel(BundleInputs(inputs), &options)?; if !evidence .named_by .as_deref() diff --git a/crates/stela-loader/src/kernel_collection.rs b/crates/stela-loader/src/kernel_collection.rs index c81618f170..56a0ae0bf1 100644 --- a/crates/stela-loader/src/kernel_collection.rs +++ b/crates/stela-loader/src/kernel_collection.rs @@ -282,6 +282,24 @@ impl KernelCollection { Ok(image) } + /// A freshly parsed file is already its memory image when its + /// disjoint segments cover every byte at the same offsets. + pub(crate) fn file_is_memory_image(&self, file_bytes: usize) -> bool { + if self.image_bytes() != file_bytes as u64 { + return false; + } + let mut covered = 0; + for segment in self.segments.iter().filter(|segment| segment.vm_size != 0) { + if segment.file_size != segment.vm_size + || segment.file_offset != segment.vm_address - self.vm_base + { + return false; + } + covered += segment.file_size; + } + covered == self.image_bytes() + } + /// Byte range from the load base covering `first` through `last`. pub fn span(&self, first: &str, last: &str) -> Result> { let start = self @@ -465,6 +483,7 @@ pub(crate) mod tests { assert!(kc.physical_address(0x8_0000_0000, BASE + 0xc000).is_err()); assert_eq!(kc.span("__TEXT_EXEC", "__LINKEDIT")?, 0x4000..0xc000); let image = kc.memory_image(&bytes)?; + assert!(!kc.file_is_memory_image(bytes.len())); assert_eq!(image.len(), 0xc000); assert_eq!(&image[0x4000..0x4010], &[0xaa; 0x10]); assert_eq!(image[0x4010], 0); diff --git a/crates/stela-loader/src/recovery.rs b/crates/stela-loader/src/recovery.rs index 9f7d053bc0..14554b745f 100644 --- a/crates/stela-loader/src/recovery.rs +++ b/crates/stela-loader/src/recovery.rs @@ -464,14 +464,15 @@ impl Reader<'_, R> { let object = self.set.require(kind)?.clone(); let file = self.file(&object)?; let parts = img4::parse(&file).within(|| refuse!("{path}", path = object.path))?; - let (bytes, receipt) = crate::im4p::decode(parts.payload, limit)?; + let im4p = crate::im4p::parse(parts.payload)?; + let (bytes, _) = im4p.decode_payload(limit)?; let decoded = Decoded { source: Source { component: self.component(kind), member: object.path.clone(), container_sha256: sha256(&file), - payload_type: receipt.payload_type, - description: receipt.description, + payload_type: im4p.payload_type, + description: im4p.description, decoded_bytes: bytes.len() as u64, decoded_sha256: sha256(&bytes), }, @@ -619,7 +620,7 @@ pub fn prepare( chip_id: manifest_id(manifest.as_ref(), "CHIP")?, board_id: manifest_id(manifest.as_ref(), "BORD")?, }, - kernel_collection: kernel.input(), + kernel_collection: kernel.input().into(), auxiliary_collection: None, sptm: sptm.input(), txm: txm.input(), diff --git a/crates/stela-loader/src/upgrade.rs b/crates/stela-loader/src/upgrade.rs index 2d5eeb58fc..612ad795b9 100644 --- a/crates/stela-loader/src/upgrade.rs +++ b/crates/stela-loader/src/upgrade.rs @@ -368,14 +368,15 @@ impl Reader<'_, R> { let file = self.file(staged)?; let parts = img4::parse(&file).within(|| refuse!("{path}", path = staged.path.as_str()))?; let im4p_sha384 = im4m::sha384(parts.payload); - let (bytes, receipt) = im4p::decode(parts.payload, limit)?; + let im4p = im4p::parse(parts.payload)?; + let (bytes, _) = im4p.decode_payload(limit)?; Ok(Decoded { source: Source { component: component.into(), member: staged.path.clone(), container_sha256: sha256(&file), - payload_type: receipt.payload_type, - description: receipt.description, + payload_type: im4p.payload_type, + description: im4p.description, decoded_bytes: bytes.len() as u64, decoded_sha256: sha256(&bytes), }, @@ -506,7 +507,7 @@ pub fn prepare( chip_id: id("CHIP"), board_id: id("BORD"), }, - kernel_collection: kernel.input(), + kernel_collection: kernel.input().into(), auxiliary_collection: None, sptm: sptm.input(), txm: txm.input(), diff --git a/crates/stela-runtime/src/platform/net/stack.rs b/crates/stela-runtime/src/platform/net/stack.rs index 615e741ff7..a0143a2ee1 100644 --- a/crates/stela-runtime/src/platform/net/stack.rs +++ b/crates/stela-runtime/src/platform/net/stack.rs @@ -56,6 +56,7 @@ const SEND_BUFFER: usize = 64 * 1024; /// polling the interface reports it. struct Phy { link: L, + tx_frame: Vec, fault: Option, /// Whether the last poll took a frame from the link. received: bool, @@ -77,8 +78,10 @@ impl phy::RxToken for Rx { impl phy::TxToken for Tx<'_, L> { fn consume R>(self, length: usize, f: F) -> R { - let mut frame = vec![0; length]; - let result = f(&mut frame); + let frame = &mut self.0.tx_frame; + frame.clear(); + frame.resize(length, 0); + let result = f(frame); // Tentative addresses stay off the wire until their DAD probe ends. if self.0.manage_ipv6 && frame.len() >= 54 && frame[12..14] == [0x86, 0xdd] { let source = Ipv6Addr::from(<[u8; 16]>::try_from(&frame[22..38]).unwrap()); @@ -86,7 +89,7 @@ impl phy::TxToken for Tx<'_, L> { return result; } } - if let Err(error) = self.0.link.transmit(&frame) { + if let Err(error) = self.0.link.transmit(frame) { self.0.fault.get_or_insert(error); } result @@ -231,6 +234,7 @@ impl Stack { config.slaac = true; let mut phy = Phy { link, + tx_frame: Vec::new(), fault: None, received: false, probes: Vec::new(), diff --git a/crates/stela-runtime/src/platform/net/stack/tests.rs b/crates/stela-runtime/src/platform/net/stack/tests.rs index 89ca514404..28f96eadaa 100644 --- a/crates/stela-runtime/src/platform/net/stack/tests.rs +++ b/crates/stela-runtime/src/platform/net/stack/tests.rs @@ -46,6 +46,32 @@ impl Link for End { } } +#[test] +fn transmit_reuses_storage_with_zeroed_bytes_and_the_current_frame_length() { + use smoltcp::phy::TxToken; + + let mut lan = Lan::new(0, TestClock::default()); + let mut transmit = |length, value| { + lan.server + .transmit(Instant::ZERO) + .unwrap() + .consume(length, |frame| { + assert!(frame.iter().all(|&byte| byte == 0)); + frame[0] = value; + frame.as_ptr() + }) + }; + let first = transmit(100, 3); + assert_eq!(transmit(60, 7), first); + assert_eq!(transmit(100, 2), first); + for (length, value) in [(100, 3), (60, 7), (100, 2)] { + let frame = lan.client.receive().unwrap().unwrap(); + assert_eq!(frame.len(), length); + assert_eq!(frame[0], value); + assert!(frame[1..].iter().all(|&byte| byte == 0)); + } +} + /// A smoltcp HTTP server serving `pattern(offset)` for ranges of a /// `size`-byte resource, stepped whenever the client reads its link; /// every `drop_every`th frame to the client is lost and every @@ -89,6 +115,7 @@ impl Lan { out: b, into: a, }, + tx_frame: Vec::new(), fault: None, received: false, probes: Vec::new(), diff --git a/crates/stela-runtime/src/platform/pc/fat32.rs b/crates/stela-runtime/src/platform/pc/fat32.rs index ec9b86475a..0480bd9a9a 100644 --- a/crates/stela-runtime/src/platform/pc/fat32.rs +++ b/crates/stela-runtime/src/platform/pc/fat32.rs @@ -90,6 +90,7 @@ pub struct Fat32 { /// The FAT bytes last read and their offset in the FAT. window: Vec, window_offset: Option, + directory_sector: Vec, } fn u16_at(bytes: &[u8], at: usize) -> u16 { @@ -172,6 +173,7 @@ impl Fat32 { root, window: vec![0; FAT_WINDOW], window_offset: None, + directory_sector: vec![0; bytes_per_sector as usize], }; if !volume.valid(root) { return Err(FatError::NotFat32("root directory cluster")); @@ -284,28 +286,30 @@ impl Fat32 { name: &[u8; 11], ) -> Result, FatError> { let directory = self.chain(path, cluster, None)?; - let mut entry = [0u8; ENTRY_BYTES]; for extent in &directory.extents { - for at in (0..extent.bytes).step_by(ENTRY_BYTES) { + for at in (0..extent.bytes).step_by(self.directory_sector.len()) { self.reader - .read_at(extent.offset + at, &mut entry) + .read_at(extent.offset + at, &mut self.directory_sector) .map_err(|e| FatError::Io(format!("{e:?}")))?; - let attributes = entry[11]; - match entry[0] { - ENTRY_END => return Ok(None), - ENTRY_FREE => continue, - _ if attributes & ATTRIBUTE_LONG_NAME == ATTRIBUTE_LONG_NAME => continue, - _ if attributes & ATTRIBUTE_VOLUME_ID != 0 => continue, - _ => {} - } - let mut stored = [0u8; 11]; - stored.copy_from_slice(&entry[..11]); - if stored[0] == ENTRY_KANJI_E5 { - stored[0] = ENTRY_FREE; - } - if stored.to_ascii_uppercase() == *name { - let first = u32::from(u16_at(&entry, 20)) << 16 | u32::from(u16_at(&entry, 26)); - return Ok(Some((attributes, first, u32_at(&entry, 28)))); + for entry in self.directory_sector.as_chunks::().0 { + let attributes = entry[11]; + match entry[0] { + ENTRY_END => return Ok(None), + ENTRY_FREE => continue, + _ if attributes & ATTRIBUTE_LONG_NAME == ATTRIBUTE_LONG_NAME => continue, + _ if attributes & ATTRIBUTE_VOLUME_ID != 0 => continue, + _ => {} + } + let mut stored = [0u8; 11]; + stored.copy_from_slice(&entry[..11]); + if stored[0] == ENTRY_KANJI_E5 { + stored[0] = ENTRY_FREE; + } + if stored.to_ascii_uppercase() == *name { + let first = + u32::from(u16_at(entry, 20)) << 16 | u32::from(u16_at(entry, 26)); + return Ok(Some((attributes, first, u32_at(entry, 28)))); + } } } } @@ -562,6 +566,47 @@ pub(crate) mod tests { } } + #[test] + fn directory_lookup_reads_each_needed_sector_once() { + struct Recorded { + disk: Sparse, + directory_reads: Vec<(u64, usize)>, + } + + impl ReadAt for Recorded { + type Error = Refusal; + + fn len(&self) -> u64 { + self.disk.len() + } + + fn read_at(&mut self, offset: u64, buffer: &mut [u8]) -> Result<()> { + if offset >= data(2) { + self.directory_reads.push((offset, buffer.len())); + } + self.disk.read_at(offset, buffer) + } + } + + let mut volume = Volume::new(); + volume.link(&[2, 7, 9]); + volume.disk.write(data(2), &[ENTRY_FREE; SECTOR as usize]); + volume.file(7, 0, b"IPSW 000", b"payload"); + let mut fat = Fat32::open(Recorded { + disk: volume.disk, + directory_reads: Vec::new(), + }) + .unwrap(); + let expected = [(data(2), SECTOR as usize), (data(7), SECTOR as usize)]; + + assert_eq!(fat.file("ipsw.000").unwrap().bytes, 7); + assert_eq!(fat.reader.directory_reads, expected); + fat.reader.directory_reads.clear(); + + assert!(matches!(fat.file("absent"), Err(FatError::Missing(_)))); + assert_eq!(fat.reader.directory_reads, expected); + } + #[test] fn malformed_chains_and_other_volumes_are_refused() { let mut volume = Volume::new(); diff --git a/crates/stela-runtime/src/restore/driver.rs b/crates/stela-runtime/src/restore/driver.rs index d399a933c6..cd966b740e 100644 --- a/crates/stela-runtime/src/restore/driver.rs +++ b/crates/stela-runtime/src/restore/driver.rs @@ -96,13 +96,28 @@ impl Driver { /// for [`Self::work`], for a caller that must not hold the ports while /// the answers sign with Apple's TSS or read the image. pub fn poll_ports(&mut self, ports: &mut impl Ports) -> Poll> { + self.poll_inner(ports, false) + } + + /// Poll without refilling a member transfer's window. The caller reads + /// those windows with [`Self::prefetch`] between polls, outside its + /// borrow of the ports. + pub fn poll_prefetched(&mut self, ports: &mut impl Ports) -> Poll> { + self.poll_inner(ports, true) + } + + fn poll_inner( + &mut self, + ports: &mut impl Ports, + read_ahead_only: bool, + ) -> Poll> { if let Some(error) = &self.failure { return Poll::Ready(Err(error.clone())); } if self.complete { return Poll::Ready(Ok(())); } - let result = self.step(ports); + let result = self.step(ports, read_ahead_only); if let Poll::Ready(Err(error)) = &result { self.failure = Some(error.clone()); } @@ -155,7 +170,11 @@ impl Driver { } Ok(()) } - fn step(&mut self, ports: &mut impl Ports) -> Poll> { + fn step( + &mut self, + ports: &mut impl Ports, + read_ahead_only: bool, + ) -> Poll> { if self.control.is_none() { self.control = Some(match ports.open(PORT) { Poll::Pending => return Poll::Pending, @@ -237,10 +256,11 @@ impl Driver { control }; if !t.closing { - match t - .job - .poll(&mut Stream { ports, handle }, &mut self.answers.store) - { + match t.job.poll_with_source( + &mut Stream { ports, handle }, + &mut self.answers.store, + read_ahead_only, + ) { Poll::Pending => { at += 1; continue; @@ -269,6 +289,9 @@ impl Driver { } self.session.finish_job(t.job.id, Ok(()))?; self.jobs.remove(at); + if self.jobs.is_empty() { + self.answers.store.release_cursors(); + } } Poll::Pending } @@ -281,6 +304,15 @@ impl Driver { return; } for transfer in &mut self.jobs { + // A waiting DataPort job has no receiver yet. Keep the ASR + // sender's existing prefetch activation before its handshake. + if transfer.closing + || (transfer.job.port.is_some() + && transfer.handle.is_none() + && transfer.job.asr().is_none()) + { + continue; + } if let Err(e) = transfer.job.prefetch(&mut self.answers.store, chunks) { self.failure = Some(super::refuse( refuse!("transfer failed: {e}", ?e), diff --git a/crates/stela-runtime/src/restore/driver/tests.rs b/crates/stela-runtime/src/restore/driver/tests.rs index d203f224c1..e87110a4ef 100644 --- a/crates/stela-runtime/src/restore/driver/tests.rs +++ b/crates/stela-runtime/src/restore/driver/tests.rs @@ -55,9 +55,17 @@ fn append(h: &mut Harness, v: Value) { fn setup() -> ( Driver, Harness, +) { + setup_with(b"payload") +} +fn setup_with( + payload: &[u8], +) -> ( + Driver, + Harness, ) { let d = Driver::new( - Answers::new(fixture(b"payload", false)), + Answers::new(fixture(payload, false)), Route::StelaFirmwareStudy, ) .unwrap(); @@ -135,7 +143,9 @@ fn transcript_short_io_concurrent_control_jobs_and_final_ack_write() { ]), ); for _ in 0..100_000 { - assert!(d.poll(&mut h).is_pending()); + assert!(d.poll_prefetched(&mut h).is_pending()); + d.work(); + d.prefetch(1); if d.session.ledger().len() == 6 && d.session.outstanding() == 0 { break; } @@ -221,6 +231,43 @@ fn transcript_short_io_concurrent_control_jobs_and_final_ack_write() { "ReceivedFinalStatusMsg" ); } +#[test] +fn file_data_on_the_control_stream_drains_before_a_competing_reply() { + let payload = vec![5; 5 * 8192 + 1]; + let (mut d, mut h) = setup_with(&payload); + restoring(&mut d, &mut h); + let s = h.streams.get_mut(&PORT).unwrap(); + let start = s.output.len(); + s.chunk = 1931; + append(&mut h, request("SourceBootObjectV4", false)); + append(&mut h, request("ReceiptManifest", false)); + for _ in 0..1_000 { + assert!(d.poll_prefetched(&mut h).is_pending()); + d.work(); + d.prefetch(1); + if d.session.outstanding() == 0 && d.session.ledger().len() == 4 { + break; + } + } + assert_eq!(d.session.ledger().len(), 4); + assert_eq!(d.session.outstanding(), 0); + let s = h.streams.get_mut(&PORT).unwrap(); + let mut stream = Memory::new(s.output[start..].to_vec(), 1931); + let mut frame = Framed::new(Endian::Big, Limits::default()); + for expected in payload.chunks(8192) { + let actual = receive(&mut frame, &mut stream).unwrap(); + assert_eq!( + actual.required("FileData").unwrap().data().unwrap(), + expected + ); + } + let done = receive(&mut frame, &mut stream).unwrap(); + assert!(done.required("FileDataDone").unwrap().boolean().unwrap()); + let reply = receive(&mut frame, &mut stream).unwrap(); + assert!(reply.get("ReceiptManifest").is_some()); + assert_eq!(stream.at, stream.input.len()); +} + #[test] fn blocked_data_keeps_control_live_and_limits_open_handles() { let (_, mut h) = setup(); diff --git a/crates/stela-runtime/src/restore/plist.rs b/crates/stela-runtime/src/restore/plist.rs index c3de7db3c3..6ca623a5ee 100644 --- a/crates/stela-runtime/src/restore/plist.rs +++ b/crates/stela-runtime/src/restore/plist.rs @@ -708,18 +708,68 @@ impl<'a> Binary<'a> { } } } +fn binary_size(out: &mut Vec, tag: u8, n: usize) { + if n < 15 { + out.push(tag | n as u8); + } else { + out.extend_from_slice(&[tag | 15, 0x13]); + out.extend_from_slice(&(n as u64).to_be_bytes()); + } +} + +fn binary_trailer(out: &mut Vec, objects: u64, root: u64, table: u64) { + out.extend_from_slice(&[0, 0, 0, 0, 0, 0, 8, 8]); + out.extend_from_slice(&objects.to_be_bytes()); + out.extend_from_slice(&root.to_be_bytes()); + out.extend_from_slice(&table.to_be_bytes()); +} + +/// Append the same three-object table as `encode_binary` for FileData. +/// The streaming sender can write the payload directly to its frame buffer. +pub(super) fn append_file_data(out: &mut Vec, data: &[u8], limits: Limits) -> Result { + const KEY: &[u8] = b"FileData"; + let mut budget = Budget::new(limits); + budget.node(0)?; + budget.node(1)?; + budget.node(1)?; + budget.bytes(KEY.len())?; + budget.bytes(data.len())?; + + // Header, key, dictionary with two references, offsets, and trailer. + const FIXED_BYTES: usize = 8 + (1 + KEY.len()) + (1 + 2 * 8) + 3 * 8 + 32; + let marker_bytes = if data.len() < 15 { 1 } else { 10 }; + let length = data + .len() + .checked_add(FIXED_BYTES + marker_bytes) + .filter(|length| *length <= limits.bytes) + .ok_or(Error::Limit("bplist encoded bytes"))?; + let wire_length = u32::try_from(length).map_err(|_| Error::Limit("plist frame u32 length"))?; + out.reserve(length); + let start = out.len(); + out.extend_from_slice(b"bplist00"); + let key = (out.len() - start) as u64; + binary_size(out, 0x50, KEY.len()); + out.extend_from_slice(KEY); + let value = (out.len() - start) as u64; + binary_size(out, 0x40, data.len()); + out.extend_from_slice(data); + let root = (out.len() - start) as u64; + binary_size(out, 0xd0, 1); + out.extend_from_slice(&0u64.to_be_bytes()); + out.extend_from_slice(&1u64.to_be_bytes()); + let table = (out.len() - start) as u64; + for offset in [key, value, root] { + out.extend_from_slice(&offset.to_be_bytes()); + } + binary_trailer(out, 3, 2, table); + debug_assert_eq!(out.len() - start, length); + Ok(wire_length) +} + /// Canonical, unshared object table; 8-byte references avoid narrowing casts. pub fn encode_binary(v: &Value, limits: Limits) -> Result> { validate(v, &mut Budget::new(limits), 0)?; let mut objects: Vec> = Vec::new(); - fn size(out: &mut Vec, tag: u8, n: usize) { - if n < 15 { - out.push(tag | n as u8); - } else { - out.extend_from_slice(&[tag | 15, 0x13]); - out.extend_from_slice(&(n as u64).to_be_bytes()); - } - } fn emit(v: &Value, objects: &mut Vec>) -> usize { let mut out = Vec::new(); match v { @@ -738,28 +788,28 @@ pub fn encode_binary(v: &Value, limits: Limits) -> Result> { out.extend_from_slice(&n.to_be_bytes()); } Value::Data(b) => { - size(&mut out, 0x40, b.len()); + binary_size(&mut out, 0x40, b.len()); out.extend_from_slice(b); } Value::String(s) => { if s.is_ascii() { - size(&mut out, 0x50, s.len()); + binary_size(&mut out, 0x50, s.len()); out.extend_from_slice(s.as_bytes()); } else { - size(&mut out, 0x60, s.encode_utf16().count()); + binary_size(&mut out, 0x60, s.encode_utf16().count()); for c in s.encode_utf16() { out.extend_from_slice(&c.to_be_bytes()); } } } Value::Array(a) => { - size(&mut out, 0xa0, a.len()); + binary_size(&mut out, 0xa0, a.len()); for v in a { out.extend_from_slice(&(emit(v, objects) as u64).to_be_bytes()); } } Value::Dict(d) => { - size(&mut out, 0xd0, d.len()); + binary_size(&mut out, 0xd0, d.len()); for k in d.keys() { out.extend_from_slice( &(emit(&Value::String(k.clone()), objects) as u64).to_be_bytes(), @@ -788,10 +838,7 @@ pub fn encode_binary(v: &Value, limits: Limits) -> Result> { for off in offsets { out.extend_from_slice(&off.to_be_bytes()); } - out.extend_from_slice(&[0, 0, 0, 0, 0, 0, 8, 8]); - out.extend_from_slice(&(objects.len() as u64).to_be_bytes()); - out.extend_from_slice(&(root as u64).to_be_bytes()); - out.extend_from_slice(&table.to_be_bytes()); + binary_trailer(&mut out, objects.len() as u64, root as u64, table); if out.len() > limits.bytes { return Err(Error::Limit("bplist encoded bytes")); } diff --git a/crates/stela-runtime/src/restore/session.rs b/crates/stela-runtime/src/restore/session.rs index 58d6583bf2..003d07138e 100644 --- a/crates/stela-runtime/src/restore/session.rs +++ b/crates/stela-runtime/src/restore/session.rs @@ -19,6 +19,9 @@ pub const PROTOCOL: u64 = 15; const MAX_JOBS: usize = 16; const MAX_LEDGER_BYTES: usize = 16 * 1024 * 1024; const FILE_CHUNK: usize = 8192; +// Four framed chunks fit a single 48 KiB mux write with room for headers. +const FILE_BATCH_BYTES: usize = 4 * FILE_CHUNK; +const _: () = assert!(MAX_READ_BYTES.is_multiple_of(FILE_BATCH_BYTES)); /// Every message type the host understands, with the value the public host /// sends for it (idevicerestore 4b3e847e `restore_supported_message_types`, /// "extracted from ac2"). Restored's `is_host_compatible` compares this @@ -474,6 +477,54 @@ impl Session { Ok(()) } } +#[derive(Default)] +struct MemberWindow { + bytes: Vec, + at: u64, + segment: Option, +} + +impl MemberWindow { + fn get(&self, segment: usize, at: u64, len: usize) -> Option<&[u8]> { + if self.segment != Some(segment) { + return None; + } + let start = usize::try_from(at.checked_sub(self.at)?).ok()?; + self.bytes.get(start..start.checked_add(len)?) + } + + fn fill( + &mut self, + store: &mut Store, + segment: usize, + path: &str, + at: u64, + len: u64, + ) -> Result<()> { + // Read in large verified runs and send them in FILE_CHUNK pieces. + // A deflated member's random read can replay its inflater. + self.bytes = store.read_at(path, at, len.min(MAX_READ_BYTES as u64) as usize)?; + self.at = at; + self.segment = Some(segment); + Ok(()) + } +} + +fn next_segment<'a>( + segments: &'a [Segment], + index: &mut usize, + offset: &mut u64, +) -> Option<&'a Segment> { + while let Some(segment) = segments.get(*index) { + if *offset != segment.len() { + return Some(segment); + } + *index += 1; + *offset = 0; + } + None +} + /// The scheduler owns the stream and close/reconnect policy. `port=None` uses /// the control stream; serialize its outbound frames with all other writers. /// DataPort jobs can run concurrently with progress/control reads. @@ -486,11 +537,12 @@ pub struct Job { raw: Output, index: usize, offset: u64, - /// Verified member bytes read ahead for segment `window_segment`, from - /// member offset `window_at`. - window: Vec, - window_at: u64, - window_segment: Option, + /// Payload bytes staged as FileData, committed when the batch drains. + file_pending: usize, + /// The stream position at which the last staged frame can be sent. + file_tail: u64, + /// Verified member bytes ready to frame. + window: MemberWindow, done: bool, failed: bool, reply_queued: bool, @@ -506,9 +558,9 @@ impl Job { raw: Output::default(), index: 0, offset: 0, - window: Vec::new(), - window_at: 0, - window_segment: None, + file_pending: 0, + file_tail: 0, + window: MemberWindow::default(), done: false, failed: false, reply_queued: false, @@ -518,13 +570,22 @@ impl Job { &mut self, s: &mut impl ByteStream, store: &mut Store, + ) -> Poll> { + self.poll_with_source(s, store, false) + } + + pub(super) fn poll_with_source( + &mut self, + s: &mut impl ByteStream, + store: &mut Store, + read_ahead_only: bool, ) -> Poll> { // Step on while each step queues or sends: the stream takes only // what the guest has room for (its receive window), so the guest's // own buffers end the turn. let r = loop { let (before, queued) = (self.written(), self.sending()); - let r = self.step(s, store); + let r = self.step(s, store, read_ahead_only); let moved = self.written() != before || !queued && self.sending(); if r.is_ready() || !moved { break r; @@ -535,13 +596,38 @@ impl Job { } r.map(|r| r.map_err(|e| super::refuse(refuse!("transfer failed: {e}", ?e), &self.request))) } - /// Read ahead what the job sends next ([`super::asr::Sender::prefetch`]), - /// up to `chunks` reads. + /// Read the next verified member window, or up to `chunks` ASR chunks. pub fn prefetch(&mut self, store: &mut Store, chunks: usize) -> Result<()> { + let limit = self.member_chunk_limit(); match &mut self.plan { - Plan::Asr(sender) => sender.prefetch(store, chunks), - _ => Ok(()), + Plan::Asr(sender) => sender.prefetch(store, chunks)?, + Plan::File(segments) | Plan::Raw(segments) | Plan::Message(segments) + if chunks != 0 && !self.done && !self.failed => + { + // Keep the existing read-ahead point at the last logical + // frame, including when a next-window check can fail. + if self.file_pending != 0 && self.frame.written() < self.file_tail { + return Ok(()); + } + let mut index = self.index; + let mut cursor = self.offset + self.file_pending as u64; + if let Some(Segment::Member { + path, + offset, + bytes, + }) = next_segment(segments, &mut index, &mut cursor) + { + let at = offset + cursor; + let remaining = bytes - cursor; + let n = remaining.min(limit as u64) as usize; + if self.window.get(index, at, n).is_none() { + self.window.fill(store, index, path, at, remaining)?; + } + } + } + _ => {} } + Ok(()) } /// The job's ASR sender, if it sends the image. pub fn asr(&self) -> Option<&super::asr::Sender> { @@ -556,10 +642,18 @@ impl Job { fn sending(&self) -> bool { self.frame.sending() || self.raw.is_pending() } + fn member_chunk_limit(&self) -> usize { + if matches!(&self.plan, Plan::File(_)) { + FILE_BATCH_BYTES + } else { + FILE_CHUNK + } + } fn step( &mut self, s: &mut impl ByteStream, store: &mut Store, + read_ahead_only: bool, ) -> Poll> { if self.failed { return Poll::Ready(Err(Error::Invalid("restore job already failed"))); @@ -569,7 +663,10 @@ impl Job { } if self.frame.sending() { return match self.frame.poll_send(s) { - Poll::Ready(Ok(())) => Poll::Pending, + Poll::Ready(Ok(())) => { + self.offset += core::mem::take(&mut self.file_pending) as u64; + Poll::Pending + } r => r, }; } @@ -579,6 +676,7 @@ impl Job { r => r, }; } + let limit = self.member_chunk_limit(); match &mut self.plan { Plan::Reply(v) => { if self.reply_queued { @@ -601,11 +699,8 @@ impl Job { Plan::File(s) | Plan::Raw(s) | Plan::Message(s) => s, _ => unreachable!(), }; - while self.index < segments.len() && self.offset == segments[self.index].len() { - self.index += 1; - self.offset = 0; - } - if self.index == segments.len() { + let Some(segment) = next_segment(segments, &mut self.index, &mut self.offset) + else { if !raw && !self.reply_queued { self.frame .queue(&Value::dict([("FileDataDone", Value::Boolean(true))]), true)?; @@ -614,43 +709,36 @@ impl Job { self.done = true; return Poll::Ready(Ok(())); } - } else { - let segment = &segments[self.index]; - let n = (segment.len() - self.offset).min(FILE_CHUNK as u64) as usize; - let bytes = match segment { - Segment::Bytes(bytes) => { - bytes[self.offset as usize..self.offset as usize + n].to_vec() - } - Segment::Member { - path, - offset, - bytes, - } => { - // Read the member in large verified runs and frame - // them in FILE_CHUNK pieces: a deflated member's - // random read replays its inflater from the start. - let at = offset + self.offset; - let start = self.window_at; - if self.window_segment != Some(self.index) - || at < start - || at + n as u64 > start + self.window.len() as u64 - { - let run = (bytes - self.offset).min(MAX_READ_BYTES as u64); - self.window = store.read_at(path, at, run as usize)?; - self.window_at = at; - self.window_segment = Some(self.index); + return Poll::Pending; + }; + let n = (segment.len() - self.offset).min(limit as u64) as usize; + let bytes = match segment { + Segment::Bytes(bytes) => &bytes[self.offset as usize..self.offset as usize + n], + Segment::Member { + path, + offset, + bytes, + } => { + let at = offset + self.offset; + if self.window.get(self.index, at, n).is_none() { + if read_ahead_only { + return Poll::Pending; } - let skip = (at - self.window_at) as usize; - self.window[skip..skip + n].to_vec() + self.window + .fill(store, self.index, path, at, bytes - self.offset)?; } - }; - self.offset += n as u64; - if raw { - self.raw.queue(bytes, FILE_CHUNK)?; - } else { - self.frame - .queue(&Value::dict([("FileData", Value::Data(bytes))]), true)?; + self.window + .get(self.index, at, n) + .ok_or(Error::Invalid("short restore member read"))? } + }; + if raw { + self.offset += n as u64; + self.raw.queue(bytes.to_vec(), FILE_CHUNK)?; + } else { + let tail = self.frame.queue_file_data(bytes.chunks(FILE_CHUNK))?; + self.file_pending = n; + self.file_tail = self.frame.written() + tail as u64; } } } diff --git a/crates/stela-runtime/src/restore/session/tests.rs b/crates/stela-runtime/src/restore/session/tests.rs index 60a960d63e..474758c332 100644 --- a/crates/stela-runtime/src/restore/session/tests.rs +++ b/crates/stela-runtime/src/restore/session/tests.rs @@ -1,4 +1,5 @@ use super::super::{ + plist, store::tests::fixture, stream::tests::{Memory, receive}, }; @@ -326,7 +327,41 @@ fn a_deflated_member_streams_whole_in_file_chunks_across_read_runs() { answers.plan(&request).unwrap(), ); let mut stream = Memory::new(Vec::new(), 1 << 20); - while job.poll(&mut stream, &mut answers.store).is_pending() {} + // The native poll cannot inflate or verify source data while its + // caller holds the guest's devices. + assert!( + job.poll_with_source(&mut stream, &mut answers.store, true) + .is_pending() + ); + assert!(stream.output.is_empty()); + + job.prefetch(&mut answers.store, 1).unwrap(); + for _ in 0..2 * MAX_READ_BYTES / FILE_CHUNK + 2 { + assert!( + job.poll_with_source(&mut stream, &mut answers.store, true) + .is_pending() + ); + if !job.sending() && job.offset == MAX_READ_BYTES as u64 { + break; + } + } + assert_eq!(job.offset, MAX_READ_BYTES as u64); + assert!(!job.sending()); + let sent = stream.output.len(); + assert!( + job.poll_with_source(&mut stream, &mut answers.store, true) + .is_pending() + ); + assert_eq!(stream.output.len(), sent); + + job.prefetch(&mut answers.store, 1).unwrap(); + for _ in 0..16 { + if let Poll::Ready(result) = job.poll_with_source(&mut stream, &mut answers.store, true) { + result.unwrap(); + break; + } + } + assert!(job.done); stream.input = core::mem::take(&mut stream.output); let mut frame = Framed::new(Endian::Big, Limits::default()); let mut got = Vec::new(); @@ -376,17 +411,32 @@ fn an_optional_missing_global_manifest_sends_only_file_data_done() { /// several FileData frames, and its end. #[test] fn one_poll_moves_every_frame_a_ready_stream_takes() { - struct Open(Vec); - impl ByteStream for Open { + use stela_soc::usb::mux::{Mux, StreamId, test_support::connected}; + + struct MuxSink { + mux: Mux, + stream: StreamId, + bytes: Vec, + writes: Vec, + } + impl ByteStream for MuxSink { fn read(&mut self, _: &mut [u8]) -> Poll> { Poll::Pending } fn write(&mut self, b: &[u8]) -> Poll> { - self.0.extend_from_slice(b); - Poll::Ready(Ok(b.len())) + let n = self.mux.write(self.stream, b).map_err(Error::Transport)?; + if n == 0 { + return Poll::Pending; + } + let packet = self.mux.take_packet().expect("mux write emitted a packet"); + // Mux v2 header and fixed TCP header. + assert_eq!(packet.len(), 36 + n); + self.bytes.extend_from_slice(&packet[36..]); + self.writes.push(n); + Poll::Ready(Ok(n)) } } - let data = vec![5; 4 * FILE_CHUNK + 1]; + let data = vec![5; FILE_BATCH_BYTES + 1]; let mut answers = Answers::new(fixture(&data, false)); answers.store.prepare().unwrap(); let request = Value::dict([ @@ -395,12 +445,86 @@ fn one_poll_moves_every_frame_a_ready_stream_takes() { ]); let plan = answers.plan(&request).unwrap(); let mut job = Job::new(1, Some(2345), request, plan); - let mut stream = Open(Vec::new()); + let (mux, stream) = connected(); + let mut stream = MuxSink { + mux, + stream, + bytes: Vec::new(), + writes: Vec::new(), + }; assert!(matches!( job.poll(&mut stream, &mut answers.store), Poll::Ready(Ok(())) )); - assert!(stream.0.len() > data.len()); + let mut expected = Vec::new(); + for chunk in data.chunks(FILE_CHUNK) { + let frame = plist::encode_binary( + &Value::dict([("FileData", Value::Data(chunk.to_vec()))]), + Limits::default(), + ) + .unwrap(); + expected.extend((frame.len() as u32).to_be_bytes()); + expected.extend(frame); + } + let done = plist::encode_binary( + &Value::dict([("FileDataDone", Value::Boolean(true))]), + Limits::default(), + ) + .unwrap(); + expected.extend((done.len() as u32).to_be_bytes()); + expected.extend(done); + assert_eq!(stream.bytes, expected); + assert_eq!(stream.writes.len(), 3); + assert_eq!(stream.writes[0], FILE_BATCH_BYTES + 4 * 104); +} + +#[test] +fn blocked_file_data_keeps_its_offset_and_a_partial_write_refusal_is_terminal() { + let data = vec![5; MAX_READ_BYTES + 1]; + let mut answers = Answers::new(fixture(&data, false)); + answers.store.prepare().unwrap(); + let request = Value::dict([ + ("DataType", Value::from("SourceBootObjectV4")), + ("Arguments", Value::dict([("ImageName", Value::from("OS"))])), + ]); + let plan = answers.plan(&request).unwrap(); + let mut job = Job::new(1, Some(2345), request, plan); + let mut stream = Memory::new(Vec::new(), 31); + job.prefetch(&mut answers.store, 1).unwrap(); + let offset = (MAX_READ_BYTES - FILE_BATCH_BYTES) as u64; + job.offset = offset; + assert!( + job.poll_with_source(&mut stream, &mut answers.store, true) + .is_pending() + ); + assert_eq!((job.offset, stream.output.len()), (offset, 0)); + job.prefetch(&mut answers.store, 1).unwrap(); + assert_eq!(job.window.at, 0); + assert!( + job.poll_with_source(&mut stream, &mut answers.store, true) + .is_pending() + ); + assert_eq!((job.offset, stream.output.len()), (offset, 31)); + let last_frame = 3 * (FILE_CHUNK + 104); + stream.chunk = last_frame - 31; + assert!( + job.poll_with_source(&mut stream, &mut answers.store, true) + .is_pending() + ); + assert_eq!((job.offset, stream.output.len()), (offset, last_frame)); + job.prefetch(&mut answers.store, 1).unwrap(); + assert_eq!(job.window.at, MAX_READ_BYTES as u64); + stream.chunk = 0; + assert!(matches!( + job.poll_with_source(&mut stream, &mut answers.store, true), + Poll::Ready(Err(_)) + )); + stream.chunk = FILE_BATCH_BYTES; + assert!(matches!( + job.poll_with_source(&mut stream, &mut answers.store, true), + Poll::Ready(Err(_)) + )); + assert_eq!((job.offset, stream.output.len()), (offset, last_frame)); } #[test] fn unknown_updater_recovery_policy_and_failure_status_keep_full_context() { diff --git a/crates/stela-runtime/src/restore/store.rs b/crates/stela-runtime/src/restore/store.rs index c0e378471b..5ccd62e989 100644 --- a/crates/stela-runtime/src/restore/store.rs +++ b/crates/stela-runtime/src/restore/store.rs @@ -23,7 +23,7 @@ use super::{ plist::{self, Limits, Value}, }; use alloc::{ - collections::BTreeMap, + collections::{BTreeMap, VecDeque}, string::{String, ToString}, vec::Vec, }; @@ -31,9 +31,11 @@ use sha2::{Digest, Sha384}; use stela_contracts::refuse; use stela_crypto::Sha256; use { - stela_formats::payload::MemberRead, stela_formats::payload::PayloadManifest, - stela_formats::payload::Purpose, stela_formats::payload::ReadAt, - stela_formats::payload::zip::Archive, stela_formats::payload::zip::Entry, + stela_formats::payload::MemberRead, + stela_formats::payload::PayloadManifest, + stela_formats::payload::Purpose, + stela_formats::payload::ReadAt, + stela_formats::payload::zip::{Archive, Entry, Progress}, }; pub const BLOCK_BYTES: usize = stela_formats::payload::HASH_BLOCK_BYTES as usize; @@ -95,6 +97,50 @@ struct Verified { /// reach. whole: Option<(u64, Sha384)>, } +/// A few simultaneous streams can share one IPSW. Keep their positions +/// separate, with bounded inflater buffers, so alternating reads do not +/// replay each deflated member from byte zero. +#[derive(Default)] +struct Cursors(VecDeque<(String, Progress)>); + +impl Cursors { + // Each deflate cursor owns a 64 KiB input buffer, a 32 KiB window, + // and the decoder state. Stored cursors have no inflater allocation. + const LIMIT: usize = 6; + + fn read( + &mut self, + archive: &Archive, + reader: &mut R, + entry: &Entry, + offset: u64, + output: &mut [u8], + ) -> Result<()> { + let cached = self + .0 + .iter() + .position(|(name, _)| *name == entry.name) + .and_then(|index| self.0.remove(index)); + let (name, mut progress) = match cached { + Some((name, progress)) => (Some(name), Some(progress)), + None => (None, None), + }; + archive + .read_member_resuming(reader, entry, &mut progress, offset, output) + .map_err(payload)?; + if let Some(progress) = progress + && progress.produced() < entry.bytes + { + if self.0.len() == Self::LIMIT { + self.0.pop_front(); + } + self.0 + .push_back((name.unwrap_or_else(|| entry.name.clone()), progress)); + } + Ok(()) + } +} + pub struct Store { reader: R, archive: Archive, @@ -106,10 +152,7 @@ pub struct Store { verified: BTreeMap, block_count: usize, verify: Verify, - /// The most recently read member and its resumable inflate position, so - /// reading a deflate member block by block inflates it once rather than - /// replaying it from the start each block. - cursor: Option<(String, stela_formats::payload::zip::Progress)>, + cursors: Cursors, } fn payload(error: impl core::fmt::Debug) -> Error { Error::Payload(refuse!("payload: {error}", ?error)) @@ -210,12 +253,16 @@ impl Store { verified: BTreeMap::new(), block_count: 0, verify: Verify::Full, - cursor: None, + cursors: Cursors::default(), }) } pub fn manifest(&self) -> &PayloadManifest { &self.manifest } + pub(super) fn release_cursors(&mut self) { + self.cursors.0.clear(); + } + pub fn reader_mut(&mut self) -> &mut R { &mut self.reader } @@ -247,10 +294,11 @@ impl Store { .iter() .map(|m| m.name.clone()) .collect(); + let mut buffer = Vec::new(); for path in paths { match self.verified.get(&path) { Some(recorded) if recorded.whole.is_some() && self.verify == Verify::Full => { - self.check_whole(&path)? + self.check_whole(&path, &mut buffer)? } Some(_) => {} None => self.verify(&path)?, @@ -330,22 +378,24 @@ impl Store { /// Blocks `blocks` of a member with recorded or scanned hashes, each /// checked against its hash: one read of the source, so the storage /// under it moves the whole run in its largest transfers. - fn blocks(&mut self, path: &str, blocks: core::ops::Range) -> Result> { - let size = self.member_len(path)?; + fn read_blocks( + &mut self, + path: &str, + blocks: core::ops::Range, + bytes: &mut Vec, + ) -> Result<()> { let verified = &self.verified[path]; let start = blocks.start * BLOCK_BYTES as u64; - let end = (blocks.end * BLOCK_BYTES as u64).min(size); - let entry = verified.entry.clone(); - let mut bytes = vec![0; (end - start) as usize]; - let mut progress = match self.cursor.take() { - Some((p, progress)) if p == path => Some(progress), - _ => None, - }; - self.archive - .read_member_resuming(&mut self.reader, &entry, &mut progress, start, &mut bytes) - .map_err(payload)?; - self.cursor = progress.map(|progress| (path.to_string(), progress)); - let expected = &self.verified[path].blocks[blocks.start as usize..blocks.end as usize]; + let end = (blocks.end * BLOCK_BYTES as u64).min(verified.entry.bytes); + bytes.resize((end - start) as usize, 0); + self.cursors.read( + &self.archive, + &mut self.reader, + &verified.entry, + start, + bytes, + )?; + let expected = &verified.blocks[blocks.start as usize..blocks.end as usize]; for (index, (block, expected)) in bytes.chunks(BLOCK_BYTES).zip(expected).enumerate() { let actual: [u8; 32] = Sha256::digest(block).into(); if actual != *expected { @@ -356,16 +406,17 @@ impl Store { ))); } } - Ok(bytes) + Ok(()) } /// Read a member with recorded hashes whole, checking each block and /// then its SHA-384. - fn check_whole(&mut self, path: &str) -> Result<()> { + fn check_whole(&mut self, path: &str, buffer: &mut Vec) -> Result<()> { let blocks = self.verified[path].blocks.len() as u64; let run = (MAX_READ_BYTES / BLOCK_BYTES) as u64; let mut hash = Sha384::new(); for first in (0..blocks).step_by(run as usize) { - hash.update(self.blocks(path, first..(first + run).min(blocks))?); + self.read_blocks(path, first..(first + run).min(blocks), buffer)?; + hash.update(&*buffer); } let verified = self.verified.get_mut(path).expect("recorded"); if Some(<[u8; 48]>::from(hash.finalize())) != verified.sha384 { @@ -495,7 +546,12 @@ impl Store { } let block = BLOCK_BYTES as u64; let first = offset / block; - let mut result = self.blocks(path, first..(offset + len as u64).div_ceil(block))?; + let mut result = Vec::new(); + self.read_blocks( + path, + first..(offset + len as u64).div_ceil(block), + &mut result, + )?; result.drain(..(offset - first * block) as usize); result.truncate(len); let verified = self.verified.get_mut(path).expect("verified above"); @@ -520,16 +576,10 @@ impl Store { } /// A device-verified member's bytes, as read. fn read_unhashed(&mut self, path: &str, offset: u64, len: usize) -> Result> { - let entry = self.verified[path].entry.clone(); + let entry = &self.verified[path].entry; let mut bytes = vec![0; len]; - let mut progress = match self.cursor.take() { - Some((p, progress)) if p == path => Some(progress), - _ => None, - }; - self.archive - .read_member_resuming(&mut self.reader, &entry, &mut progress, offset, &mut bytes) - .map_err(payload)?; - self.cursor = progress.map(|progress| (path.to_string(), progress)); + self.cursors + .read(&self.archive, &mut self.reader, entry, offset, &mut bytes)?; Ok(bytes) } pub fn read_component(&mut self, name: &str, offset: u64, len: usize) -> Result> { diff --git a/crates/stela-runtime/src/restore/store/tests.rs b/crates/stela-runtime/src/restore/store/tests.rs index 2758ded72b..c4e0687a90 100644 --- a/crates/stela-runtime/src/restore/store/tests.rs +++ b/crates/stela-runtime/src/restore/store/tests.rs @@ -186,7 +186,7 @@ fn precomputed(s: &mut Store, data: &[u8]) -> Vec { #[test] fn recorded_hashes_check_every_member_before_the_restore_by_default() { - let data: Vec = (0..BLOCK_BYTES * 2 + 5).map(|i| (i * 7) as u8).collect(); + let data: Vec = (0..MAX_READ_BYTES + 5).map(|i| (i * 7) as u8).collect(); let mut s = fixture(&data, true); let file = precomputed(&mut s, &data); s.adopt_block_hashes(&file).unwrap(); @@ -198,12 +198,13 @@ fn recorded_hashes_check_every_member_before_the_restore_by_default() { // The same records refuse a changed block or SHA-384 by name. let mut s = fixture(&data, true); let mut file = precomputed(&mut s, &data); - file[64] ^= 1; + let last = file.len() - 32; + file[last] ^= 1; s.manifest.block_hashes.as_mut().unwrap().sha256 = stela_formats::sha256(&file); s.adopt_block_hashes(&file).unwrap(); let error = s.prepare().unwrap_err().to_string(); assert!( - error.contains("os.dmg: source changed at block 2"), + error.contains("os.dmg: source changed at block 16"), "{error}" ); let mut s = fixture(&data, false); @@ -360,3 +361,65 @@ fn corrupt_inventory_fails_before_any_bytes_are_returned() { assert!(s.read_at("os.dmg", 0, 1).is_err()); assert!(s.verified.is_empty()); } + +#[test] +fn interleaved_deflated_members_resume_without_replaying_prefixes() { + struct Counting { + source: Memory, + bytes: usize, + } + impl ReadAt for Counting { + type Error = &'static str; + + fn len(&self) -> u64 { + self.source.len() + } + + fn read_at( + &mut self, + offset: u64, + buffer: &mut [u8], + ) -> core::result::Result<(), Self::Error> { + self.bytes += buffer.len(); + self.source.read_at(offset, buffer) + } + } + + let contents = |mut state: u32| -> Vec { + (0..8 * BLOCK_BYTES) + .map(|_| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state as u8 + }) + .collect() + }; + let data = contents(0x5a); + let other = contents(0x61); + let (source, manifest) = parts(&data, true, &[("Extra", "extra.dmg", &other)], &[], ERASE); + let mut store = Store::open(Counting { source, bytes: 0 }, manifest, 0).unwrap(); + store.prepare().unwrap(); + let mut read_both = |discard_cursors| { + store.reader.bytes = 0; + for offset in (0..data.len()).step_by(BLOCK_BYTES) { + for (path, expected) in [("os.dmg", &data), ("extra.dmg", &other)] { + if discard_cursors { + store.cursors.0.clear(); + } + assert_eq!( + store.read_at(path, offset as u64, BLOCK_BYTES).unwrap(), + expected[offset..offset + BLOCK_BYTES] + ); + } + } + store.reader.bytes + }; + + let resumed = read_both(false); + let replayed = read_both(true); + assert!( + replayed >= 4 * resumed, + "resumed {resumed}, replayed {replayed}" + ); +} diff --git a/crates/stela-runtime/src/restore/stream.rs b/crates/stela-runtime/src/restore/stream.rs index 20f7bfc9ee..4649fa45df 100644 --- a/crates/stela-runtime/src/restore/stream.rs +++ b/crates/stela-runtime/src/restore/stream.rs @@ -128,6 +128,34 @@ impl Framed { self.output .queue(bytes, self.limits.bytes.saturating_add(4)) } + /// Queue consecutive binary FileData frames and return the final frame's + /// byte offset in the send buffer. + pub(super) fn queue_file_data<'a>( + &mut self, + chunks: impl IntoIterator, + ) -> Result { + if self.failed { + return Err(Error::Invalid("framing stream failed")); + } + if self.output.is_pending() { + return Err(Error::Invalid("output already pending")); + } + let out = &mut self.output.bytes; + let mut last = 0; + for data in chunks { + let at = out.len(); + last = at; + out.resize(at + 4, 0); + match plist::append_file_data(out, data, self.limits) { + Ok(length) => out[at..at + 4].copy_from_slice(&self.endian.encode(length)), + Err(error) => { + out.clear(); + return Err(error); + } + } + } + Ok(last) + } pub fn poll_send(&mut self, s: &mut impl ByteStream) -> Poll> { if self.failed { return Poll::Ready(Err(Error::Invalid("framing stream failed"))); @@ -335,6 +363,51 @@ pub(crate) mod tests { } } #[test] + fn file_data_reuses_the_frame_buffer_and_preserves_the_wire_bytes() { + let limits = Limits::default(); + for endian in [Endian::Big, Endian::Little] { + let mut frame = Framed::new(endian, limits); + let mut stream = Memory::new(Vec::new(), 31); + for len in [8192, 0, 1, 14, 15, 8192] { + let data = vec![0x5a; len]; + let expected = plist::encode_binary( + &Value::dict([("FileData", Value::Data(data.clone()))]), + limits, + ) + .unwrap(); + let buffer = frame.output.bytes.as_ptr(); + let capacity = frame.output.bytes.capacity(); + frame.queue_file_data([data.as_slice()]).unwrap(); + if capacity >= frame.output.bytes.len() { + assert_eq!(frame.output.bytes.as_ptr(), buffer); + } + assert!(frame.queue_file_data([b"pending".as_slice()]).is_err()); + while frame.sending() { + if let Poll::Ready(result) = frame.poll_send(&mut stream) { + result.unwrap(); + } + } + assert_eq!(&stream.output[..4], &endian.encode(expected.len() as u32)); + assert_eq!(&stream.output[4..], expected); + stream.output.clear(); + } + } + let mut limited = Framed::new( + Endian::Big, + Limits { + bytes: 100, + ..limits + }, + ); + assert!( + limited + .queue_file_data([b"ok".as_slice(), &[0; 100]]) + .is_err() + ); + assert!(limited.queue_file_data([[0; 40].as_slice()]).is_err()); + assert!(!limited.sending()); + } + #[test] fn untrusted_lengths_fail_before_body_allocation() { let mut f = Framed::new( Endian::Big, diff --git a/crates/stela-soc/src/aic.rs b/crates/stela-soc/src/aic.rs index 0cd2de0ce6..a08df29d4c 100644 --- a/crates/stela-soc/src/aic.rs +++ b/crates/stela-soc/src/aic.rs @@ -204,7 +204,7 @@ pub struct Aic2 { software: Vec, hardware: Vec, mask: Vec, - irq_level: Vec, + irq_level: u64, /// The CPUs whose SIQ_CFG_EL1 refuses IRQs ([`Aic2::steer`]). refusing: u64, } @@ -289,7 +289,11 @@ impl Aic2 { )); } let span = layout.validate(&config).map_err(Aic2Error::InvalidConfig)?; - let words = usize::from(config.max_irq / 32) * layout.dies.len(); + // The register decoder exposes only implemented entries. Keep the + // inter-die stride, but omit unaddressable trailing state. + let preceding = usize::from(config.max_irq) * (layout.dies.len() - 1); + let interrupts = preceding + usize::from(config.nr_irq); + let words = interrupts.div_ceil(32); Ok(Self { lifecycle: LifecycleState { powered: true, @@ -300,11 +304,11 @@ impl Aic2 { }, timestamps: vec![Timestamp::default(); config.timestamps], enabled: false, - irq_cfg: vec![0; usize::from(config.max_irq) * layout.dies.len()], + irq_cfg: vec![0; interrupts], software: vec![0; words], hardware: vec![0; words], mask: vec![u32::MAX; words], - irq_level: vec![false; config.cpus], + irq_level: 0, refusing: 0, config, layout, @@ -421,32 +425,53 @@ impl Aic2 { } self.update(access); } + fn accepting_cpus(&self) -> u64 { + if self.enabled && self.lifecycle.clocked && !self.lifecycle.quiesced { + self.config.default_cpus & !self.refusing + } else { + 0 + } + } + + fn first_pending(&self) -> Option { + // Hardware inputs are range-checked. Bank writes exclude padding + // independently on each die, so the lowest set bit is implemented. + self.software + .iter() + .zip(&self.hardware) + .zip(&self.mask) + .enumerate() + .find_map(|(word, ((software, hardware), mask))| { + let pending = (software | hardware) & !mask; + (pending != 0).then(|| word * 32 + pending.trailing_zeros() as usize) + }) + } + /// The highest-priority deliverable IRQ for `cpu`. fn pending_for(&self, cpu: CpuIndex) -> Option { - if !self.enabled - || !self.lifecycle.clocked - || self.lifecycle.quiesced - || self.refusing & 1 << cpu != 0 - || self.config.default_cpus & 1 << cpu == 0 - { + if self.accepting_cpus() & 1 << cpu == 0 { return None; } - (0..self.software.len()) - .flat_map(|word| { - let pending = (self.software[word] | self.hardware[word]) & !self.mask[word]; - (0..32) - .filter(move |bit| pending & 1 << bit != 0) - .map(move |bit| word * 32 + bit) - }) - .find(|&irq| irq % usize::from(self.config.max_irq) < usize::from(self.config.nr_irq)) + self.first_pending() } + fn update(&mut self, access: &mut Access<'_>) { - for cpu in 0..self.config.cpus { - let level = self.pending_for(cpu).is_some(); - if self.irq_level[cpu] != level { - self.irq_level[cpu] = level; - access.interrupts.set_level(Wire::Irq(cpu), level); - } + // TARGET0 is shared by the eligible CPUs. Scan the pending bank once. + let accepting = self.accepting_cpus(); + let level = if accepting != 0 && self.first_pending().is_some() { + accepting + } else { + 0 + }; + let mut changed = self.irq_level ^ level; + self.irq_level = level; + while changed != 0 { + let cpu = changed.trailing_zeros() as usize; + let bit = 1 << cpu; + access + .interrupts + .set_level(Wire::Irq(cpu), level & bit != 0); + changed ^= bit; } } fn decode(&self, offset: u64) -> Option { diff --git a/crates/stela-soc/src/aic/tests.rs b/crates/stela-soc/src/aic/tests.rs index 7f02aa7b6b..5021834415 100644 --- a/crates/stela-soc/src/aic/tests.rs +++ b/crates/stela-soc/src/aic/tests.rs @@ -418,6 +418,70 @@ fn two_dies() -> (Aic2Config, Aic2Layout) { (config, layout) } +#[test] +fn the_last_die_omits_unaddressable_trailing_state() { + let (mut config, layout) = two_dies(); + config.nr_irq = 32; + let die = layout.dies[1]; + let mut aic = Aic2::new_with_layout(config, layout).unwrap(); + let mut latch = InterruptLatch::new(); + write(&mut aic, &mut latch, CONFIG, CONFIG_ENABLE); + assert_eq!(aic.irq_cfg.len(), 96); + assert_eq!(aic.software.len(), 3); + for bank in [ + die.software_set, + die.software_clear, + die.mask_set, + die.mask_clear, + die.hardware_state, + ] { + let mut access = Access::new(0, 0, &mut latch); + assert!(aic.write(bank + 4, Width::Word, 0, &mut access).is_err()); + assert!(aic.read(bank + 4, Width::Word, &mut access).is_err()); + } + assert_eq!(read(&mut aic, &mut latch, 0, EVENT), 0); + + write(&mut aic, &mut latch, die.mask_clear, 1 << 31); + write(&mut aic, &mut latch, die.software_set, 1 << 31); + assert_eq!( + read(&mut aic, &mut latch, 0, EVENT), + 1 << 24 | EVENT_TYPE_IRQ | 31 + ); +} + +#[test] +fn two_eligible_cpus_claim_valid_words_in_die_priority_order() { + let (mut config, layout) = two_dies(); + config.cpus = 64; + config.default_cpus = 1 | 1 << 63; + let (first, second) = (layout.dies[0], layout.dies[1]); + let mut aic = Aic2::new_with_layout(config, layout).unwrap(); + let mut latch = InterruptLatch::new(); + write(&mut aic, &mut latch, CONFIG, CONFIG_ENABLE); + write(&mut aic, &mut latch, first.mask_clear + 4, u32::MAX); + write(&mut aic, &mut latch, first.software_set + 4, u32::MAX); + write(&mut aic, &mut latch, second.mask_clear, 1); + write(&mut aic, &mut latch, second.software_set, 1); + + assert!(latch.pins(0).irq && latch.pins(63).irq); + assert!(!latch.pins(1).irq); + assert_eq!(read(&mut aic, &mut latch, 63, EVENT), EVENT_TYPE_IRQ | 32); + assert!(latch.pins(0).irq && latch.pins(63).irq); + aic.steer(63, true, &mut Access::new(0, 0, &mut latch)); + assert!(latch.pins(0).irq && !latch.pins(63).irq); + assert_eq!(read(&mut aic, &mut latch, 63, EVENT), 0); + assert_eq!( + read(&mut aic, &mut latch, 0, EVENT), + 1 << 24 | EVENT_TYPE_IRQ + ); + assert_eq!( + read(&mut aic, &mut latch, 0, EVENT), + 0, + "padding stays masked" + ); + assert!(!latch.pins(0).irq && !latch.pins(63).irq); +} + #[test] fn explicit_layout_routes_claims_masks_and_timestamps_independently_per_die() { let (config, layout) = two_dies(); @@ -562,7 +626,7 @@ fn unqualified_irq_cfg_selectors_and_delays_refuse_without_effects() { aic.software.clone(), aic.hardware.clone(), aic.mask.clone(), - aic.irq_level.clone(), + aic.irq_level, aic.refusing, aic.timestamps .iter() @@ -587,7 +651,7 @@ fn unqualified_irq_cfg_selectors_and_delays_refuse_without_effects() { aic.software.clone(), aic.hardware.clone(), aic.mask.clone(), - aic.irq_level.clone(), + aic.irq_level, aic.refusing, aic.timestamps .iter() diff --git a/crates/stela-soc/src/ans/commands.rs b/crates/stela-soc/src/ans/commands.rs index f4a38cf1a7..5d94141aec 100644 --- a/crates/stela-soc/src/ans/commands.rs +++ b/crates/stela-soc/src/ans/commands.rs @@ -766,7 +766,7 @@ impl Ans { { return Err(refuse!("ANS Flush fields are not modeled")); } - return self.host(key, vec![Request::Flush], Wait::Flush, port); + return self.host(key, Some(Request::Flush), Wait::Flush, port); } if cmd.opcode() == REPRIORITIZE { // The medium serves I/O in arrival order, without tiers, so there @@ -796,20 +796,19 @@ impl Ans { } let blocks = u64::from((controls & 0xffff) + 1); let lba = cmd.long(40); - if self.medium.address(cmd.nsid(), lba, blocks).is_none() { + let nsid = cmd.nsid(); + let Some(address) = self.medium.address(nsid, lba, blocks) else { return Ok(Executed::Done(Outcome::status(LBA_RANGE))); - } + }; let bytes = blocks as usize * BLOCK_BYTES as usize; if bytes > MAX_TRANSFER { return Ok(Executed::Done(Outcome::status(INVALID_FIELD))); } let prps = cmd.prps(port, bytes, NVMMU_PAGE_BYTES)?; - let (nsid, range) = (cmd.nsid(), "ANS I/O range was checked"); match cmd.opcode() { READ | COMPARE => { - let plan = self.medium.plan_read(nsid, lba, blocks).expect(range); + let plan = self.medium.plan_read(address, blocks); let request = plan.address.map(|lba| Request::Read { lba, bytes }); - let requests = request.into_iter().collect(); let wait = if cmd.opcode() == READ { let inline = inline.map(|key| (key, unit)); Wait::Read { @@ -823,7 +822,7 @@ impl Ans { prps.read(port, &mut data)?; Wait::Compare { plan, data } }; - self.host(key, requests, wait, port) + self.host(key, request, wait, port) } WRITE => { let mut data = vec![0; bytes]; @@ -831,7 +830,6 @@ impl Ans { if let Some(key) = &inline { key.transform(unit, &mut data, true)?; } - let address = self.medium.address(nsid, lba, blocks).expect(range); // Force Unit Access: this write completes durably whatever // the cache. A read returns the same bytes either way. let request = Request::Write { @@ -839,26 +837,26 @@ impl Ans { data, durable: self.write_through() || controls & FORCE_UNIT_ACCESS != 0, }; - self.host(key, vec![request], Wait::Write { nsid, lba, blocks }, port) + self.host(key, Some(request), Wait::Write { nsid, lba, blocks }, port) } _ => Err(refuse!("ANS I/O command is not modeled")), } } - /// Submit an I/O command's host transfers under `key`, none for a read + /// Submit an I/O command's host request under `key`, none for a read /// of erased blocks alone, and finish the command at once unless the - /// host disk completes them later ([`super::host`]). + /// host disk completes it later ([`super::host`]). fn host( &mut self, key: u32, - requests: Vec, + request: Option, wait: Wait, port: &mut Port<'_, '_>, ) -> Result { - if requests.is_empty() { + let Some(request) = request else { return self.finish(wait, None, port).map(Executed::Done); - } - match self.medium.device.submit(key, requests, port.access.now) { + }; + match self.medium.device.submit(key, request, port.access.now) { Some(done) => self.finish(wait, Some(done), port).map(Executed::Done), None => Ok(Executed::Host(wait)), } diff --git a/crates/stela-soc/src/ans/host.rs b/crates/stela-soc/src/ans/host.rs index c0725882ac..a5eeafd858 100644 --- a/crates/stela-soc/src/ans/host.rs +++ b/crates/stela-soc/src/ans/host.rs @@ -48,8 +48,8 @@ struct Discards { /// The batch on the disk and its runs. running: Option<(Submission, Vec)>, /// Transfers waiting for discards: each one's key, when it was - /// submitted and its requests. - held: Vec<(u32, u64, Vec)>, + /// submitted and its request. + held: Vec<(u32, u64, Request)>, /// Why the disk refused a batch. Discards are hints, so it hears no /// more; a flush has nothing to wait for. failed: Option, @@ -184,40 +184,31 @@ impl HostDisk { self.discards.outstanding() } - /// Whether `requests` must wait for discards. Their writes take their - /// blocks back whatever the answer. - fn held(&mut self, requests: &[Request]) -> bool { - let block = u64::from(self.identity().block_size); - let zeros = self.deallocates_zeroed(); - requests.iter().fold(false, |held, request| { - held | match request { - Request::Write { lba, data, .. } => self - .discards - .written(*lba, *lba + data.len() as u64 / block), - Request::WriteZeroes { lba, blocks, .. } => { - self.discards.written(*lba, *lba + *blocks) - } - Request::Flush => zeros && self.discards.outstanding(), - _ => false, + /// Whether `request` must wait for discards. A write takes its blocks + /// back whatever the answer. + fn held(&mut self, request: &Request) -> bool { + match request { + Request::Write { lba, data, .. } => { + let block = u64::from(self.identity().block_size); + self.discards + .written(*lba, *lba + data.len() as u64 / block) } - }) + Request::WriteZeroes { lba, blocks, .. } => self.discards.written(*lba, *lba + *blocks), + Request::Flush => self.discards.outstanding() && self.deallocates_zeroed(), + _ => false, + } } - /// Submit `requests`, one after another, under `key` at counter `now`: - /// their result if the first poll finishes them, else `None` until + /// Submit `request` under `key` at counter `now`: its result if the + /// first poll finishes it, else `None` until /// [`Self::poll`] gives it. Synchronous providers can also yield after /// the block layer's command admission limit. - pub(super) fn submit( - &mut self, - key: u32, - requests: Vec, - now: u64, - ) -> Option { - if self.held(&requests) { - self.discards.held.push((key, now, requests)); + pub(super) fn submit(&mut self, key: u32, request: Request, now: u64) -> Option { + if self.held(&request) { + self.discards.held.push((key, now, request)); return None; } - let mut submission = match Submission::batch(requests, self.device.identity()) { + let mut submission = match Submission::new(request, self.device.identity()) { Ok(submission) => submission, Err(error) => return Some(Err(error)), }; @@ -274,8 +265,8 @@ impl HostDisk { self.refuse_discards(error); } } - for (key, started, requests) in core::mem::take(&mut self.discards.held) { - if let Some(finished) = self.submit(key, requests, started) { + for (key, started, request) in core::mem::take(&mut self.discards.held) { + if let Some(finished) = self.submit(key, request, started) { done.push((key, finished)); } } diff --git a/crates/stela-soc/src/ans/host/tests.rs b/crates/stela-soc/src/ans/host/tests.rs index 08619ac810..74536453f5 100644 --- a/crates/stela-soc/src/ans/host/tests.rs +++ b/crates/stela-soc/src/ans/host/tests.rs @@ -115,12 +115,12 @@ fn queued(ranges: usize, unmap: bool) -> (HostDisk, Log) { (HostDisk::new(Box::new(device)), log) } -fn write(lba: u64) -> Vec { - vec![Request::Write { +fn write(lba: u64) -> Request { + Request::Write { lba, data: vec![7; 4096], durable: false, - }] + } } fn release(log: &Log, tag: u32) { @@ -185,7 +185,7 @@ fn a_flush_waits_for_discards_only_where_deallocated_blocks_stay_zeros() { for zeros in [true, false] { let (mut disk, log) = queued(256, zeros); disk.discard(0, 8); - assert!(disk.submit(1, vec![Request::Flush], 0).is_none()); + assert!(disk.submit(1, Request::Flush, 0).is_none()); assert_eq!(disk.discards.held.len(), usize::from(zeros)); if zeros { disk.poll(0); diff --git a/crates/stela-soc/src/ans/namespace.rs b/crates/stela-soc/src/ans/namespace.rs index f725334c56..bcdd19036c 100644 --- a/crates/stela-soc/src/ans/namespace.rs +++ b/crates/stela-soc/src/ans/namespace.rs @@ -222,22 +222,19 @@ impl Medium { Ok(()) } - /// The host address of a read of `blocks` blocks of namespace `id` at - /// `lba`, for the host disk to serve later, and the byte ranges of it - /// that read as zeros; no address when every block does. - pub fn plan_read(&self, id: u32, lba: u64, blocks: u64) -> Option { - let address = self.address(id, lba, blocks)?; + /// The already validated host address and the byte ranges of this read + /// that return zeros. Omit the host read when every block returns zero. + pub fn plan_read(&self, address: u64, blocks: u64) -> ReadPlan { let start = address / self.host_blocks_per_lba; let end = start + blocks; let at = |block: u64| ((block - start) * u64::from(BLOCK_BYTES)) as usize; - Some(ReadPlan { - address: (!self.erased.covers(start, end)).then_some(address), - zeros: self - .erased - .overlapping(start, end) - .map(|(s, e)| (at(s), at(e))) - .collect(), - }) + let mut overlaps = self.erased.overlapping(start, end).peekable(); + let all_erased = overlaps.peek() == Some(&(start, end)) + || (start == end && self.erased.covers(start, end)); + ReadPlan { + address: (!all_erased).then_some(address), + zeros: overlaps.map(|(s, e)| (at(s), at(e))).collect(), + } } /// `blocks` blocks of namespace `id` at `lba` were written: they hold @@ -406,6 +403,36 @@ mod tests { (medium, host) } + #[test] + fn read_plans_distinguish_erased_blocks_from_untouched_and_partial_reads() { + for block_size in [512, 4096] { + let (mut medium, _) = erasable(block_size); + medium.deallocate(2, 10, 5).unwrap(); + medium.deallocate(2, 20, 2).unwrap(); + let block = BLOCK_BYTES as usize; + for (lba, blocks, host, zeros) in [ + (8, 2, true, &[][..]), + (10, 4, false, &[(0, 4 * block)]), + (9, 14, true, &[(11 * block, 13 * block), (block, 6 * block)]), + (15, 0, false, &[]), + (19, 0, true, &[]), + ] { + let address = medium.address(2, lba, blocks).unwrap(); + let plan = medium.plan_read(address, blocks); + assert_eq!(plan.address, host.then_some(address)); + assert_eq!(plan.zeros, zeros); + let mut expected = alloc::vec![0x5a; blocks as usize * block]; + for &(start, end) in zeros { + expected[start..end].fill(0); + } + assert_eq!( + plan.finish(expected.len(), Some(alloc::vec![0x5a; expected.len()])), + expected + ); + } + } + } + #[test] fn erased_namespace_reads_zero_until_written_and_the_host_is_never_zeroed() { for block_size in [512, 4096] { diff --git a/crates/stela-soc/src/ans/prp.rs b/crates/stela-soc/src/ans/prp.rs index 06d003bbc8..ee0bde295f 100644 --- a/crates/stela-soc/src/ans/prp.rs +++ b/crates/stela-soc/src/ans/prp.rs @@ -13,6 +13,8 @@ use stela_contracts::refuse; use {stela_contracts::dma::DmaError, stela_contracts::dma::Port}; pub(super) const MAX_TRANSFER: usize = 1024 * 1024; +const ENTRY_BYTES: usize = size_of::(); +const LIST_READ_ENTRIES: usize = 16; pub(super) fn dma_error(error: DmaError) -> Refusal { match error { @@ -33,7 +35,13 @@ fn dma_error_at(address: u64, bytes: usize) -> impl FnOnce(DmaError) -> Refusal } } -pub(super) struct Prps(Vec<(u64, usize)>); +/// Direct transfers keep their ranges inline. Indirect transfers reserve +/// space for every data page the validated byte count can reach. +pub(super) enum Prps { + One([(u64, usize); 1]), + Two([(u64, usize); 2]), + List(Vec<(u64, usize)>), +} impl Prps { pub fn new( @@ -49,15 +57,14 @@ impl Prps { if first == 0 || !first.is_multiple_of(4) { return Err(refuse!("ANS PRP1 is null or not dword-aligned")); } - let mut ranges = Vec::new(); let first_bytes = bytes.min((page - first % page) as usize); first .checked_add(first_bytes as u64 - 1) .ok_or(refuse!("ANS PRP1 wraps"))?; - ranges.push((first, first_bytes)); + let first = (first, first_bytes); let mut remaining = bytes - first_bytes; if remaining == 0 { - return Ok(Self(ranges)); + return Ok(Self::One([first])); } if remaining <= page as usize { if second == 0 || !second.is_multiple_of(page) { @@ -66,42 +73,78 @@ impl Prps { second .checked_add(remaining as u64 - 1) .ok_or(refuse!("ANS PRP2 wraps"))?; - ranges.push((second, remaining)); - return Ok(Self(ranges)); + return Ok(Self::Two([first, (second, remaining)])); } if second == 0 || !second.is_multiple_of(8) { return Err(refuse!("ANS PRP list pointer is null or not qword-aligned")); } + let mut ranges = Vec::with_capacity(1 + remaining.div_ceil(page as usize)); + ranges.push(first); let mut entry = second; + let mut list = [0; ENTRY_BYTES * LIST_READ_ENTRIES]; + let mut read_entries = LIST_READ_ENTRIES; while remaining != 0 { - let mut pointer = [0; 8]; - port.read(entry, &mut pointer) - .map_err(dma_error_at(entry, pointer.len()))?; - let pointer = u64::from_le_bytes(pointer); - if pointer == 0 || !pointer.is_multiple_of(page) { - return Err(refuse!("ANS PRP list contains a null or unaligned page")); - } - let last_in_page = (entry + 8).is_multiple_of(page); - if last_in_page && remaining > page as usize { - entry = pointer; + let page_entries = (page - entry % page) as usize / ENTRY_BYTES; + let entries = remaining + .div_ceil(page as usize) + .min(page_entries) + .min(read_entries); + let bytes = entries * ENTRY_BYTES; + let loaded = port.read_progress(entry, &mut list[..bytes]); + if entries > 1 + && matches!(&loaded, Err(fault) if fault.completed == 0 && fault.error == DmaError::Memory) + { + // Some RAM owners reject a span before reading its first + // byte. Find the failing entry without replaying any prefix. + read_entries = 1; continue; } - let chunk = remaining.min(page as usize); - pointer - .checked_add(chunk as u64 - 1) - .ok_or(refuse!("ANS PRP data address wraps"))?; - ranges.push((pointer, chunk)); - remaining -= chunk; - entry = entry - .checked_add(8) - .ok_or(refuse!("ANS PRP list address wraps"))?; + // The first malformed entry in the readable prefix still takes + // precedence over a fault on a later entry in this fetch. + let readable = loaded + .as_ref() + .err() + .map_or(bytes, |fault| fault.completed.min(bytes - 1)); + for (index, pointer) in list[..readable] + .as_chunks::() + .0 + .iter() + .enumerate() + { + let pointer = u64::from_le_bytes(*pointer); + if pointer == 0 || !pointer.is_multiple_of(page) { + return Err(refuse!("ANS PRP list contains a null or unaligned page")); + } + if index + 1 == page_entries && remaining > page as usize { + entry = pointer; + break; + } + let chunk = remaining.min(page as usize); + pointer + .checked_add(chunk as u64 - 1) + .ok_or(refuse!("ANS PRP data address wraps"))?; + ranges.push((pointer, chunk)); + remaining -= chunk; + entry = entry + .checked_add(ENTRY_BYTES as u64) + .ok_or(refuse!("ANS PRP list address wraps"))?; + } + loaded.map_err(|fault| dma_error_at(entry, ENTRY_BYTES)(fault.error))?; + } + Ok(Self::List(ranges)) + } + + fn ranges(&self) -> &[(u64, usize)] { + match self { + Self::One(ranges) => ranges, + Self::Two(ranges) => ranges, + Self::List(ranges) => ranges, } - Ok(Self(ranges)) } pub fn read(&self, port: &mut Port<'_, '_>, buffer: &mut [u8]) -> Result<()> { let mut at = 0; - for &(address, bytes) in &self.0 { + for &(address, bytes) in self.ranges() { port.read(address, &mut buffer[at..at + bytes]) .map_err(dma_error_at(address, bytes))?; at += bytes; @@ -111,7 +154,7 @@ impl Prps { pub fn write(&self, port: &mut Port<'_, '_>, data: &[u8]) -> Result<()> { let mut at = 0; - for &(address, bytes) in &self.0 { + for &(address, bytes) in self.ranges() { port.write(address, &data[at..at + bytes]) .map_err(dma_error_at(address, bytes))?; at += bytes; @@ -124,8 +167,11 @@ impl Prps { mod tests { use super::*; use { - stela_contracts::bus::Access, stela_contracts::dma::Physical, - stela_contracts::dma::test_support::Ram, stela_contracts::interrupt::InterruptLatch, + stela_contracts::bus::Access, + stela_contracts::dma::test_support::Ram, + stela_contracts::dma::{Memory, Physical, TransferFault}, + stela_contracts::interrupt::InterruptLatch, + stela_contracts::refusal::Value, }; #[test] @@ -155,6 +201,31 @@ mod tests { assert!(Prps::new(&mut port, 0, 0, 4096, 4096).is_err()); } + #[test] + fn direct_prps_keep_an_offset_first_page_and_short_second_page() { + let mut ram = Ram::new(0x8000_0000, 0x8000); + let base = ram.base; + let mut latch = InterruptLatch::new(); + let mut access = Access::new(0, 0, &mut latch); + let mut port = Port { + iommu: &mut Physical, + stream: 0, + memory: &mut ram, + access: &mut access, + }; + let first = base + 0xff0; + let prps = Prps::new(&mut port, first, 0, 16, 4096).unwrap(); + assert!(matches!(prps, Prps::One([(address, 16)]) if address == first)); + let second = base + 0x3000; + let prps = Prps::new(&mut port, first, second, 24, 4096).unwrap(); + assert!(matches!(prps, Prps::Two([(a, 16), (b, 8)]) if (a, b) == (first, second))); + let data: [u8; 24] = core::array::from_fn(|index| index as u8); + prps.write(&mut port, &data).unwrap(); + let mut read = [0; 24]; + prps.read(&mut port, &mut read).unwrap(); + assert_eq!(read, data); + } + #[test] fn a_prp_list_may_start_inside_its_page_and_chains_at_the_page_end() { let mut ram = Ram::new(0x8000_0000, 0x20000); @@ -175,8 +246,8 @@ mod tests { port.write(list + index * 8, &page.to_le_bytes()).unwrap(); } let prps = Prps::new(&mut port, base + 0x1000, list, 21 * 4096, 4096).unwrap(); - assert_eq!(prps.0.len(), 21); - assert_eq!(prps.0[1], (base + 0x2000, 4096)); + assert_eq!(prps.ranges().len(), 21); + assert_eq!(prps.ranges()[1], (base + 0x2000, 4096)); // A list two entries from its page end: one data entry, then the // last slot chains to a page-aligned list page holding the rest. let near_end = base + 0xa000 - 16; @@ -189,7 +260,7 @@ mod tests { port.write(base + 0xb008, &(base + 0xe000).to_le_bytes()) .unwrap(); let prps = Prps::new(&mut port, base + 0x1000, near_end, 4 * 4096, 4096).unwrap(); - let pages: Vec = prps.0.iter().map(|&(address, _)| address).collect(); + let pages: Vec = prps.ranges().iter().map(|&(address, _)| address).collect(); assert_eq!( pages, [base + 0x1000, base + 0xc000, base + 0xd000, base + 0xe000] @@ -198,4 +269,69 @@ mod tests { assert!(Prps::new(&mut port, base + 0x1000, list + 4, 3 * 4096, 4096).is_err()); assert!(Prps::new(&mut port, base + 0x1000, 0, 3 * 4096, 4096).is_err()); } + + #[test] + fn prp_list_validates_the_readable_prefix_before_reporting_a_later_fault() { + struct ListPage { + first: u64, + partial: bool, + } + + impl Memory for ListPage { + fn read(&mut self, physical: u64, buffer: &mut [u8]) -> bool { + self.read_progress(physical, buffer).is_ok() + } + + fn write(&mut self, _: u64, _: &[u8]) -> bool { + unreachable!() + } + + fn read_progress( + &mut self, + physical: u64, + buffer: &mut [u8], + ) -> core::result::Result<(), TransferFault> { + const LIST: u64 = 0x8000_1000; + if physical == LIST && (buffer.len() == ENTRY_BYTES || self.partial) { + buffer[..ENTRY_BYTES].copy_from_slice(&self.first.to_le_bytes()); + if buffer.len() == ENTRY_BYTES { + return Ok(()); + } + return Err(TransferFault { + error: DmaError::Memory, + completed: ENTRY_BYTES, + }); + } + Err(TransferFault { + error: DmaError::Memory, + completed: 0, + }) + } + } + + let mut latch = InterruptLatch::new(); + let mut access = Access::new(0, 0, &mut latch); + for partial in [false, true] { + for (first, what) in [ + (0, "ANS PRP list contains a null or unaligned page"), + (0x8000_4000, "ANS DMA target is not guest RAM"), + ] { + let mut page = ListPage { first, partial }; + let mut port = Port { + iommu: &mut Physical, + stream: 0, + memory: &mut page, + access: &mut access, + }; + let error = Prps::new(&mut port, 0x8000_2000, 0x8000_1000, 3 * 4096, 4096) + .err() + .expect("the PRP list faults"); + assert_eq!(error.what(), what); + if first != 0 { + assert_eq!(error.value("address"), Some(&Value::Hex(0x8000_1008))); + assert_eq!(error.value("bytes"), Some(&Value::Count(8))); + } + } + } + } } diff --git a/crates/stela-soc/src/dcp.rs b/crates/stela-soc/src/dcp.rs index 79ce2875c5..4724a87f9d 100644 --- a/crates/stela-soc/src/dcp.rs +++ b/crates/stela-soc/src/dcp.rs @@ -95,6 +95,8 @@ pub enum Log { /// The composed layers' surfaces, bottom to top. surfaces: Vec, }, + /// Cumulative presentation progress in the bounded log. + PresentSummary { total: u64, last_swap: u32 }, /// A named refusal, with the call's interface row. Refused(String), /// A method of the interface with no model, answered with zeros. @@ -155,6 +157,9 @@ impl core::fmt::Display for Log { Log::Presented { swap_id, surfaces } => { write!(f, "DCP presented swap {swap_id} surfaces={surfaces:x?}") } + Log::PresentSummary { total, last_swap } => { + write!(f, "DCP present summary total={total} last_swap={last_swap}") + } Log::Refused(text) => write!(f, "DCP refused {text}"), Log::Unmodeled(tag) => { let name = abi::method(tag).map_or("", |row| row.name); @@ -373,6 +378,14 @@ impl Coprocessor { && self.afk.iter().all(|afk| afk.borrow().retained_idle()) } + /// Choose per-swap tracing or bounded presentation reports. + pub fn set_swap_tracing(&mut self, enabled: bool) { + self.link + .borrow_mut() + .service_mut() + .set_swap_tracing(enabled); + } + /// The next display-log entry. pub fn take_log(&mut self) -> Option { if let Some(entry) = self.link.borrow_mut().service_mut().take_log() { diff --git a/crates/stela-soc/src/dcp/iomfb.rs b/crates/stela-soc/src/dcp/iomfb.rs index 42805b8ecd..20b3cd840a 100644 --- a/crates/stela-soc/src/dcp/iomfb.rs +++ b/crates/stela-soc/src/dcp/iomfb.rs @@ -76,6 +76,8 @@ const LOG_CAPACITY: usize = 4096; const LOGGED_INPUT: usize = 64; /// How many `swap_submit_dcp` inputs are logged whole. const DUMPED_SWAPS: u32 = 2; +/// Report progress once this many swaps have reached the scanout. +const PRESENT_SUMMARY_INTERVAL: u64 = 256; /// `IOMFBPARAM_ADAPTIVE_SYNC` (Asahi `iomfb.h`). const ADAPTIVE_SYNC: u32 = 14; /// `D594 swap_complete_ap_gated`'s input starts with the swap ID. Its @@ -143,6 +145,10 @@ pub struct Methods { log: VecDeque, dropped: u64, dumped: u32, + /// Whether to report each swap's calls, present and completion. + trace_swaps: bool, + /// Swaps whose pixels reached the host since this display was placed. + presented: u64, /// The monitor's power and sleep state, shared with its IOAV controller. display: Rc>, /// Open IOMFB clients (`first_client_open` minus `last_client_close`). @@ -222,6 +228,8 @@ impl Methods { log: VecDeque::new(), dropped: 0, dumped: 0, + trace_swaps: true, + presented: 0, display, clients: 0, digital_out: None, @@ -264,6 +272,15 @@ impl Methods { self.last_refusal.as_deref() } + /// Choose per-swap tracing or bounded presentation reports. + pub(super) fn set_swap_tracing(&mut self, enabled: bool) { + self.trace_swaps = enabled; + } + + fn trace_swap(&self, swap_id: u32) -> bool { + self.trace_swaps || swap_id <= DUMPED_SWAPS + } + /// The next display-log entry. pub fn take_log(&mut self) -> Option { self.log.pop_front().or_else(|| { @@ -295,17 +312,24 @@ impl Methods { let Some(frame) = self.frames.front() else { return Ok(()); }; - let mode = self.mode(); - let rows = scanout::compose(&frame.layers, mode, read)?; - self.scanout.present(&rows)?; + scanout::present(self.scanout.as_mut(), &frame.layers, read)?; // Both the surface DMA and host sink can refuse. The submitted swap // owns its surfaces until presentation succeeds, or the AP explicitly // aborts/shuts down; neither failure consumes it or queues D594. let frame = self.frames.pop_front().expect("presented front frame"); - self.record_log(Log::Presented { - swap_id: frame.swap_id, - surfaces: frame.layers.iter().map(|layer| layer.surface).collect(), - }); + self.presented = self.presented.saturating_add(1); + if self.trace_swap(frame.swap_id) { + self.record_log(Log::Presented { + swap_id: frame.swap_id, + surfaces: frame.layers.iter().map(|layer| layer.surface).collect(), + }); + } + if !self.trace_swaps && self.presented.is_multiple_of(PRESENT_SUMMARY_INTERVAL) { + self.record_log(Log::PresentSummary { + total: self.presented, + last_swap: frame.swap_id, + }); + } self.completed.push_back(frame.swap_id); Ok(()) } @@ -426,11 +450,15 @@ impl Methods { impl Service for Methods { fn call(&mut self, tag: [u8; 4], input: &[u8], output: u32) -> Result> { - self.record_log(Log::Call { - tag, - input: input[..input.len().min(LOGGED_INPUT)].to_vec(), - output, - }); + if !matches!(&tag, b"A406" | b"A407") + || self.trace_swap(self.open_swap.unwrap_or(self.next_swap)) + { + self.record_log(Log::Call { + tag, + input: input[..input.len().min(LOGGED_INPUT)].to_vec(), + output, + }); + } let Some(row) = abi::method(&tag) else { return self.refuse(tag, refuse!("tag is not a method of this DCP interface")); }; @@ -746,7 +774,9 @@ impl Service for Methods { input[0..4].copy_from_slice(&swap_id.to_le_bytes()); input[SWAP_COMPLETE_DATA_NULL] = 1; self.in_flight = true; - self.callback_log(SWAP_COMPLETE, length, 0); + if self.trace_swap(swap_id) { + self.callback_log(SWAP_COMPLETE, length, 0); + } Some(Callback { tag: SWAP_COMPLETE, input, diff --git a/crates/stela-soc/src/dcp/iomfb/tests.rs b/crates/stela-soc/src/dcp/iomfb/tests.rs index e2277138a2..c145081c5f 100644 --- a/crates/stela-soc/src/dcp/iomfb/tests.rs +++ b/crates/stela-soc/src/dcp/iomfb/tests.rs @@ -741,6 +741,67 @@ fn a_swap_is_started_submitted_presented_then_completed() { assert!(logged); } +#[test] +fn bounded_swap_logs_keep_boot_samples_failures_and_guest_completions() { + let screen = TestScreen(Rc::default(), Some(MODE)); + let presented = screen.0.clone(); + let mut methods = Methods::new(Box::new(screen)); + methods.set_swap_tracing(false); + let swap = |methods: &mut Methods| { + let id = start_swap(methods); + let input = submission(id, &[]); + assert_eq!(returned(methods.call(*b"A407", &input, 0xc)), [0; 12]); + methods + .present(|_, _| panic!("a clear has no surface DMA")) + .unwrap(); + let callback = methods.take_callback().unwrap(); + assert_eq!(callback.tag, SWAP_COMPLETE); + assert_eq!(&callback.input[..4], &id.to_le_bytes()); + (callback.then)(methods, &[]).unwrap(); + input + }; + let first = swap(&mut methods); + let second = swap(&mut methods); + for _ in 2..=PRESENT_SUMMARY_INTERVAL { + swap(&mut methods); + } + assert_eq!( + presented.borrow().len() as u64, + PRESENT_SUMMARY_INTERVAL + 1 + ); + assert!(methods.call(*b"A407", &first, 0xc).is_err()); + + let records: Vec<_> = core::iter::from_fn(|| methods.take_log()).collect(); + assert_eq!(records.len(), 12); + for (index, input) in [first, second].iter().enumerate() { + let logs = &records[5 * index..][..5]; + let id = index as u32 + 1; + assert!(matches!(&logs[0], Log::Call { tag, .. } if tag == b"A406")); + assert!(matches!(&logs[1], Log::Call { tag, .. } if tag == b"A407")); + assert!( + matches!(&logs[2], Log::Payload { tag, bytes } if tag == b"A407" && bytes == input) + ); + assert!(matches!(&logs[3], Log::Presented { swap_id, .. } if *swap_id == id)); + assert!(matches!(&logs[4], Log::Callback { tag, .. } if *tag == SWAP_COMPLETE)); + } + assert_eq!( + records[10].to_string(), + "DCP present summary total=256 last_swap=256" + ); + assert!( + matches!(&records[11], Log::Refused(reason) if reason.contains("swap_submit_dcp without swap_start_dcp")) + ); + + methods.set_swap_tracing(true); + swap(&mut methods); + let exact: Vec<_> = core::iter::from_fn(|| methods.take_log()).collect(); + assert_eq!(exact.len(), 4); + assert!(matches!(&exact[0], Log::Call { tag, .. } if tag == b"A406")); + assert!(matches!(&exact[1], Log::Call { tag, .. } if tag == b"A407")); + assert!(matches!(&exact[2], Log::Presented { swap_id: 258, .. })); + assert!(matches!(&exact[3], Log::Callback { tag, .. } if *tag == SWAP_COMPLETE)); +} + #[test] fn a_layer_left_out_of_the_mask_keeps_showing() { let screen = TestScreen(Rc::default(), Some(MODE)); diff --git a/crates/stela-soc/src/machine.rs b/crates/stela-soc/src/machine.rs index 9cd9f74589..b3eb32f9ac 100644 --- a/crates/stela-soc/src/machine.rs +++ b/crates/stela-soc/src/machine.rs @@ -250,13 +250,13 @@ const USB_PACKETS_PER_MICROFRAME: usize = 13; /// work under the devices' lock. const USB_BACKLOG_MICROFRAMES: u64 = 8; -/// The packets a poll at `now`, due at `next_poll`, moves: a microframe's -/// for each microframe since the last poll, so one that comes late moves -/// those it missed. -fn usb_packets(now: u64, next_poll: u64) -> usize { - let microframes = - (now.saturating_sub(next_poll) / USB_POLL_TICKS + 1).min(USB_BACKLOG_MICROFRAMES); - microframes as usize * USB_PACKETS_PER_MICROFRAME +/// A due poll's packet budget and the next boundary. A late poll catches +/// up at most one frame while keeping the microframe clock's phase. +fn usb_poll(now: u64, due: u64) -> (usize, u64) { + let late = now - due; + let microframes = (late / USB_POLL_TICKS + 1).min(USB_BACKLOG_MICROFRAMES); + let next = now.saturating_add(USB_POLL_TICKS - late % USB_POLL_TICKS); + (microframes as usize * USB_PACKETS_PER_MICROFRAME, next) } /// A native host handle, owned by this AppleDevices instance. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1483,8 +1483,8 @@ impl AppleDevices { master.attached = true; } if now >= master.next_poll { - let packets = usb_packets(now, master.next_poll); - master.next_poll = now.saturating_add(USB_POLL_TICKS); + let (packets, next) = usb_poll(now, master.next_poll); + master.next_poll = next; let advanced = (|| { // Moving stops where every pending transfer NAKs. for _ in 0..packets { diff --git a/crates/stela-soc/src/machine/coprocessors.rs b/crates/stela-soc/src/machine/coprocessors.rs index 44377f09d2..d963b7bc13 100644 --- a/crates/stela-soc/src/machine/coprocessors.rs +++ b/crates/stela-soc/src/machine/coprocessors.rs @@ -416,13 +416,25 @@ impl AppleDevices { self.smc().ok()?.take_log() } + /// Choose per-swap display tracing or bounded presentation reports. + pub fn set_display_swap_tracing(&mut self, enabled: bool) { + for master in &self.dcp_masters { + if let Some(display) = self + .bus + .device_mut::(master.asc) + .and_then(Asc::firmware_mut::) + { + display.set_swap_tracing(enabled); + } + } + } + /// The next entry of a display coprocessor's log: what the guest sent /// the DCP model and what it answered or refused. pub fn take_display_log(&mut self) -> Option { - let ids: Vec = self.dcp_masters.iter().map(|master| master.asc).collect(); - ids.into_iter().find_map(|id| { + self.dcp_masters.iter().find_map(|master| { self.bus - .device_mut::(id) + .device_mut::(master.asc) .and_then(Asc::firmware_mut::) .and_then(dcp::Coprocessor::take_log) }) diff --git a/crates/stela-soc/src/machine/service.rs b/crates/stela-soc/src/machine/service.rs index 0d15c88210..fb9599058f 100644 --- a/crates/stela-soc/src/machine/service.rs +++ b/crates/stela-soc/src/machine/service.rs @@ -4,6 +4,10 @@ use super::*; use crate::pmgr::DomainTransition; use stela_contracts::refuse; +/// A small reusable input batch covers steady-state device traffic. A larger +/// completed batch gives back its storage. +const RETAINED_INPUTS: usize = 32; + /// A reached wire edge, with the context of its first service attempt. /// Retrying delivery must not move an AIC timestamp to a later counter value. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -48,6 +52,18 @@ pub struct ServiceBatch { } impl ServiceBatch { + fn finish(&mut self) { + let mut inputs = core::mem::take(&mut self.inputs); + inputs.clear(); + if inputs.capacity() > RETAINED_INPUTS { + inputs = Vec::new(); + } + *self = Self { + inputs, + ..Self::default() + }; + } + pub(super) fn retain_reset(&mut self, first: &mut Option, reset: Option) { if let Some(reset) = reset { if first.is_none() { @@ -97,21 +113,15 @@ impl AppleDevices { } fn capture_inputs(&mut self, cpu: CpuIndex, now: u64) { - self.service - .inputs - .extend( - self.latch - .take_aic_inputs() - .into_iter() - .map(|(input, level)| { - ServiceInput::Aic(AicDelivery { - input, - level, - cpu, - now, - }) - }), - ); + self.latch + .append_aic_inputs(&mut self.service.inputs, |(input, level)| { + ServiceInput::Aic(AicDelivery { + input, + level, + cpu, + now, + }) + }); } /// Forward queued wires and CPU releases, keeping exact progress on any @@ -128,7 +138,7 @@ impl AppleDevices { self.capture_reached(cpu, now, None); let result = self.apply_service(); match &result { - Ok(()) => self.service = ServiceBatch::default(), + Ok(()) => self.service.finish(), Err(error) => self.service.failure = Some(error.clone()), } result diff --git a/crates/stela-soc/src/machine/service/tests.rs b/crates/stela-soc/src/machine/service/tests.rs index 6a84935b72..07a33ad300 100644 --- a/crates/stela-soc/src/machine/service/tests.rs +++ b/crates/stela-soc/src/machine/service/tests.rs @@ -124,6 +124,29 @@ fn missing_aic_resumes_original_edges_and_timestamp_after_binding() { ); } +#[test] +fn completed_aic_batches_reuse_only_small_input_buffers() { + let mut board = AppleDevices::new(); + board.add_aic(AIC, 32, AicLayout::V1).unwrap(); + edge(&mut board, 1, true); + board.settle(0, 1, None).unwrap(); + let capacity = board.service.inputs.capacity(); + assert_ne!(capacity, 0); + edge(&mut board, 1, false); + board.settle(0, 2, None).unwrap(); + assert_eq!(board.service.inputs.capacity(), capacity); + assert_eq!(hardware(&mut board), 0); + assert!(board.pending_service().is_none()); + + for index in 0..=RETAINED_INPUTS { + edge(&mut board, 1, index % 2 == 0); + } + board.settle(0, 3, None).unwrap(); + assert_eq!(hardware(&mut board), 1 << 1); + assert!(board.pending_service().is_none()); + assert_eq!(board.service.inputs.capacity(), 0); +} + fn rvbar(board: &mut AppleDevices, pe: usize) { board .add_lockdown( diff --git a/crates/stela-soc/src/machine/tests.rs b/crates/stela-soc/src/machine/tests.rs index 8c92565702..21982ffe9b 100644 --- a/crates/stela-soc/src/machine/tests.rs +++ b/crates/stela-soc/src/machine/tests.rs @@ -3774,12 +3774,26 @@ fn pmgr_shared_usb_leaf_pauses_both_clients_and_cancels_sessions_only_on_reset_o #[test] fn a_late_usb_poll_moves_the_packets_of_the_microframes_it_missed() { - assert_eq!(usb_packets(USB_POLL_TICKS, USB_POLL_TICKS), 13); - assert_eq!(usb_packets(2 * USB_POLL_TICKS - 1, USB_POLL_TICKS), 13); - assert_eq!(usb_packets(3 * USB_POLL_TICKS + 7, USB_POLL_TICKS), 3 * 13); + let frame = USB_POLL_TICKS; + assert_eq!(usb_poll(frame, frame), (13, 2 * frame)); + assert_eq!(usb_poll(2 * frame - 1, frame), (13, 2 * frame)); + assert_eq!(usb_poll(3 * frame + 7, frame), (3 * 13, 4 * frame)); // A frame's at most, as for a session's first poll. - assert_eq!(usb_packets(100 * USB_POLL_TICKS, USB_POLL_TICKS), 8 * 13); - assert_eq!(usb_packets(100 * USB_POLL_TICKS, 0), 8 * 13); + assert_eq!(usb_poll(100 * frame + 7, frame), (8 * 13, 101 * frame)); + assert_eq!(usb_poll(100 * frame, 0), (8 * 13, 101 * frame)); + + // A polling interval just under two microframes must still service + // each elapsed microframe. Resetting the phase loses almost half. + let mut due = frame; + let mut packets = 0; + for poll in 1..=100 { + let now = poll * (2 * frame - 1); + let (budget, next) = usb_poll(now, due); + packets += budget; + due = next; + } + assert_eq!(packets, 199 * 13); + assert_eq!(due, 200 * frame); } #[test] diff --git a/crates/stela-soc/src/scanout.rs b/crates/stela-soc/src/scanout.rs index abd281df7a..e1865333b6 100644 --- a/crates/stela-soc/src/scanout.rs +++ b/crates/stela-soc/src/scanout.rs @@ -81,6 +81,17 @@ pub trait Scanout { /// An error leaves presentation uncommitted; the owner may retry the same /// swap. Validate fallible inputs before publishing host-visible pixels. fn present(&mut self, rows: &[u8]) -> Result<()>; + + /// Present a frame from an ordered producer, keeping each row hidden + /// until the whole frame is ready. Call the producer once per row with + /// exactly `width * 4` bytes to fill, stopping on its first error. + /// A sink without a hidden buffer declines without calling the producer. + fn try_present_rows( + &mut self, + _fill: &mut dyn FnMut(usize, &mut [u8]) -> Result<()>, + ) -> Result { + Ok(false) + } } /// A host framebuffer's 32-bit pixel given as one bit mask per channel: the @@ -218,6 +229,36 @@ impl Layer { premultiplied, }) } + + fn covers_mode(&self, mode: Mode) -> bool { + self.surface.format == mode.format + && self.source.width == mode.width + && self.source.height == mode.height + && self.destination + == (Rect { + x: 0, + y: 0, + width: mode.width, + height: mode.height, + }) + } + + fn read_row( + &self, + from_y: u64, + out: &mut [u8], + read: &mut impl FnMut(u64, &mut [u8]) -> bool, + ) -> Result<()> { + let iova = (u64::from(self.source.y) + from_y) + .checked_mul(self.surface.stride.into()) + .and_then(|offset| offset.checked_add(u64::from(self.source.x) * 4)) + .and_then(|offset| self.surface.iova.checked_add(offset)) + .ok_or(refuse!("layer row address overflows"))?; + if !read(iova, out) { + return Err(refuse!("surface row is not reachable through its DART")); + } + Ok(()) + } } /// `value * weight / 255`, rounded. @@ -277,6 +318,89 @@ fn copy_opaque(source: &[u8], out: &mut [u8], from: PixelFormat, to: PixelFormat } } +/// Copy a same-format straight-alpha row over black without reading the +/// destination or calculating coordinates for individual pixels. +#[inline(never)] +fn copy_straight_over_black(pixels: &[u8], out: &mut [u8]) { + for (out, pixel) in out + .as_chunks_mut::<4>() + .0 + .iter_mut() + .zip(pixels.as_chunks::<4>().0) + { + *out = straight_over_black(*pixel); + } +} + +#[inline] +fn straight_over_black(pixel: [u8; 4]) -> [u8; 4] { + let alpha = u32::from(pixel[3]); + [ + scale(u32::from(pixel[0]), alpha) as u8, + scale(u32::from(pixel[1]), alpha) as u8, + scale(u32::from(pixel[2]), alpha) as u8, + 0xff, + ] +} + +/// Blend an unscaled row already in the scanout's channel order. +#[inline(never)] +fn blend_row(pixels: &[u8], out: &mut [u8], premultiplied: bool) { + const LANES: u32 = 0x00ff_00ff; + // Two independent 8-bit channels in 16-bit lanes. For products up to + // 255², the shifts give the same rounded quotient as (product + 127) / 255. + let scale = |lanes: u32, weight: u32| { + let biased = lanes * weight + 0x0080_0080; + ((biased + ((biased >> 8) & LANES)) >> 8) & LANES + }; + for (out, pixel) in out + .as_chunks_mut::<4>() + .0 + .iter_mut() + .zip(pixels.as_chunks::<4>().0) + { + let below = u32::from_le_bytes(*out); + let source = u32::from_le_bytes(*pixel); + let alpha = u32::from(pixel[3]); + let blend = |source: u32, below: u32| { + let source = source & LANES; + let source = if premultiplied { + source + } else { + scale(source, alpha) + }; + let sum = source + scale(below & LANES, 255 - alpha); + let overflow = (sum & 0x0100_0100) >> 8; + (sum | (overflow * 255)) & LANES + }; + let even = blend(source, below); + let green = blend(source >> 8, below >> 8) & 0xff; + *out = (even | (green << 8) | 0xff00_0000).to_le_bytes(); + } +} + +/// Present a matching fullscreen layer directly to a sink that can hide +/// unfinished rows. Other compositions need the complete packed frame. +pub(crate) fn present( + sink: &mut dyn Scanout, + layers: &[Layer], + mut read: impl FnMut(u64, &mut [u8]) -> bool, +) -> Result<()> { + let mode = sink.mode(); + if let [layer] = layers + && mode.format.red_blue().is_some() + && layer.covers_mode(mode) + && sink.try_present_rows(&mut |y, row| { + layer.read_row(y as u64, row, &mut read)?; + make_opaque(row, layer.premultiplied); + Ok(()) + })? + { + return Ok(()); + } + sink.present(&compose(layers, mode, read)?) +} + /// Compose `layers`, bottom to top, over opaque black on `mode`'s screen and /// return the frame for one [`Scanout::present`]: the mode's rows in its /// pixel order, alpha opaque. `read` fills a byte range of a surface from @@ -298,14 +422,23 @@ pub fn compose( mut read: impl FnMut(u64, &mut [u8]) -> bool, ) -> Result> { let width = mode.width as usize; - let mut frame = [0, 0, 0, 0xff].repeat(width * mode.height as usize); let (red, blue) = mode .format .red_blue() .ok_or(refuse!("scanout mode is not an 8-bit format"))?; + // A matching bottom layer replaces every output pixel. Its DART rows + // can be read into the frame without first filling opaque black or + // routing the pixels through the scratch row. + let direct_base = layers.first().is_some_and(|layer| layer.covers_mode(mode)); + let pixels = width * mode.height as usize; + let mut frame = if direct_base { + alloc::vec![0; pixels * 4] + } else { + [0, 0, 0, 0xff].repeat(pixels) + }; let mut row = Vec::new(); let mut drawn: Vec<([usize; 2], [usize; 2])> = Vec::new(); - for layer in layers { + for (index, layer) in layers.iter().enumerate() { let (surface, source, destination) = (layer.surface, layer.source, layer.destination); let Some((xs, ys)) = on_screen(destination, mode.width, mode.height) else { continue; @@ -315,19 +448,20 @@ pub fn compose( .iter() .any(|(x, y)| x[0] < xs[1] && xs[0] < x[1] && y[0] < ys[1] && ys[0] < y[1]); let copies = surface.format.red_blue().is_some(); - row.resize(source.width as usize * 4, 0); + let direct = index == 0 && direct_base; + if !direct { + row.resize(source.width as usize * 4, 0); + } for y in ys[0]..ys[1] { let from_y = (2 * (y as u64 - u64::from(destination.y)) + 1) * u64::from(source.height) / (2 * u64::from(destination.height)); - let iova = (u64::from(source.y) + from_y) - .checked_mul(surface.stride.into()) - .and_then(|offset| offset.checked_add(u64::from(source.x) * 4)) - .and_then(|offset| surface.iova.checked_add(offset)) - .ok_or(refuse!("layer row address overflows"))?; - if !read(iova, &mut row) { - return Err(refuse!("surface row is not reachable through its DART")); - } let out = &mut frame[(y * width + xs[0]) * 4..(y * width + xs[1]) * 4]; + let input = if direct { &mut *out } else { &mut row[..] }; + layer.read_row(from_y, input, &mut read)?; + if direct { + make_opaque(out, layer.premultiplied); + continue; + } if unscaled && copies { let start = (xs[0] - destination.x as usize) * 4; let pixels = &row[start..start + out.len()]; @@ -337,6 +471,14 @@ pub fn compose( copy_opaque(pixels, out, surface.format, mode.format); continue; } + if over_black && surface.format == mode.format { + copy_straight_over_black(pixels, out); + continue; + } + if surface.format == mode.format { + blend_row(pixels, out, layer.premultiplied); + continue; + } } for (x, out) in (xs[0]..xs[1]).zip(out.as_chunks_mut::<4>().0) { let from_x = (2 * (x as u64 - u64::from(destination.x)) + 1) @@ -363,6 +505,28 @@ pub fn compose( Ok(frame) } +fn make_opaque(row: &mut [u8], premultiplied: bool) { + if !row.iter().skip(3).step_by(4).all(|&alpha| alpha == 0xff) { + opaque_over_black(row, premultiplied); + } +} + +/// The bottom layer covers this row. Alpha is opaque after composition +/// over black even if the source is translucent. +#[inline(never)] +fn opaque_over_black(row: &mut [u8], premultiplied: bool) { + let pixels = row.as_chunks_mut::<4>().0; + if premultiplied { + for pixel in pixels { + *pixel = (u32::from_le_bytes(*pixel) | 0xff00_0000).to_le_bytes(); + } + return; + } + for pixel in pixels { + *pixel = straight_over_black(*pixel); + } +} + #[cfg(test)] mod tests { use super::*; @@ -540,6 +704,35 @@ mod tests { .collect() } + #[test] + fn overlapping_rows_round_and_saturate_each_channel_independently() { + for premultiplied in [false, true] { + for alpha in 0..=255 { + for value in 0..=255 { + let source = [value, 255 - value, value ^ 0x55, alpha]; + let below = [value ^ 0xaa, value, 255 - value, 0xff]; + let mut actual = below; + blend_row(&source, &mut actual, premultiplied); + let alpha = u32::from(alpha); + let mut expected = below; + for (channel, (source, below)) in + source.into_iter().zip(below).take(3).enumerate() + { + let source = u32::from(source); + let source = if premultiplied { + source + } else { + scale(source, alpha) + }; + expected[channel] = + (source + scale(u32::from(below), 255 - alpha)).min(255) as u8; + } + assert_eq!(actual, expected); + } + } + } + } + #[test] fn the_fast_paths_compose_the_frames_the_general_path_does() { // A seeded xorshift draws surfaces (some opaque, some with random @@ -620,6 +813,150 @@ mod tests { } } + #[test] + fn a_full_base_composes_over_black_and_preserves_row_dma_boundaries() { + let base = Layer::new( + surface(6, 3, 32, 8), + Rect { + x: 1, + y: 1, + ..Rect::whole(4, 2) + }, + Rect::whole(4, 2), + false, + ) + .unwrap(); + let overlay = Layer::new( + surface(2, 1, 8, 112), + Rect::whole(2, 1), + Rect { + x: 3, + y: 1, + ..Rect::whole(2, 1) + }, + true, + ) + .unwrap(); + let mut memory = [0; 128]; + for (index, byte) in memory.iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(37); + } + memory[47] = 0; + memory[51] = 0xff; + for premultiplied in [false, true] { + let layers = [ + Layer { + premultiplied, + ..base + }, + overlay, + ]; + let mut reads = Vec::new(); + let mut outputs = Vec::new(); + let frame = compose(&layers, MODE, |iova, bytes| { + reads.push((iova, bytes.len())); + outputs.push(bytes.as_ptr()); + reader(&memory)(iova, bytes) + }) + .unwrap(); + assert_eq!(reads, [(44, 16), (76, 16), (112, 8)]); + assert_eq!( + outputs[..2], + [frame.as_ptr(), frame.as_ptr().wrapping_add(16)] + ); + assert_eq!(frame, reference(&layers, MODE, &memory)); + } + + // An unreachable row leaves the frame unpublished and the later + // overlay unread. + let mut reads = Vec::new(); + assert!( + compose(&[base, overlay], MODE, |iova, bytes| { + reads.push(iova); + bytes[0] = 99; + iova != 76 + }) + .is_err() + ); + assert_eq!(reads, [44, 76]); + } + + #[test] + fn hidden_rows_preserve_fullscreen_dma_order_and_pixels() { + #[derive(Default)] + struct Hidden { + visible: Vec, + streamed: usize, + } + + impl Scanout for Hidden { + fn mode(&self) -> Mode { + MODE + } + + fn present(&mut self, rows: &[u8]) -> Result<()> { + self.visible = rows.to_vec(); + Ok(()) + } + + fn try_present_rows( + &mut self, + fill: &mut dyn FnMut(usize, &mut [u8]) -> Result<()>, + ) -> Result { + let mut rows = [0; 32]; + for (y, row) in rows.as_chunks_mut::<16>().0.iter_mut().enumerate() { + fill(y, row)?; + } + self.streamed += 1; + self.present(&rows)?; + Ok(true) + } + } + + let layer = Layer::new( + surface(6, 3, 32, 8), + Rect { + x: 1, + y: 1, + ..Rect::whole(4, 2) + }, + Rect::whole(4, 2), + false, + ) + .unwrap(); + let memory: Vec = (0..112).map(|i| (i as u8).wrapping_mul(37)).collect(); + let mut sink = Hidden::default(); + for premultiplied in [false, true] { + let layers = [Layer { + premultiplied, + ..layer + }]; + let old_visible = sink.visible.clone(); + let mut reads = Vec::new(); + assert!( + present(&mut sink, &layers, |iova, row| { + reads.push((iova, row.len())); + reader(&memory)(iova, row) && iova != 76 + }) + .is_err() + ); + assert_eq!(reads, [(44, 16), (76, 16)]); + assert_eq!(sink.visible, old_visible); + reads.clear(); + present(&mut sink, &layers, |iova, row| { + reads.push((iova, row.len())); + reader(&memory)(iova, row) + }) + .unwrap(); + assert_eq!(reads, [(44, 16), (76, 16)]); + assert_eq!(sink.visible, reference(&layers, MODE, &memory)); + } + assert_eq!(sink.streamed, 2); + present(&mut sink, &[layer; 2], reader(&memory)).unwrap(); + assert_eq!(sink.visible, reference(&[layer; 2], MODE, &memory)); + assert_eq!(sink.streamed, 2); + } + #[test] fn bad_rectangles_and_unreachable_surfaces_refuse() { let surface = surface(2, 2, 8, 0); diff --git a/crates/stela-soc/src/usb/host.rs b/crates/stela-soc/src/usb/host.rs index 3fb4c881b9..4e349b879e 100644 --- a/crates/stela-soc/src/usb/host.rs +++ b/crates/stela-soc/src/usb/host.rs @@ -371,7 +371,16 @@ impl Host { if data.len() > MAX_TRANSFER { return Err(refuse!("USB host transfer bound exceeded")); } - self.submit(false, data.to_vec(), data.len(), terminate_with_zlp) + self.submit_out_owned(data.to_vec(), terminate_with_zlp) + } + /// The same transfer, keeping an existing frame buffer through completion. + pub(super) fn submit_out_owned( + &mut self, + data: Vec, + terminate_with_zlp: bool, + ) -> Result { + let length = data.len(); + self.submit(false, data, length, terminate_with_zlp) } /// A bulk IN of up to `length` bytes, pending until the device sends. pub fn submit_in(&mut self, length: usize) -> Result { @@ -576,7 +585,7 @@ impl Host { else { continue; }; - let mut transfer = self.bulk.remove(position).unwrap(); + let transfer = &mut self.bulk[position]; let endpoints = self.endpoints.unwrap(); let (endpoint, token) = if transfer.input { (endpoints.input, Token::In) @@ -589,22 +598,12 @@ impl Host { packet[..length] .copy_from_slice(&transfer.data[transfer.done..transfer.done + length]); } - let reply = match peer.packet(endpoint, token, &mut packet[..length]) { - Ok(reply) => reply, - Err(error) => { - self.bulk.insert(position, transfer); - return Err(error); - } - }; + let reply = peer.packet(endpoint, token, &mut packet[..length])?; let status = match reply { - Reply::Nak => { - self.bulk.insert(position, transfer); - continue; - } + Reply::Nak => continue, Reply::Stall => Some(TransferStatus::Stall), Reply::Ack(bytes) => { if bytes > length || (!transfer.input && bytes != length) { - self.bulk.insert(position, transfer); return Err(refuse!( "USB peer returned an invalid bulk acknowledgement length" )); @@ -620,14 +619,13 @@ impl Host { }; self.prefer_input = !transfer.input; if let Some(status) = status { + let transfer = self.bulk.remove(position).unwrap(); self.completions.push_back(Completion { id: transfer.id, status, bytes: transfer.data, transferred: transfer.done, }); - } else { - self.bulk.insert(position, transfer); } return Ok(true); } @@ -809,4 +807,46 @@ mod tests { assert!(!host.advance(&mut peer, 0).unwrap()); assert_eq!(peer.0, 2); } + + #[test] + fn a_failed_bulk_packet_preserves_progress_and_queue_order() { + struct Peer { + fail: bool, + seen: Vec, + } + impl BusPeer for Peer { + fn reset(&mut self) -> Result<()> { + Ok(()) + } + fn packet(&mut self, _: u8, token: Token, data: &mut [u8]) -> Result { + assert_eq!(token, Token::Out); + if self.fail { + return Err(refuse!("test USB peer failure")); + } + self.seen.push(data[0]); + Ok(Reply::Ack(data.len())) + } + } + let mut host = Host::new(); + host.state = Enumerate::Ready; + host.endpoints = mux_endpoints(&configuration(0x85, 9)).unwrap(); + let mut bytes = [1; 1024]; + bytes[512..].fill(2); + let first = host.submit_out(&bytes, false).unwrap(); + let second = host.submit_out(&[3; 17], false).unwrap(); + let mut peer = Peer { + fail: false, + seen: Vec::new(), + }; + assert!(host.advance(&mut peer, 0).unwrap()); + peer.fail = true; + assert!(host.advance(&mut peer, 0).is_err()); + assert!(host.completion().is_none()); + peer.fail = false; + assert!(host.advance(&mut peer, 0).unwrap()); + assert_eq!(host.completion().unwrap().id, first); + assert!(host.advance(&mut peer, 0).unwrap()); + assert_eq!(host.completion().unwrap().id, second); + assert_eq!(peer.seen, [1, 2, 3]); + } } diff --git a/crates/stela-soc/src/usb/mux.rs b/crates/stela-soc/src/usb/mux.rs index 95e6ea269b..86cf37204a 100644 --- a/crates/stela-soc/src/usb/mux.rs +++ b/crates/stela-soc/src/usb/mux.rs @@ -116,7 +116,7 @@ impl Mux { version.extend_from_slice(&2u32.to_be_bytes()); version.extend_from_slice(&0u32.to_be_bytes()); version.extend_from_slice(&0u32.to_be_bytes()); - mux.emit(VERSION, &version) + mux.emit(VERSION, &version, &[]) .expect("one version frame fits the empty queue"); mux } @@ -169,9 +169,9 @@ impl Mux { && bytes <= MAX_FRAME && self.queued_bytes + bytes <= MAX_QUEUED_BYTES } - fn emit(&mut self, protocol: u32, payload: &[u8]) -> Result<()> { + fn emit(&mut self, protocol: u32, prefix: &[u8], data: &[u8]) -> Result<()> { let header = self.header(); - let bytes = header + payload.len(); + let bytes = header + prefix.len() + data.len(); if bytes > TX_MTU || !self.can_emit(bytes) { return Err(refuse!("usbmux transmit queue backpressure")); } @@ -188,7 +188,8 @@ impl Mux { packet.extend_from_slice(&self.rx_sequence.to_be_bytes()); self.tx_sequence = self.tx_sequence.wrapping_add(1); } - packet.extend_from_slice(payload); + packet.extend_from_slice(prefix); + packet.extend_from_slice(data); self.outgoing.push_back(packet); self.queued_bytes += bytes; Ok(()) @@ -248,17 +249,15 @@ impl Mux { } fn send_tcp(&mut self, index: usize, flags: u8, sequence: u32, data: &[u8]) -> Result<()> { let stream = &self.streams[index]; - let mut payload = tcp_header( + let header = tcp_header( stream.id.port, stream.destination, sequence, stream.received, flags, ((RX_WINDOW - stream.input.len()) >> 8) as u16, - ) - .to_vec(); - payload.extend_from_slice(data); - self.emit(TCP, &payload)?; + ); + self.emit(TCP, &header, data)?; // Every segment carries the current ACK, and an RST ends the stream. self.streams[index].reply = None; Ok(()) @@ -336,43 +335,57 @@ impl Mux { /// Consumes fragmented/coalesced bulk bytes, including empty USB ZLPs. /// Parsing is length-bounded before reserving space. A protocol error /// terminates this connection; reset is the only recovery path. - pub fn receive(&mut self, mut bytes: &[u8]) -> Result<()> { + pub fn receive(&mut self, bytes: &[u8]) -> Result<()> { if self.state == State::Failed { return Err(refuse!("usbmux connection requires reset")); } - let result = self.receive_inner(&mut bytes); + let result = self.receive_inner(bytes); if result.is_err() { self.state = State::Failed; } self.flush_replies(); result } - fn receive_inner(&mut self, bytes: &mut &[u8]) -> Result<()> { + fn frame_length(&self, bytes: &[u8]) -> Result { + let length = u32::from_be_bytes(bytes[4..8].try_into().unwrap()) as usize; + if length < self.header() || length > MAX_FRAME { + return Err(refuse!("invalid usbmux frame length")); + } + Ok(length) + } + fn receive_inner(&mut self, mut bytes: &[u8]) -> Result<()> { while !bytes.is_empty() { - let target = if self.receive.len() < VERSION_HEADER { - VERSION_HEADER - } else { - let length = u32::from_be_bytes(self.receive[4..8].try_into().unwrap()) as usize; - if length < self.header() || length > MAX_FRAME { - return Err(refuse!("invalid usbmux frame length")); + // ACKs and other complete frames can be handled directly in + // the bulk transfer that delivered them. + if self.receive.is_empty() && bytes.len() >= VERSION_HEADER { + let length = self.frame_length(bytes)?; + if let Some((packet, rest)) = bytes.split_at_checked(length) { + self.input(packet)?; + bytes = rest; + continue; } - length - }; - let count = (target - self.receive.len()).min(bytes.len()); - self.receive.extend_from_slice(&bytes[..count]); - *bytes = &bytes[count..]; + } if self.receive.len() < VERSION_HEADER { - continue; + let missing = VERSION_HEADER - self.receive.len(); + let (header, rest) = bytes.split_at(missing.min(bytes.len())); + self.receive.extend_from_slice(header); + bytes = rest; + if self.receive.len() < VERSION_HEADER { + break; + } } - let length = u32::from_be_bytes(self.receive[4..8].try_into().unwrap()) as usize; - if length < self.header() || length > MAX_FRAME { - return Err(refuse!("invalid usbmux frame length")); + let length = self.frame_length(&self.receive)?; + let missing = length - self.receive.len(); + let (fragment, rest) = bytes.split_at(missing.min(bytes.len())); + self.receive.extend_from_slice(fragment); + bytes = rest; + if self.receive.len() == length { + let mut packet = core::mem::take(&mut self.receive); + let result = self.input(&packet); + packet.clear(); + self.receive = packet; + result?; } - if self.receive.len() != length { - continue; - } - let packet = core::mem::take(&mut self.receive); - self.input(&packet)?; } Ok(()) } @@ -401,7 +414,7 @@ impl Mux { } self.version = major; if major == 2 { - self.emit(SETUP, &[7])?; + self.emit(SETUP, &[7], &[])?; } self.state = State::Active; } @@ -440,7 +453,11 @@ impl Mux { // With the queue full the RST is dropped, as a lost segment // would be; the peer's next segment draws another. if flags & RST == 0 && self.can_emit(self.header() + TCP_HEADER) { - self.emit(TCP, &tcp_header(destination, source, 0, sequence, RST, 0))?; + self.emit( + TCP, + &tcp_header(destination, source, 0, sequence, RST, 0), + &[], + )?; } return Ok(()); }; @@ -528,7 +545,7 @@ pub mod test_support { mux.outgoing.clear(); mux.queued_bytes = 0; mux.version = version; - mux.emit(protocol, payload).unwrap(); + mux.emit(protocol, payload, &[]).unwrap(); mux.take_packet().unwrap() } pub(crate) fn version(major: u32) -> Vec { @@ -636,6 +653,23 @@ mod tests { assert!(mux.stream_state(id).is_err()); } #[test] + fn complete_and_split_frames_switch_header_sizes_during_negotiation() { + let mut bytes = version(2); + bytes.extend(wire(CONTROL, b"first", 2)); + bytes.extend(wire(CONTROL, b"second", 2)); + for split in 0..=bytes.len() { + let mut mux = Mux::new(); + mux.take_packet().unwrap(); + mux.receive(&bytes[..split]).unwrap(); + mux.receive(&bytes[split..]).unwrap(); + assert_eq!(mux.state(), State::Active); + assert_eq!(mux.take_packet().unwrap()[MUX2_HEADER..], [7]); + assert_eq!(mux.take_log().as_deref(), Some(b"first".as_slice())); + assert_eq!(mux.take_log().as_deref(), Some(b"second".as_slice())); + assert!(mux.receive.is_empty()); + } + } + #[test] fn sequence_wrap_windows_and_close() { let (mut mux, id) = connected(); let stream = &mut mux.streams[0]; @@ -697,7 +731,7 @@ mod tests { mux.open(62078).unwrap(); } assert!(mux.open(62078).is_err()); - while mux.emit(CONTROL, b"log").is_ok() {} + while mux.emit(CONTROL, b"log", &[]).is_ok() {} assert!(mux.queued_bytes <= MAX_QUEUED_BYTES); assert!(mux.outgoing.len() <= MAX_QUEUED); } @@ -720,7 +754,7 @@ mod tests { mux.streams[0].window = u32::MAX; while mux.write(id, &[0; 4096]).unwrap() != 0 {} while mux.write(id, b"x").unwrap() != 0 {} - while mux.emit(CONTROL, &[]).is_ok() {} + while mux.emit(CONTROL, &[], &[]).is_ok() {} assert!(!mux.control_ready()); let sent = mux.streams[0].next; for sequence in [1, 3] { diff --git a/crates/stela-soc/src/usb/session.rs b/crates/stela-soc/src/usb/session.rs index 15782633ee..84f0018af0 100644 --- a/crates/stela-soc/src/usb/session.rs +++ b/crates/stela-soc/src/usb/session.rs @@ -211,10 +211,8 @@ impl Session { { // A full-size last USB packet is followed by a ZLP; the mux // frame length remains independent of that USB terminator. - self.output = Some( - self.host - .submit_out(&packet, packet.len().is_multiple_of(MAX_PACKET))?, - ); + let terminate = packet.len().is_multiple_of(MAX_PACKET); + self.output = Some(self.host.submit_out_owned(packet, terminate)?); submitted = true; } Ok(moved || submitted) diff --git a/crates/stela-soc/src/usb/storage.rs b/crates/stela-soc/src/usb/storage.rs index 6c992c73a9..f39c2a2153 100644 --- a/crates/stela-soc/src/usb/storage.rs +++ b/crates/stela-soc/src/usb/storage.rs @@ -109,12 +109,13 @@ enum Plan { enum Phase { Command, /// Sending: bytes the host still accepts, bytes the device still - /// intends, buffered bytes not yet sent. + /// intends, and the cursor into the current backing read. DataIn { host: u32, device: u64, lba: u64, buffer: Vec, + sent: usize, failed: bool, }, /// Receiving: bytes the host still sends, bytes the write still takes. @@ -587,6 +588,7 @@ impl State { device, lba: 0, buffer: data, + sent: 0, failed: false, }, Plan::Read { lba, .. } => Phase::DataIn { @@ -594,6 +596,7 @@ impl State { device, lba, buffer: Vec::new(), + sent: 0, failed: false, }, Plan::Write { lba, .. } => Phase::DataOut { @@ -636,17 +639,18 @@ impl State { device, lba, buffer, + sent, failed, } => { - if buffer.is_empty() && *device > 0 && !*failed { - // Reads stream from the backing device a chunk at a time. + if *sent == buffer.len() && *device > 0 && !*failed { + // Refill only after the previous chunk has reached the host. let bytes = (*device as usize).min(CHUNK) / size * size; let bytes = bytes.max(size); - let mut chunk = vec![0u8; bytes]; - match self.device.read(*lba, &mut chunk) { + buffer.resize(bytes, 0); + *sent = 0; + match self.device.read(*lba, buffer) { Ok(()) => { *lba += (bytes / size) as u64; - *buffer = chunk; } Err(_) => *failed = true, } @@ -658,9 +662,10 @@ impl State { self.phase = Phase::Status; return Reply::Stall; } - let n = buffer.len().min(*device as usize).min(max); - packet[..n].copy_from_slice(&buffer[..n]); - buffer.drain(..n); + let data = &buffer[*sent..]; + let n = data.len().min(*device as usize).min(max); + packet[..n].copy_from_slice(&data[..n]); + *sent += n; *device -= n as u64; *host -= n as u32; self.pending.residue = *host; diff --git a/crates/stela-soc/src/usb/storage/tests.rs b/crates/stela-soc/src/usb/storage/tests.rs index b9f5da5cac..5a0a7dbc8b 100644 --- a/crates/stela-soc/src/usb/storage/tests.rs +++ b/crates/stela-soc/src/usb/storage/tests.rs @@ -17,18 +17,26 @@ use stela_drivers::{ const SERIAL: &str = "0123456789ABCDEF"; -fn device(blocks: u64, block_size: u32, read_only: bool) -> MassStorage { +fn ram_disk(blocks: u64, block_size: u32, read_only: bool) -> RamDisk { let mut disk = RamDisk::new("host", blocks, block_size); disk.identity.read_only = read_only; for (n, byte) in disk.bytes.iter_mut().enumerate() { *byte = (n / block_size as usize) as u8; } + disk +} + +fn configured(disk: impl BlockDevice + 'static) -> MassStorage { let mut d = MassStorage::new(Box::new(disk), SERIAL, "Host Disk").unwrap(); transfer(&mut d, setup(0, SET_ADDRESS, 2, 0, 0), &[]).unwrap(); transfer(&mut d, setup(0, SET_CONFIGURATION, 1, 0, 0), &[]).unwrap(); d } +fn device(blocks: u64, block_size: u32, read_only: bool) -> MassStorage { + configured(ram_disk(blocks, block_size, read_only)) +} + fn cbw(tag: u32, length: u32, input: bool, cdb: &[u8]) -> Vec { let mut bytes = vec![0u8; CBW_BYTES]; bytes[..4].copy_from_slice(&CBW_SIGNATURE.to_le_bytes()); @@ -223,6 +231,59 @@ fn reads_and_writes_move_whole_blocks_through_chunks() { assert_eq!(status, PASSED); } +#[test] +fn a_failed_refill_stalls_without_replaying_the_previous_chunk() { + struct FailingRead(RamDisk); + impl BlockDevice for FailingRead { + fn identity(&self) -> &stela_drivers::block::Identity { + self.0.identity() + } + + fn read(&mut self, lba: u64, bytes: &mut [u8]) -> Result<(), BlockError> { + if lba == 16 { + return Err(BlockError::Device { status: 1 }); + } + self.0.read(lba, bytes) + } + + fn write(&mut self, lba: u64, bytes: &[u8]) -> Result<(), BlockError> { + self.0.write(lba, bytes) + } + } + + let mut d = configured(FailingRead(ram_disk(32, 4096, false))); + let (data, residue, status) = run( + &mut d, + 1, + 17 * 4096, + true, + &[READ_10, 0, 0, 0, 0, 0, 0, 0, 17, 0], + &[], + ); + assert_eq!((data.len(), residue, status), (CHUNK, 4096, FAILED)); + assert!( + data.as_chunks::<4096>() + .0 + .iter() + .enumerate() + .all(|(lba, block)| block.iter().all(|&byte| byte == lba as u8)) + ); + assert_eq!(sense(&mut d), (3, 0x11)); + + let (data, residue, status) = run( + &mut d, + 2, + 4096, + true, + &[READ_10, 0, 0, 0, 0, 17, 0, 0, 1, 0], + &[], + ); + assert_eq!( + (data.as_slice(), residue, status), + (&[17; 4096][..], 0, PASSED) + ); +} + #[test] fn errors_report_sense_and_mismatched_lengths_follow_the_thirteen_cases() { let mut d = device(64, 512, false); diff --git a/xtask/src/boot.rs b/xtask/src/boot.rs index a3a011fc29..e8fe7c13d6 100644 --- a/xtask/src/boot.rs +++ b/xtask/src/boot.rs @@ -516,10 +516,7 @@ pub fn run(command: Command) -> Result { crate::gpu::fetch::fetch(false)?; crate::gpu::build_nvk(8)?; } - println!( - "{}", - build_with_diagnostics(release, diagnostics, nvk)?.display() - ); + println!("{}", build_for_boot(release, diagnostics, nvk)?.display()); Ok(ExitCode::SUCCESS) } Command::Run(arguments) => launch(*arguments), @@ -533,6 +530,35 @@ pub fn build(release: bool, nvk: bool) -> Result { build_with_diagnostics(release, false, nvk) } +fn build_for_boot(release: bool, diagnostics: bool, nvk: bool) -> Result { + let built = build_with_diagnostics(release, diagnostics, nvk)?; + if !release { + return Ok(built); + } + let image = built.with_file_name("stela-deploy.efi"); + deploy_image(&built, &image)?; + Ok(image) +} + +/// Keep the linked image and its symbols beside a smaller bootable image. +pub(crate) fn deploy_image(built: &Path, output: &Path) -> Result<()> { + let objcopy = crate::tools::toolchain_llvm_tool("llvm-objcopy") + .or_else(|| crate::tools::which("llvm-objcopy")) + .context("install the Rust llvm-tools component to prepare a boot image")?; + let parent = output + .parent() + .context("the boot image needs a parent directory")?; + let temporary = tempfile::NamedTempFile::new_in(parent)?; + exec( + Process::new(objcopy) + .arg("--strip-debug") + .arg(built) + .arg(temporary.path()), + )?; + temporary.persist(output)?; + Ok(()) +} + fn build_with_diagnostics(release: bool, diagnostics: bool, nvk: bool) -> Result { let mut command = cargo(); command.args(["build", "--locked", "--manifest-path", BOOT_MANIFEST]); @@ -702,7 +728,7 @@ fn launch(arguments: Run) -> Result { let attached = storage_disks(&arguments.storage_disk, &arguments.storage_serial)?; let image = match &arguments.image { Some(image) => image.clone(), - None => build_with_diagnostics(true, true, false)?, + None => build_for_boot(true, true, false)?, }; let paths = storage::Paths::new(arguments.output.clone()); if paths.output.exists() { diff --git a/xtask/src/check.rs b/xtask/src/check.rs index 8a3ef2498c..5a871acf7e 100644 --- a/xtask/src/check.rs +++ b/xtask/src/check.rs @@ -8,6 +8,8 @@ //! build in `target`. The tests then run alone. //! A lane stops at its first failure; the gate fails if any part did, once //! every part has finished. +//! Low-memory mode runs the same checks in sequence, with one job per build +//! and one test thread. use crate::tools::{cargo, exec}; use anyhow::{Context, Result, bail}; use std::{ @@ -58,7 +60,8 @@ const CROSS_TARGET_DIR: &str = "target/cross"; const RELEASE_HOST: &str = "aarch64-apple-darwin"; const DENY: [&str; 3] = ["--", "-D", "warnings"]; -pub fn run(fix: bool, nvk: bool) -> Result<()> { +pub fn run(fix: bool, nvk: bool, low_memory: bool) -> Result<()> { + let gpu_jobs = if low_memory { 1 } else { 8 }; if fix { exec(&mut command(["fmt", "--all"]))?; for manifest in FORMATTED_APART { @@ -123,7 +126,7 @@ pub fn run(fix: bool, nvk: bool) -> Result<()> { "--target-dir", BOOT_TARGET_DIR, ]); - linked.env("CARGO_BUILD_JOBS", "8"); + linked.env("CARGO_BUILD_JOBS", gpu_jobs.to_string()); boot_lane.push(linked); } boot_lane.extend(CROSS.map(|(target, packages)| { @@ -158,6 +161,32 @@ pub fn run(fix: bool, nvk: bool) -> Result<()> { build }, ]; + let run_tests = |run: fn(&mut Command) -> Result<()>| { + run(&mut command(test))?; + // The all-feature suite selects the software crypto backend. + // Check the default selector independently as well. + run(&mut command([ + "test", + "--locked", + "-p", + "stela-crypto", + "--no-default-features", + "--lib", + ])) + }; + if low_memory { + for mut format in formatting { + serial(&mut format)?; + } + cross?; + crate::gpu::fetch::fetch(false)?; + if nvk { + crate::gpu::build_nvk(gpu_jobs)?; + } + lane(boot_lane, serial)?; + lane(host_lane, serial)?; + return run_tests(serial); + } let failures: Vec = thread::scope(|scope| { let formatting: Vec<_> = formatting .into_iter() @@ -167,7 +196,7 @@ pub fn run(fix: bool, nvk: bool) -> Result<()> { let lanes = crate::gpu::fetch::fetch(false) .and_then(|()| { if nvk { - crate::gpu::build_nvk(8)?; + crate::gpu::build_nvk(gpu_jobs)?; } Ok(()) }) @@ -177,22 +206,7 @@ pub fn run(fix: bool, nvk: bool) -> Result<()> { let boot = boot.join().expect("the UEFI lane panicked"); // The tests run once nothing else does: some time their fixtures // against the host's clock. - [ - boot, - host.and_then(|()| { - exec(&mut command(test))?; - // The all-feature suite selects the software crypto backend. - // Check the default selector independently as well. - exec(&mut command([ - "test", - "--locked", - "-p", - "stela-crypto", - "--no-default-features", - "--lib", - ])) - }), - ] + [boot, host.and_then(|()| run_tests(exec))] }); let mut results: Vec> = formatting .into_iter() @@ -265,6 +279,14 @@ fn lane(commands: Vec, run: fn(&mut Command) -> Result<()>) -> Result<( Ok(()) } +fn serial(command: &mut Command) -> Result<()> { + exec( + command + .env("CARGO_BUILD_JOBS", "1") + .env("RUST_TEST_THREADS", "1"), + ) +} + /// Run `command` with its output held until it ends, so a part beside the /// streaming lane prints whole. fn buffered(command: &mut Command) -> Result<()> { diff --git a/xtask/src/dist.rs b/xtask/src/dist.rs index 487a5c831a..05f1775e60 100644 --- a/xtask/src/dist.rs +++ b/xtask/src/dist.rs @@ -5,18 +5,12 @@ //! writes it beside the old one on the USB's 200 MiB EFI partition. use crate::tools::{cargo, exec, root}; use anyhow::Result; -use std::process::Command; pub fn run(nvk: bool) -> Result<()> { crate::gpu::fetch::fetch(false)?; let built = crate::boot::build(true, nvk)?; let efi = built.with_file_name("stela-dist.efi"); - exec( - Command::new("llvm-objcopy") - .arg("--strip-debug") - .arg(&built) - .arg(&efi), - )?; + crate::boot::deploy_image(&built, &efi)?; exec( cargo() .args(["build", "--release", "--locked", "-p", "stela-cli"]) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index f714f6c3b3..3a27bb3b61 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -32,6 +32,9 @@ enum Task { /// Also build and check the complete NVIDIA/NVK UEFI image. #[arg(long)] nvk: bool, + /// Run check lanes, build jobs, and tests one at a time. + #[arg(long)] + low_memory: bool, }, /// Build the release `stela` with its matching `stela.efi` embedded. Dist { @@ -66,7 +69,11 @@ enum Task { fn main() -> ExitCode { let result = match Cli::parse().task { - Task::Check { fix, nvk } => check::run(fix, nvk).map(|()| ExitCode::SUCCESS), + Task::Check { + fix, + nvk, + low_memory, + } => check::run(fix, nvk, low_memory).map(|()| ExitCode::SUCCESS), Task::Dist { nvk } => dist::run(nvk).map(|()| ExitCode::SUCCESS), Task::Links => links::run().map(|()| ExitCode::SUCCESS), Task::Oracles(task) => task.run().map(|()| ExitCode::SUCCESS), diff --git a/xtask/src/sysregs/codegen.rs b/xtask/src/sysregs/codegen.rs index 58b36dfff1..9824d0a393 100755 --- a/xtask/src/sysregs/codegen.rs +++ b/xtask/src/sysregs/codegen.rs @@ -262,7 +262,9 @@ impl Generator<'_> { Some(index) => self.int(index)?, None => "0".into(), }; - return Ok(format!("c.error_record(ErrorRecord::{record}, {index})")); + return Ok(format!( + "{{ let index = {index}; c.error_record(ErrorRecord::{record}, index) }}" + )); } if !self.registers.contains(&rust) { self.unknown.insert(format!("register {name}")); @@ -776,7 +778,7 @@ impl Generator<'_> { None => "0".into(), }; format!( - "{{ let value = {value}; c.set_error_record(ErrorRecord::{record}, {index}, value)?; }}" + "{{ let value = {value}; let index = {index}; c.set_error_record(ErrorRecord::{record}, index, value)?; }}" ) } "AST.Function" => { diff --git a/xtask/src/tools.rs b/xtask/src/tools.rs index 81ec94b86c..4aeaab04b1 100644 --- a/xtask/src/tools.rs +++ b/xtask/src/tools.rs @@ -45,6 +45,11 @@ pub fn which(name: impl AsRef) -> Option { /// `llvm-objdump` from the Rust toolchain's `llvm-tools`. pub fn toolchain_objdump() -> Option { + toolchain_llvm_tool("llvm-objdump") +} + +/// Locate a tool bundled with the active Rust toolchain. +pub fn toolchain_llvm_tool(name: &str) -> Option { let output = Command::new(env::var_os("RUSTC").unwrap_or_else(|| "rustc".into())) .args(["--print", "sysroot"]) .output() @@ -53,7 +58,12 @@ pub fn toolchain_objdump() -> Option { fs::read_dir(sysroot.join("lib/rustlib")) .ok()? .filter_map(|entry| entry.ok()) - .map(|entry| entry.path().join("bin/llvm-objdump")) + .map(|entry| { + entry + .path() + .join("bin") + .join(format!("{name}{}", env::consts::EXE_SUFFIX)) + }) .find(|path| path.is_file()) }