diff --git a/crates/stela-compiler/src/block.rs b/crates/stela-compiler/src/block.rs index a03d85e734..9860e9bf9a 100644 --- a/crates/stela-compiler/src/block.rs +++ b/crates/stela-compiler/src/block.rs @@ -617,10 +617,11 @@ impl CompilationPlan { target, ) } else { - // Only system mode runs one agent at a time and checks the - // guest's ranges; every other profile keeps the locked recipes - // and the default checks. - let (native, fault_recovery) = if profile.has(Features::FULL_SYSTEM) { + // Only system mode checks the guest's ranges and keeps guest + // registers pinned; every other profile keeps the default checks. + // Every profile keeps the locked recipes: system mode runs its + // PEs concurrently. + let (mut native, fault_recovery) = if profile.has(Features::FULL_SYSTEM) { crate::x86_64::block::emit_system_mode( &parsed.instructions, parsed.terminal.as_ref(), diff --git a/crates/stela-compiler/src/block/tests.rs b/crates/stela-compiler/src/block/tests.rs index 9951af079e..b796df7b5d 100644 --- a/crates/stela-compiler/src/block/tests.rs +++ b/crates/stela-compiler/src/block/tests.rs @@ -24,13 +24,12 @@ fn shared_system_uses_checked_recipes_and_refuses_serial_native_specialization() let target = TargetCpu::X86_64_V2.with_atomic_load16(); let options = crate::Options::new(shared, target); let plan = || CompilationPlan::new(&source, GuestAddress(0x4000), &options).unwrap(); - assert!(!plan().options.memory_checks().single_agent); assert!( CompilationPlan::new( &source, GuestAddress(0x4000), &options.with_memory_checks(crate::x86_64::MemoryChecks { - single_agent: true, + alignment: true, ..crate::x86_64::MemoryChecks::DEFAULT }) ) diff --git a/crates/stela-compiler/src/target.rs b/crates/stela-compiler/src/target.rs index 230258deb6..147757f7fc 100644 --- a/crates/stela-compiler/src/target.rs +++ b/crates/stela-compiler/src/target.rs @@ -381,11 +381,12 @@ features! { /// compile to instructions on Intel's list, without a branch on or a /// memory index by their data, at a cost in speed. The LSE atomics, /// acquire loads, store-releases and barriers become plain loads and - /// stores (no LOCK, XCHG or MFENCE), as for a single agent, so the mode - /// requires that no other agent accesses guest memory while its code - /// runs: the system engine runs one PE at a time, and a multi-threaded - /// process must not use it. A compilation mode, not a host capability, - /// honored on the [`Self::DATA_INDEPENDENT_TIMING_TIERS`]. + /// stores (no LOCK, XCHG or MFENCE), so the mode requires serialized + /// execution, with no other agent accessing guest memory while its code + /// runs: the system engine selects it only while one PE runs at a time + /// (`Machine::timing_target`), and a multi-threaded process must not use + /// it. A compilation mode, not a host capability, honored on the + /// [`Self::DATA_INDEPENDENT_TIMING_TIERS`]. DataIndependentTiming, with_data_independent_timing, "+dit", declared; } @@ -416,7 +417,7 @@ impl TargetCpu { ..Self::Baseline }; /// `GenuineIntel` as CPUID leaf 0 returns it in EBX, EDX and ECX, which - /// identifies a [`Self::line_atomic`] host. + /// identifies a [`Self::LineAtomic`] host. pub const INTEL_VENDOR: [u32; 3] = [ u32::from_le_bytes(*b"Genu"), u32::from_le_bytes(*b"ineI"), diff --git a/crates/stela-compiler/src/x86_64.rs b/crates/stela-compiler/src/x86_64.rs index eacbad4a55..f881414706 100644 --- a/crates/stela-compiler/src/x86_64.rs +++ b/crates/stela-compiler/src/x86_64.rs @@ -387,13 +387,6 @@ pub struct MemoryChecks { /// ([`RangeCheck`]). The direct system-mode profile sets it for every block, whatever /// the engine asks, and no other profile does. pub(crate) guest_range: bool, - /// No other agent accesses guest memory while the block runs: the - /// system engine runs one PE at a time, and no device or host agent - /// writes guest RAM meanwhile. Atomics, ordered accesses and barriers - /// then need no LOCK, XCHG, MFENCE or 16-byte snapshot - /// ([`plain_ordering`]). The direct system-mode profile sets it for every block, and no - /// other profile does. - pub(crate) single_agent: bool, /// FEAT_CSV3: every access's address is masked ([`RangeCheck`]), those /// [`guest_range`] would leave to an earlier check through the same base /// included: by its own check, or in pinned blocks derived by data from @@ -426,7 +419,6 @@ impl MemoryChecks { alignment: false, ordered_granule: true, guest_range: false, - single_agent: false, every_access_masked: false, stack_checked: false, range: RangeCheck::FIVE_LEVEL, @@ -447,7 +439,6 @@ impl MemoryChecks { alignment, ordered_granule, guest_range: false, - single_agent: false, every_access_masked, stack_checked: false, range: RangeCheck::FIVE_LEVEL, @@ -480,12 +471,13 @@ impl MemoryChecks { } /// Whether atomics, ordered accesses and barriers lower to plain accesses: -/// for a single agent ([`MemoryChecks::single_agent`]), and in the -/// data-independent-timing mode, which requires one -/// ([`crate::TargetCpu::data_independent_timing`]) because LOCK, XCHG and -/// MFENCE are not on Intel's data operand independent timing list. -fn plain_ordering(target: crate::TargetCpu, checks: MemoryChecks) -> bool { - checks.single_agent || target.data_independent_timing() +/// only in the data-independent-timing mode, which requires that no other +/// agent accesses guest memory ([`crate::TargetCpu::data_independent_timing`]) +/// because LOCK, XCHG and MFENCE are not on Intel's data operand independent +/// timing list. System mode runs its PEs concurrently, so every other target +/// keeps the locked recipes whatever its checks. +fn plain_ordering(target: crate::TargetCpu, _checks: MemoryChecks) -> bool { + target.data_independent_timing() } /// The system-mode check of the access address in RAX against the guest's @@ -918,7 +910,8 @@ fn memory_writeback(code: &mut Code, base: Register, mode: AddressMode) { /// Pair loads stage both values before committing either guest destination. /// Pair stores expose completed first-element writes if the second access faults. -/// Concurrent/128-bit single-copy atomic semantics are outside this RAM profile. +/// A 16-byte aligned pair of X registers is one MOVDQA, single-copy atomic as +/// FEAT_LSE2 requires ([`memory_recipe::pair`]). fn memory_pair( code: &mut Code, checks: MemoryChecks, diff --git a/crates/stela-compiler/src/x86_64/atomic.rs b/crates/stela-compiler/src/x86_64/atomic.rs index d6f2a7e1a0..3fa0e3a249 100644 --- a/crates/stela-compiler/src/x86_64/atomic.rs +++ b/crates/stela-compiler/src/x86_64/atomic.rs @@ -43,8 +43,8 @@ pub(super) fn requires_cx16( && !super::plain_ordering(target, checks) } -/// Locked x86 updates, or for a single agent ([`super::plain_ordering`]) a -/// plain load, the update and a plain store. The plain recipes load first, +/// Locked x86 updates, or in the data-independent-timing mode +/// ([`super::plain_ordering`]) a plain load, the update and a plain store. The plain recipes load first, /// so a translation, Access flag or read-permission fault reports WnR 0 and /// a store to read-only memory WnR 1, as Arm requires of an atomic that /// reads and writes (ESR_ELx.WnR); a locked x86 update faults as a write. diff --git a/crates/stela-compiler/src/x86_64/atomic/compare_exchange.rs b/crates/stela-compiler/src/x86_64/atomic/compare_exchange.rs index 17ca3a6d52..b339bb2a04 100644 --- a/crates/stela-compiler/src/x86_64/atomic/compare_exchange.rs +++ b/crates/stela-compiler/src/x86_64/atomic/compare_exchange.rs @@ -1,5 +1,6 @@ -//! CAS through a same-width LOCK CMPXCHG, or for a single agent a plain -//! load, compare, CMOVNE and store ([`plain`]). +//! CAS through a same-width LOCK CMPXCHG, or under data-independent timing +//! ([`super::super::plain_ordering`]) a plain load, compare, CMOVNE and store +//! ([`plain`]). use super::{ QWORD_BYTES, commit_rax, input_rax, input_rcx, locked_compare_exchange, read_r8, size, store_rcx, @@ -51,7 +52,7 @@ mod tests { const HALFWORD_BYTES: u8 = 2; #[test] - fn a_single_agent_cas_loads_compares_selects_and_stores() { + fn a_plain_cas_loads_compares_selects_and_stores() { for (bytes, load, compare, select, store, result) in [ ( BYTE_BYTES, diff --git a/crates/stela-compiler/src/x86_64/atomic/compare_exchange_pair.rs b/crates/stela-compiler/src/x86_64/atomic/compare_exchange_pair.rs index ad4c81aca2..36613e9ddd 100644 --- a/crates/stela-compiler/src/x86_64/atomic/compare_exchange_pair.rs +++ b/crates/stela-compiler/src/x86_64/atomic/compare_exchange_pair.rs @@ -1,5 +1,5 @@ -//! CASP through same-width atomic updates (CMPXCHG8B/CMPXCHG16B), or for a -//! single agent a plain load, compare, CMOVNE and store. +//! CASP through same-width atomic updates (CMPXCHG8B/CMPXCHG16B), or in the +//! data-independent-timing mode a plain load, compare, CMOVNE and store. use super::{ ADDRESS, DWORD_BYTES, QWORD_BYTES, commit_rax, input_rax, input_rax_keeping_flags, input_rcx, input_rcx_keeping_flags, locked_compare_exchange, @@ -62,7 +62,7 @@ fn word_pair( plain: bool, ) { if plain { - // A single agent's CASP is one load of the old pair, a compare and a + // A plain-ordering CASP is one load of the old pair, a compare and a // store of the new pair or, as LOCK CMPXCHG does, of the old one // (Arm `Unpredictable_WRITEFAILEDCAS`). The load comes first, so a // read that would fault reports WnR 0. @@ -134,7 +134,7 @@ fn word_pair_cx8(code: &mut Code, compare: [Register; 2], source: [Register; 2]) commit_rax(code, DWORD_BYTES, compare[1]); } -/// A single agent's 128-bit CASP: the old pair into R8 and R9 (both loads +/// A plain-ordering 128-bit CASP: the old pair into R8 and R9 (both loads /// first, so a read that would fault reports WnR 0), ZF from the XOR of each /// half with its compare register, the new halves kept only when both match, /// and a store of the selected pair either way, as CMPXCHG16B writes back a @@ -242,7 +242,7 @@ mod tests { } #[test] - fn a_single_agent_casp_loads_compares_selects_and_stores_without_lock() { + fn a_plain_ordering_casp_loads_compares_selects_and_stores_without_lock() { let compare = [Register::X(0), Register::X(1)]; let source = [Register::X(2), Register::X(3)]; let words = pair(WORD_PAIR_BYTES, compare, source, true); @@ -277,7 +277,7 @@ mod tests { } #[test] - fn a_single_agent_zr_source_keeps_the_compare_flags() { + fn a_plain_ordering_zr_source_keeps_the_compare_flags() { // XOR of ECX would clear ZF between the compare and the CMOVNE. let code = pair( DOUBLEWORD_PAIR_BYTES, diff --git a/crates/stela-compiler/src/x86_64/atomic/read_modify_write.rs b/crates/stela-compiler/src/x86_64/atomic/read_modify_write.rs index e9de312a91..79d5dcae7a 100644 --- a/crates/stela-compiler/src/x86_64/atomic/read_modify_write.rs +++ b/crates/stela-compiler/src/x86_64/atomic/read_modify_write.rs @@ -1,7 +1,7 @@ //! LDADD-family atomics: direct LOCK operations where x86 has them, otherwise a //! CMPXCHG retry loop. The old value is written only after the update succeeds. -//! For a single agent or PSTATE.DIT they are a plain load, update and store -//! ([`plain`]). +//! Under PSTATE.DIT ([`super::super::plain_ordering`]) they are a plain load, +//! update and store ([`plain`]). use super::{ ADDRESS, QWORD_BYTES, commit_rax, input_rax, input_rcx, locked_compare_exchange, read_rax, size, }; @@ -59,18 +59,18 @@ fn invert_rcx(code: &mut Code, bytes: u8) { code.asm().unary(Unary::Not, register_size(bytes), Gpr::Rcx); } -/// The single-agent and data-independent-timing lowering: load the old value +/// The data-independent-timing lowering: load the old value /// into RAX, form the new one in R8 with MOV, ADD, AND (of the inverted /// operand), XOR, OR, or CMP and CMOVcc, store it, then commit the old value. /// Every instruction is on Intel's data operand independent timing list and /// nothing branches. /// /// The pair is atomic only while no other agent accesses guest memory, which -/// both modes require ([`crate::TargetCpu::data_independent_timing`], -/// [`super::super::MemoryChecks::single_agent`]). The load comes -/// first, so an address a read would fault on faults there with WnR 0 and a -/// read-only one at the store with WnR 1, as Arm requires of an atomic that -/// both reads and writes; nothing is committed before the store completes. +/// that mode requires ([`crate::TargetCpu::data_independent_timing`]). The +/// load comes first, so an address a read would fault on faults there with +/// WnR 0 and a read-only one at the store with WnR 1, as Arm requires of an +/// atomic that both reads and writes; nothing is committed before the store +/// completes. fn plain(code: &mut Code, bytes: u8, operation: Rmw, source: Register, destination: Register) { input_rcx(code, bytes, source); if operation == Rmw::Clear { diff --git a/crates/stela-compiler/src/x86_64/ordered.rs b/crates/stela-compiler/src/x86_64/ordered.rs index f7b0463866..022b1fe4b3 100644 --- a/crates/stela-compiler/src/x86_64/ordered.rs +++ b/crates/stela-compiler/src/x86_64/ordered.rs @@ -2,10 +2,10 @@ //! //! Release stores use XCHG so a later acquire load cannot pass them, and a //! full DMB is MFENCE. Checked loads crossing eight bytes read one aligned -//! 16-byte snapshot. For a single agent or PSTATE.DIT -//! ([`super::plain_ordering`]) every access is a plain load or store and a -//! DMB emits nothing: no other agent observes guest memory, and one PE -//! observes its own accesses in program order. +//! 16-byte snapshot. For PSTATE.DIT ([`super::plain_ordering`]), which the +//! engine admits only while one PE runs, every access is a plain load or +//! store and a DMB emits nothing: no other agent observes guest memory, and +//! one PE observes its own accesses in program order. use super::atomic::{address_offset, commit_rax, input_rcx, read_rax, store_rcx}; use crate::x86_64::asm::{Alu, Code, Cond, Gpr, Mem, Patch, Rm, ShiftOp, Size}; use crate::x86_64::isa::SimdOpcode; @@ -380,11 +380,7 @@ mod tests { target, MemoryChecks::DEFAULT, )); - // A single agent's acquire loads are plain loads. - let single = MemoryChecks { - single_agent: true, - ..MemoryChecks::DEFAULT - }; + // Data-independent timing's acquire loads are plain loads. let operand = Operand::Transfer { feature: crate::aarch64::ordered::Feature::Base, kind: Kind::Acquire, @@ -394,7 +390,11 @@ mod tests { displacement: 0, extension: LoadExtension::Zero, }; - assert!(!requires_atomic_load16(&operand, target, single)); + assert!(!requires_atomic_load16( + &operand, + target.with_data_independent_timing(), + MemoryChecks::DEFAULT + )); assert!(!requires_atomic_load16( &operand, target.with_line_atomic(), @@ -403,12 +403,12 @@ mod tests { } #[test] - fn a_single_agent_takes_plain_ordered_accesses_and_drops_dmb() { + fn data_independent_timing_takes_plain_ordered_accesses_and_drops_dmb() { let single = MemoryChecks { - single_agent: true, ordered_granule: false, ..MemoryChecks::DEFAULT }; + let timed = TargetCpu::detect().with_data_independent_timing(); let has = |code: &[u8], bytes: &[u8]| code.windows(bytes.len()).any(|window| window == bytes); let mut barrier = Code::new(); @@ -418,7 +418,7 @@ mod tests { option: 15, requirement: Barrier::All, }, - TargetCpu::detect(), + timed, single, ); assert_eq!(barrier, [0x90]); @@ -433,7 +433,7 @@ mod tests { extension: LoadExtension::Zero, }; let mut code = Code::new(); - emit(&mut code, &operand, TargetCpu::detect(), single); + emit(&mut code, &operand, timed, single); // No XCHG, MFENCE, 16-byte snapshot or granule branch. assert!(!has(&code, &[0x48, 0x87, 0x0a]) && !has(&code, MFENCE)); assert!(!has(&code, MOVDQA_XMM0_RDX) && !has(&code, &[0x89, 0xd0, 0x83, 0xe0])); diff --git a/crates/stela-engine/src/machine/capabilities.rs b/crates/stela-engine/src/machine/capabilities.rs index d2a60a899a..bf532d280a 100644 --- a/crates/stela-engine/src/machine/capabilities.rs +++ b/crates/stela-engine/src/machine/capabilities.rs @@ -1,16 +1,27 @@ //! Execution support policy for the immutable CPU feature descriptions. use stela_contracts::{Chip, Feature}; +/// A feature the chip has that the engine does not implement yet. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Unimplemented(pub Feature); + +impl Unimplemented { + /// The refusal's reason. + pub const fn reason(self) -> &'static str { + self.0.unimplemented() + } +} + /// Whether the chip has `feature`: `Ok(false)` without it, `Ok(true)` -/// when the engine implements it, and the reason to stop when the chip -/// has a feature the engine does not implement yet. -pub fn implemented(chip: Chip, feature: Feature) -> Result { +/// when the engine implements it, and an error when the chip has a +/// feature the engine does not implement yet. +pub fn implemented(chip: Chip, feature: Feature) -> Result { if !feature.on(chip) { Ok(false) } else if engine_implements(feature) { Ok(true) } else { - Err(feature.unimplemented()) + Err(Unimplemented(feature)) } } @@ -93,7 +104,7 @@ mod tests { for feature in Feature::ALL { assert_ne!( implemented(Chip::DEFAULT, feature), - Err(feature.unimplemented()) + Err(Unimplemented(feature)) ); } assert_eq!(implemented(Chip::AppleM2, Feature::FEAT_HCX), Ok(false)); diff --git a/crates/stela-engine/src/machine/cpu.rs b/crates/stela-engine/src/machine/cpu.rs index d2947b3700..24550d56da 100644 --- a/crates/stela-engine/src/machine/cpu.rs +++ b/crates/stela-engine/src/machine/cpu.rs @@ -212,6 +212,25 @@ pub enum GuardedRefusal { Exit, } +/// Why an SVCR change cannot complete. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SvcrError { + /// The PE has no SME state: its chip has no FEAT_SME. + NoScalableState, + /// The streaming or ZA register state cannot be allocated. + OutOfMemory, +} + +impl SvcrError { + /// The refusal's reason. + pub const fn reason(self) -> &'static str { + match self { + Self::NoScalableState => "SVCR on a PE without SME state", + Self::OutOfMemory => "cannot allocate the SME register state", + } + } +} + #[derive(Debug)] pub struct Cpu { pub state: GuestState, @@ -512,14 +531,11 @@ impl Cpu { /// Z, P and FFR registers, FPSR (to 0x0800009F) and FPMR, and enabling /// ZA zeroes ZA and ZT0. The engine applies the access checks streaming /// mode changes to each instruction ([`super::streaming`]). - pub fn set_svcr(&mut self, streaming: bool, za: bool) -> Result<(), &'static str> { - let scalable = self - .scalable - .as_mut() - .ok_or("SVCR on a PE without SME state")?; + pub fn set_svcr(&mut self, streaming: bool, za: bool) -> Result<(), SvcrError> { + let scalable = self.scalable.as_mut().ok_or(SvcrError::NoScalableState)?; scalable .apply_mode(&mut self.state, ScalableMode::new(streaming, za)) - .map_err(|_| "cannot allocate the SME register state") + .map_err(|_| SvcrError::OutOfMemory) } /// The EL an FP/SIMD access traps to, if it traps (Arm diff --git a/crates/stela-engine/src/machine/ctrr.rs b/crates/stela-engine/src/machine/ctrr.rs index 460f0886b1..4b0829eaa8 100644 --- a/crates/stela-engine/src/machine/ctrr.rs +++ b/crates/stela-engine/src/machine/ctrr.rs @@ -272,30 +272,50 @@ impl Cluster { } /// A write, or why it cannot complete. - pub fn write(&mut self, level: usize, field: Field, value: u64) -> Result<(), &'static str> { + pub fn write(&mut self, level: usize, field: Field, value: u64) -> Result<(), WriteError> { let group = &mut self.levels[level]; if group.locked { return if value == group.get(field) { Ok(()) } else { - Err(CHANGE_AFTER_LOCK) + Err(WriteError::ChangeAfterLock) }; } match field { Field::Lower => group.lower = value, Field::Upper => group.upper = value, Field::Control if value & !CONTROL_BITS != 0 => { - return Err("CTRR control bit without observed meaning"); + return Err(WriteError::UnknownControl(value & !CONTROL_BITS)); } Field::Control => group.control = value, - Field::Lock if value > 1 => return Err("CTRR lock value other than 0 or 1"), + Field::Lock if value > 1 => return Err(WriteError::LockValue(value)), Field::Lock => group.locked = value == 1, } Ok(()) } } -const CHANGE_AFTER_LOCK: &str = "CTRR register change after its lock"; +/// Why a CTRR register write cannot complete. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WriteError { + /// A locked register written with another value. + ChangeAfterLock, + /// Control bits whose meaning has not been observed. + UnknownControl(u64), + /// A lock value other than 0 or 1. + LockValue(u64), +} + +impl WriteError { + /// The refusal's reason. + pub const fn reason(self) -> &'static str { + match self { + Self::ChangeAfterLock => "CTRR register change after its lock", + Self::UnknownControl(_) => "CTRR control bit without observed meaning", + Self::LockValue(_) => "CTRR lock value other than 0 or 1", + } + } +} const REGIONS: [LockRegion; 6] = [ LockRegion::CtrrC, @@ -462,7 +482,7 @@ impl Bank { region: LockRegion, field: Field, value: u64, - ) -> Result, &'static str> { + ) -> Result, WriteError> { let window = &mut self.windows[region as usize]; let value = match field { Field::Lower | Field::Upper => value & LIMIT_MASK, @@ -477,7 +497,7 @@ impl Bank { return if value == current { Ok(None) } else { - Err(CHANGE_AFTER_LOCK) + Err(WriteError::ChangeAfterLock) }; } let mut unmodeled = None; @@ -491,7 +511,7 @@ impl Bank { CTRR_ENABLE }; if value & !(LOCK | enable) != 0 { - return Err("CTRR control bit without observed meaning"); + return Err(WriteError::UnknownControl(value & !(LOCK | enable))); } if execute_range(region) && value & enable != 0 { unmodeled = Some(CTXR_UNMODELED); @@ -504,17 +524,17 @@ impl Bank { /// CTRR-A's or CTRR-B's control: iBoot's locked handoff value, or what /// an unlocked one takes. - pub fn write_legacy(&mut self, index: usize, value: u64) -> Result<(), &'static str> { + pub fn write_legacy(&mut self, index: usize, value: u64) -> Result<(), WriteError> { let control = &mut self.legacy[index]; if *control & LOCK != 0 { return if value == *control { Ok(()) } else { - Err(CHANGE_AFTER_LOCK) + Err(WriteError::ChangeAfterLock) }; } if value & !(LOCK | CTRR_ENABLE) != 0 { - return Err("CTRR control bit without observed meaning"); + return Err(WriteError::UnknownControl(value & !(LOCK | CTRR_ENABLE))); } *control = value; Ok(()) @@ -597,8 +617,14 @@ mod tests { assert_eq!(cluster.read(0, Field::Lock), 1); // A locked level keeps its values; a repeat completes. cluster.write(0, Field::Control, 0x13).unwrap(); - assert!(cluster.write(0, Field::Lower, 0).is_err()); - assert!(cluster.write(0, Field::Lock, 0).is_err()); + assert_eq!( + cluster.write(0, Field::Lower, 0), + Err(WriteError::ChangeAfterLock) + ); + assert_eq!( + cluster.write(0, Field::Lock, 0), + Err(WriteError::ChangeAfterLock) + ); let region = cluster.levels[0].region(true).unwrap(); assert_eq!((region.first, region.last), (0x8_0200_0000, 0x8_0778_ffff)); assert!(region.write_protect && region.execute_inside_only); @@ -611,8 +637,14 @@ mod tests { }) ); assert_eq!(cluster.levels[1].region(true), None); - assert!(cluster.write(1, Field::Control, 1 << 2).is_err()); - assert!(cluster.write(1, Field::Lock, 2).is_err()); + assert!(matches!( + cluster.write(1, Field::Control, 1 << 2), + Err(WriteError::UnknownControl(_)) + )); + assert_eq!( + cluster.write(1, Field::Lock, 2), + Err(WriteError::LockValue(2)) + ); // The M1 to M3 have no CRn-11 registers. assert_eq!(decode(Chip::AppleM3, crn11(0, 0)), None); } @@ -681,14 +713,17 @@ mod tests { .unwrap(); bank.write(LockRegion::CtrrC, Field::Control, CTRR_HANDOFF) .unwrap(); - assert!(bank.write(LockRegion::CtrrC, Field::Lower, 0).is_err()); + assert_eq!( + bank.write(LockRegion::CtrrC, Field::Lower, 0), + Err(WriteError::ChangeAfterLock) + ); assert_eq!( bank.write(LockRegion::CtrrC, Field::Control, CTRR_HANDOFF), Ok(None) ); - assert!( - bank.write(LockRegion::CtrrD, Field::Control, 1 << 1) - .is_err() + assert_eq!( + bank.write(LockRegion::CtrrD, Field::Control, 1 << 1), + Err(WriteError::UnknownControl(1 << 1)) ); // A CTXR enable completes and is reported. assert_eq!( @@ -699,10 +734,10 @@ mod tests { bank.write(LockRegion::CtxrA, Field::Control, CTXR_HANDOFF[0]), Ok(Some(CTXR_UNMODELED)) ); - assert!( - bank.write(LockRegion::CtxrB, Field::Control, 1 << 40) - .is_err() - ); + assert!(matches!( + bank.write(LockRegion::CtxrB, Field::Control, 1 << 40), + Err(WriteError::UnknownControl(_)) + )); let [c, d] = protection(Chip::AppleM4, &Cluster::default(), &core, true, false); let c = c.unwrap(); assert_eq!((c.first, c.last), (0x100_06fb_8000, 0x100_0710_bfff)); @@ -731,7 +766,10 @@ mod tests { (0x100_0945_0000, 0x100_0945_3000, CTXR_HANDOFF[1]) ); assert_eq!(cluster.copies.legacy, [CTRR_HANDOFF; 2]); - assert!(cluster.copies.write_legacy(0, 0).is_err()); + assert_eq!( + cluster.copies.write_legacy(0, 0), + Err(WriteError::ChangeAfterLock) + ); assert!( cluster .copies diff --git a/crates/stela-engine/src/machine/engine/compilation.rs b/crates/stela-engine/src/machine/engine/compilation.rs index eee83401f5..414dfffab7 100644 --- a/crates/stela-engine/src/machine/engine/compilation.rs +++ b/crates/stela-engine/src/machine/engine/compilation.rs @@ -827,8 +827,14 @@ impl Machine { /// The target PSTATE.DIT code compiles for /// (`TargetCpu::data_independent_timing_target`). Without one, /// ID_AA64PFR0_EL1.DIT reads 0 (`identification::Basis::Timing`) and - /// PSTATE.DIT changes no code. + /// PSTATE.DIT changes no code. That code's atomics, ordered accesses and + /// barriers are plain accesses, which only one running PE makes atomic: + /// a machine whose PEs run concurrently (`enter_parallel`) never selects + /// it, whatever its target. pub(super) fn timing_target(&self) -> Option { + if self.parallel.is_some() || self.attached.is_some() { + return None; + } self.target.data_independent_timing_target() } diff --git a/crates/stela-engine/src/machine/engine/interrupts.rs b/crates/stela-engine/src/machine/engine/interrupts.rs index 7fffae5666..edab93c123 100644 --- a/crates/stela-engine/src/machine/engine/interrupts.rs +++ b/crates/stela-engine/src/machine/engine/interrupts.rs @@ -263,7 +263,9 @@ impl Machine { match self.cpu.registers.implemented(Feature::FEAT_WFxT) { Ok(true) => {} Ok(false) => return self.undefined(), - Err(reason) => return Err(self.unsupported(RequirementKind::Native(reason))), + Err(error) => { + return Err(self.unsupported(RequirementKind::Native(error.reason()))); + } } } let timeout = register.map(|register| { diff --git a/crates/stela-engine/src/machine/engine/pointer_authentication.rs b/crates/stela-engine/src/machine/engine/pointer_authentication.rs index 2c6558aacd..0fa58930b7 100644 --- a/crates/stela-engine/src/machine/engine/pointer_authentication.rs +++ b/crates/stela-engine/src/machine/engine/pointer_authentication.rs @@ -68,7 +68,7 @@ impl Machine { self.cpu .registers .implemented(feature) - .map_err(|reason| self.unsupported(RequirementKind::Native(reason))) + .map_err(|error| self.unsupported(RequirementKind::Native(error.reason()))) }; Ok(if has(Feature::FEAT_FPACCOMBINE)? { pauth::Version::FaultingCombined @@ -134,7 +134,7 @@ impl Machine { .cpu .registers .implemented(Feature::FEAT_PAuth_LR) - .map_err(|reason| self.unsupported(RequirementKind::Native(reason)))?; + .map_err(|error| self.unsupported(RequirementKind::Native(error.reason())))?; // Without FEAT_PAuth_LR its hint-space form (PACM) is a NOP and the // others are UNDEFINED. if let PointerAuthenticationOperation::LinkRegister(form) = instruction.operation { @@ -798,7 +798,7 @@ impl Machine { match self.cpu.registers.implemented(Feature::FEAT_CPA) { Ok(true) => {} Ok(false) => return self.undefined(), - Err(reason) => return Err(self.unsupported(RequirementKind::Native(reason))), + Err(error) => return Err(self.unsupported(RequirementKind::Native(error.reason()))), } let (base, change, subtract) = match operand.kind { Kind::Offset { diff --git a/crates/stela-engine/src/machine/engine/system/register_context.rs b/crates/stela-engine/src/machine/engine/system/register_context.rs index 2e6c9db3c9..3b8c8a8766 100644 --- a/crates/stela-engine/src/machine/engine/system/register_context.rs +++ b/crates/stela-engine/src/machine/engine/system/register_context.rs @@ -17,7 +17,7 @@ impl Context for Access<'_, H, D> { .cpu .registers .implemented(feature) - .map_err(Effect::Refused) + .map_err(|error| Effect::Refused(error.reason())) } fn el(&self) -> u64 { @@ -287,7 +287,7 @@ impl Context for Access<'_, H, D> { Register::SVCR => { return cpu .set_svcr(value & 1 != 0, value & 2 != 0) - .map_err(Effect::Refused); + .map_err(|error| Effect::Refused(error.reason())); } Register::SP_EL0 | Register::SP_EL1 | Register::SP_EL2 => { let el = match register { diff --git a/crates/stela-engine/src/machine/engine/system/tests.rs b/crates/stela-engine/src/machine/engine/system/tests.rs index c46b03bff0..1a3d933fdf 100644 --- a/crates/stela-engine/src/machine/engine/system/tests.rs +++ b/crates/stela-engine/src/machine/engine/system/tests.rs @@ -3117,6 +3117,10 @@ fn pstate_dit_is_written_read_and_kept_across_exceptions() { const MSR_DIT_ZERO: u32 = 0xd503_405f; const ERET: u32 = 0xd69f_03e0; let mut machine = machine(&[]); + // Without the host's timing guarantee ID_AA64PFR0_EL1 reports no + // FEAT_DIT, but the field is kept as on every Apple chip + // (`dit_is_kept_without_the_host_timing_guarantee`). + assert_eq!(machine.cpu.read(Register::ID_AA64PFR0_EL1) >> 48 & 0xf, 0); let read = |machine: &mut TestMachine| { machine.system_instruction(access(true, DIT, 1)).unwrap(); machine.cpu.state.x[1] @@ -3161,7 +3165,4 @@ fn pstate_dit_is_written_read_and_kept_across_exceptions() { machine.system_instruction(ERET).unwrap(); assert_eq!(machine.cpu.pstate.el, 1); assert!(!machine.cpu.pstate.dit); - // The engine withholds the feature: translated code gives no - // data-independent timing guarantee. - assert_eq!(machine.cpu.read(Register::ID_AA64PFR0_EL1) >> 48 & 0xf, 0); } diff --git a/crates/stela-engine/src/machine/engine/system_access.rs b/crates/stela-engine/src/machine/engine/system_access.rs index 365ec469af..82ddf4448e 100644 --- a/crates/stela-engine/src/machine/engine/system_access.rs +++ b/crates/stela-engine/src/machine/engine/system_access.rs @@ -92,7 +92,9 @@ impl Machine { self.next() } Ok(false) => self.undefined(), - Err(reason) => Err(self.unsupported(RequirementKind::Native(reason))), + Err(error) => { + Err(self.unsupported(RequirementKind::Native(error.reason()))) + } } } Synchronization::ErrorSynchronization => self.error_synchronization(), diff --git a/crates/stela-engine/src/machine/engine/tags.rs b/crates/stela-engine/src/machine/engine/tags.rs index d739f20ca6..80eea85ea0 100644 --- a/crates/stela-engine/src/machine/engine/tags.rs +++ b/crates/stela-engine/src/machine/engine/tags.rs @@ -105,10 +105,10 @@ impl Machine { match self.cpu.registers.implemented(feature) { Ok(true) => {} Ok(false) => return self.undefined(), - Err(reason) => { + Err(error) => { return Err(self.unsupported(RequirementKind::Instruction { word, - detail: reason.into(), + detail: error.reason().into(), })); } } @@ -166,10 +166,10 @@ impl Machine { match self.cpu.registers.implemented(Feature::FEAT_MTE) { Ok(true) => {} Ok(false) => return self.undefined(), - Err(reason) => { + Err(error) => { return Err(self.unsupported(RequirementKind::Instruction { word, - detail: reason.into(), + detail: error.reason().into(), })); } } diff --git a/crates/stela-engine/src/machine/engine/tests.rs b/crates/stela-engine/src/machine/engine/tests.rs index 4b8c1c47ec..7c8b98b0a3 100644 --- a/crates/stela-engine/src/machine/engine/tests.rs +++ b/crates/stela-engine/src/machine/engine/tests.rs @@ -7729,6 +7729,7 @@ fn upper_occupancy_lists_the_mapped_level_one_ranges_and_outermost_blocks() { assert_eq!(machine.upper_occupancy(), None); } +mod pstate_features; mod recovery; #[test] diff --git a/crates/stela-engine/src/machine/engine/tests/pstate_features.rs b/crates/stela-engine/src/machine/engine/tests/pstate_features.rs new file mode 100644 index 0000000000..d9e742757c --- /dev/null +++ b/crates/stela-engine/src/machine/engine/tests/pstate_features.rs @@ -0,0 +1,52 @@ +//! PSTATE fields whose features the host decides: DIT is kept on every +//! chip, whether or not the host gives its timing guarantee. +use super::*; + +#[test] +fn dit_is_kept_without_the_host_timing_guarantee() { + const MSR_DIT_1: u32 = 0xd503_415f; + const MSR_DIT_X0: u32 = 0xd51b_42a0; + const MRS_X0_DIT: u32 = 0xd53b_42a0; + let mut machine = machine(&[]); + assert_eq!(machine.timing_target(), None); + for word in [MSR_DIT_1, MSR_DIT_X0] { + machine.cpu.set_pstate(Pstate::reset(1)); + machine.cpu.pc = BASE; + machine.cpu.state.x[0] = 1 << 24; + machine.system_instruction(word).unwrap(); + assert_eq!(machine.cpu.pc, BASE + 4, "{word:#x}"); + assert!(machine.cpu.pstate.dit, "{word:#x}"); + } + machine.cpu.pc = BASE; + machine.cpu.state.x[0] = 0; + machine.system_instruction(MRS_X0_DIT).unwrap(); + assert_eq!(machine.cpu.state.x[0], 1 << 24); +} + +#[test] +fn ssbs_stays_writable() { + const MSR_SSBS_1: u32 = 0xd503_413f; + let mut machine = machine(&[]); + machine.cpu.set_pstate(Pstate::reset(1)); + machine.cpu.pc = BASE; + machine.system_instruction(MSR_SSBS_1).unwrap(); + assert_eq!(machine.cpu.pc, BASE + 4); + assert!(machine.cpu.pstate.ssbs); +} + +#[test] +fn a_parallel_machine_never_compiles_pstate_dit_code_for_a_timing_target() { + use super::parallel::{Hub, Kick}; + struct NoKick; + impl Kick for NoKick { + fn kick(&self, _pe: usize) {} + } + let mut machine = machine(&[0xd503_201f]); + machine.target = TargetCpu::DATA_INDEPENDENT_TIMING_TIERS[2].with_doit(); + assert!(machine.timing_target().is_some()); + let hub = Hub::new(1, NoKick); + hub.set_live(0, true); + machine.enter_parallel(hub).unwrap(); + // Its plain-ordering atomics would race the other PEs. + assert_eq!(machine.timing_target(), None); +} diff --git a/crates/stela-engine/src/machine/registers.rs b/crates/stela-engine/src/machine/registers.rs index f47996fcb9..92de026230 100644 --- a/crates/stela-engine/src/machine/registers.rs +++ b/crates/stela-engine/src/machine/registers.rs @@ -691,13 +691,13 @@ impl Cpu { use super::ctrr::{Holder, Register as Ctrr}; let el = self.pstate.el; let mut cluster = self.ctrr.borrow_mut(); - let written = |result: Result, &'static str>| match result { + let written = |result: Result, super::ctrr::WriteError>| match result { Ok(unmodeled) => Outcome::Written(Changes { translation: true, unmodeled, ..Changes::default() }), - Err(reason) => Outcome::Refused(Refusal::UnsupportedSetting(reason)), + Err(error) => Outcome::Refused(Refusal::UnsupportedSetting(error.reason())), }; let el2_only = matches!( register, @@ -1107,11 +1107,18 @@ impl Cpu { let mut changes = Changes::default(); let minimum = match (encoding.op1(), encoding.op2()) { (0, 3..=5) => 1, + // PSTATE.DIT exists on every Apple chip and XNU writes it + // without checking ID_AA64PFR0_EL1.DIT, which reports only + // whether the host keeps the timing guarantee + // (identification `Basis::Timing`). Without it the bit is + // kept as state and selects no different code. (3, 1 | 2 | 6 | 7) => 0, (3, 4) => match self.registers.implemented(Feature::FEAT_MTE) { Ok(true) => 0, Ok(false) => return Outcome::Undefined, - Err(reason) => return Outcome::Refused(Refusal::UnsupportedSetting(reason)), + Err(error) => { + return Outcome::Refused(Refusal::UnsupportedSetting(error.reason())); + } }, // CRm<3:1> selects SM, ZA or both; 0b000 and 0b1xx are // unallocated. @@ -1163,8 +1170,8 @@ impl Cpu { streaming }; let za = if immediate & 0b0100 != 0 { bit } else { za }; - if let Err(reason) = self.set_svcr(streaming, za) { - return Outcome::Refused(Refusal::UnsupportedSetting(reason)); + if let Err(error) = self.set_svcr(streaming, za) { + return Outcome::Refused(Refusal::UnsupportedSetting(error.reason())); } } (0, 3) => self.pstate.uao = bit, diff --git a/crates/stela-engine/src/machine/streaming.rs b/crates/stela-engine/src/machine/streaming.rs index f604c8414e..97586f06ed 100644 --- a/crates/stela-engine/src/machine/streaming.rs +++ b/crates/stela-engine/src/machine/streaming.rs @@ -148,7 +148,7 @@ fn fpmr_access(cpu: &Cpu) -> Result<(), Denial> { match cpu.registers.implemented(Feature::FEAT_FPMR) { Ok(true) => {} Ok(false) => return Err(Denial::Undefined), - Err(reason) => return Err(Denial::Unimplemented(reason)), + Err(error) => return Err(Denial::Unimplemented(error.reason())), } let el = cpu.pstate.el; let host = el == 2 || (el == 0 && cpu.in_host()); diff --git a/crates/stela-engine/src/machine/system/file.rs b/crates/stela-engine/src/machine/system/file.rs index f6d18d0d25..4faa4bb90e 100644 --- a/crates/stela-engine/src/machine/system/file.rs +++ b/crates/stela-engine/src/machine/system/file.rs @@ -95,7 +95,10 @@ impl File { /// Arm `IsFeatureImplemented` for the PE: [`Chip::implemented`] for a /// feature its identification presents, `Ok(false)` for one it /// withholds. - pub fn implemented(&self, feature: Feature) -> Result { + pub fn implemented( + &self, + feature: Feature, + ) -> Result { if self.withheld & 1 << feature as u64 != 0 { Ok(false) } else {