perf(engine): store each block from the guest-address fields its emitter recorded, replacing the proof queue that compiled every block twice more

This commit is contained in:
Tyler Smith committed 2026-11-11 23:46:27 -05:00
1 parent dec21ef707
commit 5fcac61b9b
47 files changed
+1000 -1054

No files matched your search

+4 -4
View File
@@ -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
+34 -106
View File
@@ -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)
+3 -3
View File
@@ -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<Result<Operand, Unsupported
let immediate = i64::from((word >> 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 {
@@ -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<Operand> {
@@ -25,7 +25,7 @@ pub fn decode(pc: GuestAddress, word: u32) -> Option<Operand> {
};
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 }),
})
);
}
@@ -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<Result<Operand, Unsupported
(word >> 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
))
);
}
}
+4 -2
View File
@@ -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());
}
+7
View File
@@ -76,6 +76,13 @@ pub trait Lifter {
pub struct NativeBlock {
pub x86_64_code: Vec<u8>,
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<Vec<u32>>,
}
/// What [`compile`] translates for: the guest services and memory checks of a
@@ -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),
})
}
}
@@ -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(),
+8 -1
View File
@@ -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);
+16
View File
@@ -32,6 +32,9 @@ pub(crate) struct Asm<'a> {
instructions: usize,
shared: Option<&'a mut usize>,
sites: Option<&'a mut Vec<EmissionSite>>,
/// 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<u32>>,
pinned: bool,
locals: Option<super::pinned::LocalRegisters>,
/// 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<Rm>, value: i32) {
debug_assert!(size != Size::Byte && size != Size::Word);
@@ -8,6 +8,10 @@ pub(crate) struct Code {
pub(super) bytes: Vec<u8>,
pub(super) instructions: usize,
pub(super) sites: Vec<EmissionSite>,
/// 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<u32>,
/// Whether guest registers live in host registers ([`super::super::pinned`]).
pub(super) pinned: bool,
locals: Option<super::super::pinned::LocalRegisters>,
@@ -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<u8>, Vec<u32>) {
(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();
}
+4 -4
View File
@@ -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);
}
+4 -4
View File
@@ -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,
@@ -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)),
@@ -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);
@@ -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]);
+1 -1
View File
@@ -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);
}
+1 -1
View File
@@ -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);
}
+1 -1
View File
@@ -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);
}
}
+6 -4
View File
@@ -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
@@ -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 {
@@ -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<u64>; REGISTER_SLOTS],
values: [Option<Constant>; REGISTER_SLOTS],
}
impl Default for ConstantRegisters {
@@ -45,15 +73,15 @@ impl ConstantRegisters {
self.values.fill(None);
}
fn read(&self, register: Register) -> Option<u64> {
fn read(&self, register: Register) -> Option<Constant> {
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<u64>) -> Option<ConstantWrite> {
fn write(&mut self, destination: Register, value: Option<Constant>) -> Option<ConstantWrite> {
let index = slot(destination)?;
self.values[index] = value;
value.map(|value| ConstantWrite { destination, value })
@@ -65,7 +93,7 @@ impl ConstantRegisters {
second: &Operation,
) -> Option<ConstantWrite> {
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)
})
);
}
}
@@ -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),
@@ -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));
@@ -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)),
@@ -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);
@@ -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,
@@ -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(
@@ -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);
@@ -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()
);
@@ -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
);
}
}
}
+5 -5
View File
@@ -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)]
+1 -1
View File
@@ -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,
@@ -615,9 +615,9 @@ impl<H: Host, D: Devices> Machine<H, D> {
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<H: Host, D: Devices> Machine<H, D> {
}
}
// 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<H: Host, D: Devices> Machine<H, D> {
}
self.relocated = relocated;
}
super::rebase::Found::Prove => prove = true,
super::rebase::Found::Keep => keep = true,
super::rebase::Found::Compile => {}
}
}
@@ -775,12 +775,11 @@ impl<H: Host, D: Devices> Machine<H, D> {
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<H: Host, D: Devices> Machine<H, D> {
&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)
@@ -239,7 +239,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
address: ScalarLoadAddress,
) -> (u64, Option<(Register, u64)>) {
match address {
ScalarLoadAddress::Literal { address } => (address, None),
ScalarLoadAddress::Literal { address } => (address.0, None),
ScalarLoadAddress::Immediate {
base,
displacement,
@@ -106,6 +106,8 @@ impl<H: Host, D: Devices> Machine<H, D> {
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(),
@@ -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::<usize>();
@@ -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<Entry>),
/// Its proof failed: it is compiled at every address.
Unprovable,
Kept(Arc<Entry>),
/// 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<Entry>),
/// 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<Part>; 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<Entry>) {
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).
@@ -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 {
@@ -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<Entry> {
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<Preparation>,
) -> 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<SharedTranslation> {
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<crate::translations::Entry> {
Self::prove_block(
/// Its block's stored form ([`stored_entry`]).
pub fn entry(&self) -> Option<Entry> {
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<crate::translations::Entry> {
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<crate::translations::Entry> {
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
@@ -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<u32> = (0..1 + random() % 8)
.map(|_| address_word(&mut random))
.collect();
words.push(ending_word(&mut random));
let mut source: Vec<u8> = 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<u8>)> = 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),
);
}
@@ -274,7 +274,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
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,
+117 -68
View File
@@ -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<Self> {
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<u32>,
) -> Option<Self> {
let code = &block.native.x86_64_code;
if relocations
.iter()
.map(|&(guest, native)| Some((page_offset(guest.0)?, u32::try_from(native).ok()?)))
.collect::<Option<_>>()?,
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::<Option<_>>()?,
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::<Option<_>>()?,
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::<Option<_>>()?,
};
entry.consistent().then_some(entry)
.collect::<Option<_>>()?,
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::<Option<_>>()?,
};
entry.consistent().then_some(entry)
}
}
#[cfg(test)]
File diff suppressed because it is too large. Load diff
+14 -5
View File
@@ -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 {
@@ -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.
+8
View File
@@ -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",