From 2e39df8dcddcf2943892ab136014cabb4e4de0c8 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:49:14 +0000 Subject: [PATCH] feat(runtime): complete owned ordinary DSB barriers --- crates/stela-compiler/src/block.rs | 14 +- .../stela-compiler/src/block/el1_platform.rs | 56 +- crates/stela-compiler/src/block/system.rs | 48 +- .../src/blocks/retirement/checked/mod.rs | 20 + .../src/blocks/retirement/checked/provider.rs | 10 +- .../retirement/checked/provider/m0_owner.rs | 24 + .../retirement/checked/provider/resources.rs | 12 + .../blocks/retirement/checked/software_el1.rs | 14 + .../retirement/checked/system_effects.rs | 269 ++++++++ .../checked/system_effects/commit.rs | 137 ++++ .../retirement/checked/system_effects/dsb.rs | 213 ++++++ .../checked/system_effects/fixture.rs | 231 +++++++ .../src/blocks/translation/owner.rs | 29 + .../src/memory/domain/physical.rs | 3 + .../src/memory/domain/physical/completion.rs | 118 ++++ .../domain/physical/source_ram_tests.rs | 43 ++ crates/stela-runtime/src/system.rs | 1 + crates/stela-runtime/src/system/barriers.rs | 364 ++++++++++ .../src/system/barriers/tests.rs | 622 ++++++++++++++++++ crates/stela-runtime/src/system/execution.rs | 3 + dev/test_translation_progress.py | 38 ++ dev/translation-progress.py | 9 +- tests/isa/a64-documented-checklist.json | 14 +- tests/isa/a64-service-forms.json | 111 ++++ 24 files changed, 2384 insertions(+), 19 deletions(-) create mode 100644 crates/stela-runtime/src/blocks/retirement/checked/system_effects.rs create mode 100644 crates/stela-runtime/src/blocks/retirement/checked/system_effects/commit.rs create mode 100644 crates/stela-runtime/src/blocks/retirement/checked/system_effects/dsb.rs create mode 100644 crates/stela-runtime/src/blocks/retirement/checked/system_effects/fixture.rs create mode 100644 crates/stela-runtime/src/memory/domain/physical/completion.rs create mode 100644 crates/stela-runtime/src/system/barriers.rs create mode 100644 crates/stela-runtime/src/system/barriers/tests.rs diff --git a/crates/stela-compiler/src/block.rs b/crates/stela-compiler/src/block.rs index 56aee9cf95..b8a7b9c0c7 100644 --- a/crates/stela-compiler/src/block.rs +++ b/crates/stela-compiler/src/block.rs @@ -843,11 +843,15 @@ fn parse( source_bytes += 4; let word = u32::from_le_bytes(*bytes); if profile.supports_system() - && let Some(decoded) = - decode_system_instruction(pc, word).map_err(|error| BlockAnalysisError { - pc, - detail: error.0, - })? + && let Some(decoded) = (if profile == BlockProfile::El1PlatformV1 { + system::decode_el1_system_instruction(pc, word) + } else { + decode_system_instruction(pc, word) + }) + .map_err(|error| BlockAnalysisError { + pc, + detail: error.0, + })? && (profile.supports_system_registers() || !matches!( decoded.operation, diff --git a/crates/stela-compiler/src/block/el1_platform.rs b/crates/stela-compiler/src/block/el1_platform.rs index 8a22d1b380..44a7f69bef 100644 --- a/crates/stela-compiler/src/block/el1_platform.rs +++ b/crates/stela-compiler/src/block/el1_platform.rs @@ -127,7 +127,7 @@ pub(super) fn validate_terminal(terminal: &Terminator) -> Result<(), CompileErro } pub(super) fn validate_system(instruction: system::SystemInstruction) -> Result<(), CompileError> { - if instruction.is_el1_context_operation() { + if instruction.is_el1_context_operation() || instruction.is_el1_ram_completion() { return Ok(()); } match instruction.operation { @@ -289,6 +289,60 @@ mod tests { .unwrap(); assert_eq!(compare.el1_platform_intent(), Some(Intent::Registers)); } + #[test] + fn ordinary_dsb_has_one_effectless_carrier_without_stealing_other_hints() { + const DSB_SY: u32 = 0xd503_3f9f; + const DSB_ISH: u32 = 0xd503_3b9f; + const DSB_ISHLD: u32 = 0xd503_399f; + const DSB_ISHST: u32 = 0xd503_3a9f; + const NOP: u32 = 0xd503_201f; + const SSBB: u32 = 0xd503_309f; + const PSSBB: u32 = 0xd503_349f; + const DSB_NXS: u32 = 0xd503_323f; + for word in [DSB_SY, DSB_ISH, DSB_ISHLD, DSB_ISHST] { + let plan = CompilationPlan::new( + &word.to_le_bytes(), + BASE, + BlockProfile::El1PlatformV1, + TargetCpu::Baseline, + ) + .unwrap(); + assert_eq!(plan.source_bytes(), size_of::()); + assert!(plan.memory_requirements().is_none()); + let Some(Intent::System(instruction)) = plan.el1_platform_intent() else { + panic!("DSB actual source carrier absent"); + }; + assert!(instruction.is_el1_ram_completion()); + assert!(instruction.matches_source(BASE, word)); + let compiled = plan.compile().unwrap(); + assert_eq!(compiled.native.source_map.len(), 1); + } + let nop = CompilationPlan::new( + &NOP.to_le_bytes(), + BASE, + BlockProfile::El1PlatformV1, + TargetCpu::Baseline, + ) + .unwrap(); + assert_eq!(nop.el1_platform_intent(), Some(Intent::Registers)); + for word in [SSBB, PSSBB, DSB_NXS] { + assert!( + super::system::decode_el1_system_instruction(BASE, word) + .unwrap() + .is_none() + ); + } + let prefix = CompilationPlan::new( + &bytes(&[ADD_X0, DSB_SY]), + BASE, + BlockProfile::El1PlatformV1, + TargetCpu::Baseline, + ) + .unwrap(); + assert_eq!(prefix.source_bytes(), size_of::()); + assert_eq!(prefix.el1_platform_intent(), Some(Intent::Registers)); + } + #[test] fn canonical_branch_operations_reach_existing_terminal_plan() { for word in [0x14000002u32, 0x54000040, 0x34000040, 0x36000040] { diff --git a/crates/stela-compiler/src/block/system.rs b/crates/stela-compiler/src/block/system.rs index 3ee9a162f9..9427e20095 100644 --- a/crates/stela-compiler/src/block/system.rs +++ b/crates/stela-compiler/src/block/system.rs @@ -20,11 +20,17 @@ const INSTRUCTION_BYTES: u64 = std::mem::size_of::() as u64; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SystemOperation { Exception(exception::Operation), + /// Canonical effect description; the actual retained owner grants admission. + Synchronization(synchronization::Operation), TagMemory(tag_memory::Operand), Register(registers::RegisterAccess), PstateImmediate(registers::Encoding), - SendEvent { local: bool }, - InstructionSynchronization { option: u8 }, + SendEvent { + local: bool, + }, + InstructionSynchronization { + option: u8, + }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] @@ -42,6 +48,7 @@ fn serialize_family( ) -> Result { serializer.serialize_str(match operation { SystemOperation::Exception(_) => "exception", + SystemOperation::Synchronization(_) => "synchronization", SystemOperation::TagMemory(_) => "tag_memory", SystemOperation::Register(_) => "system_register", SystemOperation::PstateImmediate(_) => "pstate_immediate", @@ -96,7 +103,42 @@ pub fn decode_system_instruction( })) } +/// Extend the fixed EL1 cohort only for its actual mounted RAM completion. +/// Existing NOP, PAuth aliases and unmounted hints keep their original selection. +pub(super) fn decode_el1_system_instruction( + pc: GuestAddress, + word: u32, +) -> Result, CompileError> { + if let Some(instruction) = decode_system_instruction(pc, word)? { + return Ok(Some(instruction)); + } + let Some(operation @ synchronization::Operation::DataCompletion { nxs: false, .. }) = + synchronization::decode(word) + else { + return Ok(None); + }; + let next_pc = GuestAddress(pc.0.checked_add(INSTRUCTION_BYTES).ok_or_else(|| { + CompileError("system continuation PC overflows guest address range".into()) + })?); + Ok(Some(SystemInstruction { + instruction_pc: pc, + next_pc, + word, + operation: SystemOperation::Synchronization(operation), + })) +} + impl SystemInstruction { + pub fn is_el1_ram_completion(self) -> bool { + matches!( + self.operation, + SystemOperation::Synchronization(synchronization::Operation::DataCompletion { + nxs: false, + .. + }) + ) + } + /// Source classification only. This grants no PE/control/publication loan. /// The actual lifetime-fixed platform must mount the corresponding owner. pub fn is_el1_context_operation(self) -> bool { @@ -120,7 +162,7 @@ impl SystemInstruction { pub fn matches_source(self, pc: GuestAddress, word: u32) -> bool { self.instruction_pc == pc && self.word == word - && decode_system_instruction(pc, word).ok().flatten() == Some(self) + && decode_el1_system_instruction(pc, word).ok().flatten() == Some(self) } } diff --git a/crates/stela-runtime/src/blocks/retirement/checked/mod.rs b/crates/stela-runtime/src/blocks/retirement/checked/mod.rs index b80648c84e..8cad8bd485 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/mod.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/mod.rs @@ -15,6 +15,7 @@ mod pauth_policy; mod privileged; mod privileged_debug; mod provider; +pub(crate) mod system_effects; pub(crate) use halted::{OwnedDebugOutcome, run_halted_owned}; pub(crate) use privileged::PrivilegedOwner; pub(crate) mod software_el1; @@ -80,6 +81,7 @@ pub(crate) struct OwnedRunOutcome { pub last_m0_write_observation: Option, pub last_el1_register_observation: Option, pub last_el1_system_observation: Option, + pub last_system_effect_observation: Option, pub last_el1_context_observation: Option, pub settled_prefixes: Vec, pub service_events: darwin_services::TrapServiceEvents, @@ -175,6 +177,7 @@ impl BlockRuntime { let mut last_m0_write_observation = None; let mut last_el1_register_observation = None; let mut last_el1_system_observation = None; + let mut last_system_effect_observation = None; let mut last_el1_context_observation = None; let mut settled_prefixes = Vec::new(); let mut service_events = darwin_services::TrapServiceEvents::default(); @@ -234,6 +237,22 @@ impl BlockRuntime { attempt, closed: false, }; + if self.profile == BlockProfile::El1PlatformV1 + && matches!(bound.el1_platform_intent(), + Ok(stela_compiler::block::el1_platform::Intent::System(instruction)) + if instruction.is_el1_ram_completion()) + { + match active.execute_system_effects( + &bound, + &mut accounting, + &mut last_system_effect_observation, + &mut settled_prefixes, + ) { + Ok(None) => continue, + Ok(Some(stop)) => break stop, + Err(error) => break OwnedStop::Indeterminate(error.to_string()), + } + } if self.profile == BlockProfile::El1PlatformV1 && matches!(bound.el1_platform_intent(), Ok(stela_compiler::block::el1_platform::Intent::System(instruction)) @@ -408,6 +427,7 @@ impl BlockRuntime { last_m0_write_observation, last_el1_register_observation, last_el1_system_observation, + last_system_effect_observation, last_el1_context_observation, settled_prefixes, service_events, diff --git a/crates/stela-runtime/src/blocks/retirement/checked/provider.rs b/crates/stela-runtime/src/blocks/retirement/checked/provider.rs index 5477f92743..169e195519 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/provider.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/provider.rs @@ -4,7 +4,9 @@ mod m0_owner; mod resources; pub(crate) use m0_owner::M0Owner; pub(super) use resources::M0ExecutionChecks; -pub(crate) use resources::{El1ContextResources, El1ExecutionResources, M0ExecutionResources}; +pub(crate) use resources::{ + El1ContextResources, El1ExecutionResources, El1SystemEffectResources, M0ExecutionResources, +}; use super::super::super::{checked_memory, complete_clock, complete_pauth_with_memory}; use super::super::software_async::NoAsyncSources; @@ -270,6 +272,12 @@ pub(crate) trait Owner: sealed::Concrete { } /// Actual mutable publication/monitor loan, after all native loans end. + fn split_el1_system_effect_resources( + &mut self, + ) -> anyhow::Result> { + anyhow::bail!("actual owner has no original System completion resources") + } + fn split_el1_context_resources(&mut self) -> anyhow::Result> { anyhow::bail!("actual EL1 context resources are unavailable") } diff --git a/crates/stela-runtime/src/blocks/retirement/checked/provider/m0_owner.rs b/crates/stela-runtime/src/blocks/retirement/checked/provider/m0_owner.rs index db92a02693..4b1b371df3 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/provider/m0_owner.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/provider/m0_owner.rs @@ -371,6 +371,30 @@ impl Owner for M0Owner<'_> { }) } + fn split_el1_system_effect_resources( + &mut self, + ) -> anyhow::Result> { + anyhow::ensure!( + self.cohort == InstalledCohort::El1Platform, + "System completion requires original fixed fresh platform" + ); + self.check_resources()?; + Ok(super::El1SystemEffectResources { + sources: &*self.sources, + controls: &*self.controls, + platform: self + .platform + .ok_or_else(|| anyhow::anyhow!("System completion original platform absent"))?, + checks: M0ExecutionChecks { + execution: self.execution, + pending: &self.pending, + memory: &*self.memory, + endpoint: self.endpoint, + address_space: self.address_space, + }, + }) + } + fn split_el1_context_resources(&mut self) -> anyhow::Result> { anyhow::ensure!( self.cohort == InstalledCohort::El1Platform, diff --git a/crates/stela-runtime/src/blocks/retirement/checked/provider/resources.rs b/crates/stela-runtime/src/blocks/retirement/checked/provider/resources.rs index 2cd371d5a3..086e994009 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/provider/resources.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/provider/resources.rs @@ -119,3 +119,15 @@ impl El1ContextResources<'_> { .map_err(anyhow::Error::msg) } } + +/// Borrowed only from the fixed fresh platform backend. The source/physical +/// envelope owns the complete RAM participants and all aliases for its entire +/// executable lifetime. NoAsyncSources below checks IRQ/debug producers only; +/// it is never the memory-participant closure proof. +pub(crate) struct El1SystemEffectResources<'pe> { + pub(in crate::blocks::retirement::checked) sources: &'pe InstalledM0Sources, + pub(in crate::blocks::retirement::checked) controls: &'pe TranslationControls, + pub(in crate::blocks::retirement::checked) platform: + &'pe super::super::el1_system::El1PlatformControls, + pub(in crate::blocks::retirement::checked) checks: M0ExecutionChecks<'pe>, +} diff --git a/crates/stela-runtime/src/blocks/retirement/checked/software_el1.rs b/crates/stela-runtime/src/blocks/retirement/checked/software_el1.rs index faf7e90221..da4c94f8f3 100644 --- a/crates/stela-runtime/src/blocks/retirement/checked/software_el1.rs +++ b/crates/stela-runtime/src/blocks/retirement/checked/software_el1.rs @@ -103,6 +103,8 @@ pub struct SoftwareEl1InitialRam { } pub struct SoftwareEl1Report { + #[cfg(all(test, target_arch = "x86_64"))] + system_effect_fixture_observation: Option, #[cfg(all(test, target_arch = "x86_64"))] exception_fixture_probe: Option, #[cfg(all(test, target_arch = "x86_64"))] @@ -126,6 +128,7 @@ pub struct SoftwareEl1Report { Option, pub register_observation: Option, pub system_observation: Option, + pub system_effect_observation: Option, pub context_observation: Option, pub platform_identification_sha256: Option, pub compiler_source_sha256: String, @@ -663,10 +666,16 @@ impl SoftwareEl1Machine { last_m0_write_observation, last_el1_register_observation, last_el1_system_observation, + last_system_effect_observation, last_el1_context_observation, .. } = outcome; + let system_effect_observation = last_system_effect_observation + .as_ref() + .map(|value| format!("{value:?}")); Ok(SoftwareEl1Report { + #[cfg(all(test, target_arch = "x86_64"))] + system_effect_fixture_observation: last_system_effect_observation, #[cfg(all(test, target_arch = "x86_64"))] exception_fixture_probe, declared_capacity, @@ -687,6 +696,7 @@ impl SoftwareEl1Machine { write_progress_observation, register_observation: last_el1_register_observation.map(|value| format!("{value:?}")), system_observation: last_el1_system_observation.map(|value| format!("{value:?}")), + system_effect_observation, context_observation: last_el1_context_observation .as_ref() .map(|value| format!("{value:?}")), @@ -1274,3 +1284,7 @@ mod platform_tests { #[cfg(all(test, target_arch = "x86_64"))] #[path = "el1_context/fixture.rs"] mod exception_fixture; + +#[cfg(all(test, target_arch = "x86_64"))] +#[path = "system_effects/fixture.rs"] +mod system_effect_fixture; diff --git a/crates/stela-runtime/src/blocks/retirement/checked/system_effects.rs b/crates/stela-runtime/src/blocks/retirement/checked/system_effects.rs new file mode 100644 index 0000000000..9d762ca979 --- /dev/null +++ b/crates/stela-runtime/src/blocks/retirement/checked/system_effects.rs @@ -0,0 +1,269 @@ +//! Resource-specific System effects under the original canonical retiring owner. +//! Native carrier finalization precedes preparation; actual source/control/RAM +//! loans survive the effect, sole PC settlement and post-retirement checks. +mod commit; +mod dsb; + +use super::{ + Active, ConsumerKey, OwnedStop, SettledPrefix, + el1_registers::{RegisterNativeReport, RegisterSession}, + el1_system::RetainedSystemSession, + provider, + source::BoundSource, +}; +use crate::{ + blocks::RunOutcome, + system::execution::{Boundary, EntryBoundary, authority::PeExecutionAuthority}, +}; +pub(crate) use commit::{SystemEffectCommit, SystemEffectCommitError, SystemEffectCommitView}; +use dsb::{PreparedRamDsb, RamDsbApplied, RamDsbFailure}; +use stela_compiler::{ + GuestAddress, + block::{ExitKind, SystemInstruction}, +}; + +pub(crate) struct SystemEffectObservation { + pub(crate) instruction: SystemInstruction, + pub(crate) native: RegisterNativeReport, + pub(crate) completion: Option>, + pub(crate) actual_continuation: Option, + pub(crate) failure: Option, +} + +/// Poison the original owner BEFORE the real RAM/source loans release on a +/// reached effect or settlement failure. This stores no alternate phase/state. +struct RetainedRamCompletion<'active, 'resources> { + authority: &'active mut PeExecutionAuthority, + prepared: PreparedRamDsb<'resources>, + closed: bool, +} +impl Drop for RetainedRamCompletion<'_, '_> { + fn drop(&mut self) { + if !self.closed { + self.authority.poison(); + } + } +} + +impl Active<'_, '_, B> { + pub(super) fn execute_system_effects( + mut self, + bound: &BoundSource<'_>, + accounting: &mut RunOutcome, + observation: &mut Option, + prefixes: &mut Vec, + ) -> anyhow::Result> { + self.require_native()?; + let instruction = bound + .el1_carrier_intent()? + .ok_or_else(|| anyhow::anyhow!("System effect carrier absent"))?; + anyhow::ensure!( + instruction.is_el1_ram_completion(), + "System effect owner is not mounted" + ); + let outer = self + .outer + .as_ref() + .ok_or_else(|| anyhow::anyhow!("System effect original outer absent"))?; + let result = (|| -> anyhow::Result> { + bound.recheck()?; + anyhow::ensure!( + bound.source.len() == size_of::(), + "System effect must be one original instruction" + ); + let boundary = Boundary::new( + EntryBoundary::new( + bound.entry.address_space(), + bound.entry.generation(), + bound.entry.entry(), + bound.entry.region_base(), + bound.entry.source_bytes(), + instruction.word, + ), + bound.source.len(), + instruction, + ); + // End the ORIGINAL native session and mutable context loan before + // splitting completion resources from the same retained backend. + { + let provider::El1ExecutionResources { + sources, + platform, + controls, + memory: _, + context, + checks, + } = self.pe.backend.split_el1_resources()?; + let platform = platform + .ok_or_else(|| anyhow::anyhow!("System effect original platform absent"))?; + platform.context(self.pe.system)?; + checks.check(outer)?; + let scope = sources.el1_scope().map_err(anyhow::Error::msg)?; + let session = RegisterSession::prepare( + bound, + outer, + &scope, + controls, + self.pe.system, + context, + )?; + let mut retained = RetainedSystemSession { + authority: &mut *self.pe.authority, + session, + closed: false, + }; + let mut candidate = self.pe.thread.registers.clone(); + let native = retained.session.invoke(self.pe.system, &mut candidate); + let valid = native.invoked + && native.failure.is_none() + && matches!(native.storage_after, Some(Ok(()))); + let carrier = native.raw_carrier; + *observation = Some(SystemEffectObservation { + instruction, + native, + completion: None, + actual_continuation: None, + failure: None, + }); + anyhow::ensure!( + valid, + "System effect native/storage finalization is unqualified" + ); + anyhow::ensure!( + carrier == Some((instruction.instruction_pc.0, ExitKind::System as u64)) + && candidate == self.pe.thread.registers + && self.pe.thread.pc == instruction.instruction_pc, + "effect-free carrier changed actual state or source exit" + ); + retained.session.validate_current(self.pe.system)?; + checks.check(outer)?; + retained + .authority + .enter_system(&ConsumerKey(()), self.attempt) + .map_err(|()| { + anyhow::anyhow!("System effect original SystemActive transition failed") + })?; + retained.closed = true; + } + let provider::El1SystemEffectResources { + sources, + controls, + platform, + checks, + } = self.pe.backend.split_el1_system_effect_resources()?; + checks.check(outer)?; + let scope = sources + .ram_completion_scope(bound.runtime, controls, self.pe.system, outer) + .map_err(anyhow::Error::msg)?; + let prepared = PreparedRamDsb::prepare( + &boundary, + outer, + self.pe.authority.identity(), + &scope, + controls, + platform, + &checks, + self.pe.system, + &self.pe.thread.registers, + ); + let prepared = match prepared { + Ok(prepared) => prepared, + Err(error) => { + checks.check(outer)?; + scope + .check_installed(controls, self.pe.system) + .map_err(anyhow::Error::msg)?; + let detail = format!("RAM completion preparation declined: {error:?}"); + if let Some(report) = observation { + report.failure = Some(detail.clone()); + } + self.pe + .authority + .finish_refusal(&ConsumerKey(()), self.attempt) + .map_err(|()| { + anyhow::anyhow!("System effect no-effect refusal settlement failed") + })?; + return Ok(Some(OwnedStop::HelperRefused(detail))); + } + }; + let prefix = bound.prefix(None, 0)?; + prefixes.try_reserve(1)?; + let blocks = accounting + .blocks_executed + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("System effect accounting overflow"))?; + bound.recheck()?; + checks.check(outer)?; + let mut retained = RetainedRamCompletion { + authority: &mut *self.pe.authority, + prepared, + closed: false, + }; + retained + .authority + .start_retirement(&ConsumerKey(()), self.attempt) + .map_err(|()| { + anyhow::anyhow!("System effect original Retiring transition failed") + })?; + let result = SystemEffectCommit { + authority: &*retained.authority, + boundary: &boundary, + outer, + attempt: self.attempt, + system: &mut *self.pe.system, + registers: &mut self.pe.thread.registers, + } + .apply_dsb(&mut retained.prepared); + let next = result + .as_ref() + .map(|applied| applied.next_pc) + .map_err(|failure| anyhow::anyhow!("System effect terminal failure: {failure:?}")); + if let Some(report) = observation { + report.completion = Some(result); + } + let next = next?; + // A successful apply has fully qualified the reached completion; + // no additional fallible step precedes the sole PC store. An apply + // failure after MFENCE retains Completed and blocks replay instead. + // Later owner failures preserve the actual committed PC/prefix. + self.pe.thread.pc = next; + if let Some(report) = observation { + report.actual_continuation = Some(next); + } + prefixes.push(prefix); + accounting.blocks_executed = blocks; + accounting.last_exit = Some((instruction.instruction_pc.0, ExitKind::System as u64)); + bound.recheck()?; + checks.post_retirement_el1(outer, &scope, controls, platform, self.pe.system)?; + retained + .authority + .finish_retirement(&ConsumerKey(()), self.attempt, false) + .map_err(|()| { + anyhow::anyhow!("System effect original retirement completion failed") + })?; + retained.closed = true; + Ok(None) + })(); + if let Err(error) = &result + && let Some(report) = observation + { + report.failure = Some(error.to_string()); + } + if result.is_ok() { + self.closed = true; + } + result + } +} + +impl core::fmt::Debug for SystemEffectObservation { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("SystemEffectObservation") + .field("instruction", &self.instruction) + .field("native", &self.native) + .field("completion", &self.completion) + .field("actual_continuation", &self.actual_continuation) + .field("failure", &self.failure) + .finish() + } +} diff --git a/crates/stela-runtime/src/blocks/retirement/checked/system_effects/commit.rs b/crates/stela-runtime/src/blocks/retirement/checked/system_effects/commit.rs new file mode 100644 index 0000000000..7bd4bdf248 --- /dev/null +++ b/crates/stela-runtime/src/blocks/retirement/checked/system_effects/commit.rs @@ -0,0 +1,137 @@ +//! Resource-specific System effects under the sole canonical retiring consumer. +//! Preparation retains original resource/source loans without a PE/state borrow +//! that could obstruct start_retirement. Only the parent constructs this commit. + +use crate::{ + memory::domain::MemoryExecutionLoan, + system::{ + execution::{ + Boundary, + authority::{PeExecutionAuthority, PeIdentity}, + }, + state::SystemState, + }, +}; +use stela_compiler::GuestState; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SystemEffectCommitError { + WrongRetiringAttempt, + ChangedSource, + ChangedOuter, + WrongPe, + ChangedSystemBank, + ChangedRegisterBank, +} + +/// Constructed by the canonical parent only AFTER its actual Retiring transition. +/// These are original retained objects, never copied state or replacement loans. +/// No mutable state getter, phase transition, PC write or authority mint exists. +pub(crate) struct SystemEffectCommit<'commit> { + pub(in crate::blocks::retirement::checked) authority: &'commit PeExecutionAuthority, + pub(in crate::blocks::retirement::checked) boundary: &'commit Boundary, + pub(in crate::blocks::retirement::checked) outer: &'commit MemoryExecutionLoan, + pub(in crate::blocks::retirement::checked) attempt: u64, + pub(in crate::blocks::retirement::checked) system: &'commit mut SystemState, + pub(in crate::blocks::retirement::checked) registers: &'commit mut GuestState, +} + +/// Required read-only split of the SAME live retiring commit. Only the concrete +/// family delegators below construct it; raw pointers are identity diagnostics, +/// never dereferenced and never permission without the actual borrowed phase. +pub(crate) struct SystemEffectCommitView<'commit> { + authority: &'commit PeExecutionAuthority, + boundary: &'commit Boundary, + outer: &'commit MemoryExecutionLoan, + attempt: u64, + system: *const SystemState, + registers: *const GuestState, +} + +impl SystemEffectCommitView<'_> { + pub(crate) fn validate( + &self, + boundary: &Boundary, + outer: &MemoryExecutionLoan, + pe: &PeIdentity, + system: &SystemState, + registers: &GuestState, + ) -> Result<(), SystemEffectCommitError> { + check_commit_membership( + self.authority, + self.boundary, + self.outer, + self.attempt, + boundary, + outer, + pe, + )?; + if !std::ptr::eq(self.system, system) { + return Err(SystemEffectCommitError::ChangedSystemBank); + } + if !std::ptr::eq(self.registers, registers) { + return Err(SystemEffectCommitError::ChangedRegisterBank); + } + Ok(()) + } +} + +fn check_commit_membership( + authority: &PeExecutionAuthority, + original_boundary: &Boundary, + original_outer: &MemoryExecutionLoan, + attempt: u64, + boundary: &Boundary, + outer: &MemoryExecutionLoan, + pe: &PeIdentity, +) -> Result<(), SystemEffectCommitError> { + if !authority.retiring_attempt(attempt) { + return Err(SystemEffectCommitError::WrongRetiringAttempt); + } + if !std::ptr::eq(original_boundary, boundary) { + return Err(SystemEffectCommitError::ChangedSource); + } + if !std::ptr::eq(original_outer, outer) { + return Err(SystemEffectCommitError::ChangedOuter); + } + if !authority.identity().same_pe(pe) { + return Err(SystemEffectCommitError::WrongPe); + } + Ok(()) +} + +impl SystemEffectCommit<'_> { + pub(crate) fn validate( + &self, + boundary: &Boundary, + outer: &MemoryExecutionLoan, + pe: &PeIdentity, + ) -> Result<(), SystemEffectCommitError> { + check_commit_membership( + self.authority, + self.boundary, + self.outer, + self.attempt, + boundary, + outer, + pe, + ) + } + + pub(super) fn apply_dsb( + &mut self, + prepared: &mut super::dsb::PreparedRamDsb<'_>, + ) -> Result { + prepared.validate_commit(self)?; + // Split only original fields; no whole-commit borrow overlaps banks. + let view = SystemEffectCommitView { + authority: self.authority, + boundary: self.boundary, + outer: self.outer, + attempt: self.attempt, + system: std::ptr::from_ref(&*self.system), + registers: std::ptr::from_ref(&*self.registers), + }; + prepared.apply_owned(&view, self.system, self.registers) + } +} diff --git a/crates/stela-runtime/src/blocks/retirement/checked/system_effects/dsb.rs b/crates/stela-runtime/src/blocks/retirement/checked/system_effects/dsb.rs new file mode 100644 index 0000000000..7385017cb1 --- /dev/null +++ b/crates/stela-runtime/src/blocks/retirement/checked/system_effects/dsb.rs @@ -0,0 +1,213 @@ +//! Completion of the fresh machine's original synchronous RAM participants. +//! The immutable installed-source loan excludes a simultaneous publication; +//! the physical loan serializes the actual staged Device-RAM participants. +//! This is not an arbitrary device, DMA, trace or error completion service. + +use super::{SystemEffectCommit, SystemEffectCommitError, SystemEffectCommitView}; +use crate::{ + blocks::{ + InstalledEl1SourceScope, + retirement::checked::{el1_system::El1PlatformControls, provider::M0ExecutionChecks}, + }, + memory::domain::{ + MemoryExecutionLoan, + physical::completion::{PhysicalRamCompletion, RamCompletionError, RamCompletionProgress}, + }, + system::{ + access::Resolution, + barriers::{self, DataCompletion, RequestKind}, + execution::{Boundary, authority::PeIdentity}, + state::SystemState, + translation_controls::TranslationControls, + }, +}; +use stela_compiler::{GuestAddress, GuestState}; + +pub(crate) enum RamDsbError { + Commit(SystemEffectCommitError), + Source, + Access(&'static str), + Owner(String), + ChangedState, + Completion(RamCompletionError), +} + +pub(crate) struct RamDsbFailure { + pub(crate) error: RamDsbError, + pub(crate) progress: RamCompletionProgress, +} + +pub(crate) struct RamDsbApplied { + pub(crate) next_pc: GuestAddress, + pub(crate) requirement: DataCompletion, + pub(crate) progress: RamCompletionProgress, +} + +/// No authority/state borrow survives preparation. These are original actual +/// source/control/RAM/outer loans, not a profile inferred from the DSB word. +/// The sole fresh platform factory closes its physical participants for the +/// entire executable lifetime; its constructor excludes external memory masters. +pub(super) struct PreparedRamDsb<'loan> { + boundary: &'loan Boundary, + outer: &'loan MemoryExecutionLoan, + pe: PeIdentity, + scope: &'loan InstalledEl1SourceScope<'loan>, + controls: &'loan TranslationControls, + platform: &'loan El1PlatformControls, + checks: &'loan M0ExecutionChecks<'loan>, + pstate: u64, + requirement: DataCompletion, + ram: PhysicalRamCompletion<'loan>, +} + +impl<'loan> PreparedRamDsb<'loan> { + #[allow(clippy::too_many_arguments)] + pub(super) fn prepare( + boundary: &'loan Boundary, + outer: &'loan MemoryExecutionLoan, + pe: PeIdentity, + scope: &'loan InstalledEl1SourceScope<'loan>, + controls: &'loan TranslationControls, + platform: &'loan El1PlatformControls, + checks: &'loan M0ExecutionChecks<'loan>, + system: &SystemState, + registers: &GuestState, + ) -> Result { + let instruction = boundary.instruction(); + if boundary.consumed_bytes() != size_of::() + || boundary.source().entry() != instruction.instruction_pc + || boundary.source().word() != instruction.word + || !instruction.matches_source(instruction.instruction_pc, instruction.word) + { + return Err(RamDsbError::Source); + } + checks + .check(outer) + .map_err(|error| RamDsbError::Owner(error.to_string()))?; + scope + .check_installed(controls, system) + .map_err(RamDsbError::Access)?; + let profile = platform + .context(system) + .map_err(|error| RamDsbError::Owner(error.to_string()))? + .profile; + let request = match barriers::resolve_ordinary_el2_disabled(instruction.word, profile) { + Resolution::BackendRequired(request) => request, + Resolution::Unsupported(reason) => return Err(RamDsbError::Access(reason)), + _ => return Err(RamDsbError::Access("no ordinary DSB completion request")), + }; + let RequestKind::Data(requirement) = request.kind() else { + return Err(RamDsbError::Access( + "instruction publication has a separate owner", + )); + }; + // Full RAM completion is stronger than a load/store/shareability subset. + // No nXS support or unavailable XS readback is inferred here: this pure + // EL2-disabled route admits ordinary DSB only, whose FnXS is inapplicable. + let ram = scope + .physical_space() + .prepare_ram_completion(outer) + .map_err(RamDsbError::Completion)?; + Ok(Self { + boundary, + outer, + pe, + scope, + controls, + platform, + checks, + pstate: system.pstate(registers), + requirement, + ram, + }) + } + + pub(super) fn validate_commit( + &self, + commit: &SystemEffectCommit<'_>, + ) -> Result<(), RamDsbFailure> { + commit + .validate(self.boundary, self.outer, &self.pe) + .map_err(|error| RamDsbFailure { + error: RamDsbError::Commit(error), + progress: self.ram.progress(), + }) + } + + /// This mutating entry cannot be called with loose banks: the closed view + /// checks the original Retiring attempt/source/outer/PE and both actual banks. + pub(super) fn apply_owned( + &mut self, + commit: &SystemEffectCommitView<'_>, + system: &mut SystemState, + registers: &mut GuestState, + ) -> Result { + let result = (|| -> Result<(), RamDsbError> { + commit + .validate(self.boundary, self.outer, &self.pe, system, registers) + .map_err(RamDsbError::Commit)?; + if system.pstate(registers) != self.pstate { + return Err(RamDsbError::ChangedState); + } + self.checks + .check(self.outer) + .map_err(|error| RamDsbError::Owner(error.to_string()))?; + self.scope + .check_installed(self.controls, system) + .map_err(RamDsbError::Access)?; + self.platform + .context(system) + .map_err(|error| RamDsbError::Owner(error.to_string()))?; + self.ram.complete().map_err(RamDsbError::Completion)?; + // Retain the complete reached receipt even if a later actual owner + // check fails. Such a failure is terminal, never a replay permit. + self.ram + .validate_current() + .map_err(RamDsbError::Completion)?; + Ok(()) + })(); + match result { + Ok(()) => Ok(RamDsbApplied { + next_pc: self.boundary.instruction().next_pc, + requirement: self.requirement, + progress: self.ram.progress(), + }), + Err(error) => Err(RamDsbFailure { + error, + progress: self.ram.progress(), + }), + } + } +} + +impl core::fmt::Debug for RamDsbFailure { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("RamDsbFailure") + .field("error", &self.error) + .field("progress", &self.progress) + .finish() + } +} + +impl core::fmt::Debug for RamDsbApplied { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("RamDsbApplied") + .field("next_pc", &self.next_pc) + .field("requirement", &self.requirement) + .field("progress", &self.progress) + .finish() + } +} + +impl core::fmt::Debug for RamDsbError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Commit(value) => f.debug_tuple("Commit").field(value).finish(), + Self::Source => f.write_str("Source"), + Self::Access(value) => f.debug_tuple("Access").field(value).finish(), + Self::Owner(value) => f.debug_tuple("Owner").field(value).finish(), + Self::ChangedState => f.write_str("ChangedState"), + Self::Completion(value) => f.debug_tuple("Completion").field(value).finish(), + } + } +} diff --git a/crates/stela-runtime/src/blocks/retirement/checked/system_effects/fixture.rs b/crates/stela-runtime/src/blocks/retirement/checked/system_effects/fixture.rs new file mode 100644 index 0000000000..ae8521e25e --- /dev/null +++ b/crates/stela-runtime/src/blocks/retirement/checked/system_effects/fixture.rs @@ -0,0 +1,231 @@ +//! Actual consuming RAM-store -> DSB fixture. No original ARM oracle claim. +//! Complete current state/RAM and real reached fence receipt are saved first. +use super::*; +use crate::memory::domain::physical::completion::RamCompletionProgress; +use crate::system::state::{El1Registers, PSTATE_EL1H}; +use std::path::Path; +use stela_compiler::{GuestState, TargetCpu}; + +const SOURCE_PC: u64 = 0x4008_0000; +const DATA_PA: u64 = 0x4009_0000; +const ADDRESS_SPACE: u64 = 91; +const CANARY_BYTES: usize = 32; +const CANARY: u8 = 0xa5; +const STACK_VALUE: u64 = 0x1234_5000; +const INACTIVE_STACK: u64 = 0x9876_5000; +const STP_X0_X1_X2: u32 = 0xa900_0440; +const DSB_BASE: u32 = 0xd503_309f; +const DSB_OPTION_SHIFT: u32 = 8; +const DSB_SY: u8 = 15; +const DSB_ISH: u8 = 11; +const DSB_ISHLD: u8 = 9; +const DSB_ISHST: u8 = 10; +const NOP: u32 = 0xd503_201f; + +fn state_bytes(state: &GuestState) -> &[u8] { + // SAFETY: GuestState is the same fixed all-integer 784-byte native frame; + // this reads the original fully initialized object for retained evidence. + unsafe { std::slice::from_raw_parts(std::ptr::from_ref(state).cast(), size_of::()) } +} +fn machine(cache: PathBuf, dsb: u32) -> SoftwareEl1Machine { + let mut registers = GuestState { + sp: STACK_VALUE, + nzcv: 0xa000_0000, + reserved: 0xdec0_de00, + ..Default::default() + }; + for (index, value) in registers.x.iter_mut().enumerate() { + *value = 0x1111_0000_0000_0000 | index as u64; + } + for (index, value) in registers.v.iter_mut().enumerate() { + *value = [ + 0x2222_0000_0000_0000 | index as u64, + 0x3333_0000_0000_0000 | index as u64, + ]; + } + registers.x[2] = DATA_PA; + SoftwareEl1Machine::new(SoftwareEl1Config { + profile: SoftwareEl1Profile::PlatformV1, + cache_directory: cache, + ram: SourceRamDeclaration { + address_space: ADDRESS_SPACE, + target: TargetCpu::Baseline, + declared_capacity: vec![ + PhysicalRamRange { + source_pa: SOURCE_PC, + bytes: 0x1000, + }, + PhysicalRamRange { + source_pa: DATA_PA, + bytes: CANARY_BYTES as u64, + }, + ], + initialized: vec![ + OwnedRamExtent { + source_pa: SOURCE_PC, + bytes: [STP_X0_X1_X2, dsb, NOP] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(), + permissions: SourceRamPermissions { + readable: true, + writable: false, + executable: true, + }, + }, + OwnedRamExtent { + source_pa: DATA_PA, + bytes: vec![CANARY; CANARY_BYTES], + permissions: SourceRamPermissions { + readable: true, + writable: true, + executable: false, + }, + }, + ], + }, + thread: ThreadState { + pc: GuestAddress(SOURCE_PC), + registers, + }, + system: SystemState::new( + PSTATE_EL1H | crate::system::pstate::DAIF_MASK, + INACTIVE_STACK, + El1Registers::new(1, 2, 3, 4, 0), + ) + .unwrap(), + translation: RegisterValues { + sctlr_el1: 0, + tcr_el1: 0, + ttbr0_el1: 0, + ttbr1_el1: 0, + mair_el1: 0, + }, + }) + .unwrap() +} +fn save(output: &Path, report: &SoftwareEl1Report) { + std::fs::write( + output.join("after-state.bin"), + state_bytes(&report.thread.registers), + ) + .unwrap(); + std::fs::write( + output.join("after-system.txt"), + format!("{:#?}", report.system), + ) + .unwrap(); + std::fs::write( + output.join("actual-observation.txt"), + format!( + "stop={}\npc={:x}\nblocks={}\nwrite={:?}\ncompletion={:?}\ntranslation_before={:?}\ntranslation_after={:?}\ncompiler={}\n", + report.stop, + report.thread.pc.0, + report.accounting.blocks_executed, + report.memory_write_observation, + report.system_effect_fixture_observation, + report.translation_before, + report.translation, + report.compiler_source_sha256 + ), + ) + .unwrap(); + for range in &report.ram { + match &range.captured_bytes { + Ok(bytes) => std::fs::write( + output.join(format!("actual-ram-{:x}.bin", range.source_pa)), + bytes, + ) + .unwrap(), + Err(error) => std::fs::write( + output.join(format!("actual-ram-{:x}.error", range.source_pa)), + error, + ) + .unwrap(), + } + } +} +#[test] +#[ignore = "requires current qualified x86 owner and explicit evidence output"] +fn actual_store_and_dsb_keep_original_state_ram_and_reached_completion() { + let output = PathBuf::from( + std::env::var_os("STELA_DSB_OUTPUT").expect("fresh evidence output required"), + ); + assert!(!output.exists(), "preserve previous evidence"); + std::fs::create_dir_all(&output).unwrap(); + for (name, option) in [ + ("sy", DSB_SY), + ("ish", DSB_ISH), + ("ishld", DSB_ISHLD), + ("ishst", DSB_ISHST), + ] { + let case = output.join(name); + std::fs::create_dir(&case).unwrap(); + let dsb = DSB_BASE | (u32::from(option) << DSB_OPTION_SHIFT); + let machine = machine(case.join("cache"), dsb); + let before = machine.thread.registers.clone(); + let system = machine.system.clone(); + std::fs::write(case.join("before-state.bin"), state_bytes(&before)).unwrap(); + std::fs::write(case.join("before-system.txt"), format!("{system:#?}")).unwrap(); + let source: Vec = [STP_X0_X1_X2, dsb, NOP] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + std::fs::write(case.join("source.bin"), &source).unwrap(); + let (actual_source_before, actual_data_before) = { + let memory = machine.memory.observation_loan().unwrap(); + ( + memory.snapshot(SOURCE_PC, source.len()).unwrap(), + memory.snapshot(DATA_PA, CANARY_BYTES).unwrap(), + ) + }; + std::fs::write(case.join("before-source.bin"), &actual_source_before).unwrap(); + std::fs::write(case.join("before-ram.bin"), &actual_data_before).unwrap(); + let report = machine + .run_to_shutdown(SoftwareEl1Request { + stop_pc: Some(GuestAddress(SOURCE_PC + 2 * size_of::() as u64)), + block_budget: 3, + }) + .unwrap(); + save(&case, &report); + assert_eq!(report.stop, "StopAddress"); + assert_eq!(report.accounting.blocks_executed, 2); + assert_eq!(report.thread.registers, before); + assert_eq!(report.system, system); + assert_eq!(actual_source_before, source); + assert_eq!(actual_data_before, vec![CANARY; CANARY_BYTES]); + assert_eq!( + report.translation_before.as_ref().unwrap(), + report.translation.as_ref().unwrap() + ); + let observed = report + .system_effect_fixture_observation + .as_ref() + .expect("actual DSB observation absent"); + let completion = observed + .completion + .as_ref() + .expect("actual DSB effect not reached") + .as_ref() + .expect("actual DSB failed"); + assert_eq!(completion.progress, RamCompletionProgress::Completed); + assert_eq!(completion.requirement.option(), option); + assert_eq!(observed.actual_continuation, Some(report.thread.pc)); + assert!(observed.native.invoked && observed.native.failure.is_none()); + let mut expected = vec![CANARY; CANARY_BYTES]; + expected[..8].copy_from_slice(&before.x[0].to_le_bytes()); + expected[8..16].copy_from_slice(&before.x[1].to_le_bytes()); + let data = report + .ram + .iter() + .find(|ram| ram.source_pa == DATA_PA) + .unwrap(); + assert_eq!(data.captured_bytes.as_ref().unwrap(), &expected); + let code = report + .ram + .iter() + .find(|ram| ram.source_pa == SOURCE_PC) + .unwrap(); + assert_eq!(code.captured_bytes.as_ref().unwrap(), &source); + } +} diff --git a/crates/stela-runtime/src/blocks/translation/owner.rs b/crates/stela-runtime/src/blocks/translation/owner.rs index 59dbdf7fae..b38731a411 100644 --- a/crates/stela-runtime/src/blocks/translation/owner.rs +++ b/crates/stela-runtime/src/blocks/translation/owner.rs @@ -128,6 +128,35 @@ impl InstalledCodeSources { } } + /// Retain the original complete synchronous RAM/source participants while + /// the canonical fresh EL1 owner completes a DSB. The immutable source and + /// runtime borrows exclude another publication/cache/context mutation. + /// Fresh construction owns ALL physical aliases and excludes external + /// memory masters; this does not certify arbitrary MMIO or DMA completion. + pub(in crate::blocks) fn ram_completion_scope<'run>( + &'run self, + runtime: &'run BlockRuntime, + controls: &TranslationControls, + system: &SystemState, + outer: &crate::memory::domain::MemoryExecutionLoan, + ) -> Result, &'static str> { + if !Arc::ptr_eq(&runtime.identity, &self.runtime_identity) + || runtime.profile() != self.compiler_profile + || self.compiler_profile != BlockProfile::El1PlatformV1 + { + return Err("RAM completion requires the original installed platform/cache"); + } + self.physical + .check_execution_loan(outer) + .map_err(|_| "RAM completion original physical/outer differs")?; + // Installed excludes Unbound/Failed. All successful context publication + // producers finish synchronously before returning to the original PE; + // no separate deferred maintenance producer exists in this fixed factory. + let scope = self.el1_scope()?; + scope.check_installed(controls, system)?; + Ok(scope) + } + /// Loan the SAME installed context/physical/code owners after native return. /// The canonical consumer separately binds the exact returned source and /// retains its original PE, outer and control loans through publication. diff --git a/crates/stela-runtime/src/memory/domain/physical.rs b/crates/stela-runtime/src/memory/domain/physical.rs index d086880606..642fd8222a 100644 --- a/crates/stela-runtime/src/memory/domain/physical.rs +++ b/crates/stela-runtime/src/memory/domain/physical.rs @@ -1,5 +1,8 @@ //! Source-physical reads from genuinely materialized private loader RAM. //! Guest source memory type is not inferred from coherent host storage. +#[path = "physical/completion.rs"] +pub(crate) mod completion; + use super::{ AccessKind, Arc, MemoryDomain, MemoryExecutionLoan, MemoryStatus, PhysicalAccess, access, }; diff --git a/crates/stela-runtime/src/memory/domain/physical/completion.rs b/crates/stela-runtime/src/memory/domain/physical/completion.rs new file mode 100644 index 0000000000..fd9115c231 --- /dev/null +++ b/crates/stela-runtime/src/memory/domain/physical/completion.rs @@ -0,0 +1,118 @@ +//! Actual synchronous side-effect-free coherent RAM participant completion. +//! +//! This covers the original staged Device-RAM service, not MMIO, bus masters or +//! all DSB obligations. The canonical factory must close its real data and +//! maintenance participants. No source/PE/retirement authority is created here. + +use super::{PhysicalAddressSpace, PhysicalReadPlatformError}; +use crate::memory::domain::MemoryExecutionLoan; +use std::sync::MutexGuard; +use stela_compiler::context::memory::MemoryStatus; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum RamCompletionProgress { + Unattempted, + Attempted, + Completed, +} + +pub(crate) enum RamCompletionError { + Physical(PhysicalReadPlatformError), + Ordering(MemoryStatus), + AlreadyAttempted(RamCompletionProgress), +} + +/// The same original physical/source owner, outer and Device-RAM serializer +/// stay borrowed through actual completion and canonical architectural settling. +/// This type reads/writes no target RAM and supplies no new execution loan. +#[must_use] +pub(crate) struct PhysicalRamCompletion<'loan> { + physical: &'loan PhysicalAddressSpace, + execution: &'loan MemoryExecutionLoan, + _order: MutexGuard<'loan, ()>, + progress: RamCompletionProgress, +} + +impl PhysicalRamCompletion<'_> { + pub(crate) fn validate_current(&self) -> Result<(), RamCompletionError> { + self.physical + .check_execution_loan(self.execution) + .map_err(RamCompletionError::Physical) + } + + pub(crate) const fn progress(&self) -> RamCompletionProgress { + self.progress + } + + /// Called only after the original canonical owner enters Retiring. The + /// actual SystemEffectCommit validates the exact source/outer/PE separately. + /// Failure before MFENCE is NoEffect. Completed is stored infallibly before + /// returning, so a later owner check preserves this reached prefix. + pub(crate) fn complete(&mut self) -> Result<(), RamCompletionError> { + if self.progress != RamCompletionProgress::Unattempted { + return Err(RamCompletionError::AlreadyAttempted(self.progress)); + } + self.progress = RamCompletionProgress::Attempted; + self.validate_current()?; + #[cfg(target_arch = "x86_64")] + { + // SAFETY: the SAME physical domain/current source binding and outer + // are checked above; this original MemorySystem order guard excludes + // simultaneous staged Device-RAM sessions. Its bounded host backing + // is coherent RAM; this fence grants no device-bus/MMIO semantics. + // No nomem/readonly/pure may erase the compiler memory boundary. + unsafe { + std::arch::asm!("mfence", options(nostack, preserves_flags)); + } + self.progress = RamCompletionProgress::Completed; + Ok(()) + } + #[cfg(not(target_arch = "x86_64"))] + { + Err(RamCompletionError::Physical( + PhysicalReadPlatformError::UnsupportedHost, + )) + } + } +} + +impl PhysicalAddressSpace { + /// Prepare without data/maintenance/architectural effects. Busy or poisoned + /// real order/source owners decline finitely before acquiring a completion. + /// This real RAM participant is not complete factory-wide DSB authority. + pub(crate) fn prepare_ram_completion<'loan>( + &'loan self, + execution: &'loan MemoryExecutionLoan, + ) -> Result, RamCompletionError> { + if !cfg!(target_arch = "x86_64") { + return Err(RamCompletionError::Physical( + PhysicalReadPlatformError::UnsupportedHost, + )); + } + self.check_execution_loan(execution) + .map_err(RamCompletionError::Physical)?; + let order = execution + .device_ram_order() + .map_err(RamCompletionError::Ordering)?; + let prepared = PhysicalRamCompletion { + physical: self, + execution, + _order: order, + progress: RamCompletionProgress::Unattempted, + }; + prepared.validate_current()?; + Ok(prepared) + } +} + +impl core::fmt::Debug for RamCompletionError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Physical(value) => f.debug_tuple("Physical").field(value).finish(), + Self::Ordering(value) => f.debug_tuple("Ordering").field(value).finish(), + Self::AlreadyAttempted(value) => { + f.debug_tuple("AlreadyAttempted").field(value).finish() + } + } + } +} diff --git a/crates/stela-runtime/src/memory/domain/physical/source_ram_tests.rs b/crates/stela-runtime/src/memory/domain/physical/source_ram_tests.rs index 2d09cabf23..a9a5b80424 100644 --- a/crates/stela-runtime/src/memory/domain/physical/source_ram_tests.rs +++ b/crates/stela-runtime/src/memory/domain/physical/source_ram_tests.rs @@ -1,3 +1,4 @@ +use super::completion::{RamCompletionError, RamCompletionProgress}; use super::*; use crate::memory::{ policy::{LowerAddressProfile, MemoryControls, TagCheckFaultMode}, @@ -321,3 +322,45 @@ fn test_alias_factory_rejects_invalid_extent_ranges_rights_and_alignment() { )); } } + +#[test] +fn actual_ram_completion_retains_same_order_owner_and_cannot_be_replayed() { + let actual = physical(); + let outer = actual.domain().execution_loan().unwrap(); + let mut prepared = actual.prepare_ram_completion(&outer).unwrap(); + assert_eq!(prepared.progress(), RamCompletionProgress::Unattempted); + // A second session cannot bypass this SAME machine's live serializer. + assert!(matches!( + actual.prepare_ram_completion(&outer), + Err(RamCompletionError::Ordering(_)) + )); + prepared.complete().unwrap(); + assert_eq!(prepared.progress(), RamCompletionProgress::Completed); + assert!(matches!( + prepared.complete(), + Err(RamCompletionError::AlreadyAttempted( + RamCompletionProgress::Completed + )) + )); + // Completion doesn't release original loans before architectural settlement. + assert!(matches!( + actual.prepare_ram_completion(&outer), + Err(RamCompletionError::Ordering(_)) + )); + drop(prepared); + drop(actual.prepare_ram_completion(&outer).unwrap()); +} + +#[test] +fn ram_completion_rejects_another_actual_domain_before_any_fence() { + let actual = physical(); + let foreign = physical(); + let wrong_outer = foreign.domain().execution_loan().unwrap(); + assert!(matches!( + actual.prepare_ram_completion(&wrong_outer), + Err(RamCompletionError::Physical(_)) + )); + let outer = actual.domain().execution_loan().unwrap(); + let mut prepared = actual.prepare_ram_completion(&outer).unwrap(); + prepared.complete().unwrap(); +} diff --git a/crates/stela-runtime/src/system.rs b/crates/stela-runtime/src/system.rs index 889b6f01ad..90da24a91b 100644 --- a/crates/stela-runtime/src/system.rs +++ b/crates/stela-runtime/src/system.rs @@ -1,6 +1,7 @@ //! Shared A64 system decisions, authoritative state and checked effect dispatch. pub mod access; +pub mod barriers; pub mod debug; pub mod events; pub mod exception; diff --git a/crates/stela-runtime/src/system/barriers.rs b/crates/stela-runtime/src/system/barriers.rs new file mode 100644 index 0000000000..dedaecfa0a --- /dev/null +++ b/crates/stela-runtime/src/system/barriers.rs @@ -0,0 +1,364 @@ +//! Checked DSB/DSBnXS/ISB requests and ordered owner-service execution. +//! +//! This leaf supplies no production completion/publication implementation. +//! A host fence covers only the selected synchronous Normal-WB data profile; +//! guest maintenance and instruction/context publication need their owners. + +use super::access::{ExceptionLevel, Profile, Resolution}; +use super::exception::EffectFailure; +use stela_compiler::aarch64::system::synchronization::{self, Operation, Requirement, Scope}; + +const HCRX_FNXS_MASK: u64 = 1 << 3; +const A64_INSTRUCTION_BYTES: u64 = 4; + +/// Access is derived by the authoritative control owner using FEAT_HCX, +/// EL2's execution state, SCR_EL3.HXEn and EL2Enabled, not host detection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HcrxAccess { + /// No effective-control readback was supplied. Irrelevant to ISB/nXS. + Unreported, + Disabled, + Enabled { + effective_value: u64, + }, +} + +/// BRBE feature absence differs from an implemented policy that records no ISB. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BrbeIsb { + /// No authoritative feature/policy readback was supplied. ISB must stop. + Unreported, + Absent, + DoesNotRecord, + Records, +} + +/// An unavailable readback must never become an architectural feature absence. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Xs { + Unreported, + Absent, + Present, +} + +/// Dispatch snapshot, not a second mutable machine or feature bank. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Context { + pub profile: Profile, + pub xs: Xs, + pub hcrx: HcrxAccess, + pub brbe_isb: BrbeIsb, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DataCompletion { + option: u8, + scope: Scope, + requirement: Requirement, + nxs: bool, +} + +impl DataCompletion { + pub const fn option(self) -> u8 { + self.option + } + /// June MBMaintenanceScope, not the legacy memory request domain. + pub const fn scope(self) -> Scope { + self.scope + } + pub const fn requirement(self) -> Requirement { + self.requirement + } + /// Effective nXS includes execution-controlled FnXS on ordinary DSB. + pub const fn nxs(self) -> bool { + self.nxs + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RequestKind { + Data(DataCompletion), + Instruction { option: u8, record_brbe: bool }, +} + +/// Canonical source descriptor and its validated execution-control snapshot. +#[derive(Debug, PartialEq, Eq)] +pub struct Request { + word: u32, + context: Context, + kind: RequestKind, +} + +impl Request { + pub const fn original_word(&self) -> u32 { + self.word + } + pub const fn context(&self) -> Context { + self.context + } + pub const fn kind(&self) -> RequestKind { + self.kind + } +} + +/// Resolve only this service family. Aliases remain with their existing owners. +pub fn resolve(word: u32, context: Context) -> Resolution { + let Some(operation) = synchronization::decode(word) else { + return Resolution::NotHandled; + }; + if !matches!( + operation, + Operation::DataCompletion { .. } | Operation::InstructionSynchronization { .. } + ) { + return Resolution::NotHandled; + } + let kind = match operation { + Operation::DataCompletion { + option, + scope, + requirement, + nxs, + } => { + if nxs { + match context.xs { + Xs::Absent => return Resolution::Undefined, + Xs::Unreported => { + return Resolution::Unsupported("explicit nXS requires actual XS readback"); + } + Xs::Present => {} + } + } + if !nxs + && context.xs != Xs::Absent + && matches!( + context.profile.current_el, + ExceptionLevel::El0 | ExceptionLevel::El1 + ) + && matches!(context.hcrx, HcrxAccess::Enabled { .. }) + && !context.profile.el2_enabled + { + return Resolution::Unsupported("enabled HCRX requires enabled EL2"); + } + if !nxs + && context.xs != Xs::Absent + && matches!( + context.profile.current_el, + ExceptionLevel::El0 | ExceptionLevel::El1 + ) + && context.profile.el2_enabled + && context.hcrx == HcrxAccess::Unreported + { + return Resolution::Unsupported( + "effective nXS requires actual HCRX access readback", + ); + } + let forcing_control = matches!( + context.profile.current_el, + ExceptionLevel::El0 | ExceptionLevel::El1 + ) && matches!(context.hcrx, + HcrxAccess::Enabled { effective_value } if effective_value & HCRX_FNXS_MASK != 0); + if !nxs && forcing_control && context.xs == Xs::Unreported { + return Resolution::Unsupported("effective nXS requires actual XS readback"); + } + let forced_nxs = context.xs == Xs::Present && forcing_control; + RequestKind::Data(DataCompletion { + option, + scope, + requirement, + nxs: nxs || forced_nxs, + }) + } + Operation::InstructionSynchronization { option } => { + if context.brbe_isb == BrbeIsb::Unreported { + return Resolution::Unsupported("ISB requires actual BRBE feature/policy readback"); + } + RequestKind::Instruction { + option, + record_brbe: context.brbe_isb == BrbeIsb::Records, + } + } + _ => unreachable!("operation filtered to this service family"), + }; + Resolution::BackendRequired(Request { + word, + context, + kind, + }) +} + +/// Resolve EL0/EL1 ordinary DSB when the authoritative profile disables EL2. +/// +/// June IsHCRXEL2Enabled ends with EL2Enabled, so effective HCRX is disabled +/// independently of XS/HCX availability. Preserve those unavailable readbacks +/// instead of inventing feature absence. The caller must derive Profile from +/// its actual PE/control owner; this pure decoder confers no execution permit, +/// source authority, mapped history or completion/publication implementation. +/// Explicit nXS, ISB and bypass aliases remain with the complete dispatcher. +pub fn resolve_ordinary_el2_disabled(word: u32, profile: Profile) -> Resolution { + if !matches!( + synchronization::decode(word), + Some(Operation::DataCompletion { nxs: false, .. }) + ) { + return Resolution::NotHandled; + } + if profile.el2_enabled { + return Resolution::Unsupported("ordinary no-EL2 route requires actual disabled EL2"); + } + if !matches!( + profile.current_el, + ExceptionLevel::El0 | ExceptionLevel::El1 + ) { + return Resolution::Unsupported("ordinary no-EL2 route requires actual EL0/EL1"); + } + resolve( + word, + Context { + profile, + xs: Xs::Unreported, + hcrx: HcrxAccess::Disabled, + brbe_isb: BrbeIsb::Unreported, + }, + ) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ServiceRequest { + pub original_word: u32, + pub source_pc: u64, + pub context: Context, + pub kind: RequestKind, +} + +/// A permit binds actual source/control provenance and the owning PE, machine +/// and address space throughout this one execution. Preflight has no guest or +/// barrier effect. It reserves every required service before any completion. +/// +/// Data completion combines real synchronous data completion with every +/// maintenance obligation required by the raw option/scope/effective nXS. +/// Unsupported-before-issue or immutable-code/fixed-control eligibility must +/// come from the source-generation/runtime exclusion contract. Zero counters +/// and absent host queues do not establish global architectural absence. +/// +/// Instruction synchronization publishes the actual guest instruction stream +/// and relevant control/translation changes before the next guest instruction. +/// CPUID or another host serialization recipe alone does not establish this. +/// Do not clear unrelated trace/error work: the DSB/ISB source calls no blanket +/// TraceUnitFlush or SynchronizeErrors. Any unavailable requirement stops here. +/// Every callback `Ok(())` certifies its complete architectural effect, not +/// issuance or queued work. Failure completion describes that current stage; +/// CommittedPrefix describes earlier stages that already completed. +pub trait BarrierServices { + type Permit; + type Error; + + fn preflight(&mut self, request: ServiceRequest) -> Result; + fn complete_data_and_maintenance( + &mut self, + permit: &mut Self::Permit, + request: DataCompletion, + ) -> Result<(), EffectFailure>; + fn synchronize_instructions( + &mut self, + permit: &mut Self::Permit, + ) -> Result<(), EffectFailure>; + fn record_brbe_isb( + &mut self, + permit: &mut Self::Permit, + next_pc: u64, + ) -> Result<(), EffectFailure>; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EffectStage { + DataCompletion, + InstructionSynchronization, + BrbeRecord, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CommittedPrefix { + None, + InstructionsSynchronized, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ExecuteError { + Preflight(E), + Effect { + stage: EffectStage, + committed: CommittedPrefix, + failure: EffectFailure, + }, +} + +impl Request { + /// On failure preserve earlier instructions, memory and completed owner + /// effects. A consumed request is not a whole-operation retry token. + /// The caller commits the returned PC only after successful completion. + /// On every failure the caller must settle the actual reached terminal PC + /// under the PE lease, including NoEffect after a native prefix. Failure + /// never authorizes replay from block entry or rollback of prior effects. + pub fn execute( + self, + source_pc: u64, + services: &mut S, + ) -> Result> { + let permit = services + .preflight(self.service_request(source_pc)) + .map_err(ExecuteError::Preflight)?; + self.execute_preflighted(source_pc, services, permit) + } + + /// Pure request for reservation before the canonical Retiring transition. + pub(crate) const fn service_request(&self, source_pc: u64) -> ServiceRequest { + ServiceRequest { + original_word: self.word, + source_pc, + context: self.context, + kind: self.kind, + } + } + + /// Consume the exact original prepared service permit once. No second + /// preflight, authority transition or PC commit occurs in the semantic leaf. + pub(crate) fn execute_preflighted( + self, + source_pc: u64, + services: &mut S, + mut permit: S::Permit, + ) -> Result> { + let next_pc = source_pc.wrapping_add(A64_INSTRUCTION_BYTES); + match self.kind { + RequestKind::Data(request) => services + .complete_data_and_maintenance(&mut permit, request) + .map_err(|failure| ExecuteError::Effect { + stage: EffectStage::DataCompletion, + committed: CommittedPrefix::None, + failure, + })?, + RequestKind::Instruction { record_brbe, .. } => { + services + .synchronize_instructions(&mut permit) + .map_err(|failure| ExecuteError::Effect { + stage: EffectStage::InstructionSynchronization, + committed: CommittedPrefix::None, + failure, + })?; + if record_brbe { + services + .record_brbe_isb(&mut permit, next_pc) + .map_err(|failure| ExecuteError::Effect { + stage: EffectStage::BrbeRecord, + committed: CommittedPrefix::InstructionsSynchronized, + failure, + })?; + } + } + } + Ok(next_pc) + } +} + +#[cfg(test)] +#[path = "barriers/tests.rs"] +mod tests; diff --git a/crates/stela-runtime/src/system/barriers/tests.rs b/crates/stela-runtime/src/system/barriers/tests.rs new file mode 100644 index 0000000000..322f1a75b4 --- /dev/null +++ b/crates/stela-runtime/src/system/barriers/tests.rs @@ -0,0 +1,622 @@ +use super::super::access::SecurityState; +use super::super::exception::Completion; +use super::*; + +const DSB_BASE: u32 = 0xd503_309f; +const DSB_NXS_BASE: u32 = 0xd503_323f; +const ISB_BASE: u32 = 0xd503_30df; +const OPTION_SHIFT: u32 = 8; +const NXS_SCOPE_SHIFT: u32 = 10; +const SOURCE_PC: u64 = 0x1234; + +fn context() -> Context { + Context { + profile: Profile { + current_el: ExceptionLevel::El1, + security: SecurityState::NonSecure, + el2_enabled: false, + el3_present: false, + }, + xs: Xs::Absent, + hcrx: HcrxAccess::Disabled, + brbe_isb: BrbeIsb::Absent, + } +} + +fn request(word: u32, context: Context) -> Request { + match resolve(word, context) { + Resolution::BackendRequired(request) => request, + other => panic!("expected checked backend request, got {other:?}"), + } +} + +#[test] +fn dsb_table_retains_raw_operand_and_june_maintenance_scope() { + use Requirement::{All, Reads, Writes}; + use Scope::{InnerShareable, Nonshareable, OuterShareable}; + let expected = [ + (1, Scope::None, Reads), + (2, Scope::None, Writes), + (3, OuterShareable, All), + (5, Scope::None, Reads), + (6, Scope::None, Writes), + (7, Nonshareable, All), + (8, OuterShareable, All), + (9, Scope::None, Reads), + (10, Scope::None, Writes), + (11, InnerShareable, All), + (12, OuterShareable, All), + (13, Scope::None, Reads), + (14, Scope::None, Writes), + (15, OuterShareable, All), + ]; + for (option, scope, requirement) in expected { + let word = DSB_BASE | u32::from(option) << OPTION_SHIFT; + let request = request(word, context()); + assert_eq!(request.original_word(), word); + assert_eq!( + request.kind(), + RequestKind::Data(DataCompletion { + option, + scope, + requirement, + nxs: false + }) + ); + } + for option in [0, 4] { + assert!(matches!( + resolve(DSB_BASE | option << OPTION_SHIFT, context()), + Resolution::NotHandled + )); + } +} + +#[test] +fn explicit_nxs_requires_xs_and_retains_every_scope() { + for (option, scope) in [ + Scope::OuterShareable, + Scope::Nonshareable, + Scope::InnerShareable, + Scope::OuterShareable, + ] + .into_iter() + .enumerate() + { + let word = DSB_NXS_BASE | (option as u32) << NXS_SCOPE_SHIFT; + // Irrelevant inconsistent control cannot override the decode UNDEF. + let context = Context { + hcrx: HcrxAccess::Enabled { + effective_value: HCRX_FNXS_MASK, + }, + ..context() + }; + assert!(matches!(resolve(word, context), Resolution::Undefined)); + assert_eq!( + request( + word, + Context { + xs: Xs::Present, + ..context + } + ) + .kind(), + RequestKind::Data(DataCompletion { + option: option as u8, + scope, + requirement: Requirement::All, + nxs: true + }) + ); + } +} + +#[test] +fn ordinary_nxs_forcing_uses_actual_source_el_and_effective_control() { + for current_el in [ + ExceptionLevel::El0, + ExceptionLevel::El1, + ExceptionLevel::El2, + ExceptionLevel::El3, + ] { + for xs in [false, true] { + for enabled in [false, true] { + for fnxs in [false, true] { + let base = context(); + let context = Context { + xs: if xs { Xs::Present } else { Xs::Absent }, + profile: Profile { + current_el, + el2_enabled: true, + ..base.profile + }, + hcrx: if enabled { + HcrxAccess::Enabled { + effective_value: if fnxs { HCRX_FNXS_MASK } else { 0 }, + } + } else { + HcrxAccess::Disabled + }, + ..base + }; + let RequestKind::Data(data) = + request(DSB_BASE | 15 << OPTION_SHIFT, context).kind() + else { + unreachable!() + }; + assert_eq!( + data.nxs(), + xs && enabled + && fnxs + && matches!(current_el, ExceptionLevel::El0 | ExceptionLevel::El1) + ); + } + } + } + } +} + +#[derive(Default)] +struct Services { + preflight: Vec, + calls: Vec, + data: Vec, + brbe_pc: Option, + unavailable: bool, + fail: Option, + completion: Option, +} + +impl Services { + fn step(&mut self, stage: EffectStage) -> Result<(), EffectFailure<&'static str>> { + self.calls.push(stage); + if self.fail == Some(stage) { + Err(EffectFailure { + error: "injected", + completion: self.completion.unwrap_or(Completion::Partial), + }) + } else { + Ok(()) + } + } +} + +impl BarrierServices for Services { + type Permit = (); + type Error = &'static str; + fn preflight(&mut self, request: ServiceRequest) -> Result<(), Self::Error> { + self.preflight.push(request); + if self.unavailable { + Err("required publication owner unavailable") + } else { + Ok(()) + } + } + fn complete_data_and_maintenance( + &mut self, + _: &mut (), + request: DataCompletion, + ) -> Result<(), EffectFailure> { + self.step(EffectStage::DataCompletion)?; + self.data.push(request); + Ok(()) + } + fn synchronize_instructions(&mut self, _: &mut ()) -> Result<(), EffectFailure> { + self.step(EffectStage::InstructionSynchronization) + } + fn record_brbe_isb( + &mut self, + _: &mut (), + next_pc: u64, + ) -> Result<(), EffectFailure> { + self.step(EffectStage::BrbeRecord)?; + self.brbe_pc = Some(next_pc); + Ok(()) + } +} + +#[test] +fn all_isb_options_require_publication_before_optional_brbe() { + for option in 0..=15 { + for policy in [BrbeIsb::Absent, BrbeIsb::DoesNotRecord, BrbeIsb::Records] { + let context = Context { + brbe_isb: policy, + ..context() + }; + let word = ISB_BASE | option << OPTION_SHIFT; + let request = request(word, context); + assert_eq!( + request.kind(), + RequestKind::Instruction { + option: option as u8, + record_brbe: policy == BrbeIsb::Records + } + ); + let mut services = Services::default(); + assert_eq!(request.execute(SOURCE_PC, &mut services), Ok(SOURCE_PC + 4)); + assert_eq!(services.preflight[0].original_word, word); + assert_eq!(services.preflight[0].context, context); + assert_eq!(services.preflight[0].source_pc, SOURCE_PC); + if policy == BrbeIsb::Records { + assert_eq!( + services.calls, + [ + EffectStage::InstructionSynchronization, + EffectStage::BrbeRecord + ] + ); + assert_eq!(services.brbe_pc, Some(SOURCE_PC + 4)); + } else { + assert_eq!(services.calls, [EffectStage::InstructionSynchronization]); + assert_eq!(services.brbe_pc, None); + } + } + } +} + +#[test] +fn unavailable_owner_declines_before_any_host_or_guest_completion() { + for word in [DSB_BASE | 15 << OPTION_SHIFT, ISB_BASE | 15 << OPTION_SHIFT] { + let mut services = Services { + unavailable: true, + ..Services::default() + }; + assert_eq!( + request(word, context()).execute(SOURCE_PC, &mut services), + Err(ExecuteError::Preflight( + "required publication owner unavailable" + )) + ); + assert!(services.calls.is_empty()); + } +} + +#[test] +fn data_service_receives_effective_nxs_and_failure_does_not_retire() { + let base = context(); + let context = Context { + xs: Xs::Present, + profile: Profile { + el2_enabled: true, + ..base.profile + }, + hcrx: HcrxAccess::Enabled { + effective_value: HCRX_FNXS_MASK, + }, + ..base + }; + let word = DSB_BASE | 15 << OPTION_SHIFT; + let mut services = Services::default(); + assert_eq!( + request(word, context).execute(u64::MAX - 3, &mut services), + Ok(0) + ); + assert_eq!(services.calls, [EffectStage::DataCompletion]); + assert_eq!( + services.data, + [DataCompletion { + option: 15, + scope: Scope::OuterShareable, + requirement: Requirement::All, + nxs: true + }] + ); + assert_eq!(services.brbe_pc, None); + let mut services = Services { + fail: Some(EffectStage::DataCompletion), + ..Services::default() + }; + assert_eq!( + request(word, context).execute(SOURCE_PC, &mut services), + Err(ExecuteError::Effect { + stage: EffectStage::DataCompletion, + committed: CommittedPrefix::None, + failure: EffectFailure { + error: "injected", + completion: Completion::Partial + } + }) + ); + assert_eq!(services.calls, [EffectStage::DataCompletion]); +} + +#[test] +fn failed_brbe_retains_completed_isb_and_its_own_failure_completion() { + let context = Context { + brbe_isb: BrbeIsb::Records, + ..context() + }; + for (stage, prefix) in [ + ( + EffectStage::InstructionSynchronization, + CommittedPrefix::None, + ), + ( + EffectStage::BrbeRecord, + CommittedPrefix::InstructionsSynchronized, + ), + ] { + let mut services = Services { + fail: Some(stage), + ..Services::default() + }; + assert_eq!( + request(ISB_BASE | 15 << OPTION_SHIFT, context).execute(SOURCE_PC, &mut services), + Err(ExecuteError::Effect { + stage, + committed: prefix, + failure: EffectFailure { + error: "injected", + completion: Completion::Partial + } + }) + ); + assert_eq!( + services.calls.len(), + if stage == EffectStage::BrbeRecord { + 2 + } else { + 1 + } + ); + } +} + +#[test] +fn ordinary_no_el2_route_preserves_unreported_features_for_every_option() { + for option in 0..=15 { + let word = DSB_BASE | option << OPTION_SHIFT; + let resolution = resolve_ordinary_el2_disabled(word, context().profile); + if matches!(option, 0 | 4) { + assert_eq!(resolution, Resolution::NotHandled); + continue; + } + let Resolution::BackendRequired(request) = resolution else { + panic!("ordinary DSB requires real backend, got {resolution:?}"); + }; + assert_eq!(request.context().xs, Xs::Unreported); + assert_eq!(request.context().brbe_isb, BrbeIsb::Unreported); + let RequestKind::Data(data) = request.kind() else { + unreachable!() + }; + assert!(!data.nxs()); + assert_eq!(data.option(), option as u8); + let mut services = Services::default(); + assert_eq!(request.execute(SOURCE_PC, &mut services), Ok(SOURCE_PC + 4)); + assert_eq!(services.calls, [EffectStage::DataCompletion]); + assert_eq!(services.data, [data]); + let enabled = Profile { + el2_enabled: true, + ..context().profile + }; + assert!(matches!( + resolve_ordinary_el2_disabled(word, enabled), + Resolution::Unsupported(_) + )); + } + for word in [DSB_NXS_BASE, ISB_BASE, 0xd503_209f] { + assert_eq!( + resolve_ordinary_el2_disabled(word, context().profile), + Resolution::NotHandled + ); + } + for current_el in [ExceptionLevel::El2, ExceptionLevel::El3] { + assert!(matches!( + resolve_ordinary_el2_disabled( + DSB_BASE | 15 << OPTION_SHIFT, + Profile { + current_el, + ..context().profile + } + ), + Resolution::Unsupported(_) + )); + } +} + +#[test] +fn unreported_features_never_silently_disable_required_effects() { + let base = context(); + for encoded_scope in 0..4 { + let word = DSB_NXS_BASE | encoded_scope << NXS_SCOPE_SHIFT; + assert!(matches!( + resolve( + word, + Context { + xs: Xs::Unreported, + ..base + } + ), + Resolution::Unsupported(_) + )); + assert_eq!(resolve(word, base), Resolution::Undefined); + } + for option in 0..16 { + assert!(matches!( + resolve( + ISB_BASE | option << OPTION_SHIFT, + Context { + brbe_isb: BrbeIsb::Unreported, + ..base + } + ), + Resolution::Unsupported(_) + )); + if matches!(option, 0 | 4) { + continue; + } + assert!(matches!( + resolve( + DSB_BASE | option << OPTION_SHIFT, + Context { + xs: Xs::Unreported, + profile: Profile { + el2_enabled: true, + ..base.profile + }, + hcrx: HcrxAccess::Enabled { + effective_value: HCRX_FNXS_MASK + }, + ..base + } + ), + Resolution::Unsupported(_) + )); + } +} + +#[test] +fn every_data_option_reaches_service_with_its_effective_nxs() { + let base = context(); + let forced = Context { + xs: Xs::Present, + profile: Profile { + el2_enabled: true, + ..base.profile + }, + hcrx: HcrxAccess::Enabled { + effective_value: HCRX_FNXS_MASK, + }, + ..base + }; + let ordinary = (0..16) + .filter(|&option| !matches!(option, 0 | 4)) + .map(|option| DSB_BASE | option << OPTION_SHIFT); + let explicit = (0..4).map(|scope| DSB_NXS_BASE | scope << NXS_SCOPE_SHIFT); + for word in ordinary.chain(explicit) { + let request = request(word, forced); + let RequestKind::Data(data) = request.kind() else { + unreachable!() + }; + assert!(data.nxs()); + let mut services = Services::default(); + assert_eq!(request.execute(SOURCE_PC, &mut services), Ok(SOURCE_PC + 4)); + assert_eq!(services.data, [data]); + assert_eq!(services.calls, [EffectStage::DataCompletion]); + assert_eq!(services.preflight[0].original_word, word); + } +} + +#[test] +fn unreported_hcrx_is_allowed_only_when_irrelevant_or_proven_disabled() { + for current_el in [ + ExceptionLevel::El0, + ExceptionLevel::El1, + ExceptionLevel::El2, + ExceptionLevel::El3, + ] { + for el2_enabled in [false, true] { + for xs in [Xs::Unreported, Xs::Absent, Xs::Present] { + let context = Context { + profile: Profile { + current_el, + el2_enabled, + ..context().profile + }, + xs, + hcrx: HcrxAccess::Unreported, + brbe_isb: BrbeIsb::Absent, + }; + let ordinary = resolve(DSB_BASE | 15 << OPTION_SHIFT, context); + let requires_hcrx = el2_enabled + && xs != Xs::Absent + && matches!(current_el, ExceptionLevel::El0 | ExceptionLevel::El1); + if requires_hcrx { + assert!(matches!(ordinary, Resolution::Unsupported(_))); + } else { + let Resolution::BackendRequired(request) = ordinary else { + panic!("irrelevant/unavailable HCRX was not preserved: {ordinary:?}"); + }; + let RequestKind::Data(data) = request.kind() else { + unreachable!() + }; + assert!(!data.nxs()); + } + assert!(matches!( + resolve(ISB_BASE, context), + Resolution::BackendRequired(_) + )); + assert!(matches!( + resolve( + DSB_NXS_BASE, + Context { + xs: Xs::Present, + ..context + } + ), + Resolution::BackendRequired(_) + )); + } + } + } +} + +#[test] +fn every_failure_completion_preserves_current_stage_and_completed_prefix() { + for completion in [ + Completion::None, + Completion::Partial, + Completion::Complete, + Completion::Unknown, + ] { + for (stage, word, committed, calls) in [ + ( + EffectStage::DataCompletion, + DSB_BASE | 15 << OPTION_SHIFT, + CommittedPrefix::None, + 1, + ), + ( + EffectStage::InstructionSynchronization, + ISB_BASE | 15 << OPTION_SHIFT, + CommittedPrefix::None, + 1, + ), + ( + EffectStage::BrbeRecord, + ISB_BASE | 15 << OPTION_SHIFT, + CommittedPrefix::InstructionsSynchronized, + 2, + ), + ] { + let mut services = Services { + fail: Some(stage), + completion: Some(completion), + ..Services::default() + }; + let context = Context { + brbe_isb: BrbeIsb::Records, + ..context() + }; + assert_eq!( + request(word, context).execute(SOURCE_PC, &mut services), + Err(ExecuteError::Effect { + stage, + committed, + failure: EffectFailure { + error: "injected", + completion + } + }) + ); + assert_eq!(services.calls.len(), calls); + assert_eq!(services.brbe_pc, None); + } + } +} + +#[test] +fn prepared_permit_is_consumed_without_repeating_preflight() { + let mut services = Services::default(); + let request = request(DSB_BASE | 15 << OPTION_SHIFT, context()); + services + .preflight(request.service_request(SOURCE_PC)) + .unwrap(); + assert!(services.calls.is_empty()); + assert_eq!( + request.execute_preflighted(SOURCE_PC, &mut services, ()), + Ok(SOURCE_PC + 4) + ); + assert_eq!(services.preflight.len(), 1); + assert_eq!(services.calls, [EffectStage::DataCompletion]); +} diff --git a/crates/stela-runtime/src/system/execution.rs b/crates/stela-runtime/src/system/execution.rs index 257ed536d4..487309bb32 100644 --- a/crates/stela-runtime/src/system/execution.rs +++ b/crates/stela-runtime/src/system/execution.rs @@ -579,6 +579,9 @@ impl Dispatcher for Execution<'_, B> { SystemOperation::InstructionSynchronization { .. } => Err(Failure::Unsupported( "instruction synchronization requires the actual source publication owner", )), + SystemOperation::Synchronization(_) => Err(Failure::Unsupported( + "synchronization requires the retained resource-specific System owner", + )), } } } diff --git a/dev/test_translation_progress.py b/dev/test_translation_progress.py index e6ecadb3ef..e082858438 100644 --- a/dev/test_translation_progress.py +++ b/dev/test_translation_progress.py @@ -2186,6 +2186,44 @@ class SystemServiceProfileTests(unittest.TestCase): progress.compile_probe('cli', 0x9ac21020, Path(directory), mode='service', service_profile=progress.SYSTEM_PROFILE, run=self.fake_compiler(mutation)) + def test_el1_platform_profile_keeps_source_bound_carrier_and_distinct_flags(self): + default, additional = self.contracts() + additional[progress.EL1_PLATFORM_PROFILE] = { + 'id': progress.EL1_PLATFORM_PROFILE, 'compiler_mode': 'service', + 'abi': progress.EL1_PLATFORM_ABI, 'outside_scope': ['Unowned platform effects']} + self.assertIn(progress.EL1_PLATFORM_PROFILE, + progress.validate_service_profiles(default, additional)) + def el1_manifest(manifest, native): + manifest['abi'] = progress.EL1_PLATFORM_ABI + manifest['memory_requirements'] = None + return native + with tempfile.TemporaryDirectory() as directory: + result = progress.compile_probe('cli', 0xd5033f9f, Path(directory), mode='service', + service_profile=progress.EL1_PLATFORM_PROFILE, run=self.fake_compiler(el1_manifest)) + self.assertIn('--el1-platform', self.command) + self.assertNotIn('--system-boundaries', self.command) + self.assertNotIn('--software-pauth', self.command) + self.assertEqual(result['abi'], progress.EL1_PLATFORM_ABI) + + def test_el1_platform_probe_refuses_wrong_body_abi_map_target_or_memory_contract(self): + for field in ('body', 'abi', 'source_map', 'target_cpu', 'memory_requirements', + 'missing_memory_requirements'): + def mutation(manifest, native): + manifest['abi'] = progress.EL1_PLATFORM_ABI + manifest['memory_requirements'] = None + if field == 'body': + return native[:-1] + bytes([0x90]) + if field == 'missing_memory_requirements': + del manifest['memory_requirements'] + return native + manifest[field] = {'abi': progress.SYSTEM_ABI, + 'source_map': [[progress.SYSTEM_GUEST_BASE + 4, 0]], + 'target_cpu': 'x86_64-baseline+cx16', 'memory_requirements': {}}[field] + return native + with tempfile.TemporaryDirectory() as directory, self.subTest(field=field), self.assertRaises(ValueError): + progress.compile_probe('cli', 0xd5033f9f, Path(directory), mode='service', + service_profile=progress.EL1_PLATFORM_PROFILE, run=self.fake_compiler(mutation)) + def test_service_profile_cannot_leak_into_leaf_or_unknown_lane(self): for mode, profile in [('leaf', progress.SYSTEM_PROFILE), ('service', 'unknown')]: with tempfile.TemporaryDirectory() as directory, self.assertRaises(ValueError): diff --git a/dev/translation-progress.py b/dev/translation-progress.py index 3d91c2b0e2..888a64bb6a 100644 --- a/dev/translation-progress.py +++ b/dev/translation-progress.py @@ -32,6 +32,8 @@ CHECKED_MEMORY_ABI = 'x86_64-sysv-guest-state-v3-context-block-exit-checked-gpr- BASELINE_CPU_TARGET = 'x86_64-baseline' SYSTEM_ABI = 'x86_64-sysv-guest-state-v2-block-exit-system-v1' SYSTEM_EXIT_KIND = 11 +EL1_PLATFORM_PROFILE = 'el1-platform-v1' +EL1_PLATFORM_ABI = 'x86_64-sysv-guest-state-v3-context-block-exit-el1-platform-v1' MOVABS_RAX_IMM64 = b'\x48\xb8' MOV_EDX_IMM32 = b'\xba' X86_RET = b'\xc3' @@ -45,6 +47,7 @@ SERVICE_DECODERS = { LEAF_DECODER_MATTRS = ('+sme2', '+sve2p1', '+lut', '+faminmax', '+fp8') SYSTEM_GUEST_BASE = 0x10000000 SERVICE_BINDINGS = { + EL1_PLATFORM_PROFILE: (EL1_PLATFORM_ABI, ('--el1-platform', '--cpu-target', BASELINE_CPU_TARGET)), SERVICE_PROFILE: (SERVICE_ABI, ('--software-pauth', '--software-clock')), SYSTEM_PROFILE: (SYSTEM_ABI, ('--system-boundaries', '--cpu-target', BASELINE_CPU_TARGET)), CHECKED_MEMORY_PROFILE: (CHECKED_MEMORY_ABI, ('--checked-memory-sa0-off', '--cpu-target', BASELINE_CPU_TARGET)), @@ -678,11 +681,13 @@ def compile_probe(cli, word, directory, expect_failure=None, run=subprocess.run, native = output / 'native.bin' if manifest.get('native_sha256') != sha256(native) or native.stat().st_size == 0: raise ValueError('Compiler probe native output identity mismatch') - if mode == 'service' and selected_service == SYSTEM_PROFILE: + if mode == 'service' and selected_service in (SYSTEM_PROFILE, EL1_PLATFORM_PROFILE): expected_native = (MOVABS_RAX_IMM64 + struct.pack('