From 4d689f4a55df2936f81ca56f5ff4030ad811901b Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:09:54 +0000 Subject: [PATCH 1/3] perf(engine): number a fetch's variant once through a four-entry memo per PE and keep each half's recent contexts by that number, where every fetch compared its variant field by field with each recent context of both halves and every take of a page searched the board's registry from its first variant, a few hundred bytes a compare (fetch_path_cost with 16 variants: 100 to 58 ns a fetch held by the table, 370 to 220 ns with a TLBI of everything every 840 fetches) --- crates/stela-engine/src/machine/engine.rs | 27 +++++- .../src/machine/engine/compilation.rs | 63 +++++++++++-- .../stela-engine/src/machine/engine/fetch.rs | 30 +++++-- .../stela-engine/src/machine/engine/tests.rs | 1 + .../machine/engine/tests/tlbi_keep_cost.rs | 89 +++++++++++++++++++ .../src/machine/engine/tests/variant_memo.rs | 72 +++++++++++++++ 6 files changed, 265 insertions(+), 17 deletions(-) create mode 100644 crates/stela-engine/src/machine/engine/tests/variant_memo.rs diff --git a/crates/stela-engine/src/machine/engine.rs b/crates/stela-engine/src/machine/engine.rs index 8cfafcd013..3e6dda21ed 100644 --- a/crates/stela-engine/src/machine/engine.rs +++ b/crates/stela-engine/src/machine/engine.rs @@ -674,16 +674,29 @@ struct JumpEntry { incarnation: u32, } -/// A half's recent context number, with the EL, variant and fetch epoch it -/// was found for. +/// A half's recent context number, with the EL, variant (by its number, +/// which names one variant for good) and fetch epoch it was found for. #[derive(Debug, Clone, Copy)] struct Recent { el: u8, - variant: Variant, + variant: VariantId, epoch: FetchEpoch, number: u64, } +/// The variants a PE numbered last ([`Machine::variant_memo`]): the fetch's +/// own, the guarded page's beside it, and a translated or tagged page's. +const VARIANT_MEMO: usize = 4; + +/// [`Machine::variant_memo`]: variants with their numbers in the registry +/// at `registry`, the oldest at `next`. +#[derive(Default)] +struct VariantMemo { + entries: [core::cell::Cell>; VARIANT_MEMO], + registry: core::cell::Cell, + next: core::cell::Cell, +} + /// `T` on cache lines of its own: a shared word that PEs read on every /// step or fetch, kept apart from words others write, or a word one PE /// writes kept apart from words the others read. @@ -947,6 +960,13 @@ pub struct Machine { context_frames: Vec<(mmu::Controls, u64)>, /// Each half's recent contexts, most recent first. recent: [[Option; RECENT]; 2], + /// The variants this PE numbered last: a fetch and each page it takes + /// number their variant ([`Machine::known_variant`], + /// [`Machine::variant_id`]), which [`Self::variants`] finds only by + /// comparing it with every variant before its own, each a few hundred + /// bytes. A registry's number names its variant for good, so an entry + /// goes stale only with the registry, whose address the memo keeps. + variant_memo: VariantMemo, /// The leaf sizes a fetch of each half translated through since its /// contexts were last forgotten, a bit per power of two, and whether one /// was non-global: what a TLBI by VA or ASID reaches of its lookup entries. @@ -1497,6 +1517,7 @@ impl Machine { ], context_frames: Vec::new(), recent: [[None; RECENT]; 2], + variant_memo: Default::default(), fetched_sizes: [0; 2], private_fetches: [false; 2], lower_globals: NO_GLOBALS, diff --git a/crates/stela-engine/src/machine/engine/compilation.rs b/crates/stela-engine/src/machine/engine/compilation.rs index 0edbff58ca..2293de8419 100644 --- a/crates/stela-engine/src/machine/engine/compilation.rs +++ b/crates/stela-engine/src/machine/engine/compilation.rs @@ -1175,17 +1175,68 @@ impl Machine { /// `variant`'s id, added to [`Self::variants`] the first time by /// whichever machine of the board meets it first. pub(super) fn variant_id(&mut self, variant: Variant) -> VariantId { - let id = self - .variants - .find_or_add(variant, || true) - .expect("a bounded set of variants"); - VariantId(id as u32) + if let Some(id) = self.remembered_variant(&variant) { + return id; + } + let id = VariantId( + self.variants + .find_or_add(variant, || true) + .expect("a bounded set of variants") as u32, + ); + self.remember_variant(variant, id); + id } /// `variant`'s id, once [`Self::variant_id`] gave it one: for a block /// compiled in it, or a context made in it ([`Self::context_salt`]). pub(super) fn known_variant(&self, variant: Variant) -> Option { - self.variants.find(&variant).map(|at| VariantId(at as u32)) + if let Some(id) = self.remembered_variant(&variant) { + return Some(id); + } + let id = VariantId(self.variants.find(&variant)? as u32); + self.remember_variant(variant, id); + Some(id) + } + + /// `variant`'s id if [`Machine::variant_memo`] holds it. The fields + /// that tell a fetch's variants apart are compared before the whole, + /// in place: an entry is a few hundred bytes. + fn remembered_variant(&self, variant: &Variant) -> Option { + let memo = &self.variant_memo; + // Numbers are a registry's: a machine given another (a test's board + // sharing one) forgets those of the one before. + let current = Arc::as_ptr(&self.variants) as usize; + if memo.registry.get() != current { + memo.registry.set(current); + for held in &memo.entries { + held.set(None); + } + return None; + } + memo.entries.iter().find_map(|held| { + // SAFETY: the memo is this machine's alone (a `Cell` is not + // `Sync`), and nothing sets it while this reference lives. + let (held, id) = unsafe { &*held.as_ptr() }.as_ref()?; + (held.guarded_page == variant.guarded_page + && held.translated == variant.translated + && held.single == variant.single + && held.fp == variant.fp + && held.checks == variant.checks + && held == variant) + .then_some(*id) + }) + } + + /// Remember that `variant` is numbered `id`, in place of the entry the + /// memo took longest ago. + fn remember_variant(&self, variant: Variant, id: VariantId) { + let memo = &self.variant_memo; + if memo.registry.get() != Arc::as_ptr(&self.variants) as usize { + return; + } + let next = memo.next.get(); + memo.entries[next].set(Some((variant, id))); + memo.next.set((next + 1) % VARIANT_MEMO); } /// What block `index` was compiled for. diff --git a/crates/stela-engine/src/machine/engine/fetch.rs b/crates/stela-engine/src/machine/engine/fetch.rs index 489170372a..983fe874c3 100644 --- a/crates/stela-engine/src/machine/engine/fetch.rs +++ b/crates/stela-engine/src/machine/engine/fetch.rs @@ -160,11 +160,18 @@ impl Machine { /// the guarded level, the variant and the half's translation inputs /// ([`contexts::Key`]). ITLB entries name it. pub(super) fn context(&mut self, el: u8, variant: Variant, half: usize) -> u64 { + let id = self.variant_id(variant); + self.numbered_context(el, variant, id, half) + } + + /// [`Self::context`] of `variant`, numbered `id`: the recent contexts + /// compare by the number. + fn numbered_context(&mut self, el: u8, variant: Variant, id: VariantId, half: usize) -> u64 { let epoch = self.fetch_epoch(half); if let Some(recent) = self.recent[half] .iter() .flatten() - .find(|recent| (recent.el, recent.variant, recent.epoch) == (el, variant, epoch)) + .find(|recent| recent.el == el && recent.variant == id && recent.epoch == epoch) { return recent.number; } @@ -178,7 +185,7 @@ impl Machine { Some(number) => number, None => match self.spaces[half].kept(&key) { Some(kept) if self.verify_kept(half, el, variant, kept) => kept, - _ => self.make_context(half, key, &controls), + _ => self.make_context(half, key, id, &controls), }, }; self.salt_clock += 1; @@ -186,7 +193,7 @@ impl Machine { self.recent[half].rotate_right(1); self.recent[half][0] = Some(Recent { el, - variant, + variant: id, // A frame's table may have filled and forgotten every context. epoch: self.fetch_epoch(half), number, @@ -195,8 +202,14 @@ impl Machine { } /// A new context of `half` for `key`, whose inputs are `controls`. - fn make_context(&mut self, half: usize, key: contexts::Key, controls: &mmu::Controls) -> u64 { - let salt = self.context_salt(half, key.variant, key.ttbr0); + fn make_context( + &mut self, + half: usize, + key: contexts::Key, + id: VariantId, + controls: &mmu::Controls, + ) -> u64 { + let salt = self.context_salt(half, id, key.ttbr0); let made = self.next_context; self.next_context += 1; let (number, evicted) = @@ -240,8 +253,8 @@ impl Machine { /// took it since, so that its ITLB entries take the places of a /// forgotten context's; else the least recently used, so that the /// address spaces that ran last keep slots apart. - fn context_salt(&mut self, half: usize, variant: Variant, table: u64) -> u64 { - let id = u64::from(self.variant_id(variant).0); + fn context_salt(&mut self, half: usize, variant: VariantId, table: u64) -> u64 { + let id = u64::from(variant.0); let owner = table ^ (half as u64) ^ id << 6; let salt = self.salt_owners.iter().position(|known| *known == owner); salt.unwrap_or_else(|| { @@ -278,9 +291,10 @@ impl Machine { /// generation, so that neither names a context the other's frame /// forgot. pub(super) fn contexts(&mut self, el: u8, variant: Variant) -> [u64; 2] { + let id = self.variant_id(variant); loop { let generation = self.translation_generation; - let contexts = [0, 1].map(|half| self.context(el, variant, half)); + let contexts = [0, 1].map(|half| self.numbered_context(el, variant, id, half)); if self.translation_generation == generation { return contexts; } diff --git a/crates/stela-engine/src/machine/engine/tests.rs b/crates/stela-engine/src/machine/engine/tests.rs index 362c8e6e80..8f445bc9a7 100644 --- a/crates/stela-engine/src/machine/engine/tests.rs +++ b/crates/stela-engine/src/machine/engine/tests.rs @@ -10544,6 +10544,7 @@ mod tier2_interactions; mod timer_native; mod tlbi_keep; mod tlbi_keep_cost; +mod variant_memo; #[test] fn host_work_holds_the_shared_count_only_for_a_pe_stopped_in_the_kernel() { diff --git a/crates/stela-engine/src/machine/engine/tests/tlbi_keep_cost.rs b/crates/stela-engine/src/machine/engine/tests/tlbi_keep_cost.rs index e70f78f838..3ff65f6e33 100644 --- a/crates/stela-engine/src/machine/engine/tests/tlbi_keep_cost.rs +++ b/crates/stela-engine/src/machine/engine/tests/tlbi_keep_cost.rs @@ -232,3 +232,92 @@ fn tlbi_keep_cost() { ); } } + +/// Host timing of the engine's fetch of blocks the table holds, on the same +/// PE shape as [`tlbi_keep_cost`], in boot 35's steady state: the busy +/// address spaces take turns, each fetching a run of its working set and +/// of the shared region, with a TLBI of everything every `PATH_EVERY` +/// rounds (boot 35's Finder window: about one per 800 fetches a PE). Prints +/// nanoseconds per fetch and the fetch paths taken. Manual: +/// `cargo test -p stela-engine --features test-support,std --release --lib +/// fetch_path_cost -- --ignored --nocapture` (`PATH_ROUNDS`, default 4000; +/// `PATH_EVERY`, default 10, 0 for none; `PATH_KEEP`, 1 for `--tlbi-keep`; +/// `PATH_VARIANTS`, the variants numbered before the fetches', default 16). +#[test] +#[ignore = "a host timing, run by hand"] +fn fetch_path_cost() { + let rounds = number("PATH_ROUNDS", 4000) as u64; + let every = number("PATH_EVERY", 10) as u64; + let keep = number("PATH_KEEP", 0) != 0; + let (busy, idle) = (27, 1270); + let bytes = (TABLES_AT + (busy + idle) * TABLES_BYTES) as usize; + let mut machine = machine(&[]); + machine.host.ram.resize(bytes, 0); + for frame in 0..PRIVATE_FRAMES + SHARED_FRAMES { + let at = (FRAMES_AT + frame * 0x1000) as usize; + machine.host.ram[at..at + 4].copy_from_slice(&RET.to_le_bytes()); + } + machine.set_tlbi_keep(keep, false); + normal_memory(&mut machine, false); + // A boot numbers its variants as it meets them, the busy processes' + // after the kernel's: these come before the fetches' own. + let variants = number("PATH_VARIANTS", 16) as u16; + let base = machine.current_variant(false, false); + for n in 0..variants { + let system = stela_compiler::x86_64::NativeSystem { + zero_block: Some(0x7000 + n), + ..base.system + }; + machine.variant_id(Variant { system, ..base }); + } + for space in 0..busy + idle { + let pages = if space < busy { BUSY_PAGES } else { IDLE_PAGES }; + build(&mut machine, space, pages); + } + for space in (0..busy + idle).rev() { + select(&mut machine, space); + let pages = if space < busy { BUSY_PAGES } else { IDLE_PAGES }; + for page in 0..pages { + run(&mut machine, page); + } + for page in 0..SHARED_PAGES.min(if space < busy { SHARED_PAGES } else { 4 }) { + run(&mut machine, SHARED_PAGE + page); + } + } + let mut draws = 0x9e37_79b9_7f4a_7c15u64; + let mut draw = |below: u64| { + draws ^= draws << 13; + draws ^= draws >> 7; + draws ^= draws << 17; + draws % below + }; + let paths = machine.statistics.fetch_paths; + let fetches: u64 = machine.statistics.fetches.iter().sum(); + let mut ns = 0u128; + for round in 0..rounds { + if every != 0 && round % every == 0 { + all(&mut machine); + } + let space = draw(busy); + let first = draw(BUSY_PAGES - BUSY_RUNS); + let shared = draw(SHARED_PAGES - SHARED_RUNS); + let started = Instant::now(); + select(&mut machine, space); + for page in first..first + BUSY_RUNS { + run(&mut machine, page); + } + for page in shared..shared + SHARED_RUNS { + run(&mut machine, SHARED_PAGE + page); + } + ns += started.elapsed().as_nanos(); + } + let fetched = machine.statistics.fetches.iter().sum::() - fetches; + let taken: Vec = (0..paths.len()) + .map(|path| machine.statistics.fetch_paths[path] - paths[path]) + .collect(); + println!( + "bench path keep={keep} rounds={rounds} every={every}: ns_per_fetch={:.1} fetches={fetched} \ + fast/fast_btype/itlb_miss/table_miss/btype_refused/single={taken:?}", + ns as f64 / fetched.max(1) as f64, + ); +} diff --git a/crates/stela-engine/src/machine/engine/tests/variant_memo.rs b/crates/stela-engine/src/machine/engine/tests/variant_memo.rs new file mode 100644 index 0000000000..1201fa4b7c --- /dev/null +++ b/crates/stela-engine/src/machine/engine/tests/variant_memo.rs @@ -0,0 +1,72 @@ +//! The PE's memo of variant numbers (`Machine::variant_memo`) gives what the +//! board's registry gives, for more variants than it holds, and forgets the +//! numbers of a registry the machine no longer reads. + +use super::*; + +/// The fetch's variant with `n` in a field no other test variant uses. +fn numbered(machine: &mut Machine, n: u16) -> Variant { + let base = machine.current_variant(false, false); + let system = stela_compiler::x86_64::NativeSystem { + zero_block: Some(0x6000 + n), + ..base.system + }; + Variant { system, ..base } +} + +#[test] +fn the_memo_gives_the_registry_s_numbers() { + let mut machine = machine(&[]); + let variants: Vec = (0..3 * VARIANT_MEMO as u16) + .map(|n| numbered(&mut machine, n)) + .collect(); + assert_eq!(machine.known_variant(variants[0]), None, "not numbered yet"); + let ids: Vec = variants + .iter() + .map(|&variant| machine.variant_id(variant)) + .collect(); + // In every order, through the memo and past it, each variant has the + // registry's number, and a guarded page's variant its own. + for round in 0..3 { + for (at, &variant) in variants.iter().enumerate().rev().skip(round) { + let registry = machine.variants.find(&variant).map(|at| VariantId(at as u32)); + assert_eq!(machine.known_variant(variant), Some(ids[at])); + assert_eq!(registry, Some(ids[at])); + assert_eq!(machine.variant_id(variant), ids[at]); + let guarded = Variant { + guarded_page: !variant.guarded_page, + ..variant + }; + assert_ne!(machine.variant_id(guarded), ids[at]); + assert_eq!( + machine.known_variant(guarded), + machine.variants.find(&guarded).map(|at| VariantId(at as u32)) + ); + } + } +} + +#[test] +fn another_registry_forgets_the_memo() { + let mut machine = machine(&[]); + let first = numbered(&mut machine, 1); + let second = numbered(&mut machine, 2); + machine.variant_id(first); + let id = machine.variant_id(second); + assert_eq!(machine.known_variant(second), Some(id)); + // A registry where the second variant has another number, and the + // first none. + let other = Arc::new(numbering::Registry::new(numbering::VARIANTS)); + for n in 0..=id.0 as u16 { + other.find_or_add(numbered(&mut machine, 100 + n), || true); + } + let renumbered = other.find_or_add(second, || true).unwrap(); + assert_ne!(VariantId(renumbered as u32), id); + machine.variants = other; + assert_eq!(machine.known_variant(first), None); + assert_eq!(machine.known_variant(second), Some(VariantId(renumbered as u32))); + assert_eq!( + machine.variant_id(first), + VariantId(renumbered as u32 + 1) + ); +} From 8b970e33a9a0eb7946f85897cf5cdeb63eefcb42 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:29:58 +0000 Subject: [PATCH 2/3] perf(engine): keep a fetch's variant and its number while the memory checks, native System features, FP trap, SVCR.SM and timing tier they derive from hold, and give every page a fetch and its refills take the fetch's number in that page's guard unless a page set gives it a variant of its own, where each fetch built its variant anew and found its number by a whole-variant compare, and each page taken, its leaf's other pages and each refilled page compared their variant again (fetch_path_cost with 16 variants: 58 to 43 ns a fetch held by the table, 220 to 206 ns with a TLBI of everything every 840 fetches; tlbi_keep_cost refill 804 to 753 us a TLBI) --- crates/stela-engine/src/machine/engine.rs | 21 +++ .../src/machine/engine/compilation.rs | 148 ++++++++++++++---- .../stela-engine/src/machine/engine/fetch.rs | 5 + .../src/machine/engine/native_failure.rs | 14 +- .../src/machine/engine/regime_state.rs | 6 + 5 files changed, 165 insertions(+), 29 deletions(-) diff --git a/crates/stela-engine/src/machine/engine.rs b/crates/stela-engine/src/machine/engine.rs index 3e6dda21ed..b008d3373c 100644 --- a/crates/stela-engine/src/machine/engine.rs +++ b/crates/stela-engine/src/machine/engine.rs @@ -690,6 +690,19 @@ const VARIANT_MEMO: usize = 4; /// [`Machine::variant_memo`]: variants with their numbers in the registry /// at `registry`, the oldest at `next`. +/// What a fetch's variant derives from besides the memory checks and the +/// native System features, which `version` (`Machine::derived_version`) +/// stands for, and the registry its number is in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct FetchInputs { + version: u64, + registry: usize, + fp: bool, + single: bool, + scalable: Option, + timing: bool, +} + #[derive(Default)] struct VariantMemo { entries: [core::cell::Cell>; VARIANT_MEMO], @@ -1056,6 +1069,12 @@ pub struct Machine { memory_checks: Option, /// [`Variant::system`] for the current EL, while valid. native_system: Option, + /// How many times `memory_checks` and `native_system` were derived + /// anew, which every change of either follows. + derived_version: u64, + /// A fetch's variant and its number, with what they were derived from + /// ([`Machine::fetch_variant`]). + fetch_variant: Option<(FetchInputs, Variant, VariantId)>, /// Whether blocks that branch back to their own start run their /// iterations inside themselves (`NativeSystem::self_loops`): on, but /// for tests that compare both forms. @@ -1550,6 +1569,8 @@ impl Machine { floating_point: None, memory_checks: None, native_system: None, + derived_version: 0, + fetch_variant: None, self_loops: true, regions: true, event_sample: None, diff --git a/crates/stela-engine/src/machine/engine/compilation.rs b/crates/stela-engine/src/machine/engine/compilation.rs index 2293de8419..0767bd3007 100644 --- a/crates/stela-engine/src/machine/engine/compilation.rs +++ b/crates/stela-engine/src/machine/engine/compilation.rs @@ -77,9 +77,13 @@ pub(super) fn grow_table( impl Machine { pub(super) fn fetch_block(&mut self, pc: u64, single: bool) -> Result { self.linked_at_install = None; - let context = self.current_variant(single, false); + let (context, context_id) = self.fetch_variant(single); + // The numbers of the fetch's variant in either page guard, for every + // page the fetch takes ([`Self::numbered_page_variant`]). + let mut numbers: PageNumbers = [None; 2]; + numbers[usize::from(context.guarded_page)] = Some(context_id); let el = self.cpu.pstate.el | u8::from(self.cpu.pstate.guarded) << 4; - let contexts = self.contexts(el, context); + let contexts = self.numbered_contexts(el, context, context_id); self.chain.set_contexts(contexts); if !self.dropped_refills.is_empty() || !self.refills.is_empty() { let refilling = self.host.counter(); @@ -87,7 +91,7 @@ impl Machine { self.refill_dropped(contexts); } if !self.refills.is_empty() { - self.refill_pages(el, context); + self.refill_pages(el, context, &mut numbers); } self.statistics.refill_ticks += self.host.counter().wrapping_sub(refilling); } @@ -148,19 +152,19 @@ impl Machine { // non-global fetch): the page is recorded, and dispatchers look // up, in their successors. if self.translation_generation != generation { - let contexts = self.contexts(el, context); + let contexts = self.numbered_contexts(el, context, context_id); self.chain.set_contexts(contexts); } let current = Variant { guarded_page: self.fetch_guarded(pc), ..context }; - let variant = self.page_variant(current, physical); + let (variant, variant_id) = self.numbered_page_variant(current, physical, &mut numbers); // The block another context, address space or fetch of the frame // recorded: what a TLBI ALL or a process switch leaves. - if !single && let Some(id) = self.known_variant(variant) { + if !single && let Some(id) = variant_id { let key = self.block_key(physical, id); - self.translate_leaf(pc, key, physical, current); + self.numbered_leaf(pc, key, physical, current, &mut numbers); let table = &self.code.table; let target = table.find(table.slot(pc, key), pc, key); // Every release of a block forgets its entries; the block is @@ -191,8 +195,8 @@ impl Machine { self.entered(entry.block); return Ok(Fetched::Block(entry.block)); } - let indexed = self - .known_variant(variant) + let indexed = variant_id + .or_else(|| self.known_variant(variant)) .and_then(|id| self.code.find(pc, physical, id)); self.statistics.fetches[if indexed.is_some() { 3 } else { 4 }] += 1; let index = match indexed { @@ -227,7 +231,7 @@ impl Machine { }); if !single { let key = self.block_key(physical, self.code.blocks[index].variant); - self.translate_leaf(pc, key, physical, current); + self.numbered_leaf(pc, key, physical, current, &mut numbers); } self.remember_or_link(pc, index); self.entered(index); @@ -317,13 +321,55 @@ impl Machine { /// `page_variant`), then the other pages of its leaf /// ([`Self::take_leaf_pages`]). pub(super) fn translate_leaf(&mut self, pc: u64, key: u64, physical: u64, current: Variant) { + self.numbered_leaf(pc, key, physical, current, &mut [None; 2]); + } + + /// [`Self::translate_leaf`] with what the fetch numbered of its variant + /// (`numbers`, [`Self::numbered_page_variant`]). + fn numbered_leaf( + &mut self, + pc: u64, + key: u64, + physical: u64, + current: Variant, + numbers: &mut PageNumbers, + ) { self.translate_page(pc, key); if let Some(walk) = self.cached_fetch(pc) { let record = self.fetch_record(pc); - self.take_leaf_pages(pc, physical, walk.size, current, walk.global, record); + let leaf = Leaf { + size: walk.size, + global: walk.global, + record, + }; + self.take_leaf_pages(pc, physical, leaf, current, numbers); } } + /// `page_variant(current, physical)` and its number, through `numbers`: + /// those of `current` in an unguarded and a guarded page, as far as + /// known, which every page the page's sets leave alone shares. A fetch + /// numbers its variant once, and each page it and its refills take only + /// where a set gives the page a variant of its own. `numbers` hold for + /// the one variant `current` is in either guard. + pub(super) fn numbered_page_variant( + &self, + current: Variant, + physical: u64, + numbers: &mut PageNumbers, + ) -> (Variant, Option) { + let (variant, touched) = self.page_variant_of(current, physical); + if touched { + return (variant, self.known_variant(variant)); + } + let number = &mut numbers[usize::from(variant.guarded_page)]; + if number.is_none() { + *number = self.known_variant(variant); + } + debug_assert_eq!(*number, self.known_variant(variant), "numbers of another variant"); + (variant, *number) + } + /// Give the ITLB the other 4 KiB pages of the [`LEAF_FILL`] granule /// around `pc` that the leaf of `size` bytes holding `pc` maps, whose /// page is in the frame of `physical`, as a fetch of each would take @@ -340,10 +386,13 @@ impl Machine { &mut self, pc: u64, physical: u64, - size: u64, + Leaf { + size, + global, + record, + }: Leaf, current: Variant, - global: bool, - record: Option, + numbers: &mut PageNumbers, ) { let span = size.min(LEAF_FILL); if span <= FETCH_PAGE { @@ -360,8 +409,7 @@ impl Machine { continue; } let other_frame = frame.wrapping_add(other).wrapping_sub(page); - let variant = self.page_variant(current, other_frame); - let Some(id) = self.known_variant(variant) else { + let (_, Some(id)) = self.numbered_page_variant(current, other_frame, numbers) else { continue; }; let key = self.block_key(other_frame, id); @@ -729,7 +777,7 @@ impl Machine { /// page, as a walk cache lets hardware walk ([`mmu::WalkMemo`]). Nothing /// in the batch runs guest code or changes the controls, and the walks /// make no descriptor updates; the table is dropped with the batch. - pub(super) fn refill_pages(&mut self, el: u8, context: Variant) { + pub(super) fn refill_pages(&mut self, el: u8, context: Variant, numbers: &mut PageNumbers) { let generation = self.translation_generation; let mut quiet = QuietWalk::new(&self.cpu); for pc in core::mem::take(&mut self.refills) { @@ -749,8 +797,7 @@ impl Machine { guarded_page: walk.guarded, ..context }; - let variant = self.page_variant(current, walk.physical); - if let Some(id) = self.known_variant(variant) { + if let (_, Some(id)) = self.numbered_page_variant(current, walk.physical, numbers) { let key = self.block_key(walk.physical, id); self.take_page( pc, @@ -761,14 +808,12 @@ impl Machine { walk.record, ); } - self.take_leaf_pages( - pc, - walk.physical, - walk.size, - current, - walk.global, - walk.record, - ); + let leaf = Leaf { + size: walk.size, + global: walk.global, + record: walk.record, + }; + self.take_leaf_pages(pc, walk.physical, leaf, current, numbers); } } @@ -1172,6 +1217,43 @@ impl Machine { } } + /// [`Self::current_variant`] of a fetch (`single` or not, in no guarded + /// page) and its number, kept while what they derive from holds: the + /// memory checks and native System features as derived last (a change + /// of either derives them anew, which moves `derived_version`), FP's + /// trap, SVCR.SM, the timing tier and the registry. + pub(super) fn fetch_variant(&mut self, single: bool) -> (Variant, VariantId) { + let fp = self.floating_point_enabled(); + if self.memory_checks.is_none() { + self.memory_checks(); + } + if self.native_system.is_none() { + self.native_system(); + } + let inputs = FetchInputs { + version: self.derived_version, + registry: Arc::as_ptr(&self.variants) as usize, + fp, + single, + scalable: self + .cpu + .scalable + .is_some() + .then(|| self.cpu.svcr() & 1 != 0), + timing: self.cpu.pstate.dit && self.timing_target().is_some(), + }; + if let Some((held, variant, id)) = self.fetch_variant + && held == inputs + { + debug_assert_eq!(variant, self.current_variant(single, false)); + return (variant, id); + } + let variant = self.current_variant(single, false); + let id = self.variant_id(variant); + self.fetch_variant = Some((inputs, variant, id)); + (variant, id) + } + /// `variant`'s id, added to [`Self::variants`] the first time by /// whichever machine of the board meets it first. pub(super) fn variant_id(&mut self, variant: Variant) -> VariantId { @@ -2463,6 +2545,18 @@ enum Taken { /// 16 KiB page, the granule XNU maps code with, in 4 KiB ITLB pages. const LEAF_FILL: u64 = 1 << 14; +/// The numbers of one variant in an unguarded page (0) and a guarded one +/// (1), as far as known ([`Machine::numbered_page_variant`]). +pub(super) type PageNumbers = [Option; 2]; + +/// What [`Machine::take_leaf_pages`] takes of the walk of a leaf: the bytes +/// it maps, its global bit and its record. +struct Leaf { + size: u64, + global: bool, + record: Option, +} + /// The most pages one forgotten context leaves to walk again /// ([`Machine::refill_after`]). At 512 the cap bound: after each local TLBI /// of everything a PE refilled about 510 pages and then missed about 600 diff --git a/crates/stela-engine/src/machine/engine/fetch.rs b/crates/stela-engine/src/machine/engine/fetch.rs index 983fe874c3..aaedd60ff5 100644 --- a/crates/stela-engine/src/machine/engine/fetch.rs +++ b/crates/stela-engine/src/machine/engine/fetch.rs @@ -292,6 +292,11 @@ impl Machine { /// forgot. pub(super) fn contexts(&mut self, el: u8, variant: Variant) -> [u64; 2] { let id = self.variant_id(variant); + self.numbered_contexts(el, variant, id) + } + + /// [`Self::contexts`] of `variant`, numbered `id`. + pub(super) fn numbered_contexts(&mut self, el: u8, variant: Variant, id: VariantId) -> [u64; 2] { loop { let generation = self.translation_generation; let contexts = [0, 1].map(|half| self.numbered_context(el, variant, id, half)); diff --git a/crates/stela-engine/src/machine/engine/native_failure.rs b/crates/stela-engine/src/machine/engine/native_failure.rs index 1164e03066..ff0df8cb38 100644 --- a/crates/stela-engine/src/machine/engine/native_failure.rs +++ b/crates/stela-engine/src/machine/engine/native_failure.rs @@ -433,20 +433,30 @@ impl Machine { /// `variant` for a block of the fetch page holding `physical`: in the /// translated variant when the page needs it, through the host's /// translation helper. - pub(super) fn page_variant(&self, mut variant: Variant, physical: u64) -> Variant { + pub(super) fn page_variant(&self, variant: Variant, physical: u64) -> Variant { + self.page_variant_of(variant, physical).0 + } + + /// [`Self::page_variant`], and whether the page's sets touched + /// `variant` at all: when not, it is `variant` itself. + pub(super) fn page_variant_of(&self, mut variant: Variant, physical: u64) -> (Variant, bool) { + let mut touched = false; if self.page_translated(physical) && let Some(helper) = self.host.translation_helper() { variant.translated = true; variant.checks = variant.checks.with_translation(helper); + touched = true; } if self.page_tagged(physical) { variant.checks = variant.checks.with_top_byte(self.regime_top_byte()); + touched = true; } if variant.checks.range.one_sided && self.code.two_sided.contains(physical) { variant.checks.range = variant.checks.range.one_sided(false); + touched = true; } - variant + (variant, touched) } /// An EL0 access of the fetch page holding `physical`, by a block of diff --git a/crates/stela-engine/src/machine/engine/regime_state.rs b/crates/stela-engine/src/machine/engine/regime_state.rs index 5a6929bfd0..1d9a65693b 100644 --- a/crates/stela-engine/src/machine/engine/regime_state.rs +++ b/crates/stela-engine/src/machine/engine/regime_state.rs @@ -218,6 +218,9 @@ impl Machine { /// ID_AA64PFR0_EL1.CSV3 discloses FEAT_CSV3, the guest range check at /// every access (`identification::Speculation::faulting_data`). pub(super) fn memory_checks(&mut self) -> MemoryChecks { + if self.memory_checks.is_none() { + self.derived_version += 1; + } *self.memory_checks.get_or_insert_with(|| { let sctlr = self.cpu.regime_sctlr(); let bit = if self.cpu.pstate.el == 0 { 4 } else { 3 }; @@ -247,6 +250,9 @@ impl Machine { } pub(super) fn native_system(&mut self) -> NativeSystem { + if self.native_system.is_none() { + self.derived_version += 1; + } *self.native_system.get_or_insert_with(|| NativeSystem { zero_block: system::native_zero_block(&self.cpu, &self.profile_missing), cache_clean: system::native_cache_clean(&self.cpu), From ead114f77fad9a31cb068d1c63f3f4211e133b5e Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:05:45 +0000 Subject: [PATCH 3/3] style(engine): compile the variant-taking `context` and `translate_leaf` only for the tests that call them, now that fetches number their variant first, and format the fetch path's new code, where clippy refused both as dead code --- .../src/machine/engine/compilation.rs | 9 +++++++-- .../stela-engine/src/machine/engine/fetch.rs | 18 ++++++++++++------ .../src/machine/engine/tests/variant_memo.rs | 16 +++++++++++----- 3 files changed, 30 insertions(+), 13 deletions(-) diff --git a/crates/stela-engine/src/machine/engine/compilation.rs b/crates/stela-engine/src/machine/engine/compilation.rs index 0767bd3007..9b28170618 100644 --- a/crates/stela-engine/src/machine/engine/compilation.rs +++ b/crates/stela-engine/src/machine/engine/compilation.rs @@ -320,11 +320,12 @@ impl Machine { /// `physical` in `current` (its variant before the page's own: /// `page_variant`), then the other pages of its leaf /// ([`Self::take_leaf_pages`]). + #[cfg(test)] pub(super) fn translate_leaf(&mut self, pc: u64, key: u64, physical: u64, current: Variant) { self.numbered_leaf(pc, key, physical, current, &mut [None; 2]); } - /// [`Self::translate_leaf`] with what the fetch numbered of its variant + /// `translate_leaf` with what the fetch numbered of its variant /// (`numbers`, [`Self::numbered_page_variant`]). fn numbered_leaf( &mut self, @@ -366,7 +367,11 @@ impl Machine { if number.is_none() { *number = self.known_variant(variant); } - debug_assert_eq!(*number, self.known_variant(variant), "numbers of another variant"); + debug_assert_eq!( + *number, + self.known_variant(variant), + "numbers of another variant" + ); (variant, *number) } diff --git a/crates/stela-engine/src/machine/engine/fetch.rs b/crates/stela-engine/src/machine/engine/fetch.rs index aaedd60ff5..3a41d9a4a7 100644 --- a/crates/stela-engine/src/machine/engine/fetch.rs +++ b/crates/stela-engine/src/machine/engine/fetch.rs @@ -156,16 +156,17 @@ impl Machine { self.next() } - /// The number of the context a fetch in `half` runs in now: the EL with - /// the guarded level, the variant and the half's translation inputs - /// ([`contexts::Key`]). ITLB entries name it. + /// [`Self::numbered_context`] of `variant`, numbered here. + #[cfg(test)] pub(super) fn context(&mut self, el: u8, variant: Variant, half: usize) -> u64 { let id = self.variant_id(variant); self.numbered_context(el, variant, id, half) } - /// [`Self::context`] of `variant`, numbered `id`: the recent contexts - /// compare by the number. + /// The number of the context a fetch in `half` runs in now: the EL with + /// the guarded level, the variant (`variant`, numbered `id`) and the + /// half's translation inputs ([`contexts::Key`]). ITLB entries name it. + /// The recent contexts compare variants by their numbers. fn numbered_context(&mut self, el: u8, variant: Variant, id: VariantId, half: usize) -> u64 { let epoch = self.fetch_epoch(half); if let Some(recent) = self.recent[half] @@ -296,7 +297,12 @@ impl Machine { } /// [`Self::contexts`] of `variant`, numbered `id`. - pub(super) fn numbered_contexts(&mut self, el: u8, variant: Variant, id: VariantId) -> [u64; 2] { + pub(super) fn numbered_contexts( + &mut self, + el: u8, + variant: Variant, + id: VariantId, + ) -> [u64; 2] { loop { let generation = self.translation_generation; let contexts = [0, 1].map(|half| self.numbered_context(el, variant, id, half)); diff --git a/crates/stela-engine/src/machine/engine/tests/variant_memo.rs b/crates/stela-engine/src/machine/engine/tests/variant_memo.rs index 1201fa4b7c..e92715c4de 100644 --- a/crates/stela-engine/src/machine/engine/tests/variant_memo.rs +++ b/crates/stela-engine/src/machine/engine/tests/variant_memo.rs @@ -29,7 +29,10 @@ fn the_memo_gives_the_registry_s_numbers() { // registry's number, and a guarded page's variant its own. for round in 0..3 { for (at, &variant) in variants.iter().enumerate().rev().skip(round) { - let registry = machine.variants.find(&variant).map(|at| VariantId(at as u32)); + let registry = machine + .variants + .find(&variant) + .map(|at| VariantId(at as u32)); assert_eq!(machine.known_variant(variant), Some(ids[at])); assert_eq!(registry, Some(ids[at])); assert_eq!(machine.variant_id(variant), ids[at]); @@ -40,7 +43,10 @@ fn the_memo_gives_the_registry_s_numbers() { assert_ne!(machine.variant_id(guarded), ids[at]); assert_eq!( machine.known_variant(guarded), - machine.variants.find(&guarded).map(|at| VariantId(at as u32)) + machine + .variants + .find(&guarded) + .map(|at| VariantId(at as u32)) ); } } @@ -64,9 +70,9 @@ fn another_registry_forgets_the_memo() { assert_ne!(VariantId(renumbered as u32), id); machine.variants = other; assert_eq!(machine.known_variant(first), None); - assert_eq!(machine.known_variant(second), Some(VariantId(renumbered as u32))); assert_eq!( - machine.variant_id(first), - VariantId(renumbered as u32 + 1) + machine.known_variant(second), + Some(VariantId(renumbered as u32)) ); + assert_eq!(machine.variant_id(first), VariantId(renumbered as u32 + 1)); }