diff --git a/crates/stela-engine/src/machine/engine.rs b/crates/stela-engine/src/machine/engine.rs index 2d6f9fde29..f46239d071 100644 --- a/crates/stela-engine/src/machine/engine.rs +++ b/crates/stela-engine/src/machine/engine.rs @@ -480,7 +480,6 @@ struct Block { device_stub: bool, /// An HLE composite's mark ([`hle::Mark`]): where its native fast path /// ends, which a fault inside it is taken back from. - #[expect(dead_code, reason = "the fault bypass reads it next")] hle: Option, } diff --git a/crates/stela-engine/src/machine/engine/hle.rs b/crates/stela-engine/src/machine/engine/hle.rs index 744ae9391c..df73281bea 100644 --- a/crates/stela-engine/src/machine/engine/hle.rs +++ b/crates/stela-engine/src/machine/engine/hle.rs @@ -18,14 +18,22 @@ //! instruction at the entry's PC and fetch page, so an IC IVAU of any byte //! of the function retires it, and it is never stored, offered or rebased. //! Its block holds a [`Mark`]: where its fast path ends. +//! +//! A guest access's fault inside the fast path ([`Machine::hle_fault`]) +//! puts the PC back at the entry with the guest state the fast path found, +//! which it has not changed, and the next step runs the entry's first +//! instruction alone ([`Machine::take_hle_bypass`]): the original takes the +//! fault itself, with the ESR, FAR, ELR and state it would have without +//! HLE. use super::*; use crate::hle::{Config, Id, PREFIX_BYTES, Refusal, Signature, Statistics}; use core::num::NonZeroU8; use stela_compiler::x86_64::hle::{self as composite, Request}; /// A machine's HLE: its configuration, what it did, the bytes of a -/// candidate function longer than the compile's window, and the mark of -/// the composite it is installing, for its block ([`Self::installing`]). +/// candidate function longer than the compile's window, the mark of the +/// composite it is installing, for its block ([`Self::installing`]), and +/// the entry whose original the next step runs ([`Self::bypass`]). #[derive(Default)] pub(super) struct State { config: Config, @@ -34,6 +42,9 @@ pub(super) struct State { /// While a composite installs: the mark its block takes, as /// `installing_stub` marks a device stub's. pub(super) installing: Option, + /// The entry of the composite whose fast path faulted: a step there + /// next runs its first instruction alone. + bypass: Option, } /// What a composite block holds of its composite: the length of its fast @@ -62,7 +73,6 @@ impl Mark { /// Where the fast path ends and the original's first instruction /// starts, in the block's code. - #[expect(dead_code, reason = "the fault bypass reads it next")] pub(super) fn prefix_end(self) -> usize { usize::from(self.prefix_units.get()) * composite::PREFIX_ALIGN as usize } @@ -257,4 +267,64 @@ impl Machine { self.hle.statistics.installed += 1; Ok(Some(fetched)) } + + /// `fault`, in block `index`'s code after `chained_retired` instructions + /// of the run's earlier blocks, entered with `chained_btype` by a link: + /// when the block is a composite and the fault one of a guest access in + /// its fast path, settle the run as `native_fault` does at the block's + /// first instruction with none of it retired, which is the guest state + /// the fast path found (it writes no guest register or frame field + /// before it can no longer fault), put the PC at the entry and have the + /// next step there run the original's first instruction alone. `None` + /// for any other fault: one in the bail's code is the original's own, + /// settled by its rows, and any other trap in a fast path stops the PE + /// as `native_fault` stops for a fault no row covers. + /// + /// A guest access's fault is one `native_fault` takes at a guest access + /// site: a #PF of a plain read or write (no fetch, reserved-bit or key + /// error code), or a #GP or #SS of a non-canonical address, as a fast + /// path's address that passed its range check can be on a host whose + /// placement's limit lies past its canonical range. + pub(super) fn hle_fault( + &mut self, + index: usize, + fault: &NativeFault, + chained_retired: u64, + chained_btype: Option, + ) -> Option { + let block = self.code.blocks.get(index)?; + let (entry, mark) = (block.pc, block.hle?); + let access = match fault.trap { + 14 => { + fault.error_code & !0b111 == 0 && !matches!(fault.cause, FaultCause::InvalidOpcode) + } + 12 | 13 => fault.error_code == 0 && matches!(fault.cause, FaultCause::NonCanonical), + _ => false, + }; + if fault.offset >= mark.prefix_end() + || fault.origin != NativeFaultOrigin::Exception + || !access + { + return None; + } + let mut staged = self.cpu.state.clone(); + stela_compiler::x86_64::pinned::settle(&fault.registers, &mut staged); + self.cpu.state = staged; + self.cpu.retired = self.cpu.retired.wrapping_add(chained_retired); + self.cpu.pc = entry; + if let Some(btype) = chained_btype { + self.cpu.pstate.btype = btype; + } + self.hle.bypass = Some(entry); + self.hle.statistics.bypassed += 1; + Some(Ok(())) + } + + /// Whether the step at `pc` runs the original's first instruction alone + /// after its composite's fast path faulted there. Every step that + /// fetches takes the bypass, so one left when an interrupt moved the PC + /// elsewhere does not outlive that step. + pub(super) fn take_hle_bypass(&mut self, pc: u64) -> bool { + self.hle.bypass.take() == Some(pc) + } } diff --git a/crates/stela-engine/src/machine/engine/native_failure.rs b/crates/stela-engine/src/machine/engine/native_failure.rs index 005bcd12a0..1d8233bbf6 100644 --- a/crates/stela-engine/src/machine/engine/native_failure.rs +++ b/crates/stela-engine/src/machine/engine/native_failure.rs @@ -153,6 +153,9 @@ impl Machine { use stela_compiler::block::{ FaultRecovery, HostFaultSnapshot, RecoverySiteKind, RetirementPhase, }; + if let Some(step) = self.hle_fault(index, &fault, chained_retired, chained_btype) { + return step; + } // Source maps locate diagnostics; only a checked exact // operand/check site can authorize architectural fault projection. let Some(block) = self.code.blocks.get(index) else { diff --git a/crates/stela-engine/src/machine/engine/scheduler.rs b/crates/stela-engine/src/machine/engine/scheduler.rs index e664530489..0dafaba832 100644 --- a/crates/stela-engine/src/machine/engine/scheduler.rs +++ b/crates/stela-engine/src/machine/engine/scheduler.rs @@ -233,7 +233,8 @@ impl Machine { self.cpu.step_advance = mode.step; // PSTATE.PACM applies to the one instruction after PACM. let pacm = self.cpu.pstate.pacm; - let single = mode.breakpoints || mode.step || pacm; + let bypass = self.take_hle_bypass(pc); + let single = bypass || mode.breakpoints || mode.step || pacm; let fetching = self.timing_start(); let fetched = self.fetch_block(pc, single); let fetched_at = self.timing_charge(step_timing::Phase::Fetch, fetching); diff --git a/crates/stela-engine/tests/hle_differential.rs b/crates/stela-engine/tests/hle_differential.rs index 683cef5bc0..3aebb4e0a8 100644 --- a/crates/stela-engine/tests/hle_differential.rs +++ b/crates/stela-engine/tests/hle_differential.rs @@ -273,10 +273,10 @@ fn a_reused_session_runs_as_a_fresh_machine() -> Result<()> { for stand_in in direct.iter().chain(&called) { let id = stand_in.id; // Off, and on with each test routine that suits the stand-in: Bail - // for all, Touch for touch's where a Branch Target exception comes - // before its fast path could fault. + // for all, Touch for touch's, whose fast path faults and bypasses + // where X0's page is unreadable. let mut routines = vec![None, Some(Id::Bail)]; - if id == Id::Touch && stand_in.caller.is_some() { + if id == Id::Touch { routines.push(Some(Id::Touch)); } for routine in routines { @@ -288,7 +288,11 @@ fn a_reused_session_runs_as_a_fresh_machine() -> Result<()> { let (mut returned, mut aborted, mut after_abort) = (0, 0, false); let count = if stand_in.caller.is_some() { 48 } else { 120 }; for case in cases(id, 23, count) { + let bypassed = session.hle().bypassed; let reused = session.run(&case)?; + // A fast path faults only on a page that is not mapped. + let mapped = case.unreadable.is_none() && case.read_only.is_none(); + assert!(!mapped || session.hle().bypassed == bypassed); // The first calls, every abort and every call after one. if returned < 4 || after_abort || reused.abort.is_some() { let fresh = run(stand_in, &case, hle.clone())?.0; diff --git a/crates/stela-engine/tests/hle_install.rs b/crates/stela-engine/tests/hle_install.rs index 096425e242..47d9b67eef 100644 --- a/crates/stela-engine/tests/hle_install.rs +++ b/crates/stela-engine/tests/hle_install.rs @@ -270,6 +270,182 @@ fn a_disabled_id_never_matches() -> Result<()> { Ok(()) } +/// The Touch routine over touch's stand-in, enabled. +fn touch() -> Config { + Config::with_table(table(&stand_in(Id::Touch), Id::Touch), &[Id::Touch]) +} + +/// A call of touch's stand-in with X0 and X1 at data offsets `x0` and `x1` +/// (offsets wrap: any address is one) and page `unreadable` unreadable. +fn touching(x0: u64, x1: u64, unreadable: Option) -> Case { + Case { + x: [x0, x1, 0], + unreadable, + read_only: None, + ..cases(Id::Touch, 21, 1).remove(0) + } +} + +/// Touch's X1, readable on the data mapping's third page. +const X1: u64 = 2 * PAGE as u64 + 5; + +#[test] +fn a_fault_in_the_native_prefix_is_taken_by_the_original() -> Result<()> { + // X0's page is unreadable: the fast path's load of it faults, and the + // original then loads X1 and faults at its second instruction. + let stand_in = stand_in(Id::Touch); + let case = touching(100, X1, Some(0)); + let (on, statistics) = run(&stand_in, &case, Some(touch()))?; + let (off, _) = run(&stand_in, &case, None)?; + assert_eq!(on, off); + let (_, far, elr, _) = on.abort.expect("the original's data abort"); + assert_eq!((far, elr), (data_base() + 100, stand_in.pc() + 4)); + assert_eq!(on.retired, 1); + assert_eq!((statistics.installed, statistics.bypassed), (1, 1)); + Ok(()) +} + +#[test] +fn a_call_that_always_faults_bypasses_every_time_and_stays_exact() -> Result<()> { + let stand_in = stand_in(Id::Touch); + let case = touching(100, X1, Some(0)); + let off = run(&stand_in, &case, None)?.0; + let mut session = Session::new(&stand_in, Some(touch()))?; + for call in 1..=3 { + assert_eq!(session.run(&case)?, off, "call {call}"); + assert_eq!(session.hle().bypassed, call); + } + assert_eq!(session.hle().installed, 1); + Ok(()) +} + +#[test] +fn every_touch_combination_agrees() -> Result<()> { + let stand_in = stand_in(Id::Touch); + // X0 and X1 apart with neither, X0's or X1's page unreadable; both on + // one unreadable page; and X0 on a read-only page, which reads. + let read_only = Case { + read_only: Some(0), + ..touching(100, X1, None) + }; + for (case, bypassed) in [ + (touching(100, X1, None), 0), + (touching(100, X1, Some(0)), 1), + (touching(100, X1, Some(2)), 0), + (touching(100, 107, Some(0)), 1), + (read_only, 0), + ] { + let (on, statistics) = run(&stand_in, &case, Some(touch()))?; + let (off, _) = run(&stand_in, &case, None)?; + assert_eq!(agree(&stand_in, &case, &off, &on), Ok(()), "{case:?}"); + assert_eq!(statistics.bypassed, bypassed, "{:x?}", case.x); + assert_eq!(statistics.installed, 1); + } + Ok(()) +} + +#[test] +fn a_touch_native_agrees_with_the_original_on_random_cases() -> Result<()> { + // Unreadable and read-only pages anywhere: a call bypasses exactly when + // X0's page is unreadable, the only fault its fast path can take. + let stand_in = stand_in(Id::Touch); + let mut on = Session::new(&stand_in, Some(touch()))?; + let mut off = Session::new(&stand_in, None)?; + let (mut bypassed, mut aborted) = (0, 0); + for case in cases(Id::Touch, 0x70c4, case_count(4000)) { + let before = on.hle().bypassed; + let (expected, got) = (off.run(&case)?, on.run(&case)?); + assert_eq!( + agree(&stand_in, &case, &expected, &got), + Ok(()), + "{case:x?}" + ); + let faults = case.unreadable == Some(case.x[0] as usize / PAGE); + assert_eq!( + on.hle().bypassed - before, + u64::from(faults), + "{:x?}", + case.x + ); + assert!(!mapped(&case) || !faults); + bypassed += usize::from(faults); + aborted += usize::from(got.abort.is_some()); + } + assert!(bypassed > 0 && aborted > bypassed, "{bypassed} bypassed"); + assert_eq!(on.hle().installed, 1); + Ok(()) +} + +#[test] +fn an_out_of_range_pointer_bails_before_the_fast_path_loads() -> Result<()> { + use stela_engine::machine::Host as _; + let stand_in = stand_in(Id::Touch); + let limit = Session::new(&stand_in, None)? + .machine() + .host + .placement() + .check() + .lower_limit(); + let at = |address: u64| address.wrapping_sub(data_base()); + for (address, faults) in [ + // At and past the limit, in the upper half and top-byte tagged: the + // range check bails and the original's access takes the fault. + (limit, false), + (limit + PAGE as u64, false), + (u64::MAX - 7, false), + ((data_base() + 100) | 0x5a << 56, false), + // In range and not mapped: the fast path's load faults and the + // original takes it. + (0x10, true), + // In the test host's five-level range but past 2^47: on a + // four-level host the fast path's load takes a #GP, which bypasses + // as a #PF does, and the original's access stops the engine as an + // unsupported address check, alike with HLE. + (limit - 64, true), + ] { + let case = touching(at(address), X1, None); + let (on, statistics) = run(&stand_in, &case, Some(touch()))?; + let (off, _) = run(&stand_in, &case, None)?; + assert_eq!(on, off, "{address:#x}"); + let canonical = !(1 << 47..0xffff_8000_0000_0000).contains(&address); + assert!( + on.abort.is_some() || !canonical, + "{address:#x}: {:?}", + on.stop + ); + assert_eq!(statistics.bypassed, u64::from(faults), "{address:#x}"); + } + Ok(()) +} + +#[test] +fn software_step_never_enters_the_native() -> Result<()> { + // MDSCR_EL1.SS with the OS lock clear, and PSTATE.SS: each instruction + // is a block of its own, which HLE never matches. + let stand_in = stand_in(Id::Touch); + let case = touching(100, X1, None); + let mut outcomes = Vec::new(); + for hle in [None, Some(touch())] { + let mut session = Session::new(&stand_in, hle)?; + let machine = session.machine(); + machine + .cpu + .registers + .set_raw(Register::OSLSR_EL1, 0, 0b1000); + machine.cpu.registers.set_raw(Register::MDSCR_EL1, 0, 1); + machine.cpu.pstate.ss = true; + let outcome = session.run(&case)?; + outcomes.push((outcome, session.hle())); + } + let ((off, _), (on, statistics)) = (&outcomes[0], &outcomes[1]); + assert_eq!(on, off); + let (esr, ..) = on.abort.expect("a software step exception"); + assert_eq!(exception_class(esr), 0x32, "{esr:#x}"); + assert_eq!(on.retired, 1); + assert_eq!(*statistics, Statistics::default()); + Ok(()) +} + #[test] fn a_function_longer_than_the_first_window_is_matched_once_per_compile() -> Result<()> { // 39 NOPs and a `ret`: 160 bytes, past the 128 a compile reads first,