diff --git a/crates/stela-boot/src/engine/run.rs b/crates/stela-boot/src/engine/run.rs index c57f04331b..ecfa68e659 100644 --- a/crates/stela-boot/src/engine/run.rs +++ b/crates/stela-boot/src/engine/run.rs @@ -1779,7 +1779,7 @@ fn board_code( let churn = format!( " churn=new/ring/ivau/slot/other:{}/{}/{}/{}/{} same_bytes={} \ ages=turn/four/older:{}/{}/{} aliases=pc/variant:{}/{} ghosts_overwritten={} \ - rebased=hits/proven/unprovable/kib:{}/{}/{}/{}", + rebased=hits/kept/unstorable/kib:{}/{}/{}/{}", churn.new, churn.again[0], churn.again[1], @@ -1793,10 +1793,10 @@ fn board_code( churn.variants, churn.overwritten, now.rebases.hits.saturating_sub(was.rebases.hits), - now.rebases.proven.saturating_sub(was.rebases.proven), + now.rebases.kept.saturating_sub(was.rebases.kept), now.rebases - .unprovable - .saturating_sub(was.rebases.unprovable), + .unstorable + .saturating_sub(was.rebases.unstorable), now.rebases.bytes / 1024, ); // The parts young and tenured code hold, installs sent to the tenured diff --git a/crates/stela-boot/src/engine/translations.rs b/crates/stela-boot/src/engine/translations.rs index 32609bd453..c68dd9ea4e 100644 --- a/crates/stela-boot/src/engine/translations.rs +++ b/crates/stela-boot/src/engine/translations.rs @@ -5,8 +5,9 @@ //! gives this translator the preallocated spare file when it has no pack //! yet, reads as much of the pack as this PC's RAM budget holds and notes //! the volume's GPT partition. The engine reads blocks from the pack -//! ([`install`]) and, when the guest restarts or powers off, proves the -//! blocks it compiled anew and rewrites the pack in place over the file's +//! ([`install`]) and keeps the stored form of each block it compiles anew; +//! when the guest restarts or powers off, the pack is rewritten in place +//! with them over the file's //! clusters, within the same budget ([`write`]), found by Stela's own FAT32 //! reader on the partition the storage drivers opened. The pack is a cache: //! every failure leaves the boot running without a store, or without @@ -15,8 +16,7 @@ //! When every PE runs on its own host core (the default), their machines //! share the store ([`Shared`]), split by page key into parts behind locks //! of their own, and it keeps the blocks any of them compiled for the others -//! to install ([`share`]). A PE that compiles at EL0 proves a few waiting -//! blocks now and then, so that a stop has fewer left to prove. +//! to install ([`share`]). use super::bundle::Bytes; use crate::{firmware, handoff::Region, output, paging::PAGE}; use alloc::{boxed::Box, format, string::String, vec}; @@ -489,9 +489,6 @@ struct Costs { lookups: AtomicU64, lookup_ticks: AtomicU64, decode_ticks: AtomicU64, - /// Proof batches run during the boot, and their TSC ticks. - batches: AtomicU64, - batch_ticks: AtomicU64, } static COSTS: Costs = Costs { @@ -501,35 +498,17 @@ static COSTS: Costs = Costs { lookups: AtomicU64::new(0), lookup_ticks: AtomicU64::new(0), decode_ticks: AtomicU64::new(0), - batches: AtomicU64::new(0), - batch_ticks: AtomicU64::new(0), }; -/// Proof during the boot: one PE at a time proves a batch of this many -/// blocks, at EL0, and the next batch waits until the time since this one -/// began is [`PROOF_SPACING`] times its own. The prover then takes at most -/// a fraction of one core, and no PE holds a kernel lock while it proves. -const PROOF_BATCH_BLOCKS: usize = 32; -const PROOF_SPACING: u64 = 4; -/// Counter ticks after a look that found nothing to prove before the next: -/// about a millisecond at the clocks Stela runs on. -const IDLE_LOOK_TICKS: u64 = 1 << 22; -static PROVING: AtomicBool = AtomicBool::new(false); -static NEXT_PROOF: AtomicU64 = AtomicU64::new(0); -static PROOF_PART: AtomicUsize = AtomicUsize::new(0); -/// The most a stop spends proving what the boot left: the rest is not kept. -const STOP_PROOF_MILLIS: u64 = 3000; - /// What the store keeps beyond its pack, for an engine heap of `heap` bytes: -/// blocks waiting for proof, entries proven during the boot, decoded -/// records, and the fetch pages the machines keep (a page and its bookkeeping +/// entries added during the boot, decoded records, and the fetch pages the +/// machines keep (a page and its bookkeeping /// take about 4.5 KiB). fn bounds(heap: usize) -> (pack::Bounds, usize) { const MIB: usize = 1 << 20; let defaults = pack::Bounds::default(); let bounds = pack::Bounds { - pending: (heap / 64).clamp(defaults.pending, 256 * MIB), - proven: (heap / 32).clamp(defaults.proven, 512 * MIB), + added: (heap / 32).clamp(defaults.added, 512 * MIB), decoded: (heap / 64).clamp(defaults.decoded, 128 * MIB), }; (bounds, (heap / 64 / (4608)).max(4096)) @@ -564,62 +543,25 @@ impl Shared { drop(retired); } + /// Keep the offer's stored form, made before the lock is taken, and + /// share its block. fn publish_writable(offer: Offer) { let bound = AVAILABLE.shared_bound.load(Ordering::Acquire) / PARTS; - let mut staged = StagedOffer::for_writable(&offer, bound); - let retired = part(&offer.key()).with(|store| { - let store = store.as_mut()?; - store.keep_pending(&offer); - store.accept_shared(staged.as_mut()?) + let entry = offer.entry(); + let lock = part(&offer.key()); + lock.with(|store| { + if let Some(store) = store { + store.keep(&offer, entry); + } }); + let Some(mut staged) = StagedOffer::new(offer, bound) else { + return; + }; + let retired = lock.with(|store| store.as_mut()?.accept_shared(&mut staged)); drop(retired); - if offer.quiet() { - prove_some(); - } } } -/// Prove one batch of the blocks waiting for proof outside the store's -/// locks, when no other PE does and the last batch is long enough past. -fn prove_some() { - let now = output::now(); - if now < NEXT_PROOF.load(Ordering::Relaxed) || PROVING.swap(true, Ordering::SeqCst) { - return; - } - // A stop clears the capability before it waits for `PROVING`. - let mut proved = false; - if available(WRITE_PACK) && !crate::ALLOCATOR.low() { - for _ in 0..PARTS { - let lock = &STORES[PROOF_PART.fetch_add(1, Ordering::Relaxed) % PARTS]; - let Some(batch) = lock.with(|store| store.as_mut()?.take_batch(PROOF_BATCH_BLOCKS)) - else { - continue; - }; - let proven = batch.prove(); - lock.with(|store| { - if let Some(store) = store { - store.fold(proven); - } - }); - proved = true; - break; - } - } - let spent = output::now().wrapping_sub(now); - // Only batches proven count: a look that found every part empty or - // full is not one, and the next look waits a while, so that EL0 - // compiles do not each look through every part. - let wait = if proved { - COSTS.batches.fetch_add(1, Ordering::Relaxed); - COSTS.batch_ticks.fetch_add(spent, Ordering::Relaxed); - spent.saturating_mul(PROOF_SPACING) - } else { - IDLE_LOOK_TICKS - }; - NEXT_PROOF.store(now.wrapping_add(wait), Ordering::Relaxed); - PROVING.store(false, Ordering::SeqCst); -} - impl Translations for Shared { /// The pack bytes outlive the lock, so other PEs can reach the store /// while a record is decoded. A writer also tracks absent keys. @@ -878,7 +820,7 @@ fn millis(ticks: u64) -> u64 { } /// Report what the store did and cost this boot: lookups and their causes, -/// shared misses by reason, proof during the boot and lock waits. +/// shared misses by reason, stored forms kept and checked, and lock waits. fn report(counters: &pack::Counters) { let costs = &COSTS; let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed); @@ -910,20 +852,21 @@ fn report(counters: &pack::Counters) { contended += load(&lock.contended); spun += load(&lock.spun); } + let checks = stela_engine::machine::entry_checks(); output::arguments(format_args!( - "TRANSLATIONS early proven={} unprovable={} unkept={} batches={} batch_ms={} \ + "TRANSLATIONS added={} unstorable={} unkept={} checked={} differed={} \ locks acquired={acquired} contended={contended} spin_ms={}\n", - counters.proven, - counters.unprovable, + counters.added, + counters.unstorable, counters.unkept, - load(&costs.batches), - millis(load(&costs.batch_ticks)), + checks.checked, + checks.differed, millis(spun), )); } -/// At a quiescent point (the guest restarts or powers off): prove the -/// blocks compiled anew and rewrite the pack in place. +/// At a quiescent point (the guest restarts or powers off): rewrite the +/// pack in place with the entries the boot added. pub fn write() { let Some(boot) = BOOT.with(|boot| { AVAILABLE.capabilities.store(0, Ordering::SeqCst); @@ -932,10 +875,6 @@ pub fn write() { }) else { return; }; - // A batch being proven is folded back before the parts are taken. - while PROVING.load(Ordering::SeqCst) { - core::hint::spin_loop(); - } let mut parts = STORES.iter().filter_map(|lock| lock.with(Option::take)); let Some(mut store) = parts.next() else { return; @@ -955,20 +894,11 @@ pub fn write() { return; }; output::arguments(format_args!( - "TRANSLATIONS proving {} blocks (loaded={} absent={} invalid={} dropped={})\n", - store.pending(), - counters.loaded, - counters.absent, - counters.invalid, - counters.dropped + "TRANSLATIONS planning {} added entries (loaded={} absent={} invalid={})\n", + counters.added, counters.loaded, counters.absent, counters.invalid, )); - // Proof recompiles the original and both relocation probes; stop while - // the heap still has room for the layout and the write, and before the - // stop waits long. let started = output::now(); - let planned = store.plan(bound, || { - !crate::ALLOCATOR.low() && output::millis_since(started) < STOP_PROOF_MILLIS - }); + let planned = store.plan(bound); let heap = crate::ALLOCATOR.usage(); let written: u64 = match planned.layout.changed() { None => planned.layout.bytes(), @@ -1010,13 +940,11 @@ pub fn write() { &planned.layout, ) { Ok(()) => output::arguments(format_args!( - "TRANSLATIONS written records={} bytes={} changed={written} proven={} unprovable={} \ - unproven={} evicted={} expired={} ms={}\n", + "TRANSLATIONS written records={} bytes={} changed={written} added={} evicted={} \ + expired={} ms={}\n", planned.layout.records(), planned.layout.bytes(), - planned.proven, - planned.unprovable, - planned.unproven, + counters.added, planned.evicted, planned.expired, output::millis_since(started) diff --git a/crates/stela-compiler/src/aarch64/literal.rs b/crates/stela-compiler/src/aarch64/literal.rs index abf2122e01..9e540bf38b 100644 --- a/crates/stela-compiler/src/aarch64/literal.rs +++ b/crates/stela-compiler/src/aarch64/literal.rs @@ -34,7 +34,7 @@ pub enum Transfer { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Operand { - pub address: u64, + pub address: GuestAddress, pub transfer: Transfer, } @@ -69,7 +69,7 @@ pub fn decode(pc: GuestAddress, word: u32) -> Option> IMMEDIATE_SHIFT) & IMMEDIATE_MASK); let signed = (immediate << IMMEDIATE_SIGN_SHIFT) >> IMMEDIATE_SIGN_SHIFT; Some(Ok(Operand { - address: pc.0.wrapping_add_signed(signed * INSTRUCTION_BYTES), + address: GuestAddress(pc.0.wrapping_add_signed(signed * INSTRUCTION_BYTES)), transfer, })) } @@ -92,7 +92,7 @@ mod tests { .unwrap() .unwrap(); assert_eq!( - operand.address, + operand.address.0, (i128::from(pc) + i128::from(immediate) * 4) as u64 ); let expected = match form { diff --git a/crates/stela-compiler/src/aarch64/pc_relative.rs b/crates/stela-compiler/src/aarch64/pc_relative.rs index d9aa6a4907..c01b50c1cd 100644 --- a/crates/stela-compiler/src/aarch64/pc_relative.rs +++ b/crates/stela-compiler/src/aarch64/pc_relative.rs @@ -5,7 +5,7 @@ use crate::GuestAddress; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Operand { pub destination: Register, - pub address: u64, + pub address: GuestAddress, } pub fn decode(pc: GuestAddress, word: u32) -> Option { @@ -25,7 +25,7 @@ pub fn decode(pc: GuestAddress, word: u32) -> Option { }; Some(Operand { destination: register(word & 31, false), - address, + address: GuestAddress(address), }) } @@ -56,7 +56,7 @@ mod tests { }; let operand = decode(GuestAddress(pc), word(page, immediate, destination)).unwrap(); - assert_eq!(operand.address, expected); + assert_eq!(operand.address.0, expected); assert_eq!(operand.destination, register(destination, false)); } } @@ -78,7 +78,7 @@ mod tests { instruction.operation, Operation::PcRelative(Operand { destination: Register::Zero, - address: if page { 0x5000 } else { 0x4005 }, + address: GuestAddress(if page { 0x5000 } else { 0x4005 }), }) ); } diff --git a/crates/stela-compiler/src/aarch64/prefetch.rs b/crates/stela-compiler/src/aarch64/prefetch.rs index a0b099dbde..88f3b618cc 100644 --- a/crates/stela-compiler/src/aarch64/prefetch.rs +++ b/crates/stela-compiler/src/aarch64/prefetch.rs @@ -50,7 +50,7 @@ pub enum Address { extend: IndexExtend, shift: u8, }, - Literal(u64), + Literal(GuestAddress), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -100,7 +100,7 @@ pub fn decode(pc: GuestAddress, word: u32) -> Option> LITERAL_IMMEDIATE_SHIFT) & LITERAL_IMMEDIATE_MASK, LITERAL_IMMEDIATE_BITS, ) * INSTRUCTION_BYTES; - Address::Literal(pc.0.wrapping_add_signed(displacement)) + Address::Literal(GuestAddress(pc.0.wrapping_add_signed(displacement))) } else { return None; }; @@ -224,7 +224,9 @@ mod tests { assert_eq!(operand.hint.encoding(), hint as u8); assert_eq!( operand.address, - Address::Literal((i128::from(pc) + i128::from(immediate) * 4) as u64) + Address::Literal(GuestAddress( + (i128::from(pc) + i128::from(immediate) * 4) as u64 + )) ); } } diff --git a/crates/stela-compiler/src/block/scalar.rs b/crates/stela-compiler/src/block/scalar.rs index c4f804ae87..f79261e070 100644 --- a/crates/stela-compiler/src/block/scalar.rs +++ b/crates/stela-compiler/src/block/scalar.rs @@ -13,7 +13,7 @@ use crate::{ #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ScalarLoadAddress { Literal { - address: u64, + address: crate::GuestAddress, }, Immediate { base: Register, @@ -148,7 +148,9 @@ mod tests { assert_eq!(literal.bytes(), 8); assert_eq!( literal.address(), - ScalarLoadAddress::Literal { address: 0x1008 } + ScalarLoadAddress::Literal { + address: crate::GuestAddress(0x1008) + } ); assert!(ScalarStore::from_instruction(&lift(0x79c0_0c41)).is_none()); } diff --git a/crates/stela-compiler/src/lib.rs b/crates/stela-compiler/src/lib.rs index 5d5eb60028..75bbb3c9ed 100644 --- a/crates/stela-compiler/src/lib.rs +++ b/crates/stela-compiler/src/lib.rs @@ -76,6 +76,13 @@ pub trait Lifter { pub struct NativeBlock { pub x86_64_code: Vec, pub source_map: Vec<(GuestAddress, usize)>, + /// The offsets of the 8-byte fields of the code that hold guest + /// addresses, ascending, as the emitter recorded them: the code depends + /// on its block's address through these alone, so it moves to another + /// page by adding the page's displacement to each. `None` for code the + /// emitter assembled without recording them, which is not moved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub relocations: Option>, } /// What [`compile`] translates for: the guest services and memory checks of a diff --git a/crates/stela-compiler/src/scalable_context.rs b/crates/stela-compiler/src/scalable_context.rs index 72464e30c0..5a4b1a7c14 100644 --- a/crates/stela-compiler/src/scalable_context.rs +++ b/crates/stela-compiler/src/scalable_context.rs @@ -404,9 +404,11 @@ impl Leaf { })?; code.patch(displacement, relative.to_le_bytes()); } + let (x86_64_code, relocations) = code.into_parts(); Ok(NativeBlock { - x86_64_code: code.into_bytes(), + x86_64_code, source_map, + relocations: Some(relocations), }) } } diff --git a/crates/stela-compiler/src/scalable_context/block.rs b/crates/stela-compiler/src/scalable_context/block.rs index 6201d5a3b8..200294f304 100644 --- a/crates/stela-compiler/src/scalable_context/block.rs +++ b/crates/stela-compiler/src/scalable_context/block.rs @@ -191,6 +191,7 @@ impl Prefix { } debug_assert!(fixups.is_empty(), "context block prefix cannot transfer"); let mut terminal_bytes = Vec::new(); + let mut terminal_relocations = Some(Vec::new()); match self.terminal { Some(Terminal::Shared(plan)) => { let shared = plan.compile()?; @@ -203,6 +204,10 @@ impl Prefix { .map(|(pc, at)| (pc, at + offset)), ); terminal_bytes = shared.native.x86_64_code; + terminal_relocations = shared + .native + .relocations + .map(|fields| fields.into_iter().map(|at| at + offset as u32).collect()); } Some(Terminal::Numerical(instruction)) => { let pc = instruction.instruction_pc(); @@ -247,12 +252,17 @@ impl Prefix { } None => x86_64::block::direct_exit(&mut code, self.next_pc, ExitKind::Fallthrough), } - let mut bytes = code.into_bytes(); + let (mut bytes, mut relocations) = code.into_parts(); bytes.extend(terminal_bytes); + let relocations = terminal_relocations.map(|terminal| { + relocations.extend(terminal); + relocations + }); Ok(CompiledBlock { native: NativeBlock { x86_64_code: bytes, source_map, + relocations, }, source_bytes: self.source_bytes, direct_exits: Vec::new(), diff --git a/crates/stela-compiler/src/x86_64.rs b/crates/stela-compiler/src/x86_64.rs index d901397497..8d1e6a993e 100644 --- a/crates/stela-compiler/src/x86_64.rs +++ b/crates/stela-compiler/src/x86_64.rs @@ -77,9 +77,11 @@ pub(crate) struct Emitted { impl Emitted { pub(crate) fn into_native(self) -> crate::NativeBlock { + let (x86_64_code, relocations) = self.x86_64_code.into_parts(); crate::NativeBlock { - x86_64_code: self.x86_64_code.into_bytes(), + x86_64_code, source_map: self.source_map, + relocations: Some(relocations), } } } @@ -1268,6 +1270,11 @@ fn immediate(code: &mut Code, value: u64) { code.asm().mov_imm64(asm::Gpr::Rax, value); } +/// `movabs rax,address`, its field a relocation of the block. +fn guest_immediate(code: &mut Code, address: GuestAddress) { + code.asm().guest_imm64(asm::Gpr::Rax, address); +} + fn nzcv(code: &mut Code, subtract: bool) { if code.is_pinned() { return flag_word::capture(code, subtract); diff --git a/crates/stela-compiler/src/x86_64/asm.rs b/crates/stela-compiler/src/x86_64/asm.rs index 8deaeb9533..77f8b74954 100644 --- a/crates/stela-compiler/src/x86_64/asm.rs +++ b/crates/stela-compiler/src/x86_64/asm.rs @@ -32,6 +32,9 @@ pub(crate) struct Asm<'a> { instructions: usize, shared: Option<&'a mut usize>, sites: Option<&'a mut Vec>, + /// The [`Code`]'s guest-address fields ([`Self::guest_imm64`]); none for + /// code built outside a block (thunks and tails the engine places). + relocations: Option<&'a mut Vec>, pinned: bool, locals: Option, /// The locals a fault recovers from their hosts ([`super::pinned::Span`]). @@ -68,6 +71,7 @@ impl<'a> Asm<'a> { instructions: 0, shared: None, sites: None, + relocations: None, pinned: false, locals: None, dirty: Default::default(), @@ -347,6 +351,18 @@ impl<'a> Asm<'a> { self.opcode_reg(Size::Qword, 0xb8, destination); self.data(&value.to_le_bytes()); } + /// `movabs destination, address`: a guest address, whose field the + /// code records among its relocations so that the block, stored, moves + /// with its page. Every guest address a block's code holds is emitted + /// here; [`Self::mov_imm64`] takes no [`crate::GuestAddress`]. + pub(crate) fn guest_imm64(&mut self, destination: Gpr, address: crate::GuestAddress) { + self.opcode_reg(Size::Qword, 0xb8, destination); + let at = self.code.len(); + self.data(&address.0.to_le_bytes()); + if let Some(relocations) = self.relocations.as_deref_mut() { + relocations.push(u32::try_from(at).expect("code under 4 GiB")); + } + } /// `mov rm, imm32` (C7 /0), sign-extended for a quadword. pub(crate) fn mov_rm_imm32(&mut self, size: Size, rm: impl Into, value: i32) { debug_assert!(size != Size::Byte && size != Size::Word); diff --git a/crates/stela-compiler/src/x86_64/asm/code.rs b/crates/stela-compiler/src/x86_64/asm/code.rs index 25ae2e9b7d..55122a0bd8 100644 --- a/crates/stela-compiler/src/x86_64/asm/code.rs +++ b/crates/stela-compiler/src/x86_64/asm/code.rs @@ -8,6 +8,10 @@ pub(crate) struct Code { pub(super) bytes: Vec, pub(super) instructions: usize, pub(super) sites: Vec, + /// The offsets of the 8-byte fields that hold guest addresses + /// ([`super::Asm::guest_imm64`]), ascending: what a stored block adds its + /// page's displacement to when it is installed at another address. + pub(super) relocations: Vec, /// Whether guest registers live in host registers ([`super::super::pinned`]). pub(super) pinned: bool, locals: Option, @@ -100,6 +104,7 @@ impl Code { bytes: Vec::with_capacity(INITIAL_BYTES), instructions: 0, sites: Vec::new(), + relocations: Vec::new(), pinned: false, locals: None, dirty: Default::default(), @@ -216,6 +221,7 @@ impl Code { instructions: 0, shared: Some(&mut self.instructions), sites: Some(&mut self.sites), + relocations: Some(&mut self.relocations), pinned: self.pinned, locals: self.locals, dirty: self.dirty, @@ -262,6 +268,10 @@ impl Code { pub(crate) fn sites(&self) -> &[EmissionSite] { &self.sites } + /// The bytes and their guest-address fields. + pub(crate) fn into_parts(self) -> (Vec, Vec) { + (self.bytes, self.relocations) + } /// The instructions emitted through [`Self::asm`]. pub(crate) const fn instructions(&self) -> usize { self.instructions @@ -273,6 +283,8 @@ impl Code { pub(crate) fn append(&mut self, other: Code) { debug_assert!(other.locals.is_none()); let base = self.bytes.len(); + self.relocations + .extend(other.relocations.iter().map(|at| base as u32 + at)); self.sites .extend(other.sites.into_iter().map(|site| EmissionSite { start: base + site.start, @@ -313,8 +325,19 @@ impl Code { assert!( span.end.bytes <= source.bytes.len() && span.end.instructions <= source.instructions ); + let base = self.bytes.len(); self.bytes .extend_from_slice(&source.bytes[span.start.bytes..span.end.bytes]); + for &at in &source.relocations { + let at = at as usize; + if at + 8 > span.start.bytes && at < span.end.bytes { + assert!( + at >= span.start.bytes && at + 8 <= span.end.bytes, + "span preserves complete guest-address fields" + ); + self.relocations.push((base + at - span.start.bytes) as u32); + } + } for site in &source.sites { if site.start < span.end.bytes && site.end > span.start.bytes { assert!( @@ -336,6 +359,12 @@ impl Code { let end = offset .checked_add(N) .expect("patch field offset does not overflow"); + assert!( + self.relocations + .iter() + .all(|&at| at as usize + 8 <= offset || at as usize >= end), + "a patch leaves guest-address fields whole" + ); self.bytes .get_mut(offset..end) .expect("patch field lies in emitted code") @@ -363,6 +392,17 @@ impl Code { ..site }) .collect(); + assert!( + self.relocations + .iter() + .all(|&field| field as usize + 8 <= at.bytes || field as usize >= at.bytes), + "split preserves complete guest-address fields" + ); + let relocations = self + .relocations + .extract_if(.., |field| *field as usize >= at.bytes) + .map(|field| field - at.bytes as u32) + .collect(); let failures = self .failures .extract_if(.., |(jump, _, _)| jump.at >= at.bytes) @@ -378,6 +418,7 @@ impl Code { bytes: self.bytes.split_off(at.bytes), instructions: self.instructions - at.instructions, sites, + relocations, pinned: self.pinned, locals: None, dirty: Default::default(), @@ -402,6 +443,8 @@ impl Code { "truncate preserves complete faulting instructions" ); self.sites.retain(|site| site.end <= at.bytes); + self.relocations + .retain(|&field| field as usize + 8 <= at.bytes); self.failures.retain(|(jump, _, _)| jump.at < at.bytes); self.bytes.truncate(at.bytes); self.instructions = at.instructions; @@ -438,6 +481,14 @@ impl Code { } jump.at -= removed; } + self.relocations + .retain(|&field| field as usize + 8 <= range.start || field as usize >= range.end); + for field in self.relocations.iter_mut().rev() { + if (*field as usize) < range.end { + break; + } + *field -= removed as u32; + } self.bytes.drain(range); self.instructions = self .instructions @@ -449,6 +500,7 @@ impl Code { self.bytes.clear(); self.instructions = 0; self.sites.clear(); + self.relocations.clear(); self.instruction = 0; self.failures.clear(); } diff --git a/crates/stela-compiler/src/x86_64/block.rs b/crates/stela-compiler/src/x86_64/block.rs index 65c82e73fd..80a20a5101 100644 --- a/crates/stela-compiler/src/x86_64/block.rs +++ b/crates/stela-compiler/src/x86_64/block.rs @@ -71,7 +71,7 @@ pub(super) fn direct_exit_with(asm: &mut Asm, target: GuestAddress, word: impl I let word = word.into(); let slot = super::chain::link_slot(asm.linked_block(), target, word.kind); super::chain::empty_link(asm, slot); - asm.mov_imm64(Gpr::Rax, target.0); + asm.guest_imm64(Gpr::Rax, target); exit_kind_with(asm, word); } @@ -469,7 +469,7 @@ pub(super) fn fold_address_pair( }; (destination == address.destination && source == destination).then_some(pc_relative::Operand { destination, - address: address.address.wrapping_add(u64::from(immediate)), + address: GuestAddress(address.address.0.wrapping_add(u64::from(immediate))), }) } @@ -2300,7 +2300,7 @@ fn emit_terminal( direct_exit(code, trap.instruction_pc, ExitKind::Trap); } Terminator::DirectCall(target) => { - super::immediate(code, fallthrough.0); + super::guest_immediate(code, fallthrough); super::store(code, Register::X(30)); direct_exit(code, *target, ExitKind::Call); } @@ -2309,7 +2309,7 @@ fn emit_terminal( if *kind == ExitKind::Call { // Capture BLR X30's target before LR is overwritten. code.asm().mov(Size::Qword, Gpr::Rcx, Gpr::Rax); - super::immediate(code, fallthrough.0); + super::guest_immediate(code, fallthrough); super::store(code, Register::X(30)); code.asm().mov(Size::Qword, Gpr::Rax, Gpr::Rcx); } diff --git a/crates/stela-compiler/src/x86_64/literal.rs b/crates/stela-compiler/src/x86_64/literal.rs index d73aa531e6..ca02afbb38 100644 --- a/crates/stela-compiler/src/x86_64/literal.rs +++ b/crates/stela-compiler/src/x86_64/literal.rs @@ -7,7 +7,7 @@ use crate::aarch64::{ use crate::x86_64::asm::{Code, Gpr, Mem, Size}; pub(super) fn emit(code: &mut Code, operand: &Operand, checks: super::MemoryChecks) { - code.asm().mov_imm64(Gpr::Rax, operand.address); + code.asm().guest_imm64(Gpr::Rax, operand.address); let bytes = match operand.transfer { Transfer::Integer { width: Width::X64, @@ -60,7 +60,7 @@ mod tests { emit( &mut code, &Operand { - address: u64::MAX, + address: crate::GuestAddress(u64::MAX), transfer: Transfer::Integer { destination: Register::Zero, width, @@ -86,7 +86,7 @@ mod tests { emit( &mut code, &Operand { - address: 0x1004, + address: crate::GuestAddress(0x1004), transfer: Transfer::Integer { destination: Register::X(0), width, @@ -113,7 +113,7 @@ mod tests { emit( &mut code, &Operand { - address: 0x123456789abc, + address: crate::GuestAddress(0x123456789abc), transfer: Transfer::Simd { destination: 31, bytes, diff --git a/crates/stela-compiler/src/x86_64/memory_context/callback.rs b/crates/stela-compiler/src/x86_64/memory_context/callback.rs index fe0f45cfff..12dcdb438f 100644 --- a/crates/stela-compiler/src/x86_64/memory_context/callback.rs +++ b/crates/stela-compiler/src/x86_64/memory_context/callback.rs @@ -89,7 +89,8 @@ pub(crate) fn request( ] { asm.mov_rm_imm32(Size::Dword, stack(request_offset + field), value as i32); } - asm.mov_imm64(Gpr::Rcx, pc); + // The guest PC of the access: a field that moves with the block. + asm.guest_imm64(Gpr::Rcx, crate::GuestAddress(pc)); asm.mov_store( Size::Qword, stack(request_offset + MEMORY_REQUEST_PC_OFFSET), @@ -148,7 +149,7 @@ pub(crate) fn fault(code: &mut Code, status: MemoryStatus, pc: u64) { field(offset_of!(MemoryContextView, fault_address)), Gpr::Rax, ); - asm.mov_imm64(Gpr::Rcx, pc); + asm.guest_imm64(Gpr::Rcx, crate::GuestAddress(pc)); asm.mov_store( Size::Qword, field(offset_of!(MemoryContextView, fault_pc)), diff --git a/crates/stela-compiler/src/x86_64/memory_store/checked_scalar.rs b/crates/stela-compiler/src/x86_64/memory_store/checked_scalar.rs index db9995da54..56815125dc 100644 --- a/crates/stela-compiler/src/x86_64/memory_store/checked_scalar.rs +++ b/crates/stela-compiler/src/x86_64/memory_store/checked_scalar.rs @@ -32,7 +32,7 @@ const fn scratch(offset: u32) -> Mem { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Address { Literal { - address: u64, + address: crate::GuestAddress, }, Immediate { displacement: i32, @@ -320,7 +320,7 @@ pub(crate) fn emit_context(code: &mut Code, operand: &Operand, pc: u64) { .mov_store(Size::Qword, scratch(DATA_OFFSET), Gpr::Rax); } match operand.address { - Address::Literal { address } => crate::x86_64::immediate(code, address), + Address::Literal { address } => crate::x86_64::guest_immediate(code, address), Address::Immediate { displacement, mode } => address::immediate_with_checks( code, operand.base, @@ -447,7 +447,9 @@ mod tests { assert_eq!( operand.address, Address::Literal { - address: pc.wrapping_add_signed(i64::from(immediate) * 4) + address: crate::GuestAddress( + pc.wrapping_add_signed(i64::from(immediate) * 4) + ) } ); assert_eq!(operand.base, Register::Zero); diff --git a/crates/stela-compiler/src/x86_64/pc_relative.rs b/crates/stela-compiler/src/x86_64/pc_relative.rs index 310ac595ae..2d85ec6681 100644 --- a/crates/stela-compiler/src/x86_64/pc_relative.rs +++ b/crates/stela-compiler/src/x86_64/pc_relative.rs @@ -10,7 +10,7 @@ pub(super) fn emit(code: &mut Code, operand: &Operand) { return; } // MOVABS leaves guest NZCV untouched. - super::immediate(code, operand.address); + super::guest_immediate(code, operand.address); store(code, operand.destination); } @@ -27,7 +27,7 @@ mod tests { &mut code, &Operand { destination: Register::Zero, - address: u64::MAX, + address: crate::GuestAddress(u64::MAX), }, ); assert_eq!(code, [0x90]); @@ -36,7 +36,7 @@ mod tests { &mut code, &Operand { destination: Register::X(30), - address: 0xfedcba9876543210, + address: crate::GuestAddress(0xfedcba9876543210), }, ); assert_eq!(&code[..2], &[0x48, 0xb8]); diff --git a/crates/stela-compiler/src/x86_64/pinned.rs b/crates/stela-compiler/src/x86_64/pinned.rs index f9a35607bb..e1fc04c738 100644 --- a/crates/stela-compiler/src/x86_64/pinned.rs +++ b/crates/stela-compiler/src/x86_64/pinned.rs @@ -311,7 +311,7 @@ pub(super) fn compare_held_immediate(code: &mut Code, width: Width, immediate: u 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); + code.asm().guest_imm64(work, operand.address); finish(code, work, operand.destination, false, false); } diff --git a/crates/stela-compiler/src/x86_64/pointer.rs b/crates/stela-compiler/src/x86_64/pointer.rs index afd54bfd6c..83a9b6612a 100644 --- a/crates/stela-compiler/src/x86_64/pointer.rs +++ b/crates/stela-compiler/src/x86_64/pointer.rs @@ -417,7 +417,7 @@ pub fn thunk(form: Form, pc: GuestAddress, tags: Place, service: u64) -> Thunk { } Finish::Branch { link } => { if link { - asm.mov_imm64(Rcx, next_pc.0); + asm.guest_imm64(Rcx, next_pc); let storage = asm.guest(Register::X(30)).expect("X30 has storage"); asm.mov_store(Qword, storage, Rcx); } diff --git a/crates/stela-compiler/src/x86_64/prefetch.rs b/crates/stela-compiler/src/x86_64/prefetch.rs index d4aade43ce..19cff6734f 100644 --- a/crates/stela-compiler/src/x86_64/prefetch.rs +++ b/crates/stela-compiler/src/x86_64/prefetch.rs @@ -68,7 +68,7 @@ pub(super) fn emit(code: &mut Code, operand: &Operand) { } } Address::Literal(address) => { - code.asm().mov_imm64(Gpr::Rax, address); + code.asm().guest_imm64(Gpr::Rax, address); immediate(code, locality, 0); } } diff --git a/crates/stela-compiler/src/x86_64/region.rs b/crates/stela-compiler/src/x86_64/region.rs index 155961b67b..2b260f1f3b 100644 --- a/crates/stela-compiler/src/x86_64/region.rs +++ b/crates/stela-compiler/src/x86_64/region.rs @@ -736,7 +736,7 @@ impl Emitter<'_> { 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.emit(|code| write.value.emit(code, POOL[index], immediate_width)); self.locations[guest] = Location::Host(POOL[index]); self.resident[index] = Some(Resident { guest, dirty: true }); self.output.stats.commits += 1; @@ -746,7 +746,7 @@ impl Emitter<'_> { self.emit(encoding::nop); } } else { - self.emit(|code| encoding::immediate(code, RESULT, write.value, immediate_width)); + self.emit(|code| write.value.emit(code, RESULT, immediate_width)); if let Some(pc) = continuation { self.output.source_map.push((pc, self.output.code.len())); } @@ -830,7 +830,7 @@ impl Emitter<'_> { self.output.stats.commits += 1; } Operation::PcRelative(operand) => { - self.emit(|code| encoding::immediate(code, RESULT, operand.address, Width::X64)); + self.emit(|code| encoding::guest_immediate(code, RESULT, operand.address)); self.commit(operand.destination, Width::X64); } Operation::MoveWide { @@ -1345,7 +1345,9 @@ fn emit_prefix_selected<'a>( 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() { + let width = if let constant::Constant::Plain(value) = write.value + && u32::try_from(value).is_ok() + { Width::W32 } else { Width::X64 diff --git a/crates/stela-compiler/src/x86_64/region/apx.rs b/crates/stela-compiler/src/x86_64/region/apx.rs index 862906d19c..dba6b7a645 100644 --- a/crates/stela-compiler/src/x86_64/region/apx.rs +++ b/crates/stela-compiler/src/x86_64/region/apx.rs @@ -219,7 +219,7 @@ fn instruction(a: &mut Asm, operation: &Operation, ndd: bool) { Operation::Nop => a.nop(), Operation::PcRelative(operand) => { if let Some(destination) = value(operand.destination) { - a.mov_imm64(destination, operand.address); + a.guest_imm64(destination, operand.address); } } Operation::MoveWide { diff --git a/crates/stela-compiler/src/x86_64/region/constant.rs b/crates/stela-compiler/src/x86_64/region/constant.rs index 07d43dd117..ff33f6f5b8 100644 --- a/crates/stela-compiler/src/x86_64/region/constant.rs +++ b/crates/stela-compiler/src/x86_64/region/constant.rs @@ -1,20 +1,48 @@ //! Compile-time constant facts for non-faulting scalar sequences. Each separately //! entered region starts with no facts. +//! +//! A fact derived from the guest PC stays a guest address only while it +//! moves with the block's page: ADR, ADRP and 64-bit additions to them. A +//! MOVK or 32-bit result of one is a value no relocation reproduces, so the +//! fact is dropped and the instruction computes it at run time. +use super::encoding::{self, HostGpr}; +use crate::GuestAddress; use crate::aarch64::{Instruction, Operation, Register, WideMove, Width}; +use crate::x86_64::asm::Code; const REGISTER_SLOTS: usize = 32; const SP_SLOT: usize = 31; const W32_MASK: u64 = u32::MAX as u64; +/// A known register value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Constant { + /// The same at every address of the block. + Plain(u64), + /// Moves with the block's page: emitted as a relocation field. + Guest(GuestAddress), +} + +impl Constant { + /// Load it into `destination`: a plain value at `width`, a guest + /// address always as a full relocated field. + pub(super) fn emit(self, code: &mut Code, destination: HostGpr, width: Width) { + match self { + Self::Plain(value) => encoding::immediate(code, destination, value, width), + Self::Guest(address) => encoding::guest_immediate(code, destination, address), + } + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct ConstantWrite { pub destination: Register, - pub value: u64, + pub value: Constant, } #[derive(Clone, Debug)] pub(super) struct ConstantRegisters { - values: [Option; REGISTER_SLOTS], + values: [Option; REGISTER_SLOTS], } impl Default for ConstantRegisters { @@ -45,15 +73,15 @@ impl ConstantRegisters { self.values.fill(None); } - fn read(&self, register: Register) -> Option { + fn read(&self, register: Register) -> Option { if register == Register::Zero { - Some(0) + Some(Constant::Plain(0)) } else { slot(register).and_then(|index| self.values[index]) } } - fn write(&mut self, destination: Register, value: Option) -> Option { + fn write(&mut self, destination: Register, value: Option) -> Option { let index = slot(destination)?; self.values[index] = value; value.map(|value| ConstantWrite { destination, value }) @@ -65,7 +93,7 @@ impl ConstantRegisters { second: &Operation, ) -> Option { let folded = super::super::block::fold_address_pair(first, second)?; - self.write(folded.destination, Some(folded.address)) + self.write(folded.destination, Some(Constant::Guest(folded.address))) } pub(super) fn fold_wide_run( @@ -126,15 +154,18 @@ impl ConstantRegisters { let value = match kind { WideMove::Zero => Some(lane), WideMove::Not => Some(!lane), - WideMove::Keep => self - .read(destination) - .map(|previous| (previous & !(u64::from(u16::MAX) << shift)) | lane), + WideMove::Keep => match self.read(destination) { + Some(Constant::Plain(previous)) => { + Some((previous & !(u64::from(u16::MAX) << shift)) | lane) + } + _ => None, + }, } - .map(|value| narrow(value, width)); + .map(|value| Constant::Plain(narrow(value, width))); self.write(destination, value) } Operation::PcRelative(operand) => { - self.write(operand.destination, Some(operand.address)) + self.write(operand.destination, Some(Constant::Guest(operand.address))) } Operation::AddSub { width, @@ -144,17 +175,23 @@ impl ConstantRegisters { source, immediate, } => { - let value = self.read(source).map(|source| { - let immediate = u64::from(immediate); - narrow( - if subtract { - source.wrapping_sub(immediate) - } else { - source.wrapping_add(immediate) - }, - width, - ) - }); + let immediate = u64::from(immediate); + let add = |source: u64| { + if subtract { + source.wrapping_sub(immediate) + } else { + source.wrapping_add(immediate) + } + }; + let value = match (self.read(source), width) { + (Some(Constant::Plain(source)), _) => { + Some(Constant::Plain(narrow(add(source), width))) + } + (Some(Constant::Guest(source)), Width::X64) => { + Some(Constant::Guest(GuestAddress(add(source.0)))) + } + _ => None, + }; self.write(destination, value) } Operation::Nop => None, @@ -199,7 +236,10 @@ mod tests { for (operation, value) in operations.iter().zip(expected) { assert_eq!( facts.step(operation), - Some(ConstantWrite { destination, value }) + Some(ConstantWrite { + destination, + value: Constant::Plain(value) + }) ); } } @@ -222,7 +262,7 @@ mod tests { facts.step(&Operation::PcRelative( crate::aarch64::pc_relative::Operand { destination: source, - address: u64::MAX - 15, + address: GuestAddress(u64::MAX - 15), }, )); assert_eq!( @@ -236,7 +276,7 @@ mod tests { }), Some(ConstantWrite { destination, - value: 16 + value: Constant::Guest(GuestAddress(16)) }) ); } @@ -267,6 +307,41 @@ mod tests { facts.step(&wide(WideMove::Not, Width::X64, Register::Zero, 0, 0)), None ); - assert_eq!(facts.read(Register::Zero), Some(0)); + assert_eq!(facts.read(Register::Zero), Some(Constant::Plain(0))); + } + + #[test] + fn a_guest_address_narrowed_or_patched_is_no_longer_known() { + let address = || { + Operation::PcRelative(crate::aarch64::pc_relative::Operand { + destination: Register::X(1), + address: GuestAddress(0x1_2345_6000), + }) + }; + let mut facts = ConstantRegisters::default(); + facts.step(&address()); + assert_eq!( + facts.step(&wide(WideMove::Keep, Width::X64, Register::X(1), 7, 0)), + None + ); + facts.step(&address()); + let narrowed = Operation::AddSub { + width: Width::W32, + subtract: false, + flags: false, + destination: Register::X(2), + source: Register::X(1), + immediate: 8, + }; + assert_eq!(facts.step(&narrowed), None); + let mut facts = ConstantRegisters::default(); + facts.step(&wide(WideMove::Zero, Width::X64, Register::X(1), 0x10, 16)); + assert_eq!( + facts.step(&narrowed), + Some(ConstantWrite { + destination: Register::X(2), + value: Constant::Plain(0x10_0008) + }) + ); } } diff --git a/crates/stela-compiler/src/x86_64/region/encoding.rs b/crates/stela-compiler/src/x86_64/region/encoding.rs index bd6e706db3..798f62bb99 100644 --- a/crates/stela-compiler/src/x86_64/region/encoding.rs +++ b/crates/stela-compiler/src/x86_64/region/encoding.rs @@ -150,6 +150,11 @@ pub fn store_nzcv(code: &mut Code, source: HostGpr) { code.asm().mov_store(Size::Dword, nzcv(), source.gpr()); } +/// `movabs destination,address`, its field a relocation of the block. +pub fn guest_immediate(code: &mut Code, destination: HostGpr, address: crate::GuestAddress) { + code.asm().guest_imm64(destination.gpr(), address); +} + pub fn immediate(code: &mut Code, destination: HostGpr, value: u64, width: Width) { match width { Width::X64 => code.asm().mov_imm64(destination.gpr(), 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 310a63a2df..f3941b36b1 100644 --- a/crates/stela-compiler/src/x86_64/region/self_loop.rs +++ b/crates/stela-compiler/src/x86_64/region/self_loop.rs @@ -381,8 +381,12 @@ pub(crate) fn prefix_with_budget(mut native: NativeBlock, base: GuestAddress) -> encoding::patch_relative(&mut code, body_jump, body); encoding::decrement_stored_budget(&mut code); let prefix = code.len(); - let mut bytes = code.into_bytes(); + let (mut bytes, mut relocations) = code.into_parts(); bytes.extend(native.x86_64_code); + native.relocations = native.relocations.map(|fields| { + relocations.extend(fields.into_iter().map(|at| at + prefix as u32)); + relocations + }); for (_, offset) in &mut native.source_map { *offset += prefix; } @@ -688,9 +692,11 @@ impl LegacyPlan { if let Some((_, offset)) = emitter.output.source_map.first_mut() { *offset = 0; } + let (x86_64_code, relocations) = emitter.output.code.into_parts(); Ok(NativeBlock { - x86_64_code: emitter.output.code.into_bytes(), + x86_64_code, source_map: emitter.output.source_map, + relocations: Some(relocations), }) } } @@ -830,9 +836,11 @@ fn allocated_loop( // Hot pressure is the primary loop cost. Equal pressure uses the smallest // complete body, then the smaller native callee-save footprint. let cost = (hot_frame, emitter.output.code.len(), callee_slots); + let (x86_64_code, relocations) = emitter.output.code.into_parts(); let native = NativeBlock { - x86_64_code: emitter.output.code.into_bytes(), + x86_64_code, source_map: emitter.output.source_map, + relocations: Some(relocations), }; if best.as_ref().is_none_or(|(old, _)| cost < *old) { best = Some((cost, native)); diff --git a/crates/stela-compiler/src/x86_64/region/tests.rs b/crates/stela-compiler/src/x86_64/region/tests.rs index fb801e7c5a..89510d465e 100644 --- a/crates/stela-compiler/src/x86_64/region/tests.rs +++ b/crates/stela-compiler/src/x86_64/region/tests.rs @@ -119,7 +119,7 @@ fn address_pair_shares_one_literal_and_preserves_distinct_source_rows() { 0, Operation::PcRelative(crate::aarch64::pc_relative::Operand { destination: x0, - address: u64::MAX, + address: crate::GuestAddress(u64::MAX), }), ), instruction(1, add(x0, x0)), diff --git a/crates/stela-compiler/src/x86_64/register_read.rs b/crates/stela-compiler/src/x86_64/register_read.rs index 048af2f6c4..1941374276 100644 --- a/crates/stela-compiler/src/x86_64/register_read.rs +++ b/crates/stela-compiler/src/x86_64/register_read.rs @@ -359,7 +359,7 @@ pub fn thread_switch_thunk(pc: GuestAddress, rt: u8, cell: Place, places: &Threa asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, frame)), Rax); load_x(&mut asm, 30); asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, link)), Rax); - asm.mov_imm64(Rax, pc.0); + asm.guest_imm64(Rax, pc); asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, pc)), Rax); load_x(&mut asm, rt); asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, next)), Rax); diff --git a/crates/stela-compiler/src/x86_64/simd/memory_checked.rs b/crates/stela-compiler/src/x86_64/simd/memory_checked.rs index 4a9ec254cd..19b4009b27 100644 --- a/crates/stela-compiler/src/x86_64/simd/memory_checked.rs +++ b/crates/stela-compiler/src/x86_64/simd/memory_checked.rs @@ -39,7 +39,7 @@ fn scratch(offset: u8) -> Mem { #[derive(Clone, Copy)] enum Address { Literal { - address: u64, + address: crate::GuestAddress, }, Immediate { displacement: i32, @@ -178,7 +178,8 @@ impl Transfer { fn naturally_aligned(self) -> bool { match self.address { Address::Literal { address } => { - address.is_multiple_of(u64::from(self.quantity_bytes())) + // Its page offset alone decides: the same at every page. + address.0.is_multiple_of(u64::from(self.quantity_bytes())) } Address::Immediate { displacement, mode } => { crate::x86_64::memory_store::aligned_immediate( @@ -333,7 +334,7 @@ fn transfer_requirements( fn address(code: &mut Code, transfer: Transfer, profile: CheckedMemoryProfile) { match transfer.address { - Address::Literal { address } => crate::x86_64::immediate(code, address), + Address::Literal { address } => crate::x86_64::guest_immediate(code, address), Address::Immediate { displacement, mode } => { service::address::immediate_with_checks( code, diff --git a/crates/stela-compiler/src/x86_64/simd/memory_checked/tests.rs b/crates/stela-compiler/src/x86_64/simd/memory_checked/tests.rs index 0fd5183f63..3ca6af9441 100644 --- a/crates/stela-compiler/src/x86_64/simd/memory_checked/tests.rs +++ b/crates/stela-compiler/src/x86_64/simd/memory_checked/tests.rs @@ -63,7 +63,7 @@ fn literal_adapter_preserves_absolute_source_address_and_rejects_invalid_shapes( assert!(!checked.transfer.writeback()); assert!( matches!(checked.transfer.address, Address::Literal { address } - if address == (i128::from(pc) + i128::from(immediate) * 4) as u64) + if address.0 == (i128::from(pc) + i128::from(immediate) * 4) as u64) ); assert_eq!(checked.requirements().required_flags, flags::ASIMD); assert_eq!( @@ -78,7 +78,7 @@ fn literal_adapter_preserves_absolute_source_address_and_rejects_invalid_shapes( assert!( CheckedOperand::from_operation( &Operation::Literal(literal::Operand { - address: GUEST_BASE, + address: crate::GuestAddress(GUEST_BASE), transfer: literal::Transfer::Simd { destination, bytes }, }), CheckedMemoryProfile::SpAlignmentDisabled, @@ -579,7 +579,7 @@ fn literal_loads_zero_upper_bits_and_commit_only_after_the_complete_read() { for residue in [0, 4, 8, 12] { let address = GUEST_BASE + 32 + residue; let operation = Operation::Literal(literal::Operand { - address, + address: crate::GuestAddress(address), transfer: literal::Transfer::Simd { destination, bytes }, }); let checked = CheckedOperand::from_operation( diff --git a/crates/stela-compiler/src/x86_64/transition.rs b/crates/stela-compiler/src/x86_64/transition.rs index ca094d3eb2..a730666183 100644 --- a/crates/stela-compiler/src/x86_64/transition.rs +++ b/crates/stela-compiler/src/x86_64/transition.rs @@ -466,7 +466,7 @@ pub fn guarded_enter_thunk(pc: GuestAddress, syndrome: u32, places: &Places) -> asm.mov_load(Qword, Rcx, record_field(offset_of!(Record, spsr))); asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); asm.mov_load(Qword, Rcx, record_field(offset_of!(Record, elr))); - asm.mov_imm64(Rax, pc.0.wrapping_add(4)); + asm.guest_imm64(Rax, GuestAddress(pc.0.wrapping_add(4))); asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); asm.mov_load(Qword, Rcx, record_field(offset_of!(Record, esr))); asm.mov_imm32(Rax, syndrome); @@ -733,7 +733,7 @@ pub fn supervisor_call_thunk(pc: GuestAddress, syndrome: u32, places: &Places) - asm.mov_load(Qword, Rcx, record_field(offset_of!(Record, spsr))); asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); asm.mov_load(Qword, Rcx, record_field(offset_of!(Record, elr))); - asm.mov_imm64(Rax, pc.0.wrapping_add(4)); + asm.guest_imm64(Rax, GuestAddress(pc.0.wrapping_add(4))); asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); asm.mov_load(Qword, Rcx, record_field(offset_of!(Record, esr))); asm.mov_imm32(Rax, syndrome); diff --git a/crates/stela-engine/src/artifact/prepare.rs b/crates/stela-engine/src/artifact/prepare.rs index 580e4e1218..7a4eb0bdb5 100644 --- a/crates/stela-engine/src/artifact/prepare.rs +++ b/crates/stela-engine/src/artifact/prepare.rs @@ -17,6 +17,7 @@ pub(crate) fn generate( let stela_compiler::NativeBlock { x86_64_code, source_map, + .. } = compile()?; require!( !x86_64_code.is_empty() && x86_64_code.len() <= MAX_CACHE_NATIVE_BYTES, @@ -141,6 +142,7 @@ mod tests { generate(identity, None, || Ok(stela_compiler::NativeBlock { x86_64_code: vec![], source_map: vec![], + relocations: None, })) .is_err() ); diff --git a/crates/stela-engine/src/execution/checked_memory/tests.rs b/crates/stela-engine/src/execution/checked_memory/tests.rs index bd164fccca..0460b572ca 100644 --- a/crates/stela-engine/src/execution/checked_memory/tests.rs +++ b/crates/stela-engine/src/execution/checked_memory/tests.rs @@ -473,7 +473,10 @@ fn checked_low128_literal_entry_requires_context_and_preserves_full_fault_state( assert_eq!(pc.0, expected.x[30]); } assert_eq!(registers, expected); - assert_eq!(literal::decode(PC, word).unwrap().unwrap().address, address); + assert_eq!( + literal::decode(PC, word).unwrap().unwrap().address.0, + address + ); } } } diff --git a/crates/stela-engine/src/machine.rs b/crates/stela-engine/src/machine.rs index 0abf58f553..304a9866af 100644 --- a/crates/stela-engine/src/machine.rs +++ b/crates/stela-engine/src/machine.rs @@ -31,11 +31,11 @@ pub use cpu::{Cpu, Exception}; #[cfg(test)] pub(crate) use engine::test_preparation; pub use engine::{ - ConsumedPair, Description, DeviceError, DeviceRegister, Devices, Event, FaultCause, Host, - InstallError, Machine, NativeCode, NativeExit, NativeFault, NativeFaultOrigin, NativeView, - NoDevices, Offer, PeState, PeerState, Preparation, Prepared, Refused, Regime, Requirement, - RequirementKind, Reset, StaleCode, StaleOrigin, Statistics, Stop, Transition, Translations, - window, + ConsumedPair, Description, DeviceError, DeviceRegister, Devices, EntryChecks, Event, + FaultCause, Host, InstallError, Machine, NativeCode, NativeExit, NativeFault, + NativeFaultOrigin, NativeView, NoDevices, Offer, PeState, PeerState, Preparation, Prepared, + Refused, Regime, Requirement, RequirementKind, Reset, StaleCode, StaleOrigin, Statistics, Stop, + Transition, Translations, entry_checks, window, }; pub use registers::{CpuProfile, Lines}; #[cfg(test)] diff --git a/crates/stela-engine/src/machine/engine.rs b/crates/stela-engine/src/machine/engine.rs index f319f893d4..49f28010df 100644 --- a/crates/stela-engine/src/machine/engine.rs +++ b/crates/stela-engine/src/machine/engine.rs @@ -158,7 +158,7 @@ use stela_compiler::{ pub use stela_contracts::bus::Transition; pub use stela_contracts::dma::Memory; pub use stela_contracts::gate::{CallerFault, CallerMemory, GateCall, GateOutcome}; -pub use stored::{Offer, SharedTranslation, StoreEvent, Translations}; +pub use stored::{EntryChecks, Offer, SharedTranslation, StoreEvent, Translations, entry_checks}; pub use system::FP_TRAPS_WRITABLE; use { super::cpu::Cpu, super::cpu::Exception, super::cpu::HCR_AMO, super::cpu::HCR_API, diff --git a/crates/stela-engine/src/machine/engine/compilation.rs b/crates/stela-engine/src/machine/engine/compilation.rs index 8539de5848..d2f351bc77 100644 --- a/crates/stela-engine/src/machine/engine/compilation.rs +++ b/crates/stela-engine/src/machine/engine/compilation.rs @@ -615,9 +615,9 @@ impl Machine { let context = stored .is_some() .then(|| self.stored_context(variant, &preparation, page)); - // Compiled at another PC of the same page content before: proven - // once compiled here ([`super::rebase`]). - let mut prove = false; + // Compiled at another PC of the same page content before: its + // stored form is kept once compiled here ([`super::rebase`]). + let mut keep = false; if let (Some((key, record)), Some(context)) = (&stored, &context) { // The machine's buffers take the entry's relocated code: an // install from the store allocates nothing. @@ -676,7 +676,7 @@ impl Machine { } } // The same page content, compiled at another address of this - // boot: its proven entry, rebased to this page. + // boot: its kept entry, rebased to this page. match self.code.rebases.look(key, offset as u16, context, pc) { super::rebase::Found::Entry(entry) => { if entry.input.len() > available && !whole { @@ -711,7 +711,7 @@ impl Machine { } self.relocated = relocated; } - super::rebase::Found::Prove => prove = true, + super::rebase::Found::Keep => keep = true, super::rebase::Found::Compile => {} } } @@ -775,12 +775,11 @@ impl Machine { compiled, preparation, )); - if prove + if keep && !self.host.memory_low() && let (Some((key, _)), Some(context)) = (&stored, &context) { - let proving = self.host.counter(); - let entry = Offer::prove_block( + let entry = super::stored::stored_entry( &emission.block, &emission.input, page, @@ -789,10 +788,9 @@ impl Machine { &emission.preparation, ); self.code.rebases.keep(key, offset as u16, context, entry); - self.statistics.compile_ticks += self.host.counter().wrapping_sub(proving); } - // An offer is kept until the store proves it. With memory low the - // store holds no more for proof, but the other PEs still take the + // A store keeps an offer's stored form. With memory low it keeps no + // more, but the other PEs still take the // block: this one retains the emission anyway, and each reuse saves // a compile and a copy. if let (Some((key, _)), Some(context)) = (stored, context) diff --git a/crates/stela-engine/src/machine/engine/data_access.rs b/crates/stela-engine/src/machine/engine/data_access.rs index 81fa495186..19cc0dd505 100644 --- a/crates/stela-engine/src/machine/engine/data_access.rs +++ b/crates/stela-engine/src/machine/engine/data_access.rs @@ -239,7 +239,7 @@ impl Machine { address: ScalarLoadAddress, ) -> (u64, Option<(Register, u64)>) { match address { - ScalarLoadAddress::Literal { address } => (address, None), + ScalarLoadAddress::Literal { address } => (address.0, None), ScalarLoadAddress::Immediate { base, displacement, diff --git a/crates/stela-engine/src/machine/engine/device_access.rs b/crates/stela-engine/src/machine/engine/device_access.rs index 60bd345f21..76b8e6a599 100644 --- a/crates/stela-engine/src/machine/engine/device_access.rs +++ b/crates/stela-engine/src/machine/engine/device_access.rs @@ -106,6 +106,8 @@ impl Machine { native: stela_compiler::NativeBlock { x86_64_code: chain::direct_exit(GuestAddress(pc), ExitKind::System).to_vec(), source_map: alloc::vec![(GuestAddress(pc), 0)], + // A device stub is never stored. + relocations: None, }, source_bytes: INSTRUCTION as usize, direct_exits: Vec::new(), diff --git a/crates/stela-engine/src/machine/engine/rebase.rs b/crates/stela-engine/src/machine/engine/rebase.rs index bff11f59bb..99acf6076a 100644 --- a/crates/stela-engine/src/machine/engine/rebase.rs +++ b/crates/stela-engine/src/machine/engine/rebase.rs @@ -1,13 +1,12 @@ //! In-boot reuse of a block at another virtual address: the same page //! content mapped at a new address on each exec (a main program, the loader) -//! is rebased from a proven entry instead of compiled again. +//! is rebased from a stored entry instead of compiled again. //! //! The board keeps, by (page key, entry offset, entry context), what its //! PEs compiled there: first only the PC it was compiled at (`Seen`). A -//! compile of the same key, offset and context at another PC proves the -//! block ([`crate::translations::prove`], the pack's proof: the block -//! compiled again at both probe addresses) and keeps the proven entry; later -//! fetches at any page of that content relocate it +//! compile of the same key, offset and context at another PC keeps the +//! block's stored form ([`Entry::stored`], from the relocations its +//! compiler recorded); later fetches at any page of that content relocate it //! ([`Entry::relocate`]), with the checks the pack's entries pass: the //! admitted input equal to the fetch's bytes, a page-aligned rebase and //! recovery rows that rebase. @@ -36,7 +35,7 @@ const PARTS: usize = 8; type Key = (Digest, u16, Digest); /// What a key, its slot and its place in the order cost, apart from a -/// proven entry's buffers. +/// kept entry's buffers. const KEY_BYTES: usize = 2 * core::mem::size_of::<(Key, Slot, u64)>() + core::mem::size_of::<(Key, u64)>() + 4 * core::mem::size_of::(); @@ -45,16 +44,17 @@ const KEY_BYTES: usize = 2 * core::mem::size_of::<(Key, Slot, u64)>() enum Slot { /// Compiled at this PC only so far. Seen(u64), - Proven(Arc), - /// Its proof failed: it is compiled at every address. - Unprovable, + Kept(Arc), + /// Its compiler found a value no relocation reproduces: it is compiled + /// at every address. + Unstorable, } impl Slot { fn bytes(&self) -> usize { KEY_BYTES + match self { - Self::Proven(entry) => entry.retained_bytes(), + Self::Kept(entry) => entry.retained_bytes(), _ => 0, } } @@ -128,32 +128,32 @@ impl Part { pub(super) enum Found { /// Relocate this entry. Entry(Arc), - /// Compile it, then prove it ([`Rebases::keep`]): it was compiled at - /// another PC before. - Prove, + /// Compile it, then keep its stored form ([`Rebases::keep`]): it was + /// compiled at another PC before. + Keep, /// Compile it. Compile, } -/// Reuse hits and proofs, for `PES CODE`. +/// Reuse hits and entries kept, for `PES CODE`. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct RebaseCounts { - /// Installs relocated from a proven entry. + /// Installs relocated from a kept entry. pub hits: u64, - /// Entries proven, and proofs that failed. - pub proven: u64, - pub unprovable: u64, + /// Entries kept, and blocks with no stored form. + pub kept: u64, + pub unstorable: u64, /// The bytes kept now. pub bytes: usize, } -/// The board's proven entries, by page key, offset and context. +/// The board's kept entries, by page key, offset and context. pub(super) struct Rebases { parts: [Mutex; PARTS], bound: usize, hits: AtomicU64, - proven: AtomicU64, - unprovable: AtomicU64, + kept: AtomicU64, + unstorable: AtomicU64, } impl Rebases { @@ -162,8 +162,8 @@ impl Rebases { parts: core::array::from_fn(|_| Mutex::new(Part::default())), bound: bound / PARTS, hits: AtomicU64::new(0), - proven: AtomicU64::new(0), - unprovable: AtomicU64::new(0), + kept: AtomicU64::new(0), + unstorable: AtomicU64::new(0), } } @@ -180,12 +180,12 @@ impl Rebases { let slot = (*key, offset, *context); let mut part = self.part(key); match part.slots.get(&slot) { - Some((Slot::Proven(entry), _)) => { + Some((Slot::Kept(entry), _)) => { let entry = Arc::clone(entry); part.touch(&slot); Found::Entry(entry) } - Some((Slot::Seen(seen), _)) if *seen != pc => Found::Prove, + Some((Slot::Seen(seen), _)) if *seen != pc => Found::Keep, Some(_) => Found::Compile, None => { part.put(slot, Slot::Seen(pc), self.bound); @@ -194,24 +194,24 @@ impl Rebases { } } - /// Keep the proof of the block at `offset` of `key` in `context`: its - /// entry, or `None` when it moves by other than its address. + /// Keep the stored form of the block at `offset` of `key` in + /// `context`: its entry, or `None` when it has none. pub(super) fn keep(&self, key: &Digest, offset: u16, context: &Digest, entry: Option) { let slot = match entry { Some(entry) => { - self.proven.fetch_add(1, Ordering::Relaxed); - Slot::Proven(Arc::new(entry)) + self.kept.fetch_add(1, Ordering::Relaxed); + Slot::Kept(Arc::new(entry)) } None => { - self.unprovable.fetch_add(1, Ordering::Relaxed); - Slot::Unprovable + self.unstorable.fetch_add(1, Ordering::Relaxed); + Slot::Unstorable } }; self.part(key) .put((*key, offset, *context), slot, self.bound); } - /// Count an install relocated from a proven entry. + /// Count an install relocated from a kept entry. pub(super) fn hit(&self) { self.hits.fetch_add(1, Ordering::Relaxed); } @@ -219,8 +219,8 @@ impl Rebases { pub(super) fn counts(&self) -> RebaseCounts { RebaseCounts { hits: self.hits.load(Ordering::Relaxed), - proven: self.proven.load(Ordering::Relaxed), - unprovable: self.unprovable.load(Ordering::Relaxed), + kept: self.kept.load(Ordering::Relaxed), + unstorable: self.unstorable.load(Ordering::Relaxed), bytes: (0..PARTS) .map(|at| { self.parts[at] @@ -252,21 +252,21 @@ mod tests { } #[test] - fn a_second_pc_proves_and_a_proven_entry_serves_every_pc() { + fn a_second_pc_keeps_the_entry_and_it_serves_every_pc() { let rebases = Rebases::new(BOUND); let (key, context) = (Digest([1; 32]), Digest([2; 32])); assert!(matches!( rebases.look(&key, 8, &context, 0x1008), Found::Compile )); - // The same PC again (its block went) compiles; another proves. + // The same PC again (its block went) compiles; another keeps. assert!(matches!( rebases.look(&key, 8, &context, 0x1008), Found::Compile )); assert!(matches!( rebases.look(&key, 8, &context, 0x5008), - Found::Prove + Found::Keep )); rebases.keep(&key, 8, &context, Some(entry(8, 64))); for pc in [0x1008, 0x5008, 0x9008] { @@ -290,13 +290,13 @@ mod tests { Found::Compile )); let counts = rebases.counts(); - assert_eq!((counts.proven, counts.unprovable), (1, 1)); + assert_eq!((counts.kept, counts.unstorable), (1, 1)); } #[test] fn the_oldest_keys_go_when_the_bound_is_full() { // One part's share holds about ten keys with a small entry each. - let one = Slot::Proven(Arc::new(entry(0, 256))).bytes(); + let one = Slot::Kept(Arc::new(entry(0, 256))).bytes(); let rebases = Rebases::new(PARTS * one * 10); let context = Digest::default(); // Keys of one part (the same first byte). diff --git a/crates/stela-engine/src/machine/engine/recovery/tests.rs b/crates/stela-engine/src/machine/engine/recovery/tests.rs index fd59754fb9..711004c272 100644 --- a/crates/stela-engine/src/machine/engine/recovery/tests.rs +++ b/crates/stela-engine/src/machine/engine/recovery/tests.rs @@ -106,7 +106,7 @@ fn exact_lazy_qualification_replaces_portable_bank_with_only_minted_rows() { assert!(!expected.is_empty()); let translator = translator_id(); let mut record = Record::new(translator, key); - record.insert(offer.prove().unwrap()); + record.insert(offer.entry().unwrap()); let record = Record::decode(&record.encode(), &translator, &key).unwrap(); let origin = Arc::new(StoredOrigin { key, @@ -157,7 +157,7 @@ fn a_kept_entry_qualifies_at_its_new_page_without_a_record() { ) .unwrap() }; - let entry = Arc::new(at(BASE).prove().unwrap()); + let entry = Arc::new(at(BASE).entry().unwrap()); let expected = at(moved).block().fault_recovery.clone(); assert!(!expected.is_empty()); let origin = Arc::new(StoredOrigin { diff --git a/crates/stela-engine/src/machine/engine/stored.rs b/crates/stela-engine/src/machine/engine/stored.rs index 1185487022..b87f763a12 100644 --- a/crates/stela-engine/src/machine/engine/stored.rs +++ b/crates/stela-engine/src/machine/engine/stored.rs @@ -4,14 +4,95 @@ //! record has is rebased instead of compiled. A block the store's process //! already prepared at the same PC (another thread's, or ahead-of-time //! translation's) is installed as it is. A block compiled anew is offered -//! back, with what the host needs to compile it again at the probe -//! addresses (`translations::prove`). +//! back; its stored form is its code with the relocations its compiler +//! recorded made relative to its page ([`stored_entry`]). use super::recovery::StoredOrigin; use super::{Devices, FETCH_PAGE, Host, Machine, Preparation, Variant}; -use crate::translations::{Digest, PAGE_BYTES, Record}; +use crate::translations::{Digest, Entry, PAGE_BYTES, Record}; use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use core::sync::atomic::{AtomicU64, Ordering}; use stela_compiler::block::CompiledBlock; +/// A profile build checks one stored form in this many ([`stored_entry`]). +const CHECK_INTERVAL: u64 = 1024; + +/// Stored forms made, checked against the block compiled at other pages, +/// and those the check found to differ ([`EntryChecks`]). +static ENTRIES: AtomicU64 = AtomicU64::new(0); +static CHECKED: AtomicU64 = AtomicU64::new(0); +static DIFFERED: AtomicU64 = AtomicU64::new(0); + +/// Stored forms checked against a compile at other pages, and those that +/// differed and were not stored ([`stored_entry`]). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct EntryChecks { + pub checked: u64, + pub differed: u64, +} + +/// The stored-form checks of this process so far. +pub fn entry_checks() -> EntryChecks { + EntryChecks { + checked: CHECKED.load(Ordering::Relaxed), + differed: DIFFERED.load(Ordering::Relaxed), + } +} + +/// The stored form of `block`, compiled through `preparation` at `pc` of +/// the page at `page` from `input` ([`Entry::stored`]). The compiler makes +/// it as it emits; a check compiles the block again at both probe addresses +/// of its page and requires the fields that move to be the relocations it +/// recorded ([`crate::translations::prove`]). Test and debug builds check +/// every one and panic on a difference; a profile build checks one in +/// [`CHECK_INTERVAL`], counts any that differ ([`entry_checks`]) and keeps +/// those out of the store. Other builds trust the compiler. +pub(super) fn stored_entry( + block: &CompiledBlock, + input: &[u8], + page: u64, + pc: u64, + context: Digest, + preparation: &Preparation, +) -> Option { + let entry = Entry::stored(block, input, page, pc, context)?; + let due = if cfg!(any(test, debug_assertions)) { + true + } else if cfg!(feature = "native-profile") { + ENTRIES + .fetch_add(1, Ordering::Relaxed) + .is_multiple_of(CHECK_INTERVAL) + } else { + false + }; + if !due { + return Some(entry); + } + CHECKED.fetch_add(1, Ordering::Relaxed); + let probes = crate::translations::probe_displacements(page).map(|displacement| { + preparation + .compile_input(input, pc.wrapping_add(displacement)) + .ok() + }); + let proven = match &probes { + [Some(first), Some(second)] => { + crate::translations::prove(block, input, page, pc, context, [first, second]) + } + _ => None, + }; + if proven.as_ref() == Some(&entry) { + return Some(entry); + } + DIFFERED.fetch_add(1, Ordering::Relaxed); + debug_assert!( + false, + "the relocations recorded for the block at {pc:#x} are not the fields that move: \ + recorded {:?}, moved {:?}", + entry.relocations, + proven.map(|proven| proven.relocations) + ); + None +} + /// A block as compiled, with its complete admitted input and the /// preparation that compiled it: immutable once made, so the store and every /// PE that installs it share one. Its fault recovery rows are qualified. @@ -27,8 +108,8 @@ impl Emission { mut block: CompiledBlock, preparation: Arc, ) -> Self { - // The store keeps an emission until it proves it, sharing its bound - // by capacity: none of it is slack. + // The shared cache keeps an emission within its bound by capacity: + // none of it is slack. input.shrink_to_fit(); block.native.x86_64_code.shrink_to_fit(); block.native.source_map.shrink_to_fit(); @@ -247,23 +328,9 @@ impl Offer { }) } - /// Writable stores keep the original offer for proof admission. The - /// shared cache does not need the offer's separate successor list. - pub(crate) fn shared_for_proof(&self) -> Arc { - Arc::new(SharedTranslation { - emission: Arc::clone(&self.emission), - key: self.key, - page: self.page, - pc: self.pc, - context: self.context, - }) - } - - /// Its block's stored form: the block compiled again at both probe - /// addresses of its page, proven to move only by them - /// ([`translations::prove`](crate::translations::prove)). - pub fn prove(&self) -> Option { - Self::prove_block( + /// Its block's stored form ([`stored_entry`]). + pub fn entry(&self) -> Option { + stored_entry( self.block(), self.input(), self.page, @@ -272,41 +339,6 @@ impl Offer { 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) - } - - pub(super) 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 80e36fc154..a1b566bc6a 100644 --- a/crates/stela-engine/src/machine/engine/stored/tests.rs +++ b/crates/stela-engine/src/machine/engine/stored/tests.rs @@ -179,7 +179,7 @@ fn cached_blocks_do_not_cross_presented_instruction_features() { )); let offer = first.host.store.as_mut().unwrap().offers.pop().unwrap(); let mut record = Record::new(translations::translator_id(), offer.key); - record.insert(proven(&offer)); + record.insert(offer.entry().unwrap()); for shared in [false, true] { for same_profile in [false, true] { let mut store = MemoryStore::default(); @@ -239,11 +239,6 @@ fn a_block_another_thread_prepared_at_the_same_pc_is_installed_as_it_is() { assert_eq!(second.statistics.compiled, 1); } -/// What the directory store's workers do with an offer. -fn proven(offer: &Offer) -> translations::Entry { - offer.prove().unwrap() -} - #[test] fn a_stored_block_of_the_same_page_bytes_is_installed_without_compiling() { // adr x0, #8; add x0, x0, #1; svc #0 @@ -260,7 +255,7 @@ fn a_stored_block_of_the_same_page_bytes_is_installed_without_compiling() { let offer = first.host.store.as_mut().unwrap().offers.pop().unwrap(); assert_eq!((offer.page, offer.pc), (BASE, BASE + 4)); let mut record = Record::new(translations::translator_id(), offer.key); - record.insert(proven(&offer)); + record.insert(offer.entry().unwrap()); let mut store = MemoryStore::default(); store.records.insert(offer.key, Arc::new(record)); let mut second = machine(&words); @@ -322,7 +317,7 @@ fn a_block_longer_than_the_first_window_compiles_and_is_stored_whole() { 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); - record.insert(proven(&offer)); + record.insert(offer.entry().unwrap()); let mut store = MemoryStore::default(); store.records.insert(offer.key, Arc::new(record)); let mut second = machine(&words); @@ -458,7 +453,7 @@ fn a_stored_install_relocates_into_the_machines_own_buffers() { let offers = core::mem::take(&mut first.host.store.as_mut().unwrap().offers); let mut record = Record::new(translations::translator_id(), offers[0].key); for offer in &offers { - record.insert(proven(offer)); + record.insert(offer.entry().unwrap()); } let mut store = MemoryStore::default(); store.records.insert(offers[0].key, Arc::new(record)); @@ -518,7 +513,7 @@ fn installs_count_where_their_block_came_from_at_their_level() { let offer = first.host.store.as_mut().unwrap().offers.pop().unwrap(); let mut record = Record::new(translations::translator_id(), offer.key); - record.insert(proven(&offer)); + record.insert(offer.entry().unwrap()); let mut store = MemoryStore::default(); store.records.insert(offer.key, Arc::new(record)); store @@ -561,7 +556,7 @@ fn installs_count_where_their_block_came_from_at_their_level() { } /// The same page content at four addresses: compiled at the first, -/// compiled and proven at the second, rebased at the third, where it is +/// compiled and kept at the second, rebased at the third, where it is /// what a compile there installs. A rewritten page is compiled again. #[test] fn a_block_compiled_at_two_addresses_is_rebased_at_a_third() { @@ -577,16 +572,16 @@ fn a_block_compiled_at_two_addresses_is_rebased_at_a_third() { let mut reusing = machine(&words); reusing.host.store = Some(MemoryStore::default()); assert!(reusing.fetch_block(page(0), false).is_ok()); - assert_eq!(reusing.code.rebases.counts().proven, 0); + assert_eq!(reusing.code.rebases.counts().kept, 0); assert!(reusing.fetch_block(page(1), false).is_ok()); assert_eq!(reusing.statistics.compiled, 2); - assert_eq!(reusing.code.rebases.counts().proven, 1); + assert_eq!(reusing.code.rebases.counts().kept, 1); let Ok(Fetched::Block(rebased)) = reusing.fetch_block(page(2), false) else { panic!("rebased block") }; assert_eq!(reusing.statistics.compiled, 2); let counts = reusing.code.rebases.counts(); - assert_eq!((counts.hits, counts.proven, counts.unprovable), (1, 1, 0)); + assert_eq!((counts.hits, counts.kept, counts.unstorable), (1, 1, 0)); assert_eq!( reusing.statistics.store_sources[1][super::super::StoreSource::Rebased as usize], 1 @@ -625,7 +620,7 @@ fn a_block_compiled_at_two_addresses_is_rebased_at_a_third() { panic!("compiled block") }; assert_eq!(installed(&reusing, changed), installed(&fresh, compiled)); - // The fourth page still holds the proven content. + // The fourth page still holds the kept content. assert!(reusing.fetch_block(page(3), false).is_ok()); assert_eq!( ( @@ -635,3 +630,275 @@ fn a_block_compiled_at_two_addresses_is_rebased_at_a_third() { (3, 2) ); } + +/// What fetching every block of a code image costs, as the engine +/// prepares them: `STELA_COMPILE_BENCH` names a file of A64 code +/// (`STELA_COMPILE_OFFSET`, `STELA_COMPILE_BYTES` choose a part), swept +/// block after block from its start. Prints per-block costs of the +/// compile, the store's proof and its record encoding and decoding. +/// A preparation as a boot's kernel PEs compile with: system mode with its +/// range checks, exclusives, pointer cells and self loops. +fn system_preparation(target: stela_compiler::TargetCpu) -> Preparation { + use stela_compiler::x86_64::{MemoryChecks, NativeSystem, RangeCheck}; + let chip = crate::machine::test_chip(); + let checks = MemoryChecks::system(true, false, true, false) + .with_range(RangeCheck::four_level(4).one_sided(true)); + let system = NativeSystem { + exclusive: true, + pointer: Some(super::super::pointer::CELLS), + self_loops: true, + ..NativeSystem::NONE + }; + Preparation::new( + chip, + Arc::new(chip.admit_table(0).expect("admit")), + target, + true, + checks, + None, + system, + ) +} + +/// One instruction word of a kind whose code may name its own address or +/// fold a value derived from it: PC-relative addresses, additions and wide +/// moves over them, literal loads and prefetches, branches and links, and +/// ordinary memory and register work between them. Registers come from a +/// few, so that the words depend on each other. +fn address_word(random: &mut impl FnMut() -> u32) -> u32 { + let register = |value: u32| value % 4; + let (r, n, value) = (register(random()), register(random()), random()); + match random() % 16 { + 0 => 0x1000_0000 | ((value & 3) << 29) | (((value >> 2) & 0x7ffff) << 5) | r, + 1 => 0x9000_0000 | ((value & 3) << 29) | (((value >> 2) & 0x7ffff) << 5) | r, + 2 | 3 => 0x9100_0000 | ((value & 0xfff) << 10) | (n << 5) | r, + 4 => 0x1100_0000 | ((value & 0xfff) << 10) | (n << 5) | r, + 5 => 0xd100_0000 | ((value & 0xfff) << 10) | (n << 5) | r, + 6 => 0xd280_0000 | ((value & 3) << 21) | (((value >> 2) & 0xffff) << 5) | r, + 7 => 0xf280_0000 | ((value & 3) << 21) | (((value >> 2) & 0xffff) << 5) | r, + 8 => 0x7280_0000 | ((value & 1) << 21) | (((value >> 2) & 0xffff) << 5) | r, + 9 => { + [0x5800_0000, 0x1800_0000, 0x9800_0000, 0x9c00_0000][value as usize % 4] + | (((value >> 2) & 0x3ff) << 5) + | r + } + 10 => 0xd800_0000 | (((value >> 2) & 0x3ff) << 5), + 11 => 0xf940_0000 | ((value & 0x3f) << 10) | (n << 5) | r, + 12 => 0xf900_0000 | ((value & 0x3f) << 10) | (n << 5) | r, + 13 => 0x8b00_0000 | ((value & 3) << 16) | (n << 5) | r, + 14 => 0xd503_201f, + _ => 0xaa00_03e0 | (n << 16) | r, + } +} + +/// A word that ends a block: conditional, compare and test branches near +/// and far, direct and linked branches, a register call, a return or a +/// trap. +fn ending_word(random: &mut impl FnMut() -> u32) -> u32 { + let (r, value) = (random() % 4, random()); + match random() % 8 { + 0 => 0x5400_0000 | (((value >> 4) & 0x7ffff) << 5) | (value % 14), + 1 => 0xb400_0000 | (((value >> 4) & 0x7ffff) << 5) | r, + 2 => 0x3600_0000 | ((value & 0x1f) << 19) | (((value >> 5) & 0x3fff) << 5) | r, + 3 => 0x1400_0000 | (value >> 6), + 4 => 0x9400_0000 | (value >> 6), + 5 => 0xd63f_0000 | (r << 5), + 6 => 0xd65f_03c0, + _ => 0xd400_0001, + } +} + +/// Every block's stored form, made from the relocations its compiler +/// recorded, is what compiling it again at other pages proves: the fields +/// that move are those, each by its page's displacement, and nothing else +/// moves. Blocks of every kind above, in a process's preparation and a +/// kernel's, at several places in their page. +#[test] +fn recorded_relocations_are_the_fields_that_move_with_the_page() { + use super::super::Prepared; + let mut state = 0x9e37_79b9u32; + let mut random = move || { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state + }; + let preparations = [ + crate::machine::test_preparation(), + system_preparation(stela_compiler::TargetCpu::Baseline), + ]; + let page = 0x1_8000_4000u64; + let (mut stored, mut checked) = (0, 0); + for block in 0..4000 { + let mut words: Vec = (0..1 + random() % 8) + .map(|_| address_word(&mut random)) + .collect(); + words.push(ending_word(&mut random)); + let mut source: Vec = words.iter().flat_map(|word| word.to_le_bytes()).collect(); + let preparation = &preparations[block % 2]; + preparation.admit(&mut source); + let pc = page + u64::from(random() % 64) * 4; + let Ok(Prepared::Block { + compiled, input, .. + }) = preparation.prepare(&source, pc, source.len()) + else { + continue; + }; + let input = &source[..input]; + let context = preparation.context(page); + let entry = translations::Entry::stored(&compiled, input, page, pc, context); + let probes = translations::probe_displacements(page) + .map(|displacement| preparation.compile_input(input, pc.wrapping_add(displacement))); + let [Ok(first), Ok(second)] = &probes else { + panic!("{words:08x?} compiles at every page"); + }; + let proven = translations::prove(&compiled, input, page, pc, context, [first, second]); + assert_eq!( + entry.as_ref().map(|entry| &entry.relocations), + proven.as_ref().map(|entry| &entry.relocations), + "{words:08x?} at {pc:#x}" + ); + assert_eq!(entry, proven, "{words:08x?} at {pc:#x}"); + checked += 1; + stored += usize::from(entry.is_some()); + } + // Every block has a stored form. + assert!(checked > 3500 && stored == checked, "{stored} of {checked}"); +} + +#[test] +#[ignore = "manual: opt-in"] +fn compile_bench() { + use super::super::{Prepared, window}; + let path = std::env::var("STELA_COMPILE_BENCH").expect("STELA_COMPILE_BENCH"); + let number = |name: &str, default: usize| { + std::env::var(name) + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(default) + }; + let offset = number("STELA_COMPILE_OFFSET", 0); + let bytes = number("STELA_COMPILE_BYTES", 4 << 20); + let image = std::fs::read(path).expect("the code image"); + let image = &image[offset.min(image.len())..(offset + bytes).min(image.len())]; + let preparation = system_preparation(stela_compiler::TargetCpu::detect()); + let base = 0x1_8000_0000u64; + let (mut blocks, mut instructions, mut code, mut refused) = (0u64, 0u64, 0u64, 0u64); + let mut kept = Vec::new(); + let started = std::time::Instant::now(); + let mut at = 0usize; + while at + 4 <= image.len() { + let pc = base + at as u64; + let page_end = (at as u64 | (FETCH_PAGE - 1)) + 1; + let end = (page_end as usize).min(image.len()).min(at + window(pc)); + let mut source = image[at..end].to_vec(); + preparation.admit(&mut source); + match preparation.prepare(&source, pc, source.len()) { + Ok(Prepared::Block { + compiled, input, .. + }) => { + blocks += 1; + instructions += compiled.source_bytes as u64 / 4; + code += compiled.native.x86_64_code.len() as u64; + at += compiled.source_bytes.max(4); + if kept.len() < 20_000 { + kept.push((pc, source[..input].to_vec(), compiled)); + } + } + _ => { + refused += 1; + at += 4; + } + } + } + let compile = started.elapsed(); + // Each kept block's stored form as the compiler made it, then the + // block compiled again at both probe pages: the fields that moved + // must be the relocations it recorded. + let started = std::time::Instant::now(); + let mut entries = Vec::new(); + for (pc, input, compiled) in &kept { + let page = pc & !(FETCH_PAGE - 1); + let context = preparation.context(page); + if let Some(entry) = translations::Entry::stored(compiled, input, page, *pc, context) { + entries.push((page, *pc, entry)); + } + } + let store = started.elapsed(); + let (mut differed, mut provable_unstorable) = (0, 0); + for (pc, input, compiled) in &kept { + let page = pc & !(FETCH_PAGE - 1); + let context = preparation.context(page); + let probes = translations::probe_displacements(page) + .map(|displacement| preparation.compile_input(input, pc.wrapping_add(displacement))); + let proven = match &probes { + [Ok(first), Ok(second)] => { + translations::prove(compiled, input, page, *pc, context, [first, second]) + } + _ => None, + }; + let stored = entries + .iter() + .find(|(_, at, _)| at == pc) + .map(|(_, _, entry)| entry); + match (stored, &proven) { + (Some(stored), proven) if proven.as_ref() != Some(stored) => { + differed += 1; + println!("DIFFERED {pc:#x}"); + } + (None, Some(_)) => provable_unstorable += 1, + _ => {} + } + } + let entries: Vec<(u64, translations::Entry)> = entries + .into_iter() + .map(|(page, _, entry)| (page, entry)) + .collect(); + let translator = translations::translator_id(); + let mut records = std::collections::BTreeMap::new(); + for (page, entry) in &entries { + records + .entry(*page) + .or_insert_with(|| { + translations::Record::new(translator, Digest::of(&page.to_le_bytes())) + }) + .insert(entry.clone()); + } + let started = std::time::Instant::now(); + let encoded: Vec<(Digest, Vec)> = records + .values() + .map(|record| (record.key, record.encode())) + .collect(); + let encode = started.elapsed(); + let started = std::time::Instant::now(); + for (key, bytes) in &encoded { + translations::Record::decode(bytes, &translator, key).expect("a record"); + } + let decode = started.elapsed(); + let encoded_bytes: usize = encoded.iter().map(|(_, bytes)| bytes.len()).sum(); + let retained: usize = entries + .iter() + .map(|(_, entry)| entry.retained_bytes()) + .sum(); + let per = + |time: std::time::Duration, count: usize| time.as_secs_f64() * 1e6 / count.max(1) as f64; + println!( + "blocks={blocks} refused={refused} instructions={instructions} \ + host_bytes_per_instruction={:.1} compile_us_per_block={:.2}", + code as f64 / instructions.max(1) as f64, + per(compile, blocks as usize), + ); + println!( + "stored={} of {} differed={differed} provable_unstorable={provable_unstorable} \ + store_us_per_block={:.2} records={} encode_us_per_entry={:.2} \ + decode_us_per_entry={:.2} encoded_bytes_per_entry={} retained_bytes_per_entry={}", + entries.len(), + kept.len(), + per(store, kept.len()), + encoded.len(), + per(encode, entries.len()), + per(decode, entries.len()), + encoded_bytes / entries.len().max(1), + retained / entries.len().max(1), + ); +} diff --git a/crates/stela-engine/src/machine/engine/watch.rs b/crates/stela-engine/src/machine/engine/watch.rs index eaaa52ff16..131ec70f07 100644 --- a/crates/stela-engine/src/machine/engine/watch.rs +++ b/crates/stela-engine/src/machine/engine/watch.rs @@ -274,7 +274,7 @@ impl Machine { literal::Transfer::Integer { .. } => 8, literal::Transfer::Simd { bytes, .. } => u64::from(bytes), }; - one(operand.address, bytes, true) + one(operand.address.0, bytes, true) } Operation::Simd(simd::Operand::Memory { load, diff --git a/crates/stela-engine/src/translations.rs b/crates/stela-engine/src/translations.rs index 21a225fb10..1a2cdeecac 100644 --- a/crates/stela-engine/src/translations.rs +++ b/crates/stela-engine/src/translations.rs @@ -1,7 +1,9 @@ //! The persistent translation store's format: page records of //! block translations keyed by the SHA-256 of their guest fetch page, with -//! guest addresses in the native code stored relative to the page, and the -//! proof that a block's code depends on its address only through them. +//! guest addresses in the native code stored relative to the page. The +//! compiler records each such field as it emits it ([`Entry::stored`]); a +//! check compiles a block again at other pages and requires the fields +//! that move to be those ([`prove`]). //! //! The format is the same in every container: the directory store //! and the pack `stela.efi` keeps @@ -23,7 +25,7 @@ use stela_crypto::digest::Digest as _; /// The bytes of the fetch page a record covers: no block leaves it. pub const PAGE_BYTES: usize = 4096; -pub const SCHEMA: u32 = 3; +pub const SCHEMA: u32 = 4; const RECORD_MAGIC: [u8; 8] = *b"STLTPAGE"; const HEADER_BYTES: usize = 88; const TRAILER_BYTES: usize = 32; @@ -191,6 +193,7 @@ impl Entry { (GuestAddress(page + u64::from(guest)), native as usize) }) .collect(), + relocations: Some(self.relocations.clone()), }, source_bytes: usize::from(self.source_bytes), direct_exits, @@ -294,8 +297,26 @@ impl Entry { } } + /// Whether the source map has a row for each instruction, in order, + /// whose native offsets lie in the `code` bytes and never go back. As in + /// the compiled block, a prologue may precede the first instruction's + /// code, and an instruction fused into the next has the next's offset. + fn source_map_fits(&self, code: usize) -> bool { + self.source_map.len() == usize::from(self.source_bytes / 4) + && self + .source_map + .iter() + .zip((self.offset..).step_by(4)) + .all(|(&(guest, native), expected)| guest == expected && (native as usize) < code) + && self + .source_map + .windows(2) + .all(|pair| pair[0].1 <= pair[1].1) + } + /// Check what decoding cannot: offsets inside the code and the page, - /// ascending source map and relocations, and fields that do not overlap. + /// the source map ([`Self::source_map_fits`]), and relocation fields in + /// order that do not overlap. fn consistent(&self) -> bool { let code = self.code.len(); let in_code = |offset: u32, bytes: usize| (offset as usize).saturating_add(bytes) <= code; @@ -317,16 +338,7 @@ impl Entry { .relocations .iter() .all(|&offset| in_code(offset, FIELD_BYTES)) - && crate::artifact::validate_source_map_geometry( - u64::from(self.offset), - usize::from(self.source_bytes), - code, - 0, - self.source_map - .iter() - .map(|&(guest, native)| (u64::from(guest), native as usize)), - ) - .is_ok() + && self.source_map_fits(code) && self.exits.iter().all(|exit| { in_code(exit.offset, 0) && ExitKind::try_from(u64::from(exit.kind)).is_ok() }) @@ -766,11 +778,12 @@ pub fn probe_displacements(page: u64) -> [u64; 2] { }) } -/// The stored form of `block`, compiled at `pc` in the page at `page`, given -/// the same source compiled at the two [`probe_displacements`] of the page: -/// `None` unless the three differ only in 8-byte fields, each by exactly -/// its probe's displacement, and in their exit targets and source maps by -/// the same. +/// The stored form of `block`, compiled at `pc` in the page at `page`, as +/// the same source compiled at the two [`probe_displacements`] of the page +/// shows it: `None` unless the three differ only in 8-byte fields, each by +/// exactly its probe's displacement, and in their exit targets and source +/// maps by the same. The check of the relocations the compiler records +/// ([`Entry::stored`]). pub fn prove( block: &CompiledBlock, input: &[u8], @@ -863,58 +876,94 @@ pub fn prove( relocations.push(start as u32); at = start + FIELD_BYTES; } - let mut stored = code.clone(); - for &start in &relocations { - let start = start as usize; - let value = field(code, start).wrapping_sub(page); - stored[start..start + FIELD_BYTES].copy_from_slice(&value.to_le_bytes()); + Entry::with_relocations(block, input, page, pc, context, relocations) +} + +impl Entry { + /// The stored form of `block`, compiled at `pc` in the page at `page` + /// from `input`: its code with each relocation field the compiler + /// recorded made relative to the page. `None` when the compiler found + /// a value no relocation reproduces, or the block does not fit an entry. + pub fn stored( + block: &CompiledBlock, + input: &[u8], + page: u64, + pc: u64, + context: Digest, + ) -> Option { + let relocations = block.native.relocations.clone()?; + Self::with_relocations(block, input, page, pc, context, relocations) } - let page_offset = |guest: u64| { - u16::try_from(guest.wrapping_sub(page)) - .ok() - .filter(|&offset| usize::from(offset) < PAGE_BYTES) - }; - let entry = Entry { - context, - offset: page_offset(pc)?, - source_bytes: u16::try_from(block.source_bytes).ok()?, - input: input.to_vec(), - code: stored, - relocations, - source_map: block - .native - .source_map + + fn with_relocations( + block: &CompiledBlock, + input: &[u8], + page: u64, + pc: u64, + context: Digest, + relocations: Vec, + ) -> Option { + let code = &block.native.x86_64_code; + if relocations .iter() - .map(|&(guest, native)| Some((page_offset(guest.0)?, u32::try_from(native).ok()?))) - .collect::>()?, - exits: block - .direct_exits - .iter() - .map(|exit| { - Some(Exit { - offset: u32::try_from(exit.offset).ok()?, - target: exit.target.0.wrapping_sub(page), - kind: exit.kind as u8, - skipped: exit.skipped, + .any(|&start| start as usize + FIELD_BYTES > code.len()) + { + return None; + } + let mut stored = code.clone(); + for &start in &relocations { + let start = start as usize; + let field = &mut stored[start..start + FIELD_BYTES]; + let value = u64::from_le_bytes((&*field).try_into().expect("8 bytes")); + field.copy_from_slice(&value.wrapping_sub(page).to_le_bytes()); + } + let page_offset = |guest: u64| { + u16::try_from(guest.wrapping_sub(page)) + .ok() + .filter(|&offset| usize::from(offset) < PAGE_BYTES) + }; + let entry = Entry { + context, + offset: page_offset(pc)?, + source_bytes: u16::try_from(block.source_bytes).ok()?, + input: input.to_vec(), + code: stored, + relocations, + source_map: block + .native + .source_map + .iter() + .map(|&(guest, native)| Some((page_offset(guest.0)?, u32::try_from(native).ok()?))) + .collect::>()?, + exits: block + .direct_exits + .iter() + .map(|exit| { + Some(Exit { + offset: u32::try_from(exit.offset).ok()?, + target: exit.target.0.wrapping_sub(page), + kind: exit.kind as u8, + skipped: exit.skipped, + }) }) - }) - .collect::>()?, - recovery: block - .fault_recovery - .iter() - .map(|row| { - let mut row = UnqualifiedFaultRecovery::from(row); - row.retirement = row - .retirement - .relocated(GuestAddress( - row.retirement.instruction_pc().0.checked_sub(page)?, - )) - .ok()?; - Some(row) - }) - .collect::>()?, - }; - entry.consistent().then_some(entry) + .collect::>()?, + recovery: block + .fault_recovery + .iter() + .map(|row| { + let mut row = UnqualifiedFaultRecovery::from(row); + row.retirement = row + .retirement + .relocated(GuestAddress( + row.retirement.instruction_pc().0.checked_sub(page)?, + )) + .ok()?; + Some(row) + }) + .collect::>()?, + }; + entry.consistent().then_some(entry) + } } #[cfg(test)] diff --git a/crates/stela-engine/src/translations/pack.rs b/crates/stela-engine/src/translations/pack.rs index 7a22dd56a1..4ced94d5da 100644 --- a/crates/stela-engine/src/translations/pack.rs +++ b/crates/stela-engine/src/translations/pack.rs @@ -7,18 +7,19 @@ //! follows from the index, so a file allocated larger than its pack (to be //! rewritten in place) holds bytes past it that are never read. //! -//! The store hands the engine the pack's records and keeps the blocks the -//! engine compiled anew. A store shared by machines that run at once (one -//! per PE) also keeps those blocks' native code, within a bound, for the -//! other machines to install instead of compiling them again. At a quiescent point it proves them (each compiled -//! again at its page's probe addresses) and lays out the next pack within a -//! bound: the records that gained entries, then the records this boot used, -//! then the others, as long as they fit. +//! The store hands the engine the pack's records and keeps the stored form +//! of each block the engine compiled anew, which its compiler made as it +//! emitted the block ([`Offer::entry`]). A store shared by machines that +//! run at once (one per PE) also keeps those blocks' native code, within a +//! bound, for the other machines to install instead of compiling them +//! again. At a quiescent point it lays out the next pack within a bound: +//! the records that gained entries, then the records this boot used, then +//! the others, as long as they fit. mod codec; -use super::{Digest, FormatError, Record}; +use super::{Digest, Entry, FormatError, Record}; use crate::machine::engine::SharedTranslation; -use crate::machine::{Offer, Preparation, Translations}; +use crate::machine::{Offer, Translations}; use alloc::{ collections::{BTreeMap, VecDeque}, sync::{Arc, Weak}, @@ -47,18 +48,11 @@ pub const MAX_UNUSED_BOOTS: u8 = 3; const CHECKSUM_BYTES: usize = DIGEST_BYTES; /// The most records a pack holds. pub const MAX_RECORDS: usize = 1 << 22; -/// The most memory the blocks waiting for proof take by default; later -/// blocks are counted as dropped ([`Store::set_bounds`]). -const MAX_PENDING_BYTES: usize = 16 << 20; /// The default bound of the decoded-record cache, least recently used first /// out ([`Store::set_bounds`]). One record takes at most an eighth of it. const DECODED_BYTES: usize = 8 << 20; -/// The default bound of the entries proven during the run -/// ([`Store::prove_batch`]). -const PROVEN_BYTES: usize = 64 << 20; -/// What a page waiting for proof costs beyond its buffers: an entry in a -/// B-tree node about half full. -const PENDING_PAGE_BYTES: usize = 2 * size_of::<(PendingKey, PendingPage)>(); +/// The default bound of the entries added during the run ([`Store::keep`]). +const ADDED_BYTES: usize = 64 << 20; /// The direct-mapped tables that name why a shared lookup missed: offers /// being compiled, offers evicted, and the last offer of each PC and page. const MISS_SLOTS: usize = 4096; @@ -615,13 +609,11 @@ pub struct Counters { pub repeated: u64, pub cached: u64, pub decoded: u64, - /// Blocks offered and kept for proof, and those past the memory bound. - pub offered: u64, - pub dropped: u64, - /// Blocks proven during the run ([`Store::prove_batch`]), and proven - /// entries left out because the proven bound was full. - pub proven: u64, - pub unprovable: u64, + /// Blocks offered whose stored form was added, those whose compiler + /// made none, and those left out because the added bound was full + /// ([`Store::keep`]). + pub added: u64, + pub unstorable: u64, pub unkept: u64, /// Shared lookups that found a block, and why the others missed: no /// offer of it, an offer of its PC and page in another context, its @@ -643,10 +635,8 @@ impl Counters { repeated, cached, decoded, - offered, - dropped, - proven, - unprovable, + added, + unstorable, unkept, shared_hits, shared_absent, @@ -660,10 +650,8 @@ impl Counters { self.repeated += repeated; self.cached += cached; self.decoded += decoded; - self.offered += offered; - self.dropped += dropped; - self.proven += proven; - self.unprovable += unprovable; + self.added += added; + self.unstorable += unstorable; self.unkept += unkept; self.shared_hits += shared_hits; self.shared_absent += shared_absent; @@ -673,65 +661,6 @@ impl Counters { } } -/// A block offered for proof: its place in its page and its input's in the -/// page's [`PendingPage::inputs`]. The proof compiles the block again. -#[derive(Debug, Clone, Copy)] -struct PendingBlock { - offset: u16, - length: u16, - start: u32, -} - -/// A page's blocks of one context waiting for proof, by offset. What the -/// blocks share is held once, so a block costs little more than its words. -#[derive(Debug)] -struct PendingPage { - preparation: Arc, - blocks: Vec, - inputs: Vec, -} - -impl PendingPage { - /// What the page is charged against the pending bound. - fn charge(&self) -> usize { - self.blocks.capacity() * size_of::() - + self.inputs.capacity() - + PENDING_PAGE_BYTES - } -} - -/// A pending page's key, guest page and context. -type PendingKey = (Digest, u64, Digest); - -/// Stage bounded growth without changing a retained allocation. Either -/// buffer may fail, so the owner installs their replacements together. -fn grow_pending( - current: Option<&Vec>, - additional: usize, - minimum: usize, - limit: usize, -) -> Result>, ()> { - let held = current.map_or(0, Vec::capacity); - let used = current.map_or(0, Vec::len); - let required = used.checked_add(additional).ok_or(())?; - if required.max(held) > limit { - return Err(()); - } - if required <= held { - return Ok(None); - } - let capacity = held.saturating_mul(2).max(minimum).max(required).min(limit); - let mut replacement = Vec::new(); - replacement.try_reserve_exact(capacity).map_err(|_| ())?; - if replacement.capacity() > limit { - return Err(()); - } - if let Some(current) = current { - replacement.extend_from_slice(current); - } - Ok(Some(replacement)) -} - /// A shared block's PC and the leading words of its page key and context: /// a compact index whose rare collision only replaces an entry, as a hit /// still matches the whole key and context ([`SharedTranslation::matches`]). @@ -842,13 +771,6 @@ impl StagedOffer { Some(Self::entry(key, bytes, offer.shared())) } - /// Stage only the shared emission while leaving its producer's proof - /// input available. Admission still checks the live shared bound. - pub fn for_writable(offer: &Offer, bound: usize) -> Option { - let (key, bytes) = Self::charge(offer, bound)?; - Some(Self::entry(key, bytes, offer.shared_for_proof())) - } - fn charge(offer: &Offer, bound: usize) -> Option<(SharedKey, usize)> { if bound == 0 { return None; @@ -1005,58 +927,6 @@ impl DecodedCache { } } -/// Pending pages taken from a store to prove outside its lock -/// ([`Store::take_batch`]). -pub struct ProofBatch { - pages: Vec<(PendingKey, PendingPage)>, -} - -/// What proving a [`ProofBatch`] made: each page key's new entries, and -/// the blocks proven and refused. -pub struct ProvenBatch { - records: Vec<(Digest, Vec)>, - proven: u64, - unprovable: u64, -} - -impl ProofBatch { - /// The blocks in the batch. - pub fn blocks(&self) -> usize { - self.pages.iter().map(|(_, page)| page.blocks.len()).sum() - } - - /// Compile each block again at its page's probe addresses and keep the - /// entries proven to move only by them. Needs no store. - pub fn prove(self) -> ProvenBatch { - let (mut proven, mut unprovable) = (0, 0); - let mut records: Vec<(Digest, Vec)> = Vec::new(); - for ((key, page, context), held) in self.pages { - let mut entries = Vec::new(); - for block in &held.blocks { - let start = block.start as usize; - let input = &held.inputs[start..start + usize::from(block.length)]; - let pc = page + u64::from(block.offset); - match Offer::prove_input(input, page, pc, context, &held.preparation) { - Some(entry) => { - proven += 1; - entries.push(entry); - } - None => unprovable += 1, - } - } - match records.last_mut() { - Some((last, held)) if *last == key => held.extend(entries), - _ => records.push((key, entries)), - } - } - ProvenBatch { - records, - proven, - unprovable, - } - } -} - /// One boot's store over the pack it read. #[derive(Debug)] pub struct Store<'a> { @@ -1068,21 +938,10 @@ pub struct Store<'a> { loaded: BTreeMap, decoded: DecodedCache, decode_scratch: DecodeScratch, - pending: BTreeMap, - /// The blocks in `pending`. - pending_blocks: usize, - /// What `pending` holds: a charge for each page's entry and tree node, - /// and the capacity of its buffers. - pending_bytes: usize, - pending_bound: usize, - /// Entries proven during the run, by page key, and their retained bytes. - proven: BTreeMap, - proven_bytes: usize, - proven_bound: usize, - /// A fold left an entry out for the proven bound: a batch proven now - /// would be left out too, so none is taken until the bound grows - /// ([`Self::take_batch`]). Its pages wait for the stop's proof instead. - proven_full: bool, + /// Entries added during the run, by page key, and their retained bytes. + added: BTreeMap, + added_bytes: usize, + added_bound: usize, /// The blocks offered, by page key, PC and context, for the other /// machines sharing the store, oldest first. The bound charges kept /// source/template buffers, Arc payloads, index entries and FIFO capacity; @@ -1099,11 +958,6 @@ pub struct Store<'a> { #[derive(Debug)] pub struct Planned<'a> { pub layout: Layout<'a>, - /// Blocks proven and refused by their proofs, and those left unproven - /// when the room to prove them ran out. - pub proven: u64, - pub unprovable: u64, - pub unproven: u64, /// Records of the read pack left out to stay within the bound, and new /// ones that did not fit. pub evicted: u64, @@ -1115,10 +969,8 @@ pub struct Planned<'a> { /// What a store keeps beyond its pack, in bytes ([`Store::set_bounds`]). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Bounds { - /// Inputs of blocks waiting for proof. - pub pending: usize, - /// Entries proven during the run. - pub proven: usize, + /// Entries added during the run. + pub added: usize, /// Decoded pack records. pub decoded: usize, } @@ -1126,8 +978,7 @@ pub struct Bounds { impl Default for Bounds { fn default() -> Self { Self { - pending: MAX_PENDING_BYTES, - proven: PROVEN_BYTES, + added: ADDED_BYTES, decoded: DECODED_BYTES, } } @@ -1138,8 +989,7 @@ impl Bounds { pub fn share(self, parts: usize) -> Self { let parts = parts.max(1); Self { - pending: self.pending / parts, - proven: self.proven / parts, + added: self.added / parts, decoded: self.decoded / parts, } } @@ -1168,14 +1018,9 @@ impl<'a> Store<'a> { loaded: BTreeMap::new(), decoded: DecodedCache::new(bounds.decoded), decode_scratch: DecodeScratch::default(), - pending: BTreeMap::new(), - pending_blocks: 0, - pending_bytes: 0, - pending_bound: bounds.pending, - proven: BTreeMap::new(), - proven_bytes: 0, - proven_bound: bounds.proven, - proven_full: false, + added: BTreeMap::new(), + added_bytes: 0, + added_bound: bounds.added, shared: BTreeMap::new(), shared_order: VecDeque::new(), shared_bytes: 0, @@ -1188,58 +1033,19 @@ impl<'a> Store<'a> { /// Bound what the store keeps beyond its pack. Records the decoded /// cache lets go come back, to drop outside a lock. pub fn set_bounds(&mut self, bounds: Bounds) -> Vec> { - self.pending_bound = bounds.pending; - if bounds.proven > self.proven_bound { - self.proven_full = false; - } - self.proven_bound = bounds.proven; + self.added_bound = bounds.added; self.decoded.shrink(bounds.decoded) } /// Take `other`'s run (another part of one store over the same pack): - /// what it looked up, its blocks waiting for proof, its proven entries - /// and its counts. Its shared blocks are dropped. + /// what it looked up, its added entries and its counts. Its shared + /// blocks are dropped. pub fn absorb(&mut self, other: Self) { for (key, valid) in other.loaded { self.loaded.entry(key).or_insert(valid); } - for (group, page) in other.pending { - match self.pending.entry(group) { - alloc::collections::btree_map::Entry::Vacant(slot) => { - self.pending_blocks += page.blocks.len(); - self.pending_bytes += page.charge(); - slot.insert(page); - } - alloc::collections::btree_map::Entry::Occupied(mut slot) => { - // One page's offers reach one part: merge them anyway. - let held = slot.get_mut(); - let before = held.charge(); - for block in page.blocks { - if let Err(place) = held - .blocks - .binary_search_by_key(&block.offset, |held| held.offset) - { - let start = held.inputs.len(); - let from = block.start as usize; - held.inputs.extend_from_slice( - &page.inputs[from..from + usize::from(block.length)], - ); - held.blocks.insert( - place, - PendingBlock { - start: start as u32, - ..block - }, - ); - self.pending_blocks += 1; - } - } - self.pending_bytes += held.charge() - before; - } - } - } - for (key, record) in other.proven { - match self.proven.entry(key) { + for (key, record) in other.added { + match self.added.entry(key) { alloc::collections::btree_map::Entry::Vacant(slot) => { slot.insert(record); } @@ -1248,8 +1054,7 @@ impl<'a> Store<'a> { } } } - self.proven_bytes += other.proven_bytes; - self.proven_full |= other.proven_full; + self.added_bytes += other.added_bytes; self.counters.add(&other.counters); } @@ -1332,152 +1137,35 @@ impl<'a> Store<'a> { } } - /// Admit the original input for durable proof independently of shared - /// emission admission. A writable owner may call both under one lock. - pub fn keep_pending(&mut self, offer: &Offer) { + /// Keep `entry`, the stored form of `offer` ([`Offer::entry`], made + /// before the store's lock is taken), for the next pack while the added + /// bound has room. + pub fn keep(&mut self, offer: &Offer, entry: Option) { + let key = offer.key(); self.misses - .offered(shared_key(&offer.key(), offer.pc(), &offer.context())); - if !self.reserve_pending(offer) { - self.counters.dropped += 1; - } - } - - /// Keep `offer` for proof unless its page holds the block already: - /// whether it fit. - fn reserve_pending(&mut self, offer: &Offer) -> bool { - const BLOCK_BYTES: usize = size_of::(); - let (Ok(offset), Ok(length)) = ( - u16::try_from(offer.pc() - offer.page()), - u16::try_from(offer.input().len()), - ) else { - return false; + .offered(shared_key(&key, offer.pc(), &offer.context())); + let Some(entry) = entry else { + self.counters.unstorable += 1; + return; }; - let group = (offer.key(), offer.page(), offer.context()); if self - .proven - .get(&offer.key()) - .is_some_and(|record| record.find(offset, &offer.context()).is_some()) + .added + .get(&key) + .is_some_and(|record| record.find(entry.offset, &entry.context).is_some()) { - // Proven during the run already. - return true; + return; } - let known = self.pending.get(&group); - let place = known.map_or(Err(0), |page| { - page.blocks - .binary_search_by_key(&offset, |block| block.offset) - }); - let Err(place) = place else { - return true; - }; - let new_page = if known.is_some() { - 0 - } else { - PENDING_PAGE_BYTES - }; - let held_slots = known.map_or(0, |page| page.blocks.capacity()); - let held_inputs = known.map_or(0, |page| page.inputs.capacity()); - let held = held_slots * BLOCK_BYTES + held_inputs; - let Some(available) = self - .pending_bound - .checked_sub(self.pending_bytes) - .and_then(|available| available.checked_sub(new_page)) - else { - return false; - }; - let limit = held + available; - // A page's inputs stay far below 4 GiB: each offset is unique and - // both it and the associated block length fit in 16 bits. - let start = known.map_or(0, |page| page.inputs.len()); - let required_inputs = (start + usize::from(length)).max(held_inputs); - let Some(slot_limit) = limit.checked_sub(required_inputs) else { - return false; - }; - let Ok(blocks) = grow_pending( - known.map(|page| &page.blocks), - 1, - 4, - slot_limit / BLOCK_BYTES, - ) else { - return false; - }; - let slots = blocks.as_ref().map_or(held_slots, Vec::capacity); - let Ok(inputs) = grow_pending( - known.map(|page| &page.inputs), - usize::from(length), - 8, - limit - slots * BLOCK_BYTES, - ) else { - return false; - }; - let page = self.pending.entry(group).or_insert_with(|| PendingPage { - preparation: Arc::clone(offer.preparation()), - blocks: Vec::new(), - inputs: Vec::new(), - }); - if let Some(blocks) = blocks { - page.blocks = blocks; - } - if let Some(inputs) = inputs { - page.inputs = inputs; - } - page.blocks.insert( - place, - PendingBlock { - offset, - length, - start: start as u32, - }, - ); - page.inputs.extend_from_slice(offer.input()); - let grown = page.blocks.capacity() * BLOCK_BYTES + page.inputs.capacity() - held; - self.pending_bytes += grown + new_page; - self.pending_blocks += 1; - self.counters.offered += 1; - true - } - - /// Pending pages holding at least `blocks` blocks (all, when fewer - /// wait), oldest key first, to prove outside the store's lock; `None` - /// when none wait or the proven bound is full: reached, or short of an - /// entry a fold left out. A batch then would be proven only to be - /// dropped, and its pages with it. - pub fn take_batch(&mut self, blocks: usize) -> Option { - if self.pending.is_empty() || self.proven_full || self.proven_bytes >= self.proven_bound { - return None; - } - let mut pages = Vec::new(); - let mut taken = 0; - while taken < blocks.max(1) - && let Some((group, page)) = self.pending.pop_first() - { - taken += page.blocks.len(); - self.pending_blocks -= page.blocks.len(); - self.pending_bytes -= page.charge(); - pages.push((group, page)); - } - Some(ProofBatch { pages }) - } - - /// Keep what a [`ProofBatch`] of this store proved, within the proven - /// bound; the rest is counted as unkept. - pub fn fold(&mut self, batch: ProvenBatch) { - self.counters.proven += batch.proven; - self.counters.unprovable += batch.unprovable; - for (key, entries) in batch.records { - for entry in entries { - let bytes = entry.retained_bytes(); - if self.proven_bytes + bytes > self.proven_bound { - self.counters.unkept += 1; - self.proven_full = true; - continue; - } - self.proven_bytes += bytes; - self.proven - .entry(key) - .or_insert_with(|| Record::new(self.translator, key)) - .insert(entry); - } + let bytes = entry.retained_bytes(); + if self.added_bytes + bytes > self.added_bound { + self.counters.unkept += 1; + return; } + self.added_bytes += bytes; + self.counters.added += 1; + self.added + .entry(key) + .or_insert_with(|| Record::new(self.translator, key)) + .insert(entry); } /// The translator whose records the store keeps. @@ -1571,52 +1259,18 @@ impl<'a> Store<'a> { self.pack.as_ref() } - /// Blocks waiting for proof. - pub fn pending(&self) -> usize { - self.pending_blocks - } - - /// Prove the offered blocks while `room` says there is memory to, and - /// lay out the next pack within `bound` bytes: the records that gained - /// entries, then those this boot used, then the others, as long as - /// they fit. Records kept unchanged stay where they were in the pack - /// read ([`Layout::changed`]). - pub fn plan(&mut self, bound: u64, room: impl Fn() -> bool) -> Planned<'a> { - let mut proven = core::mem::take(&mut self.proven); - self.proven_bytes = 0; - self.proven_full = false; - let (mut count, mut unprovable) = (0, 0); - let pending = core::mem::take(&mut self.pending); - let mut unproven = self.pending_blocks as u64; - 'pages: for ((key, page, context), held) in pending { - for block in held.blocks { - if !room() { - break 'pages; - } - unproven -= 1; - let start = block.start as usize; - let input = &held.inputs[start..start + usize::from(block.length)]; - let pc = page + u64::from(block.offset); - let entry = Offer::prove_input(input, page, pc, context, &held.preparation); - match entry { - Some(entry) => { - count += 1; - proven - .entry(key) - .or_insert_with(|| Record::new(self.translator, key)) - .insert(entry); - } - None => unprovable += 1, - } - } - } - self.pending_blocks = 0; - self.pending_bytes = 0; + /// Lay out the next pack within `bound` bytes: the records that gained + /// entries, then those this boot used, then the others, as long as they + /// fit. Records kept unchanged stay where they were in the pack read + /// ([`Layout::changed`]). + pub fn plan(&mut self, bound: u64) -> Planned<'a> { + let mut added = core::mem::take(&mut self.added); + self.added_bytes = 0; // Gained entries first, then this boot's records, then the others. let mut scratch = core::mem::take(&mut self.decode_scratch); let mut candidates: Vec<(Digest, Piece<'a>)> = Vec::new(); let (mut ages, mut expired) = (Ages::new(), 0); - for (key, record) in &mut proven { + for (key, record) in &mut added { if let Some(stored) = self.pack.and_then(|pack| pack.record(key)) { match stored.decode(&self.translator, key, &mut scratch) { Ok(previous) => { @@ -1642,7 +1296,7 @@ impl<'a> Store<'a> { if let Some(pack) = self.pack { for (key, valid) in &self.loaded { if *valid - && !proven.contains_key(key) + && !added.contains_key(key) && let Some(bytes) = pack.get(key) { candidates.push((*key, Piece::Kept(bytes))); @@ -1652,7 +1306,7 @@ impl<'a> Store<'a> { // youngest are kept first, and those unused too long leave. let mut unused: Vec<(u8, Digest, &'a [u8])> = Vec::new(); for (index, (key, bytes)) in pack.iter().enumerate() { - if !self.loaded.contains_key(&key) && !proven.contains_key(&key) { + if !self.loaded.contains_key(&key) && !added.contains_key(&key) { let age = entry_age(pack.bytes, index).saturating_add(1); if age > MAX_UNUSED_BOOTS { expired += 1; @@ -1681,9 +1335,6 @@ impl<'a> Store<'a> { let format = self.pack.map_or(PackFormat::Raw, |pack| pack.format); Planned { layout: layout_over(&self.translator, self.pack, kept, format, bound, &ages), - proven: count, - unprovable, - unproven, evicted, expired, } @@ -1725,7 +1376,8 @@ impl Translations for Store<'_> { } fn offer(&mut self, offer: Offer) { - self.keep_pending(&offer); + let entry = offer.entry(); + self.keep(&offer, entry); self.lend(offer); } @@ -1835,7 +1487,7 @@ mod tests { 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(); + let mut entry = offer(0x1000, key).entry().unwrap(); entry.code.resize(DECODED_BYTES / 8, 0); large.insert(entry); let bytes = Layout::new(&translator, vec![(key, Piece::New(large.encode()))]).to_vec(); @@ -1871,7 +1523,7 @@ mod tests { let first = Digest::of(b"compressed"); let second = Digest::of(b"raw"); let mut compressed_record = Record::new(translator, first); - let mut entry = offer(0x1000, first).prove().unwrap(); + let mut entry = offer(0x1000, first).entry().unwrap(); entry.code.resize(4096, 0); compressed_record.insert(entry); let raw = compressed_record.encode(); @@ -1908,7 +1560,7 @@ mod tests { assert_eq!(*held, compressed_record); assert!(Arc::ptr_eq(&held, &store.record(&first).unwrap())); assert_eq!(store.record(&second).unwrap().key, second); - let output = store.plan(u64::MAX, || true).layout.to_vec(); + let output = store.plan(u64::MAX).layout.to_vec(); let pack = Pack::parse(&output, &translator).unwrap(); assert_eq!(pack.format, PackFormat::Mixed); assert_eq!(pack.get(&first), Some(compressed.as_slice())); @@ -2015,7 +1667,7 @@ mod tests { 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); + assert_eq!(store.counters.added, 0); drop(retired); assert!(old.upgrade().is_none()); @@ -2026,97 +1678,6 @@ mod tests { assert!(store.prepared(&key, 0x1000, &context).is_none()); } - #[test] - fn pending_budget_caps_capacity_growth_and_keeps_exact_input() { - let key = Digest::of(b"page"); - let base = 0x1_0000_4000; - let mut store = Store::new(translator_id(), None).0; - for index in 0..4 { - store.keep_pending(&offer(base + index * 8, key)); - } - let page = store.pending.values().next().unwrap(); - assert_eq!((page.blocks.len(), page.inputs.len()), (4, 32)); - assert_eq!((page.blocks.capacity(), page.inputs.capacity()), (4, 32)); - - // The other pages consume the rest of the budget. There is room - // for one exact block and its input, but no geometric slack. - let extra = size_of::() + 8; - store.pending_bytes = MAX_PENDING_BYTES - extra; - let next = offer(base + 32, key); - store.keep_pending(&next); - assert_eq!(store.pending_bytes, MAX_PENDING_BYTES); - let page = store.pending.values().next().unwrap(); - assert_eq!((page.blocks.capacity(), page.inputs.capacity()), (5, 40)); - assert_eq!(&page.inputs[32..], next.input()); - - // A duplicate has no charge. A fresh block cannot replace an old - // allocation or corrupt the input offsets at the exhausted limit. - let previous = page.inputs.clone(); - store.keep_pending(&next); - store.keep_pending(&offer(base + 40, key)); - assert_eq!(store.pending_bytes, MAX_PENDING_BYTES); - assert_eq!((store.pending(), store.counters.dropped), (5, 1)); - let page = store.pending.values().next().unwrap(); - assert_eq!(page.inputs, previous); - assert_eq!( - page.blocks - .iter() - .map(|block| block.start) - .collect::>(), - [0, 8, 16, 24, 32] - ); - } - - #[test] - fn writable_staging_preserves_proof_with_and_without_shared_admission() { - let translator = translator_id(); - let key = Digest::of(b"page"); - let first = offer(0x1_0000_4008, key); - let second = offer(0x1_0000_4010, key); - 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).0; - store.share(bound); - - let mut staged = StagedOffer::for_writable(&first, bound).unwrap(); - store.keep_pending(&first); - assert!(store.accept_shared(&mut staged).is_none()); - let owner = Arc::downgrade(&store.prepared(&key, first.pc(), &first.context()).unwrap()); - - let mut staged = StagedOffer::for_writable(&second, bound).unwrap(); - store.keep_pending(&second); - let retired = store.accept_shared(&mut staged).unwrap(); - assert!(Arc::ptr_eq(&retired, &owner.upgrade().unwrap())); - assert!(store.prepared(&key, first.pc(), &first.context()).is_none()); - assert!(store.shared_usage() <= bound); - drop(retired); - assert!(owner.upgrade().is_none()); - - // A live store change may refuse shared publication after staging. - let mut staged = StagedOffer::for_writable(&second, bound).unwrap(); - store.share(0); - store.keep_pending(&second); - assert!(store.accept_shared(&mut staged).is_none()); - assert!(staged.entry.is_some()); - assert!(StagedOffer::for_writable(&first, 0).is_none()); - assert_eq!(store.pending(), 2); - assert_eq!((store.counters.offered, store.counters.dropped), (2, 0)); - - // Reuse and eviction are independent of durable proof input. - let planned = store.plan(u64::MAX, || true); - assert_eq!( - (planned.proven, planned.unprovable, planned.unproven), - (2, 0, 0) - ); - let bytes = planned.layout.to_vec(); - let mut next = Store::new(translator, Some(&bytes)).0; - let record = next.record(&key).unwrap(); - assert!(record.find(8, &first.context()).is_some()); - assert!(record.find(16, &second.context()).is_some()); - } - #[test] fn a_shared_store_hands_offered_blocks_to_other_machines_and_forgets_the_oldest_when_full() { let translator = Digest::of(b"translator"); @@ -2180,8 +1741,8 @@ mod tests { assert!(store.prepared(&key, 0x1000, &first.context()).is_some()); assert!(store.prepared(&key, 0x1020, &fifth.context()).is_some()); assert!(store.shared_usage() <= 4 * bytes + fifo); - // Each distinct block waits for proof once, however often offered. - assert_eq!(store.pending(), 5); + // Each distinct block is added once, however often offered. + assert_eq!(store.counters.added, 5); } #[test] @@ -2238,35 +1799,22 @@ mod tests { } #[test] - fn blocks_past_the_room_to_prove_them_stay_unproven() { - let translator = translator_id(); - let (first, second) = (Digest::of(b"first page"), Digest::of(b"second page")); - let mut store = Store::new(translator, None).0; - store.offer(offer(0x1_0000_4008, first)); - store.offer(offer(0x1_0000_8010, second)); - let tried = core::cell::Cell::new(0); - let planned = store.plan(u64::MAX, || { - tried.set(tried.get() + 1); - tried.get() == 1 - }); - assert_eq!((planned.proven, planned.unproven), (1, 1)); - assert_eq!(planned.layout.records(), 1); - } - - #[test] - fn a_boot_proves_its_blocks_into_the_next_pack_and_the_one_after_reads_them() { + fn a_boot_keeps_its_blocks_in_the_next_pack_and_the_one_after_reads_them() { let translator = translator_id(); let (first, second) = (Digest::of(b"first page"), Digest::of(b"second page")); let mut store = Store::new(translator, None).0; store.offer(offer(0x1_0000_4008, first)); store.offer(offer(0x1_0000_8010, second)); assert_eq!(store.record(&first), None); - let planned = store.plan(u64::MAX, || true); + let planned = store.plan(u64::MAX); assert_eq!( - (planned.proven, planned.unprovable, planned.evicted), + ( + store.counters.added, + store.counters.unstorable, + planned.evicted + ), (2, 0, 0) ); - assert_eq!(store.pending(), 0); let bytes = planned.layout.to_vec(); let mut next = Store::new(translator, Some(&bytes)).0; @@ -2282,7 +1830,7 @@ mod tests { assert_eq!(next.counters.loaded, 1); // The record this boot used is kept first under a tight bound. let one = layout_bytes(1, next.pack().unwrap().get(&first).unwrap().len() as u64); - let planned = next.plan(one, || true); + let planned = next.plan(one); assert_eq!((planned.layout.records(), planned.evicted), (1, 1)); let kept = planned.layout.to_vec(); let pack = Pack::parse(&kept, &translator).unwrap(); @@ -2301,10 +1849,10 @@ mod tests { let key = Digest::of(b"page"); let mut store = Store::new(translator, None).0; store.offer(offer(0x1_0000_4008, key)); - let bytes = store.plan(u64::MAX, || true).layout.to_vec(); + let bytes = store.plan(u64::MAX).layout.to_vec(); let mut next = Store::new(translator, Some(&bytes)).0; next.offer(offer(0x1_0000_4010, key)); - let merged = next.plan(u64::MAX, || true).layout.to_vec(); + let merged = next.plan(u64::MAX).layout.to_vec(); let pack = Pack::parse(&merged, &translator).unwrap(); let record = Record::decode(pack.get(&key).unwrap(), &translator, &key).unwrap(); let mut offsets: Vec = record.entries.iter().map(|entry| entry.offset).collect(); @@ -2329,7 +1877,7 @@ mod tests { for (index, key) in keys[..4].iter().enumerate() { store.offer(offer(0x1_0000_4008 + 0x1000 * index as u64, *key)); } - let first = store.plan(u64::MAX, || true).layout; + let first = store.plan(u64::MAX).layout; assert_eq!(first.changed(), None); let old = first.to_vec(); // The next boot uses one record and offers a new block in another @@ -2338,7 +1886,7 @@ mod tests { assert!(next.record(&keys[1]).is_some()); next.offer(offer(0x1_0000_9010, keys[4])); next.offer(offer(0x1_0000_6010, keys[2])); - let layout = next.plan(u64::MAX, || true).layout; + let layout = next.plan(u64::MAX).layout; let new = layout.to_vec(); assert_eq!(new.len() as u64, layout.bytes()); let changed = layout.changed().expect("an incremental layout").to_vec(); @@ -2390,7 +1938,7 @@ mod tests { for key in read.keys() { assert!(idle.record(key).is_some()); } - let layout = idle.plan(u64::MAX, || true).layout; + let layout = idle.plan(u64::MAX).layout; (layout.changed().unwrap().to_vec(), layout.to_vec()) }; let (ranges, young) = used(&new); @@ -2415,7 +1963,7 @@ mod tests { .to_vec(); let mut store = Store::new(translator, Some(&old)).0; store.offer(offer(0x1_0000_4008, keys[1])); - let layout = store.plan(u64::MAX, || true).layout; + let layout = store.plan(u64::MAX).layout; assert_eq!(layout.changed(), None); let roomy = layout.to_vec(); let pack = Pack::parse(&roomy, &translator).unwrap(); @@ -2429,13 +1977,13 @@ mod tests { assert!(first >= prefix_length(2 + MIN_INDEX_SLACK)); let mut next = Store::new(translator, Some(&roomy)).0; next.offer(offer(0x1_0000_5008, keys[2])); - let grown = next.plan(u64::MAX, || true).layout; + let grown = next.plan(u64::MAX).layout; assert!(grown.changed().is_some()); assert_eq!(records_of(&grown.to_vec(), &translator).len(), 3); // Under a bound without room for it, the records follow the index. let mut used = Store::new(translator, Some(&old)).0; assert!(used.record(&keys[0]).is_some()); - let tight = used.plan(old.len() as u64, || true).layout; + let tight = used.plan(old.len() as u64).layout; assert_eq!(tight.to_vec(), old); } @@ -2476,103 +2024,6 @@ mod tests { assert_eq!(layout.changed(), None); } - #[test] - fn blocks_proven_in_batches_during_the_run_reach_the_next_pack() { - let translator = translator_id(); - let (first, second) = (Digest::of(b"first page"), Digest::of(b"second page")); - let mut store = Store::new(translator, None).0; - store.offer(offer(0x1_0000_4008, first)); - store.offer(offer(0x1_0000_4010, first)); - store.offer(offer(0x1_0000_8010, second)); - let batch = store.take_batch(1).unwrap(); - assert_eq!(batch.blocks(), 2); - assert_eq!(store.pending(), 1); - store.fold(batch.prove()); - assert_eq!(store.counters.proven, 2); - // An offer already proven waits no more, and frees nothing twice. - store.offer(offer(0x1_0000_4008, first)); - assert_eq!(store.pending(), 1); - let planned = store.plan(u64::MAX, || true); - assert_eq!((planned.proven, planned.unproven), (1, 0)); - let bytes = planned.layout.to_vec(); - let mut next = Store::new(translator, Some(&bytes)).0; - let context = offer(0x1_0000_4008, first).context(); - let record = next.record(&first).unwrap(); - assert!(record.find(8, &context).is_some() && record.find(16, &context).is_some()); - assert!(next.record(&second).unwrap().find(16, &context).is_some()); - - // Past the proven bound a batch's entries are counted, not kept. - let mut full = Store::new(translator, None).0; - drop(full.set_bounds(Bounds { - proven: 0, - ..Bounds::default() - })); - full.offer(offer(0x1_0000_4008, first)); - assert!(full.take_batch(1).is_none()); - drop(full.set_bounds(Bounds { - proven: 1, - ..Bounds::default() - })); - let batch = full.take_batch(1).unwrap(); - full.fold(batch.prove()); - assert_eq!((full.counters.proven, full.counters.unkept), (1, 1)); - } - - /// Once a fold left an entry out for the proven bound, a batch proven - /// then would be left out too: none is taken, and the pages wait for - /// the stop's proof, which keeps them. Before, every batch was proven - /// and dropped with its pages for the rest of the run. - #[test] - fn a_store_short_of_an_entry_proves_no_batch_until_its_bound_grows() { - let translator = translator_id(); - let keys: Vec = (0u8..4).map(|index| Digest::of(&[index])).collect(); - let mut store = Store::new(translator, None).0; - drop(store.set_bounds(Bounds { - proven: 1, - ..Bounds::default() - })); - for (index, key) in keys.iter().enumerate() { - store.offer(offer(0x1_0000_4008 + 0x4000 * index as u64, *key)); - } - assert_eq!(store.pending(), 4); - let batch = store.take_batch(1).unwrap(); - assert_eq!(batch.blocks(), 1); - store.fold(batch.prove()); - assert_eq!((store.counters.proven, store.counters.unkept), (1, 1)); - // Room is left under the bound, but not for an entry: no batch. - for _ in 0..8 { - assert!(store.take_batch(1).is_none()); - } - assert_eq!((store.counters.proven, store.pending()), (1, 3)); - // A smaller bound changes nothing; a larger one proves again. - drop(store.set_bounds(Bounds { - proven: 0, - ..Bounds::default() - })); - assert!(store.take_batch(1).is_none()); - drop(store.set_bounds(Bounds::default())); - let batch = store.take_batch(1).unwrap(); - store.fold(batch.prove()); - assert_eq!((store.counters.proven, store.counters.unkept), (2, 1)); - assert_eq!(store.pending(), 2); - // The stop proves the two that still wait, and the next pack holds - // them with the one proven during the run. - let planned = store.plan(u64::MAX, || true); - assert_eq!((planned.proven, planned.unproven), (2, 0)); - let bytes = planned.layout.to_vec(); - let mut next = Store::new(translator, Some(&bytes)).0; - // All but the page the first, unkept batch took. - let context = offer(0x1_0000_4008, keys[0]).context(); - let kept = keys - .iter() - .filter(|key| { - next.record(key) - .is_some_and(|record| record.find(8, &context).is_some()) - }) - .count(); - assert_eq!(kept, 3); - } - /// A record no boot looks up ages by a boot at each write and leaves /// after [`MAX_UNUSED_BOOTS`]; one looked up is young again. Only the /// index is written for a change of ages. @@ -2583,11 +2034,11 @@ mod tests { let mut store = Store::new(translator, None).0; store.offer(offer(0x1_0000_4008, used)); store.offer(offer(0x1_0000_8008, unused)); - let mut bytes = store.plan(u64::MAX, || true).layout.to_vec(); + let mut bytes = store.plan(u64::MAX).layout.to_vec(); for boot in 1..=u64::from(MAX_UNUSED_BOOTS) + 1 { let mut next = Store::new(translator, Some(&bytes)).0; assert!(next.record(&used).is_some()); - let planned = next.plan(u64::MAX, || true); + let planned = next.plan(u64::MAX); let ranges = planned.layout.changed().unwrap().to_vec(); let expected = if boot > u64::from(MAX_UNUSED_BOOTS) { (1, 1) @@ -2614,28 +2065,34 @@ mod tests { // A boot that uses every record and changes no age writes nothing. let mut next = Store::new(translator, Some(&bytes)).0; assert!(next.record(&used).is_some()); - assert_eq!(next.plan(u64::MAX, || true).layout.changed(), Some(&[][..])); + assert_eq!(next.plan(u64::MAX).layout.changed(), Some(&[][..])); } - #[test] - fn a_larger_pending_bound_keeps_offers_a_smaller_one_drops() { + fn entries_past_the_added_bound_are_counted_not_kept() { let translator = translator_id(); let key = Digest::of(b"page"); let offers: Vec = (0..64) .map(|index| offer(0x1_0000_4000 + 8 * index, key)) .collect(); + let one = offers[0].entry().unwrap().retained_bytes(); let mut small = Store::new(translator, None).0; drop(small.set_bounds(Bounds { - pending: 256, + added: 4 * one, ..Bounds::default() })); let mut large = Store::new(translator, None).0; for offer in &offers { - small.keep_pending(offer); - large.keep_pending(offer); + small.keep(offer, offer.entry()); + large.keep(offer, offer.entry()); } - assert!(small.counters.dropped > 0); - assert_eq!((large.pending(), large.counters.dropped), (64, 0)); + assert_eq!((small.counters.added, small.counters.unkept), (4, 60)); + assert_eq!((large.counters.added, large.counters.unkept), (64, 0)); + // An offer the compiler gave no stored form is counted apart. + large.keep(&offers[0], None); + assert_eq!(large.counters.unstorable, 1); + let bytes = small.plan(u64::MAX).layout.to_vec(); + let mut next = Store::new(translator, Some(&bytes)).0; + assert_eq!(next.record(&key).unwrap().entries().len(), 4); } #[test] @@ -2690,11 +2147,10 @@ mod tests { for part in parts { merged.absorb(part); } - assert_eq!(merged.pending(), whole.pending()); - assert_eq!(merged.counters.offered, whole.counters.offered); + assert_eq!(merged.counters.added, whole.counters.added); assert_eq!( - merged.plan(u64::MAX, || true).layout.to_vec(), - whole.plan(u64::MAX, || true).layout.to_vec() + merged.plan(u64::MAX).layout.to_vec(), + whole.plan(u64::MAX).layout.to_vec() ); } } diff --git a/crates/stela-engine/src/translations/tests.rs b/crates/stela-engine/src/translations/tests.rs index ac58968f80..426eead037 100644 --- a/crates/stela-engine/src/translations/tests.rs +++ b/crates/stela-engine/src/translations/tests.rs @@ -320,7 +320,20 @@ fn records_reject_malformed_source_geometry_with_a_valid_checksum() { Ok(good.clone()) ); type Mutation = (&'static str, fn(&mut Entry)); - let mutations: [Mutation; 15] = [ + // As in compiled blocks, a prologue may precede the first instruction + // and an instruction fused into the next shares its native offset. + let accepted: [Mutation; 2] = [ + ("prologue", |entry| entry.source_map[0].1 = 1), + ("fused instruction", |entry| { + entry.source_map[1].1 = entry.source_map[0].1 + }), + ]; + for (name, mutate) in accepted { + let mut fine = entry.clone(); + mutate(&mut fine); + assert!(fine.consistent(), "{name}"); + } + let mutations: [Mutation; 13] = [ ("missing word", |entry| { entry.source_map.remove(1); }), @@ -328,9 +341,6 @@ fn records_reject_malformed_source_geometry_with_a_valid_checksum() { entry.source_map[1].0 = entry.source_map[0].0 }), ("guest gap", |entry| entry.source_map[1].0 += 4), - ("equal native", |entry| { - entry.source_map[1].1 = entry.source_map[0].1 - }), ("descending native", |entry| { entry.source_map[3].1 = entry.source_map[2].1 - 1 }), @@ -340,7 +350,6 @@ fn records_reject_malformed_source_geometry_with_a_valid_checksum() { ("out-of-range native", |entry| { entry.source_map[3].1 = u32::try_from(entry.code.len() + 1).unwrap() }), - ("wrong native entry", |entry| entry.source_map[0].1 = 1), ("unaligned source base", |entry| { entry.offset += 1; for (guest, _) in &mut entry.source_map { diff --git a/crates/stela-runtime/src/translation_store.rs b/crates/stela-runtime/src/translation_store.rs index 766acb18c4..1d6382c416 100644 --- a/crates/stela-runtime/src/translation_store.rs +++ b/crates/stela-runtime/src/translation_store.rs @@ -310,7 +310,7 @@ mod tests { for (key, _) in records() { assert!(store.record(&key).is_some()); } - let planned = store.plan(u64::MAX, || true); + let planned = store.plan(u64::MAX); assert_eq!(planned.layout.changed(), Some(&[][..])); write_in_place(&mut disk, &extents, &planned.layout).unwrap(); assert_eq!(disk.flushes, 0); @@ -410,7 +410,7 @@ mod tests { for (key, _) in trimmed.iter() { assert!(store.record(&key).is_some()); } - let planned = store.plan(limit, || true); + let planned = store.plan(limit); assert_eq!(planned.layout.changed(), Some(&[][..])); assert_eq!(planned.layout.records(), part.records); // A budget the index alone passes reads nothing. diff --git a/xtask/src/oracles/manifest.json b/xtask/src/oracles/manifest.json index 96405e0445..2aa91076d1 100644 --- a/xtask/src/oracles/manifest.json +++ b/xtask/src/oracles/manifest.json @@ -4762,6 +4762,14 @@ "inputs": [], "reason": "host timing measurement; run on request" }, + { + "package": "stela-engine", + "test": "compile_bench", + "source": "crates/stela-engine/src/machine/engine/stored/tests.rs", + "kind": "manual", + "inputs": [], + "reason": "host timing measurement over a code image named by STELA_COMPILE_BENCH; run on request" + }, { "package": "stela-engine", "test": "exit_transition_cold_costs",