Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c26f78bfce |
No files matched your search
@@ -43,27 +43,6 @@ pub const MAINTENANCE_WRITE: &str = "--maintenance-write";
|
||||
pub const SINGLE_USER: &str = "--single-user";
|
||||
/// Keeps the newest presented frame at one logged address.
|
||||
pub const SCANOUT_MIRROR: &str = "--scanout-mirror";
|
||||
/// Verify the hosted Reims device through Stela's owned host PCI mappings.
|
||||
pub const PROBE_HOSTED_REIMS: &str = "--probe-hosted-reims";
|
||||
/// Place the hosted Reims apertures at the supplied ARM physical base.
|
||||
pub const HOSTED_REIMS_BASE: &str = "--hosted-reims-base";
|
||||
/// Wire hosted Reims completions to an ARM AIC vector.
|
||||
pub const HOSTED_REIMS_IRQ: &str = "--hosted-reims-irq";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HostedReimsIrq {
|
||||
Auto,
|
||||
Vector(u32),
|
||||
}
|
||||
|
||||
impl fmt::Display for HostedReimsIrq {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Auto => formatter.write_str("auto"),
|
||||
Self::Vector(vector) => write!(formatter, "{vector}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub const WIFI: &str = "--wifi";
|
||||
pub const WIFI_KEY: &str = "--wifi-key";
|
||||
pub const WIFI_COUNTRY: &str = "--wifi-country";
|
||||
@@ -240,9 +219,6 @@ pub struct System {
|
||||
/// Keep the newest presented frame in host memory for a debugger to read:
|
||||
/// a passed-through GPU's picture otherwise leaves only through its port.
|
||||
pub scanout_mirror: bool,
|
||||
pub probe_hosted_reims: bool,
|
||||
pub hosted_reims_base: Option<u64>,
|
||||
pub hosted_reims_irq: Option<HostedReimsIrq>,
|
||||
/// The NVRAM boot volume the loader chose (`--boot-volume`), naming the
|
||||
/// Preboot disk's container and volume group.
|
||||
pub boot_volume: Option<BootVolume>,
|
||||
@@ -398,9 +374,6 @@ impl Default for System {
|
||||
single_user: false,
|
||||
bundle_repair: false,
|
||||
scanout_mirror: false,
|
||||
probe_hosted_reims: false,
|
||||
hosted_reims_base: None,
|
||||
hosted_reims_irq: None,
|
||||
boot_command: None,
|
||||
upgrade: false,
|
||||
recovery: None,
|
||||
@@ -830,9 +803,6 @@ impl fmt::Display for System {
|
||||
line.flag(SINGLE_USER, self.single_user)?;
|
||||
line.flag(boot_selection::BUNDLE_REPAIR_OPTION, self.bundle_repair)?;
|
||||
line.flag(SCANOUT_MIRROR, self.scanout_mirror)?;
|
||||
line.flag(PROBE_HOSTED_REIMS, self.probe_hosted_reims)?;
|
||||
line.value(HOSTED_REIMS_BASE, self.hosted_reims_base.map(Hex))?;
|
||||
line.value(HOSTED_REIMS_IRQ, self.hosted_reims_irq)?;
|
||||
line.flag(boot_selection::UPGRADE_OPTION, self.upgrade)?;
|
||||
line.flag(
|
||||
boot_selection::PAIRED_RECOVERY_OPTION,
|
||||
|
||||
@@ -26,8 +26,6 @@ pub enum Error {
|
||||
AudioMode,
|
||||
DumpRegister,
|
||||
Number,
|
||||
HostedReimsBase,
|
||||
HostedReimsIrq,
|
||||
UrlScheme,
|
||||
UrlPath,
|
||||
UrlHost,
|
||||
@@ -146,12 +144,6 @@ impl Error {
|
||||
}
|
||||
Self::DumpRegister => "a dump register is x0 to x30",
|
||||
Self::Number => "invalid number in system options",
|
||||
Self::HostedReimsBase => {
|
||||
"--hosted-reims-base needs one nonzero 1 GiB aligned base and excludes --probe-hosted-reims"
|
||||
}
|
||||
Self::HostedReimsIrq => {
|
||||
"--hosted-reims-irq needs auto or one AIC vector, with --hosted-reims-base"
|
||||
}
|
||||
Self::UrlScheme => "URL scheme must be http or https",
|
||||
Self::UrlPath => "URL without a path",
|
||||
Self::UrlHost => "URL without a host",
|
||||
|
||||
@@ -39,26 +39,6 @@ impl ParseState<'_> {
|
||||
MAINTENANCE_WRITE => options.maintenance_write = true,
|
||||
SINGLE_USER => options.single_user = true,
|
||||
SCANOUT_MIRROR => options.scanout_mirror = true,
|
||||
PROBE_HOSTED_REIMS => options.probe_hosted_reims = true,
|
||||
HOSTED_REIMS_BASE => {
|
||||
let base = number(value().ok_or(Error::MissingNumericValue)?)?;
|
||||
if options.hosted_reims_base.replace(base).is_some() {
|
||||
return Err(Error::HostedReimsBase);
|
||||
}
|
||||
}
|
||||
HOSTED_REIMS_IRQ => {
|
||||
let requested = value().ok_or(Error::HostedReimsIrq)?;
|
||||
let irq = if requested == "auto" {
|
||||
HostedReimsIrq::Auto
|
||||
} else {
|
||||
let vector = u32::try_from(number(requested)?)
|
||||
.map_err(|_| Error::HostedReimsIrq)?;
|
||||
HostedReimsIrq::Vector(vector)
|
||||
};
|
||||
if options.hosted_reims_irq.replace(irq).is_some() {
|
||||
return Err(Error::HostedReimsIrq);
|
||||
}
|
||||
}
|
||||
"--monitor-trace" => options.monitor_trace = true,
|
||||
"--display-trace" => options.display_trace = true,
|
||||
"--native-shared-check" => flag(
|
||||
|
||||
@@ -137,45 +137,6 @@ fn scanout_mirror_round_trips() {
|
||||
assert!(round_trip(&format!("--system {SCANOUT_MIRROR}")).scanout_mirror);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_reims_probe_round_trips() {
|
||||
assert!(!round_trip("--system").probe_hosted_reims);
|
||||
assert!(round_trip(&format!("--system {PROBE_HOSTED_REIMS}")).probe_hosted_reims);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_reims_guest_base_must_be_aligned_and_excludes_probe() {
|
||||
assert_eq!(
|
||||
round_trip("--system --hosted-reims-base 0x200000000").hosted_reims_base,
|
||||
Some(0x200000000)
|
||||
);
|
||||
for invalid in [
|
||||
"--system --hosted-reims-base 0",
|
||||
"--system --hosted-reims-base 0x200004000",
|
||||
"--system --hosted-reims-base 0x200000000 --probe-hosted-reims",
|
||||
] {
|
||||
assert_eq!(System::parse(invalid).unwrap_err(), Error::HostedReimsBase);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_reims_irq_requires_a_guest_aperture() {
|
||||
assert_eq!(
|
||||
round_trip("--system --hosted-reims-base 0x300000000 --hosted-reims-irq 740")
|
||||
.hosted_reims_irq,
|
||||
Some(HostedReimsIrq::Vector(740))
|
||||
);
|
||||
assert_eq!(
|
||||
round_trip("--system --hosted-reims-base 0x300000000 --hosted-reims-irq auto")
|
||||
.hosted_reims_irq,
|
||||
Some(HostedReimsIrq::Auto)
|
||||
);
|
||||
assert_eq!(
|
||||
System::parse("--system --hosted-reims-irq 740").unwrap_err(),
|
||||
Error::HostedReimsIrq
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maintenance_writes_require_an_explicit_preboot_selection() {
|
||||
let ordinary = round_trip(&format!("--system --preboot {DISK}"));
|
||||
|
||||
@@ -8,14 +8,6 @@ pub(super) fn system(options: &System) -> Result<(), Error> {
|
||||
install(options)?;
|
||||
boot_selection(options)?;
|
||||
dram(options)?;
|
||||
if options.hosted_reims_base.is_some_and(|base| {
|
||||
options.probe_hosted_reims || stela_contracts::reims_hosted::Apertures::at(base).is_none()
|
||||
}) {
|
||||
return Err(Error::HostedReimsBase);
|
||||
}
|
||||
if options.hosted_reims_irq.is_some() && options.hosted_reims_base.is_none() {
|
||||
return Err(Error::HostedReimsIrq);
|
||||
}
|
||||
if options.audio_own_hpet && options.audio_check.is_none() {
|
||||
return Err(Error::Constraint(Constraint::AudioHpetDependency));
|
||||
}
|
||||
|
||||
@@ -19,21 +19,6 @@ pub fn place(ram: &mut [RamRange], base: u64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay the DRAM ranges of `ram` out end to end from `base`, keeping any range
|
||||
/// whose host physical address equals `fixed_host` at its fixed guest address
|
||||
/// and keeping `ram` sorted by guest physical address.
|
||||
pub fn place_except_host(ram: &mut [RamRange], base: u64, fixed_host: Option<u64>) {
|
||||
let mut guest = base;
|
||||
for range in ram.iter_mut() {
|
||||
if Some(range.host) == fixed_host {
|
||||
continue;
|
||||
}
|
||||
range.guest = guest;
|
||||
guest += range.bytes;
|
||||
}
|
||||
ram.sort_by_key(|range| range.guest);
|
||||
}
|
||||
|
||||
/// The longest RAM run starting at `guest`, as (host physical, bytes).
|
||||
pub fn run(ram: &[RamRange], guest: u64) -> Option<(u64, u64)> {
|
||||
let index = ram.partition_point(|range| range.guest <= guest);
|
||||
|
||||
Generated
-1
@@ -1135,7 +1135,6 @@ dependencies = [
|
||||
"stela-fingerprint",
|
||||
"stela-formats",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -30,10 +30,6 @@ test = false
|
||||
[features]
|
||||
default = []
|
||||
diagnostics = ["stela-drivers/irq-diagnostics"]
|
||||
# Include the arm64e device driver built by cargo xtask guest.
|
||||
hosted-reims-kext = []
|
||||
# Include a prepared ReimsGraphics KEXT instead of the diagnostic driver.
|
||||
hosted-reims-graphics = []
|
||||
native-profile = ["stela-soc/native-profile", "stela-engine/native-profile"]
|
||||
# NVK, NIR and NAK in the image, from `cargo xtask gpu nvk`.
|
||||
nvk = ["dep:stela-mesa", "stela-drivers/metal-linked"]
|
||||
|
||||
@@ -33,20 +33,6 @@ mod kext {
|
||||
"/../../target/guest/StelaGPU.kext.rs"
|
||||
));
|
||||
}
|
||||
#[cfg(all(feature = "hosted-reims-kext", not(feature = "hosted-reims-graphics")))]
|
||||
mod hosted_reims_kext {
|
||||
include!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../target/guest/ReimsHostedDevice.kext.rs"
|
||||
));
|
||||
}
|
||||
#[cfg(feature = "hosted-reims-graphics")]
|
||||
mod hosted_reims_graphics {
|
||||
include!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../target/guest/ReimsGraphics.kext.rs"
|
||||
));
|
||||
}
|
||||
#[cfg(feature = "nvk")]
|
||||
mod refused;
|
||||
#[cfg(feature = "nvk")]
|
||||
@@ -2019,36 +2005,17 @@ pub(super) fn no_metal_device() -> Option<&'static str> {
|
||||
Some("this stela.efi was built without GPU drivers (the `nvk` feature)")
|
||||
}
|
||||
|
||||
/// The GPU kexts this boot links into its system.
|
||||
pub(super) fn kexts(_hosted_reims: bool) -> Vec<stela_loader::aux_kc::Kext<'static>> {
|
||||
#[allow(unused_mut)]
|
||||
let mut bundles = Vec::new();
|
||||
/// The kexts a boot that gives the GPUs to nouveau links into its system.
|
||||
pub(super) fn kexts() -> Vec<stela_loader::aux_kc::Kext<'static>> {
|
||||
#[cfg(feature = "nvk")]
|
||||
bundles.push(stela_loader::aux_kc::Kext {
|
||||
return alloc::vec![stela_loader::aux_kc::Kext {
|
||||
info: kext::INFO,
|
||||
objects: kext::OBJECTS.to_vec(),
|
||||
bundle_path: "/Library/Extensions/StelaGPU.kext".into(),
|
||||
trusted_code: kext::TRUSTED_CODE.to_vec(),
|
||||
});
|
||||
#[cfg(all(feature = "hosted-reims-kext", not(feature = "hosted-reims-graphics")))]
|
||||
if _hosted_reims {
|
||||
bundles.push(stela_loader::aux_kc::Kext {
|
||||
info: hosted_reims_kext::INFO,
|
||||
objects: hosted_reims_kext::OBJECTS.to_vec(),
|
||||
bundle_path: "/Library/Extensions/ReimsHostedDevice.kext".into(),
|
||||
trusted_code: hosted_reims_kext::TRUSTED_CODE.to_vec(),
|
||||
});
|
||||
}
|
||||
#[cfg(feature = "hosted-reims-graphics")]
|
||||
if _hosted_reims {
|
||||
bundles.push(stela_loader::aux_kc::Kext {
|
||||
info: hosted_reims_graphics::INFO,
|
||||
objects: hosted_reims_graphics::OBJECTS.to_vec(),
|
||||
bundle_path: "/Library/Extensions/ReimsGraphics.kext".into(),
|
||||
trusted_code: hosted_reims_graphics::TRUSTED_CODE.to_vec(),
|
||||
});
|
||||
}
|
||||
bundles
|
||||
}];
|
||||
#[cfg(not(feature = "nvk"))]
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Takes the display for the GPUs [`open`] bound, in the monitor's own mode
|
||||
|
||||
@@ -120,14 +120,7 @@ impl Owner {
|
||||
/// backing, before a guest regime, frame or registered RAM exists: the
|
||||
/// host drivers that read a bundle's DRAM base run after `install`.
|
||||
/// Root contexts and MMIO views see only the host spans, which stay.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn place_ram(&mut self, base: u64) -> Result<()> {
|
||||
self.place_ram_except_host(base, None)
|
||||
}
|
||||
|
||||
/// [`Self::place_ram`], keeping any range backed by `fixed_host` at its
|
||||
/// fixed guest physical address and maintaining guest-address order.
|
||||
pub(crate) fn place_ram_except_host(&mut self, base: u64, fixed_host: Option<u64>) -> Result<()> {
|
||||
if current() != self.local.as_ptr() {
|
||||
return Err(refuse!("native Host owner migrated"));
|
||||
}
|
||||
@@ -137,7 +130,7 @@ impl Owner {
|
||||
"guest RAM is placed before the guest's memory is registered"
|
||||
));
|
||||
}
|
||||
super::ram::place_except_host(&mut state.ram, base, fixed_host);
|
||||
super::ram::place(&mut state.ram, base);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -109,7 +109,7 @@ fn from_disk(
|
||||
} else if let Some(kind) = options.recovery {
|
||||
bundle::recovery_from_disk(partition, kind, options.boot_volume, &defaults)
|
||||
} else {
|
||||
let kexts = gpu::kexts(options.hosted_reims_irq.is_some());
|
||||
let kexts = gpu::kexts();
|
||||
let request = installed::Request {
|
||||
volume: options.boot_volume,
|
||||
kexts: &kexts,
|
||||
@@ -157,7 +157,6 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
|
||||
if options.boots_macos()
|
||||
&& !options.single_user
|
||||
&& !options.bundle_repair
|
||||
&& host.devices.hosted_reims.is_none()
|
||||
&& let Some(reason) = gpu::no_metal_device()
|
||||
{
|
||||
output::fatal(format_args!("macOS cannot run without a GPU: {reason}"));
|
||||
@@ -397,37 +396,6 @@ fn open_host(
|
||||
// read from its disk by the host drivers, which run after the host is
|
||||
// installed; the placements then move there (`HostOwner::place_ram`).
|
||||
let mut ram = guest_ram(handoff, options).unwrap_or_else(|error| output::fatal(error));
|
||||
let fixed_reims_host = if let Some(base) = options.hosted_reims_base
|
||||
&& handoff.hosted_reims_region.bytes == stela_contracts::reims_hosted::REGION_BYTES
|
||||
{
|
||||
let apertures = stela_contracts::reims_hosted::Apertures::at(base)
|
||||
.unwrap_or_else(|| output::fatal("invalid hosted Reims guest address"));
|
||||
if ram.iter().any(|range| apertures.overlaps(range.guest, range.bytes)) {
|
||||
output::fatal("hosted Reims apertures overlap guest RAM");
|
||||
}
|
||||
// SAFETY: BSP at CPL0 with IF=0 and APs parked, before root_identity
|
||||
// capture and AP startup so every core adopts the WB MTRR.
|
||||
unsafe {
|
||||
crate::native_memory::ensure_writeback_mtrr(
|
||||
handoff.hosted_reims_region.physical,
|
||||
handoff.hosted_reims_region.bytes,
|
||||
)
|
||||
}
|
||||
.unwrap_or_else(|error| {
|
||||
output::fatal(format_args!(
|
||||
"hosted Reims BAR2 write-back MTRR refused: {error:?}"
|
||||
))
|
||||
});
|
||||
ram.push(RamRange {
|
||||
guest: apertures.region,
|
||||
host: handoff.hosted_reims_region.physical,
|
||||
bytes: handoff.hosted_reims_region.bytes,
|
||||
});
|
||||
ram.sort_by_key(|range| range.guest);
|
||||
Some(handoff.hosted_reims_region.physical)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// The translation store the loader read, and its partition when the
|
||||
// pack can be rewritten.
|
||||
let translation_store = handoff.files[..handoff.file_count]
|
||||
@@ -604,22 +572,15 @@ fn open_host(
|
||||
options.dram_base = base;
|
||||
}
|
||||
}
|
||||
ram::place_except_host(&mut ram, options.dram_base, fixed_reims_host);
|
||||
ram::place(&mut ram, options.dram_base);
|
||||
host_owner
|
||||
.place_ram_except_host(options.dram_base, fixed_reims_host)
|
||||
.place_ram(options.dram_base)
|
||||
.unwrap_or_else(|error| output::fatal(error));
|
||||
for range in &ram {
|
||||
if Some(range.host) == fixed_reims_host {
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims RAM pa={:#x} bytes={:#x} host={:#x}\n",
|
||||
range.guest, range.bytes, range.host
|
||||
));
|
||||
} else {
|
||||
output::arguments(format_args!(
|
||||
"GUEST DRAM pa={:#x} bytes={:#x} host={:#x}\n",
|
||||
range.guest, range.bytes, range.host
|
||||
));
|
||||
}
|
||||
output::arguments(format_args!(
|
||||
"GUEST DRAM pa={:#x} bytes={:#x} host={:#x}\n",
|
||||
range.guest, range.bytes, range.host
|
||||
));
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(url) = &options.network_check {
|
||||
@@ -1029,7 +990,6 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
guest_network,
|
||||
host_disks,
|
||||
fdr: mut fdr_device,
|
||||
hosted_reims,
|
||||
..
|
||||
},
|
||||
ram: worker_ram,
|
||||
@@ -1056,9 +1016,9 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
.map(|assigned| gpu::gate::place(&mut assigned.tree))
|
||||
.unwrap_or_default();
|
||||
#[cfg(feature = "nvk")]
|
||||
let metal_device = !gpu_gates.is_empty() || hosted_reims.is_some();
|
||||
let metal_device = !gpu_gates.is_empty();
|
||||
#[cfg(not(feature = "nvk"))]
|
||||
let metal_device = hosted_reims.is_some();
|
||||
let metal_device = false;
|
||||
if let Some(assigned) = &mut assigned
|
||||
&& options.hides_agx(metal_device)
|
||||
{
|
||||
@@ -1079,19 +1039,6 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
));
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "hosted-reims-graphics")]
|
||||
if let Some(assigned) = &mut assigned
|
||||
&& hosted_reims.is_some()
|
||||
{
|
||||
let retired = stela_loader::devices::hide_external_outputs(&mut assigned.tree);
|
||||
if !retired.is_empty() {
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims hides DCP external outputs ({} nodes) so ReimsGraphics is the sole display\n",
|
||||
retired.len()
|
||||
));
|
||||
hidden_devices.extend(retired);
|
||||
}
|
||||
}
|
||||
hardware_step("canonical-ram");
|
||||
// SAFETY: all raw guest input copies have ended, AP executors are waiting
|
||||
// for their guest contexts, and no guest/device DMA producer has entered.
|
||||
@@ -1122,35 +1069,6 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
boot_processor,
|
||||
));
|
||||
}
|
||||
let direct_reims_region =
|
||||
handoff.hosted_reims_region.bytes == stela_contracts::reims_hosted::REGION_BYTES;
|
||||
let reims = hosted_reims.as_ref().map(|_| {
|
||||
let (apertures, vector) = hosted_reims_placement(
|
||||
options,
|
||||
&worker_ram,
|
||||
direct_reims_region.then_some(handoff.hosted_reims_region.physical),
|
||||
board.as_ref(),
|
||||
assigned.as_ref().map(|assigned| &assigned.tree),
|
||||
);
|
||||
if let (Some(assigned), Some(vector)) = (&mut assigned, vector) {
|
||||
stela_loader::stela_gpu::place_hosted_reims(&mut assigned.tree, apertures, vector)
|
||||
.unwrap_or_else(|error| output::fatal(error));
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims DeviceTree /arm-io/reims-graphics irq={vector}\n"
|
||||
));
|
||||
}
|
||||
(apertures, vector)
|
||||
});
|
||||
let projected_bytes = assigned.as_ref().map(|assigned| assigned.tree.serialize());
|
||||
if reims.is_some_and(|(_, vector)| vector.is_some())
|
||||
&& let (Some(previous), Some(bytes)) = (&board, &projected_bytes)
|
||||
{
|
||||
let described = board::board(bytes).unwrap_or_else(|error| output::fatal(error));
|
||||
if described.aic != previous.aic {
|
||||
output::fatal("Reims DeviceTree changed the board's AIC capacity");
|
||||
}
|
||||
board = Some(described);
|
||||
}
|
||||
// The verified image is placed and its provenance is owned. The
|
||||
// remaining device and flash consumers read board firmware by name.
|
||||
if let Some(files) = &mut built {
|
||||
@@ -1160,6 +1078,7 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
.unwrap_or_default();
|
||||
files.retain(|(name, _)| firmware.contains(name));
|
||||
}
|
||||
let projected_bytes = assigned.as_ref().map(|assigned| assigned.tree.serialize());
|
||||
let tree = projected_bytes
|
||||
.as_deref()
|
||||
.or_else(|| loaded_tree.as_ref().map(|tree| tree.bytes()));
|
||||
@@ -1218,33 +1137,6 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
loaded_source.as_ref(),
|
||||
tree,
|
||||
);
|
||||
if let Some((transport, (apertures, vector))) = hosted_reims.zip(reims) {
|
||||
let installed = match (direct_reims_region, vector) {
|
||||
(true, Some(vector)) => {
|
||||
devices.add_hosted_reims_direct_region_with_interrupt(apertures, transport, vector)
|
||||
}
|
||||
(true, None) => devices.add_hosted_reims_direct_region(apertures, transport),
|
||||
(false, Some(vector)) => {
|
||||
devices.add_hosted_reims_with_interrupt(apertures, transport, vector)
|
||||
}
|
||||
(false, None) => devices.add_hosted_reims(apertures, transport),
|
||||
};
|
||||
installed
|
||||
.unwrap_or_else(|error| output::fatal(format_args!("hosted Reims guest bus: {error:?}")));
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims MMIO registers={:#x} region={:#x} doorbells={:#x}\n",
|
||||
apertures.registers, apertures.region, apertures.doorbells
|
||||
));
|
||||
if direct_reims_region {
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims region direct-mapped RAM pa={:#x} host={:#x}\n",
|
||||
apertures.region, handoff.hosted_reims_region.physical
|
||||
));
|
||||
}
|
||||
if let Some(vector) = vector {
|
||||
output::arguments(format_args!("GUEST Reims AIC vector={vector}\n"));
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "nvk")]
|
||||
hardware_step("add-gpu-gates");
|
||||
#[cfg(feature = "nvk")]
|
||||
@@ -3227,7 +3119,6 @@ struct HostDevices {
|
||||
guest_network: Option<network::GuestNetwork>,
|
||||
host_disks: storage::HostDisks,
|
||||
fdr: Option<alloc::boxed::Box<dyn stela_drivers::block::BlockDevice>>,
|
||||
hosted_reims: Option<stela_drivers::probe::reims_hosted::PciTransport>,
|
||||
}
|
||||
|
||||
/// Probe the host's devices once, with the native services when the
|
||||
@@ -3251,7 +3142,6 @@ fn start_devices(
|
||||
} = wanted;
|
||||
let mut fdr_device = None;
|
||||
let mut host_usb = None;
|
||||
let mut hosted_reims = None;
|
||||
let mut host_bluetooth: Option<bluetooth::HostBluetooth> = None;
|
||||
let (services, medium, preboot, host_input, host_network, usb_disks, guest_network, host_disks) =
|
||||
if targets.is_empty()
|
||||
@@ -3262,8 +3152,6 @@ fn start_devices(
|
||||
&& options.usb_storage.is_empty()
|
||||
&& !options.external_disks
|
||||
&& !options.guest_network
|
||||
&& !options.probe_hosted_reims
|
||||
&& options.hosted_reims_base.is_none()
|
||||
&& translation_store.is_none()
|
||||
&& fdr_partition.is_none()
|
||||
{
|
||||
@@ -3445,11 +3333,6 @@ fn start_devices(
|
||||
crate::status::warn(&stela_boot_core::work_status::gpu_without_work(reason));
|
||||
}
|
||||
});
|
||||
if options.probe_hosted_reims || options.hosted_reims_base.is_some() {
|
||||
let work = work.unwrap_or_else(|error| output::fatal(error));
|
||||
hosted_reims =
|
||||
prepare_hosted_reims(handoff, options, &gpus, work, mmio, remappers, host_acpi);
|
||||
}
|
||||
if options.boots_macos()
|
||||
&& let Ok(work) = work
|
||||
&& open_gpus(
|
||||
@@ -3616,100 +3499,5 @@ fn start_devices(
|
||||
guest_network,
|
||||
host_disks,
|
||||
fdr: fdr_device,
|
||||
hosted_reims,
|
||||
}
|
||||
}
|
||||
|
||||
fn hosted_reims_placement(
|
||||
options: &Options,
|
||||
ram: &[RamRange],
|
||||
fixed_reims_host: Option<u64>,
|
||||
board: Option<&board::Board>,
|
||||
tree: Option<&DeviceTree>,
|
||||
) -> (stela_contracts::reims_hosted::Apertures, Option<u32>) {
|
||||
use stela_boot_core::options::HostedReimsIrq;
|
||||
use stela_contracts::reims_hosted::Apertures;
|
||||
let apertures = options
|
||||
.hosted_reims_base
|
||||
.and_then(Apertures::at)
|
||||
.unwrap_or_else(|| output::fatal("invalid hosted Reims guest address"));
|
||||
if ram
|
||||
.iter()
|
||||
.filter(|ram| Some(ram.host) != fixed_reims_host)
|
||||
.any(|ram| apertures.overlaps(ram.guest, ram.bytes))
|
||||
{
|
||||
output::fatal("hosted Reims apertures overlap guest RAM");
|
||||
}
|
||||
let vector = options.hosted_reims_irq.map(|requested| {
|
||||
let (layout, inputs) = board.map_or_else(
|
||||
|| (AicLayout::aic2(J473_AIC_EVENT, J473_AIC_TIMESTAMPS), J473_AIC.1),
|
||||
|board| (board.aic.layout, board.aic.inputs),
|
||||
);
|
||||
let occupied = tree.map_or_else(
|
||||
|| alloc::vec![J473_UART.2, J473_WDT.2],
|
||||
|tree| stela_loader::stela_gpu::aic_vectors_in_use(tree)
|
||||
.unwrap_or_else(|error| output::fatal(error)),
|
||||
);
|
||||
let vector = match requested {
|
||||
HostedReimsIrq::Auto => layout
|
||||
.free_vector(inputs, &occupied)
|
||||
.unwrap_or_else(|| output::fatal("hosted Reims has no free AIC vector")),
|
||||
HostedReimsIrq::Vector(vector) => vector,
|
||||
};
|
||||
if occupied.contains(&vector) {
|
||||
output::fatal("hosted Reims AIC vector is already assigned");
|
||||
}
|
||||
vector
|
||||
});
|
||||
(apertures, vector)
|
||||
}
|
||||
|
||||
fn prepare_hosted_reims(
|
||||
handoff: &Handoff,
|
||||
options: &Options,
|
||||
gpus: &[stela_drivers::gpu::Adapter],
|
||||
work: &kernel_work::KernelWork,
|
||||
mmio: Option<&'static crate::native_mmio::Source>,
|
||||
remappers: &'static remapping::Remappers,
|
||||
acpi: Option<&'static aml::HostAcpi>,
|
||||
) -> Option<stela_drivers::probe::reims_hosted::PciTransport> {
|
||||
use stela_drivers::{gpu::Vendor, probe::reims_hosted};
|
||||
let mut matches = gpus.iter().filter(|adapter| {
|
||||
adapter.vendor == Vendor::Other(reims_hosted::VENDOR)
|
||||
&& adapter.device == reims_hosted::DEVICE
|
||||
});
|
||||
let Some(adapter) = matches.next().filter(|_| matches.next().is_none()) else {
|
||||
output::fatal("expected one hosted Reims PCI device");
|
||||
};
|
||||
let mmio = mmio.unwrap_or_else(|| output::fatal("hosted Reims needs native MMIO"));
|
||||
let address = adapter.address;
|
||||
let heap = handoff.heap.physical..handoff.heap.physical + handoff.heap.bytes;
|
||||
let clock = handoff.tsc_hz;
|
||||
let usb4_approved = options.usb4_approved.clone();
|
||||
let retain = options.hosted_reims_base.is_some();
|
||||
let direct_region = (retain
|
||||
&& handoff.hosted_reims_region.bytes == stela_contracts::reims_hosted::REGION_BYTES)
|
||||
.then_some(handoff.hosted_reims_region.physical);
|
||||
let (transport, [registers, region, doorbells]) = work
|
||||
.call_owned(DEVICES_START_US, move || {
|
||||
let native = services::Services::new(mmio, remappers, acpi, heap, clock, usb4_approved);
|
||||
if let Some(expected_region) = direct_region {
|
||||
let transport =
|
||||
reims_hosted::PciTransport::open_direct_region(&native, address, expected_region)?;
|
||||
let bases = transport.bases()?;
|
||||
Ok((Some(transport), bases))
|
||||
} else if retain {
|
||||
let transport = reims_hosted::PciTransport::open(&native, address)?;
|
||||
let bases = transport.bases()?;
|
||||
Ok((Some(transport), bases))
|
||||
} else {
|
||||
reims_hosted::PciTransport::probe(&native, address).map(|bases| (None, bases))
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|error| output::fatal(format_args!("hosted Reims probe work: {error}")))
|
||||
.unwrap_or_else(|error| output::fatal(error));
|
||||
output::arguments(format_args!(
|
||||
"HOST Reims PCI {address}: wire v2 via BAR0={registers:#x} BAR2={region:#x} BAR4={doorbells:#x}\n"
|
||||
));
|
||||
transport
|
||||
}
|
||||
@@ -141,9 +141,6 @@ pub struct Handoff {
|
||||
/// engine runs a copy of this image taken before any Rust state
|
||||
/// existed, so it learns the result here, not from its own statics.
|
||||
pub(crate) serial_present: bool,
|
||||
/// Direct-mapped BAR2 (command and allocation region) of the hosted Reims
|
||||
/// PCI device when `--hosted-reims-base` is configured. Empty when absent.
|
||||
pub(crate) hosted_reims_region: Region,
|
||||
}
|
||||
|
||||
/// A read of the firmware's real-time clock: its time as UTC and its
|
||||
|
||||
@@ -292,15 +292,6 @@ pub(crate) unsafe fn qualify_reserved_writeback(
|
||||
cache::verify_writeback(cpu, physical, bytes, SOURCE.table_offset())
|
||||
}
|
||||
|
||||
/// Ensure a naturally aligned host range (such as hosted Reims BAR2) has a
|
||||
/// Write-Back variable MTRR on the BSP before platform/AP capture.
|
||||
///
|
||||
/// # Safety
|
||||
/// CPL0 on BSP with interrupts disabled and all APs parked.
|
||||
pub(crate) unsafe fn ensure_writeback_mtrr(physical: u64, bytes: u64) -> Result<(), MemoryError> {
|
||||
unsafe { cache::ensure_writeback_mtrr(physical, bytes) }
|
||||
}
|
||||
|
||||
/// Exercise the registered mapping and allocator through the Linux page
|
||||
/// catalog and the page source. Called by the mount's host check.
|
||||
pub fn verify() -> Result<(), MemoryError> {
|
||||
|
||||
@@ -70,13 +70,7 @@ pub(crate) fn verify_writeback(
|
||||
// table pages; every index is within its 4 KiB page.
|
||||
Some(unsafe { (address as *const u64).read_volatile() })
|
||||
},
|
||||
)
|
||||
.map_err(|err| {
|
||||
crate::output::arguments(format_args!(
|
||||
"NATIVE RAM verify_mappings failed cpu={cpu:#x} pa={start:#x} bytes={bytes:#x} err={err:?}\n"
|
||||
));
|
||||
err
|
||||
})?;
|
||||
)?;
|
||||
let count = msr(MTRR_CAP) as u8;
|
||||
let variables = (0..count).filter_map(|index| {
|
||||
let base = msr(MTRR_PHYS_BASE.at(2 * u32::from(index)));
|
||||
@@ -102,175 +96,6 @@ pub(crate) fn verify_writeback(
|
||||
physical_bits,
|
||||
}
|
||||
.writeback(start, bytes, variables)
|
||||
.map_err(|err| {
|
||||
crate::output::arguments(format_args!(
|
||||
"NATIVE RAM MTRR writeback failed pa={start:#x} bytes={bytes:#x} default={default:#x} count={count} err={err:?}\n"
|
||||
));
|
||||
err
|
||||
})
|
||||
}
|
||||
|
||||
/// Ensure a naturally aligned power-of-two range (such as a host RAM-backed
|
||||
/// PCI BAR2 region) is covered as Write-Back in the BSP's variable MTRRs.
|
||||
///
|
||||
/// # Safety
|
||||
/// Must be called on the BSP at CPL0 with interrupts disabled and all APs
|
||||
/// parked, before `root_identity` capture and AP startup so that `executor::start`
|
||||
/// replicates the updated MTRR image to every AP.
|
||||
pub(crate) unsafe fn ensure_writeback_mtrr(start: u64, bytes: u64) -> Result<(), MemoryError> {
|
||||
use crate::cpu::msr::{MTRR_CAP, MTRR_DEFAULT, MTRR_PHYS_BASE, Msr};
|
||||
use core::arch::{asm, x86_64::__cpuid};
|
||||
const VALID: u64 = 1 << 11;
|
||||
const MTRR_ENABLE: u64 = 1 << 11;
|
||||
const WRITE_BACK: u64 = 6;
|
||||
if bytes == 0 || !bytes.is_power_of_two() || !start.is_multiple_of(bytes) || start < (1 << 20) {
|
||||
return Err(MemoryError::InvalidSize);
|
||||
}
|
||||
let vendor = __cpuid(0);
|
||||
if [vendor.ebx, vendor.edx, vendor.ecx] != [0x756e_6547, 0x4965_6e69, 0x6c65_746e] {
|
||||
return Ok(());
|
||||
}
|
||||
let features = __cpuid(1).edx;
|
||||
if features & (1 << 12) == 0 {
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
let maximum = __cpuid(0x8000_0000).eax;
|
||||
let physical_bits = if maximum >= 0x8000_0008 {
|
||||
__cpuid(0x8000_0008).eax as u8
|
||||
} else {
|
||||
36
|
||||
};
|
||||
if !(32..=52).contains(&physical_bits) {
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
let end = start.checked_add(bytes).ok_or(MemoryError::InvalidSize)?;
|
||||
if end > 1u64 << physical_bits {
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
let address_mask = ((1u64 << physical_bits) - 1) & !4095;
|
||||
let read_msr = |register: Msr| unsafe { register.read() };
|
||||
let default = read_msr(MTRR_DEFAULT);
|
||||
let count = read_msr(MTRR_CAP) as u8;
|
||||
let cr0: u64;
|
||||
unsafe { asm!("mov {}, cr0", out(reg) cr0, options(nomem, nostack, preserves_flags)) };
|
||||
let variables = (0..count).filter_map(|index| {
|
||||
let base = read_msr(MTRR_PHYS_BASE.at(2 * u32::from(index)));
|
||||
let mask = read_msr(MTRR_PHYS_BASE.at(2 * u32::from(index) + 1));
|
||||
if mask & VALID == 0 {
|
||||
return None;
|
||||
}
|
||||
let size = ((!mask) & address_mask) + 4096;
|
||||
let base_addr = base & address_mask;
|
||||
Some(if size.is_power_of_two() && base_addr.is_multiple_of(size) {
|
||||
Ok(Variable {
|
||||
range: base_addr..base_addr + size,
|
||||
kind: base as u8,
|
||||
})
|
||||
} else {
|
||||
Err(MemoryError::CacheAttributeUnavailable)
|
||||
})
|
||||
});
|
||||
let policy = Policy {
|
||||
enabled: default & MTRR_ENABLE != 0,
|
||||
caches_enabled: cr0 & (1 << 30 | 1 << 29) == 0,
|
||||
default_kind: default as u8,
|
||||
physical_bits,
|
||||
};
|
||||
if let Ok(len) = usize::try_from(bytes)
|
||||
&& policy.writeback(start, len, variables.clone()).is_ok()
|
||||
{
|
||||
crate::output::arguments(format_args!(
|
||||
"HOST Reims MTRR already WB pa={start:#x} bytes={bytes:#x} default={default:#x}\n"
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
if default & MTRR_ENABLE == 0 {
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
let mut free_slots = alloc::vec::Vec::new();
|
||||
let mut conflict = None;
|
||||
for index in 0..count {
|
||||
let base = read_msr(MTRR_PHYS_BASE.at(2 * u32::from(index)));
|
||||
let mask = read_msr(MTRR_PHYS_BASE.at(2 * u32::from(index) + 1));
|
||||
if mask & VALID == 0 {
|
||||
free_slots.push(index);
|
||||
continue;
|
||||
}
|
||||
let size = ((!mask) & address_mask) + 4096;
|
||||
let base_addr = base & address_mask;
|
||||
let kind = base as u8;
|
||||
if size.is_power_of_two() && base_addr.is_multiple_of(size) {
|
||||
let v_end = base_addr.saturating_add(size);
|
||||
if base_addr < end && start < v_end && kind != WRITE_BACK as u8 {
|
||||
if conflict.is_some() || kind != 0 || base_addr > start || v_end < end {
|
||||
crate::output::arguments(format_args!(
|
||||
"HOST Reims MTRR uncarvable conflict slot={index} range={base_addr:#x}..{v_end:#x} kind={kind}\n"
|
||||
));
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
conflict = Some((index, base_addr, v_end, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut updates: alloc::vec::Vec<(u8, u64, u64)> = alloc::vec::Vec::new();
|
||||
if let Some((slot, v_start, v_end, kind)) = conflict {
|
||||
// Split [v_start, start) and [end, v_end) into aligned power-of-two UC MTRRs
|
||||
// so [start, end) is carved cleanly out of the 64-bit PCI UC aperture.
|
||||
let mut pieces: alloc::vec::Vec<(u64, u64)> = alloc::vec::Vec::new();
|
||||
for (mut cur, limit) in [(v_start, start), (end, v_end)] {
|
||||
while cur < limit {
|
||||
let remaining = limit - cur;
|
||||
let align_size = 1u64 << cur.trailing_zeros().min(62);
|
||||
let max_pow2 = 1u64 << (63 - remaining.leading_zeros());
|
||||
let chunk = align_size.min(max_pow2);
|
||||
pieces.push((cur, chunk));
|
||||
cur += chunk;
|
||||
}
|
||||
}
|
||||
let mut avail = alloc::vec::Vec::with_capacity(1 + free_slots.len());
|
||||
avail.push(slot);
|
||||
avail.extend_from_slice(&free_slots);
|
||||
if pieces.len() <= avail.len() {
|
||||
for (s, (p_start, p_len)) in avail.iter().copied().zip(pieces.iter().copied()) {
|
||||
let b = (p_start & address_mask) | u64::from(kind);
|
||||
let m = ((!(p_len - 1)) & address_mask) | VALID;
|
||||
updates.push((s, b, m));
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
updates.push((slot, 0, 0));
|
||||
}
|
||||
free_slots = avail[pieces.len().max(1)..].to_vec();
|
||||
} else {
|
||||
// Fewer free variable MTRRs than carved chunks; clear the broad 64-bit UC window
|
||||
// (all native MMIO mappings explicitly enforce UC via PAT).
|
||||
updates.push((slot, 0, 0));
|
||||
}
|
||||
}
|
||||
if (default as u8) != WRITE_BACK as u8 {
|
||||
let slot = free_slots
|
||||
.first()
|
||||
.copied()
|
||||
.ok_or(MemoryError::CacheAttributeUnavailable)?;
|
||||
let base_val = (start & address_mask) | WRITE_BACK;
|
||||
let mask_val = ((!(bytes - 1)) & address_mask) | VALID;
|
||||
updates.push((slot, base_val, mask_val));
|
||||
}
|
||||
// SAFETY: Intel SDM Vol. 3A 11.11.8 MTRR update on BSP with IF=0 and APs parked.
|
||||
unsafe {
|
||||
MTRR_DEFAULT.write(default & !MTRR_ENABLE);
|
||||
asm!("wbinvd", options(nostack, preserves_flags));
|
||||
for &(slot, base_val, mask_val) in &updates {
|
||||
MTRR_PHYS_BASE.at(2 * u32::from(slot)).write(base_val);
|
||||
MTRR_PHYS_BASE.at(2 * u32::from(slot) + 1).write(mask_val);
|
||||
}
|
||||
asm!("wbinvd", options(nostack, preserves_flags));
|
||||
MTRR_DEFAULT.write(default);
|
||||
}
|
||||
crate::output::arguments(format_args!(
|
||||
"HOST Reims MTRR carved WB pa={start:#x} bytes={bytes:#x} default={default:#x} updates={}\n",
|
||||
updates.len()
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// AMD's effective DRAM routing is additional to the common PAT/MTRR fields.
|
||||
|
||||
@@ -26,7 +26,6 @@ const HUGE: u64 = 1 << 7;
|
||||
const NX: u64 = 1 << 63;
|
||||
const APERTURE_OFFSET: u64 = 0x5_0000_0000;
|
||||
const ENTRIES: usize = 512;
|
||||
const DIRECTORY_BYTES: u64 = PAGE << 18;
|
||||
|
||||
fn failed<T>(_: T) -> Error {
|
||||
Error::Unavailable
|
||||
|
||||
@@ -23,8 +23,6 @@ const MAX_MEMORY: usize = firmware_map::INVENTORY_ENTRIES;
|
||||
const TABLE_BYTES: usize = 65536;
|
||||
/// Leaf tables in the aperture: 4 KiB mappings for 32 MiB.
|
||||
pub(super) const LEAVES: usize = 16;
|
||||
/// Two directories let a full 1 GiB BAR coexist with the 4 KiB window.
|
||||
pub(super) const DIRECTORIES: usize = 2;
|
||||
|
||||
pub(super) type Memory = firmware_map::Entry;
|
||||
/// All fields are initialized by the loader. Kept in reserved
|
||||
@@ -35,9 +33,9 @@ pub(crate) struct Wire {
|
||||
pub(super) root: u64,
|
||||
/// The aperture's first leaf table, which the scoped diagnostics use.
|
||||
pub(super) leaf: u64,
|
||||
/// The aperture's consecutive page directories. The first LEAVES entries
|
||||
/// hold the leaf tables. The other entries map 2 MiB pages.
|
||||
pub(super) directories: [u64; DIRECTORIES],
|
||||
/// The aperture's page directory: its first `LEAVES` entries hold the
|
||||
/// leaf tables, the rest map 2 MiB pages.
|
||||
pub(super) directory: u64,
|
||||
pub(super) leaves: [u64; LEAVES],
|
||||
pub(super) virtual_base: u64,
|
||||
pub(super) cores: u32,
|
||||
@@ -363,26 +361,19 @@ impl Prepared {
|
||||
}
|
||||
*slot = leaf as u64;
|
||||
}
|
||||
for (index, slot) in wire.directories.iter_mut().enumerate() {
|
||||
let address = base + index as u64 * DIRECTORY_BYTES;
|
||||
let first = crate::tables::entry(frames, root, address, 1, true)?
|
||||
.ok_or(refuse!("MMIO aperture directory missing"))?;
|
||||
let directory = first as u64 & ADDRESS;
|
||||
if first as u64 != directory {
|
||||
return Err(refuse!("MMIO aperture is not directory aligned"));
|
||||
}
|
||||
let used = if index == 0 { LEAVES } else { 0 };
|
||||
// SAFETY: this directory belongs to the loader's page-table builder.
|
||||
if (used..ENTRIES).any(|i| unsafe { first.add(i).read_volatile() } != 0) {
|
||||
return Err(refuse!("MMIO aperture overlaps an existing mapping"));
|
||||
}
|
||||
*slot = directory;
|
||||
let first = crate::tables::entry(frames, root, base, 1, false)?
|
||||
.ok_or(refuse!("MMIO aperture directory missing"))?;
|
||||
let directory = first as u64 & ADDRESS;
|
||||
if first as u64 != directory {
|
||||
return Err(refuse!("MMIO aperture is not directory aligned"));
|
||||
}
|
||||
if wire.directories[0] == wire.directories[1] {
|
||||
return Err(refuse!("MMIO aperture directories alias each other"));
|
||||
// SAFETY: the directory the builder walked for `base`.
|
||||
if (LEAVES..ENTRIES).any(|i| unsafe { first.add(i).read_volatile() } != 0) {
|
||||
return Err(refuse!("MMIO aperture overlaps an existing mapping"));
|
||||
}
|
||||
wire.root = root;
|
||||
wire.leaf = wire.leaves[0];
|
||||
wire.directory = directory;
|
||||
wire.virtual_base = base;
|
||||
wire.cores = u32::try_from(cores).map_err(|_| refuse!("MMIO core count overflow"))?;
|
||||
wire.levels = crate::layout::top_level() + 1;
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
use super::*;
|
||||
use super::{
|
||||
aliases::{aliases, owned_table},
|
||||
capture::{DIRECTORIES, LEAVES},
|
||||
capture::LEAVES,
|
||||
};
|
||||
use crate::{
|
||||
engine::host::{HostOwner, MmioRoots, RootIdentity},
|
||||
@@ -157,7 +157,7 @@ impl Size {
|
||||
fn slots(self) -> core::ops::Range<usize> {
|
||||
match self {
|
||||
Size::Page => 0..LEAVES * ENTRIES,
|
||||
Size::Large => LEAVES..DIRECTORIES * ENTRIES,
|
||||
Size::Large => LEAVES..ENTRIES,
|
||||
}
|
||||
}
|
||||
/// The size a request maps with: 2 MiB pages when it is 2 MiB aligned at
|
||||
@@ -228,9 +228,7 @@ impl Platform {
|
||||
Size::Page => {
|
||||
owned_table(wire, wire.leaves[index / ENTRIES])?.wrapping_add(index % ENTRIES)
|
||||
}
|
||||
Size::Large => {
|
||||
owned_table(wire, wire.directories[index / ENTRIES])?.wrapping_add(index % ENTRIES)
|
||||
}
|
||||
Size::Large => owned_table(wire, wire.directory)?.wrapping_add(index),
|
||||
})
|
||||
}
|
||||
fn address(&self, size: Size, index: usize) -> u64 {
|
||||
@@ -565,10 +563,10 @@ impl Source {
|
||||
});
|
||||
let mut written = Vec::new();
|
||||
written
|
||||
.try_reserve_exact(LEAVES + DIRECTORIES)
|
||||
.try_reserve_exact(LEAVES + 1)
|
||||
.map_err(refused("MMIO aperture: room for the aperture's table list"))?;
|
||||
written.extend_from_slice(&wire.leaves);
|
||||
written.extend_from_slice(&wire.directories);
|
||||
written.push(wire.directory);
|
||||
for &table in &written {
|
||||
crate::native_memory::cache::verify_writeback(
|
||||
crate::layout::physical(table),
|
||||
@@ -588,34 +586,32 @@ impl Source {
|
||||
platform.check_context(space).map_err(named(
|
||||
"the boot processor's root does not share the aperture",
|
||||
))?;
|
||||
for (index, &directory) in wire.directories.iter().enumerate() {
|
||||
let base = wire.virtual_base + index as u64 * DIRECTORY_BYTES;
|
||||
for root in catalog.roots() {
|
||||
let mut table = *root;
|
||||
for level in (2..wire.levels).rev() {
|
||||
let slot = ((base >> (12 + 9 * level)) & 511) as usize;
|
||||
// SAFETY: an owned table page.
|
||||
let entry = unsafe {
|
||||
owned_table(wire, table)
|
||||
.map_err(named("a root's aperture path leaves the capture's tables"))?
|
||||
.add(slot)
|
||||
.read_volatile()
|
||||
};
|
||||
if entry & (PRESENT | HUGE) != PRESENT {
|
||||
return Err(refuse(&alloc::format!(
|
||||
"root {root:#x} has entry {entry:#x} at level {level} of the aperture's path"
|
||||
)));
|
||||
}
|
||||
table = entry & ADDRESS;
|
||||
}
|
||||
if table != directory {
|
||||
for root in catalog.roots() {
|
||||
let mut table = *root;
|
||||
for level in (2..wire.levels).rev() {
|
||||
let slot = ((wire.virtual_base >> (12 + 9 * level)) & 511) as usize;
|
||||
// SAFETY: an owned table page.
|
||||
let entry = unsafe {
|
||||
owned_table(wire, table)
|
||||
.map_err(named("a root's aperture path leaves the capture's tables"))?
|
||||
.add(slot)
|
||||
.read_volatile()
|
||||
};
|
||||
if entry & (PRESENT | HUGE) != PRESENT {
|
||||
return Err(refuse(&alloc::format!(
|
||||
"root {root:#x} reaches {table:#x}, not the aperture's directory {directory:#x}"
|
||||
"root {root:#x} has entry {entry:#x} at level {level} of the aperture's path"
|
||||
)));
|
||||
}
|
||||
table = entry & ADDRESS;
|
||||
}
|
||||
if table != wire.directory {
|
||||
return Err(refuse(&alloc::format!(
|
||||
"root {root:#x} reaches {table:#x}, not the aperture's directory {:#x}",
|
||||
wire.directory
|
||||
)));
|
||||
}
|
||||
}
|
||||
let directory = owned_table(wire, wire.directories[0]).map_err(named(
|
||||
let directory = owned_table(wire, wire.directory).map_err(named(
|
||||
"the aperture's directory is not a table page the capture owns",
|
||||
))?;
|
||||
for (index, &leaf) in wire.leaves.iter().enumerate() {
|
||||
|
||||
@@ -142,19 +142,17 @@ unsafe fn reserve_with_limit(
|
||||
.host
|
||||
.checked_add(range.bytes)
|
||||
.ok_or(refuse!("canonical guest RAM extent wraps"))?;
|
||||
let in_guest = handoff.guest[..handoff.guest_count]
|
||||
.iter()
|
||||
.any(|reservation| {
|
||||
reservation.physical <= range.host
|
||||
&& reservation
|
||||
.physical
|
||||
.checked_add(reservation.bytes)
|
||||
.is_some_and(|top| end <= top)
|
||||
});
|
||||
let is_reims_region = handoff.hosted_reims_region.bytes != 0
|
||||
&& range.host == handoff.hosted_reims_region.physical
|
||||
&& range.bytes == handoff.hosted_reims_region.bytes;
|
||||
if range.bytes == 0 || !(in_guest || is_reims_region) {
|
||||
if range.bytes == 0
|
||||
|| !handoff.guest[..handoff.guest_count]
|
||||
.iter()
|
||||
.any(|reservation| {
|
||||
reservation.physical <= range.host
|
||||
&& reservation
|
||||
.physical
|
||||
.checked_add(reservation.bytes)
|
||||
.is_some_and(|top| end <= top)
|
||||
})
|
||||
{
|
||||
return Err(refuse!(
|
||||
"canonical guest RAM is outside actual loader ownership"
|
||||
));
|
||||
|
||||
@@ -755,49 +755,3 @@ pub(crate) fn xhci_legacy_capabilities() -> Vec<(Address, u64)> {
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The unique hosted Reims PCI function's 1 GiB BAR2 host range, observed
|
||||
/// before boot services exit so the loader can map it write-back in the
|
||||
/// physmap for direct guest RAM access.
|
||||
pub(crate) fn hosted_reims_region() -> Option<crate::handoff::Region> {
|
||||
use stela_contracts::reims_hosted::REGION_BYTES;
|
||||
use stela_drivers::probe::reims_hosted::{DEVICE, VENDOR};
|
||||
let handles = boot::find_handles::<PciIo>().ok()?;
|
||||
let mut found = None;
|
||||
for handle in handles {
|
||||
let Ok(mut io) = get_protocol::<PciIo>(handle) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(header) = io.read_header() else {
|
||||
continue;
|
||||
};
|
||||
let vendor = u16::from_le_bytes([header[0], header[1]]);
|
||||
let device = u16::from_le_bytes([header[2], header[3]]);
|
||||
if vendor != VENDOR || device != DEVICE {
|
||||
continue;
|
||||
}
|
||||
let Ok(regions) = io.bar_regions(2) else {
|
||||
return None;
|
||||
};
|
||||
let [region] = regions.as_slice() else {
|
||||
return None;
|
||||
};
|
||||
if region.resource_type != 0
|
||||
|| region.translation != 0
|
||||
|| region.host != region.pci
|
||||
|| region.host.start == 0
|
||||
|| !region.host.start.is_multiple_of(crate::tables::LARGE)
|
||||
|| region.host.end.checked_sub(region.host.start) != Some(REGION_BYTES)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if found.is_some() {
|
||||
return None;
|
||||
}
|
||||
found = Some(crate::handoff::Region {
|
||||
physical: region.host.start,
|
||||
bytes: REGION_BYTES,
|
||||
});
|
||||
}
|
||||
found
|
||||
}
|
||||
@@ -331,8 +331,6 @@ fn inputs(options: &[u8], mut volume: FileSystem) -> Result<Inputs> {
|
||||
|| system.network_check.is_some()
|
||||
|| system.audio_check.is_some()
|
||||
|| !system.usb_storage.is_empty()
|
||||
|| system.probe_hosted_reims
|
||||
|| system.hosted_reims_base.is_some()
|
||||
|| system.input
|
||||
|| system.install.is_some()
|
||||
|| system.guest_network;
|
||||
@@ -833,19 +831,7 @@ fn load(
|
||||
let image_bytes = crate::native_image::ResidentImage::allocation_bytes(snapshot.bytes);
|
||||
let (bundle, storage) = translation_store(bundle, storage, cores, image_bytes);
|
||||
crate::status::begin("Setting up Stela's memory");
|
||||
let hosted_reims_region = if system.hosted_reims_base.is_some() {
|
||||
let region = crate::pci_io::hosted_reims_region().unwrap_or_default();
|
||||
if region.bytes != 0 {
|
||||
output::arguments(format_args!(
|
||||
"HOST Reims BAR2 direct physmap={:#x} bytes={:#x}\n",
|
||||
region.physical, region.bytes
|
||||
));
|
||||
}
|
||||
region
|
||||
} else {
|
||||
Region::default()
|
||||
};
|
||||
let image = memory::prepare_image(&snapshot, hosted_reims_region)?;
|
||||
let image = memory::prepare_image(&snapshot)?;
|
||||
let mut memory = memory::reserve(cores, &image.ram)?;
|
||||
let tsc_hz = crate::firmware::tsc_hz();
|
||||
if !crate::cpu::INVARIANT_TSC.present() {
|
||||
@@ -1197,7 +1183,6 @@ fn load(
|
||||
stop_record: crate::stop_record::services(),
|
||||
runtime_regions: runtime.regions,
|
||||
serial_present: crate::serial::present(),
|
||||
hosted_reims_region,
|
||||
});
|
||||
}
|
||||
// SAFETY: boot services ended; the completed root maps this code and
|
||||
|
||||
@@ -21,7 +21,6 @@ pub(super) struct EngineImage {
|
||||
pub ram: Vec<(usize, usize)>,
|
||||
pub screen: Option<Framebuffer>,
|
||||
pub apic: u64,
|
||||
pub hosted_reims_region: Region,
|
||||
pub placement: Placement,
|
||||
}
|
||||
|
||||
@@ -47,10 +46,7 @@ pub(super) struct EngineMemory {
|
||||
}
|
||||
|
||||
/// Copy and relocate the pristine image into the selected host window.
|
||||
pub(super) fn prepare_image(
|
||||
snapshot: &Snapshot,
|
||||
hosted_reims_region: Region,
|
||||
) -> Result<EngineImage> {
|
||||
pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
|
||||
let image = firmware::Image::loaded()?;
|
||||
if image.start != snapshot.start || image.end - image.start != snapshot.bytes {
|
||||
return Err(refuse!("image layout changed after the snapshot"));
|
||||
@@ -58,26 +54,7 @@ pub(super) fn prepare_image(
|
||||
let ram = firmware::ram()?;
|
||||
let screen = Framebuffer::for_engine()?;
|
||||
let apic_base = crate::apic::base_msr();
|
||||
let hosted_reims_end = if hosted_reims_region.bytes != 0 {
|
||||
let end = hosted_reims_region
|
||||
.physical
|
||||
.checked_add(hosted_reims_region.bytes)
|
||||
.ok_or(refuse!("hosted Reims BAR2 extent overflows"))?;
|
||||
if hosted_reims_region.physical == 0
|
||||
|| !hosted_reims_region.physical.is_multiple_of(tables::LARGE)
|
||||
|| !hosted_reims_region.bytes.is_multiple_of(tables::LARGE)
|
||||
|| ram
|
||||
.iter()
|
||||
.any(|&(start, end_ram)| (start as u64) < end && hosted_reims_region.physical < end_ram as u64)
|
||||
{
|
||||
return Err(refuse!("hosted Reims BAR2 overlaps RAM or is unaligned"));
|
||||
}
|
||||
Some(end)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// The physmap reaches RAM, the framebuffer, the local APIC, and any
|
||||
// direct-mapped hosted Reims BAR2 region.
|
||||
// The physmap reaches RAM, the framebuffer and the local APIC.
|
||||
let apic = apic_base & crate::apic::BASE_ADDRESS;
|
||||
let top = ram
|
||||
.iter()
|
||||
@@ -89,7 +66,6 @@ pub(super) fn prepare_image(
|
||||
.filter_map(|s| s.flip)
|
||||
.map(|r| r as u64 + PAGE),
|
||||
)
|
||||
.chain(hosted_reims_end)
|
||||
.chain(core::iter::once(apic + PAGE))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
@@ -126,7 +102,6 @@ pub(super) fn prepare_image(
|
||||
ram,
|
||||
screen,
|
||||
apic,
|
||||
hosted_reims_region,
|
||||
placement,
|
||||
})
|
||||
}
|
||||
@@ -299,7 +274,6 @@ pub(super) fn map(
|
||||
ram,
|
||||
screen,
|
||||
apic,
|
||||
hosted_reims_region,
|
||||
..
|
||||
} = image;
|
||||
let EngineMemory {
|
||||
@@ -455,7 +429,7 @@ pub(super) fn map(
|
||||
code.bytes,
|
||||
PRESENT | tables::GLOBAL,
|
||||
)?;
|
||||
// The physmap: all RAM, any direct-mapped hosted Reims BAR2, the framebuffer and the local APIC.
|
||||
// The physmap: all RAM, the framebuffer and the local APIC.
|
||||
for &(start, end) in ram {
|
||||
let (start, end) = (start as u64, end as u64);
|
||||
tables::map_range(
|
||||
@@ -467,16 +441,6 @@ pub(super) fn map(
|
||||
data | tables::GLOBAL,
|
||||
)?;
|
||||
}
|
||||
if hosted_reims_region.bytes != 0 {
|
||||
tables::map_range(
|
||||
frames,
|
||||
root,
|
||||
layout::physical(hosted_reims_region.physical),
|
||||
hosted_reims_region.physical,
|
||||
hosted_reims_region.bytes,
|
||||
data | tables::GLOBAL,
|
||||
)?;
|
||||
}
|
||||
if let Some(screen) = screen {
|
||||
let start = screen.base as u64 & !(PAGE - 1);
|
||||
let end = ((screen.base + screen.bytes) as u64).next_multiple_of(PAGE);
|
||||
|
||||
@@ -311,24 +311,6 @@ fn group_symbol(module: &str) -> String {
|
||||
format!("stela_linux_group__{DOMAIN}__{}", token(module))
|
||||
}
|
||||
|
||||
fn compiler_source(path: &Path) -> &Path {
|
||||
// Windows Clang opens a verbatim DOS source path but cannot find its
|
||||
// sibling quoted includes. Keep the canonical path for the input owner
|
||||
// and use the equivalent short DOS path for Clang.
|
||||
#[cfg(windows)]
|
||||
if let Some(dos) = path
|
||||
.to_str()
|
||||
.and_then(|path| path.strip_prefix(r"\\?\"))
|
||||
.filter(|path| {
|
||||
path.as_bytes().get(1..3) == Some(b":\\") && path.encode_utf16().count() < 260
|
||||
})
|
||||
&& fs::canonicalize(dos).is_ok_and(|normalized| normalized == path)
|
||||
{
|
||||
return Path::new(dos);
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// The compiler on `PATH`, as the registry records what built each object.
|
||||
fn resolved(program: &Path) -> PathBuf {
|
||||
let found = env::var_os("PATH")
|
||||
@@ -448,14 +430,13 @@ pub fn compile(
|
||||
.collect();
|
||||
// System-header diagnostics are normally suppressed. Keep the original
|
||||
// function prototypes checked before producing an object for any class.
|
||||
let compiler_source = compiler_source(&placement.source).to_path_buf();
|
||||
crate::linux_build::check_declarations(&build, std::slice::from_ref(&compiler_source));
|
||||
crate::linux_build::check_declarations(&build, std::slice::from_ref(&placement.source));
|
||||
let object = placement.output.join(format!("captured-{token}.o"));
|
||||
let depfile = object.with_extension("d");
|
||||
run(compiler
|
||||
.to_command()
|
||||
.arg("-c")
|
||||
.arg(&compiler_source)
|
||||
.arg(&placement.source)
|
||||
.arg("-o")
|
||||
.arg(&object)
|
||||
.arg("-MD")
|
||||
|
||||
@@ -20,6 +20,7 @@ pub mod pc_relative;
|
||||
pub mod prefetch;
|
||||
pub mod register_offset;
|
||||
pub mod scalable;
|
||||
pub mod semantics;
|
||||
pub mod simd;
|
||||
pub mod sme;
|
||||
pub mod sve;
|
||||
|
||||
@@ -0,0 +1,604 @@
|
||||
//! Explicit architectural semantics for core A64 integer flag-setting and
|
||||
//! conditional-select instructions.
|
||||
use super::{
|
||||
Operation, Register, RegisterExtend, Shift, Width,
|
||||
conditional_select::Otherwise,
|
||||
flags::{NZCV_C, NZCV_N, NZCV_SHIFT, NZCV_V, NZCV_Z, condition_holds},
|
||||
};
|
||||
use crate::GuestState;
|
||||
|
||||
/// Bitmask of the four architectural condition flags (`N`, `Z`, `C`, `V`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct FlagMask(u8);
|
||||
|
||||
impl FlagMask {
|
||||
pub const NONE: Self = Self(0);
|
||||
pub const N: Self = Self(1 << 3);
|
||||
pub const Z: Self = Self(1 << 2);
|
||||
pub const C: Self = Self(1 << 1);
|
||||
pub const V: Self = Self(1 << 0);
|
||||
pub const ALL: Self = Self(0b1111);
|
||||
|
||||
pub const fn bits(self) -> u8 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub const fn is_empty(self) -> bool {
|
||||
self.0 == 0
|
||||
}
|
||||
|
||||
pub const fn contains(self, other: Self) -> bool {
|
||||
(self.0 & other.0) == other.0
|
||||
}
|
||||
|
||||
pub const fn intersects(self, other: Self) -> bool {
|
||||
(self.0 & other.0) != 0
|
||||
}
|
||||
|
||||
pub const fn union(self, other: Self) -> Self {
|
||||
Self(self.0 | other.0)
|
||||
}
|
||||
|
||||
pub const fn difference(self, other: Self) -> Self {
|
||||
Self(self.0 & !other.0)
|
||||
}
|
||||
|
||||
pub const fn from_nzcv(nzcv: u32) -> Self {
|
||||
Self(((nzcv >> NZCV_SHIFT) & 0xf) as u8)
|
||||
}
|
||||
|
||||
pub const fn to_nzcv_mask(self) -> u32 {
|
||||
(self.0 as u32) << NZCV_SHIFT
|
||||
}
|
||||
|
||||
/// The subset of `NZCV` flags read by A64 condition `condition` (`0..16`).
|
||||
pub const fn condition_reads(condition: u8) -> Self {
|
||||
match condition >> 1 {
|
||||
0 => Self::Z, // EQ / NE
|
||||
1 => Self::C, // CS / CC
|
||||
2 => Self::N, // MI / PL
|
||||
3 => Self::V, // VS / VC
|
||||
4 => Self(Self::C.0 | Self::Z.0), // HI / LS
|
||||
5 => Self(Self::N.0 | Self::V.0), // GE / LT
|
||||
6 => Self(Self::N.0 | Self::Z.0 | Self::V.0), // GT / LE
|
||||
_ => Self::NONE, // AL / NV
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bitmask over architectural integer state (`X0..=X30` in bits `0..=30`, `SP` in bit `31`).
|
||||
/// `XZR`/`WZR` (`Register::Zero`) is excluded because reads yield 0 and writes discard.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct RegisterSet(u32);
|
||||
|
||||
impl RegisterSet {
|
||||
pub const NONE: Self = Self(0);
|
||||
|
||||
pub const fn bits(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub const fn is_empty(self) -> bool {
|
||||
self.0 == 0
|
||||
}
|
||||
|
||||
pub const fn of(register: Register) -> Self {
|
||||
match Self::bit(register) {
|
||||
Some(bit) => Self(bit),
|
||||
None => Self::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_registers(registers: impl IntoIterator<Item = Register>) -> Self {
|
||||
registers
|
||||
.into_iter()
|
||||
.fold(Self::NONE, |set, register| set.union(Self::of(register)))
|
||||
}
|
||||
|
||||
pub const fn contains(self, register: Register) -> bool {
|
||||
match Self::bit(register) {
|
||||
Some(bit) => (self.0 & bit) != 0,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn union(self, other: Self) -> Self {
|
||||
Self(self.0 | other.0)
|
||||
}
|
||||
|
||||
pub const fn difference(self, other: Self) -> Self {
|
||||
Self(self.0 & !other.0)
|
||||
}
|
||||
|
||||
pub const fn intersects(self, other: Self) -> bool {
|
||||
(self.0 & other.0) != 0
|
||||
}
|
||||
|
||||
const fn bit(register: Register) -> Option<u32> {
|
||||
match register {
|
||||
Register::X(index) if index < 31 => Some(1u32 << index),
|
||||
Register::Sp => Some(1u32 << 31),
|
||||
Register::X(_) | Register::Zero => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an ALU operand is sourced before optional bitwise inversion.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueSource {
|
||||
Register(Register),
|
||||
Immediate(u64),
|
||||
ShiftedRegister {
|
||||
register: Register,
|
||||
shift: Shift,
|
||||
amount: u8,
|
||||
},
|
||||
ExtendedRegister {
|
||||
register: Register,
|
||||
extend: RegisterExtend,
|
||||
amount: u8,
|
||||
},
|
||||
}
|
||||
|
||||
/// Carry input consumed by [`SemanticKind::AddWithCarry`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CarryInput {
|
||||
Zero,
|
||||
One,
|
||||
CarryFlag,
|
||||
}
|
||||
|
||||
/// Pure architectural effect shape for a lifted instruction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SemanticKind {
|
||||
/// Arm `AddWithCarry(left, if invert_right { NOT(right) } else { right }, carry_in)`.
|
||||
AddWithCarry {
|
||||
left: ValueSource,
|
||||
right: ValueSource,
|
||||
invert_right: bool,
|
||||
carry_in: CarryInput,
|
||||
set_flags: bool,
|
||||
destination: Register,
|
||||
},
|
||||
/// Arm `CSEL`/`CSINC`/`CSINV`/`CSNEG`: chooses `true_register` if `ConditionHolds(condition)`,
|
||||
/// otherwise transforms `false_register` per `otherwise`; never modifies `NZCV`.
|
||||
ConditionalSelect {
|
||||
condition: u8,
|
||||
true_register: Register,
|
||||
false_register: Register,
|
||||
otherwise: Otherwise,
|
||||
destination: Register,
|
||||
},
|
||||
}
|
||||
|
||||
/// Explicit per-instruction operand width, register/flag side effects, and semantics.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct InstructionSemantics {
|
||||
pub width: Width,
|
||||
pub gpr_reads: RegisterSet,
|
||||
pub gpr_writes: RegisterSet,
|
||||
pub flag_reads: FlagMask,
|
||||
pub flag_writes: FlagMask,
|
||||
pub kind: SemanticKind,
|
||||
}
|
||||
|
||||
/// Return explicit architectural semantics for supported integer arithmetic,
|
||||
/// carry arithmetic, and conditional select operations.
|
||||
pub fn semantics_of(operation: &Operation) -> Option<InstructionSemantics> {
|
||||
match *operation {
|
||||
Operation::AddSub {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
source,
|
||||
immediate,
|
||||
} => Some(InstructionSemantics {
|
||||
width,
|
||||
gpr_reads: RegisterSet::of(source),
|
||||
gpr_writes: RegisterSet::of(destination),
|
||||
flag_reads: FlagMask::NONE,
|
||||
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
|
||||
kind: SemanticKind::AddWithCarry {
|
||||
left: ValueSource::Register(source),
|
||||
right: ValueSource::Immediate(u64::from(immediate)),
|
||||
invert_right: subtract,
|
||||
carry_in: if subtract {
|
||||
CarryInput::One
|
||||
} else {
|
||||
CarryInput::Zero
|
||||
},
|
||||
set_flags: flags,
|
||||
destination,
|
||||
},
|
||||
}),
|
||||
Operation::AddSubRegister {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
shift,
|
||||
amount,
|
||||
} => Some(InstructionSemantics {
|
||||
width,
|
||||
gpr_reads: RegisterSet::from_registers([left, right]),
|
||||
gpr_writes: RegisterSet::of(destination),
|
||||
flag_reads: FlagMask::NONE,
|
||||
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
|
||||
kind: SemanticKind::AddWithCarry {
|
||||
left: ValueSource::Register(left),
|
||||
right: ValueSource::ShiftedRegister {
|
||||
register: right,
|
||||
shift,
|
||||
amount,
|
||||
},
|
||||
invert_right: subtract,
|
||||
carry_in: if subtract {
|
||||
CarryInput::One
|
||||
} else {
|
||||
CarryInput::Zero
|
||||
},
|
||||
set_flags: flags,
|
||||
destination,
|
||||
},
|
||||
}),
|
||||
Operation::AddSubExtended {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
extend,
|
||||
amount,
|
||||
} => Some(InstructionSemantics {
|
||||
width,
|
||||
gpr_reads: RegisterSet::from_registers([left, right]),
|
||||
gpr_writes: RegisterSet::of(destination),
|
||||
flag_reads: FlagMask::NONE,
|
||||
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
|
||||
kind: SemanticKind::AddWithCarry {
|
||||
left: ValueSource::Register(left),
|
||||
right: ValueSource::ExtendedRegister {
|
||||
register: right,
|
||||
extend,
|
||||
amount,
|
||||
},
|
||||
invert_right: subtract,
|
||||
carry_in: if subtract {
|
||||
CarryInput::One
|
||||
} else {
|
||||
CarryInput::Zero
|
||||
},
|
||||
set_flags: flags,
|
||||
destination,
|
||||
},
|
||||
}),
|
||||
Operation::AddSubCarry {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
} => Some(InstructionSemantics {
|
||||
width,
|
||||
gpr_reads: RegisterSet::from_registers([left, right]),
|
||||
gpr_writes: RegisterSet::of(destination),
|
||||
flag_reads: FlagMask::C,
|
||||
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
|
||||
kind: SemanticKind::AddWithCarry {
|
||||
left: ValueSource::Register(left),
|
||||
right: ValueSource::Register(right),
|
||||
invert_right: subtract,
|
||||
carry_in: CarryInput::CarryFlag,
|
||||
set_flags: flags,
|
||||
destination,
|
||||
},
|
||||
}),
|
||||
Operation::ConditionalSelect(op) if op.condition < 16 => {
|
||||
let reads = if op.condition >= 14 {
|
||||
RegisterSet::of(op.left)
|
||||
} else {
|
||||
RegisterSet::from_registers([op.left, op.right])
|
||||
};
|
||||
Some(InstructionSemantics {
|
||||
width: op.width,
|
||||
gpr_reads: reads,
|
||||
gpr_writes: RegisterSet::of(op.destination),
|
||||
flag_reads: FlagMask::condition_reads(op.condition),
|
||||
flag_writes: FlagMask::NONE,
|
||||
kind: SemanticKind::ConditionalSelect {
|
||||
condition: op.condition,
|
||||
true_register: op.left,
|
||||
false_register: op.right,
|
||||
otherwise: op.otherwise,
|
||||
destination: op.destination,
|
||||
},
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact Arm `AddWithCarry(N, x, y, carry_in)` specification returning `(result, nzcv)`.
|
||||
pub fn add_with_carry(width: Width, left: u64, right: u64, carry_in: bool) -> (u64, u32) {
|
||||
let carry = u128::from(carry_in);
|
||||
let carry_signed = i128::from(carry_in);
|
||||
let (result, negative, unsigned_sum, signed_matches) = match width {
|
||||
Width::W32 => {
|
||||
let x = left as u32;
|
||||
let y = right as u32;
|
||||
let unsigned_sum = u128::from(x) + u128::from(y) + carry;
|
||||
let signed_sum = i128::from(x as i32) + i128::from(y as i32) + carry_signed;
|
||||
let result = unsigned_sum as u32;
|
||||
let negative = (result >> 31) != 0;
|
||||
let signed_matches = i128::from(result as i32) == signed_sum;
|
||||
(u64::from(result), negative, unsigned_sum, signed_matches)
|
||||
}
|
||||
Width::X64 => {
|
||||
let unsigned_sum = u128::from(left) + u128::from(right) + carry;
|
||||
let signed_sum = i128::from(left as i64) + i128::from(right as i64) + carry_signed;
|
||||
let result = unsigned_sum as u64;
|
||||
let negative = (result >> 63) != 0;
|
||||
let signed_matches = i128::from(result as i64) == signed_sum;
|
||||
(result, negative, unsigned_sum, signed_matches)
|
||||
}
|
||||
};
|
||||
let mut nzcv = 0u32;
|
||||
if negative {
|
||||
nzcv |= NZCV_N;
|
||||
}
|
||||
if result == 0 {
|
||||
nzcv |= NZCV_Z;
|
||||
}
|
||||
if unsigned_sum != u128::from(result) {
|
||||
nzcv |= NZCV_C;
|
||||
}
|
||||
if !signed_matches {
|
||||
nzcv |= NZCV_V;
|
||||
}
|
||||
(result, nzcv)
|
||||
}
|
||||
|
||||
/// Reference architectural execution of a modeled instruction on `state`.
|
||||
pub fn eval_instruction(semantics: &InstructionSemantics, state: &mut GuestState) {
|
||||
let width = semantics.width;
|
||||
match semantics.kind {
|
||||
SemanticKind::AddWithCarry {
|
||||
left,
|
||||
right,
|
||||
invert_right,
|
||||
carry_in,
|
||||
set_flags,
|
||||
destination,
|
||||
} => {
|
||||
let lhs = eval_value_source(width, left, state);
|
||||
let mut rhs = eval_value_source(width, right, state);
|
||||
if invert_right {
|
||||
rhs = mask_width(width, !rhs);
|
||||
}
|
||||
let carry = match carry_in {
|
||||
CarryInput::Zero => false,
|
||||
CarryInput::One => true,
|
||||
CarryInput::CarryFlag => (state.nzcv & NZCV_C) != 0,
|
||||
};
|
||||
let (result, nzcv) = add_with_carry(width, lhs, rhs, carry);
|
||||
write_register(width, destination, result, state);
|
||||
if set_flags {
|
||||
state.nzcv = nzcv;
|
||||
}
|
||||
}
|
||||
SemanticKind::ConditionalSelect {
|
||||
condition,
|
||||
true_register,
|
||||
false_register,
|
||||
otherwise,
|
||||
destination,
|
||||
} => {
|
||||
let selected = if condition_holds(condition, state.nzcv) {
|
||||
read_register(width, true_register, state)
|
||||
} else {
|
||||
let value = read_register(width, false_register, state);
|
||||
let adjusted = match otherwise {
|
||||
Otherwise::Unchanged => value,
|
||||
Otherwise::Increment => value.wrapping_add(1),
|
||||
Otherwise::Invert => !value,
|
||||
Otherwise::Negate => value.wrapping_neg(),
|
||||
};
|
||||
mask_width(width, adjusted)
|
||||
};
|
||||
write_register(width, destination, selected, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mask_width(width: Width, value: u64) -> u64 {
|
||||
match width {
|
||||
Width::W32 => u64::from(value as u32),
|
||||
Width::X64 => value,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_register(width: Width, register: Register, state: &GuestState) -> u64 {
|
||||
let raw = match register {
|
||||
Register::X(index) if index < 31 => state.x[usize::from(index)],
|
||||
Register::Sp => state.sp,
|
||||
Register::X(_) | Register::Zero => 0,
|
||||
};
|
||||
mask_width(width, raw)
|
||||
}
|
||||
|
||||
fn write_register(width: Width, register: Register, value: u64, state: &mut GuestState) {
|
||||
let value = mask_width(width, value);
|
||||
match register {
|
||||
Register::X(index) if index < 31 => state.x[usize::from(index)] = value,
|
||||
Register::Sp => state.sp = value,
|
||||
Register::X(_) | Register::Zero => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_value_source(width: Width, source: ValueSource, state: &GuestState) -> u64 {
|
||||
match source {
|
||||
ValueSource::Register(register) => read_register(width, register, state),
|
||||
ValueSource::Immediate(immediate) => mask_width(width, immediate),
|
||||
ValueSource::ShiftedRegister {
|
||||
register,
|
||||
shift,
|
||||
amount,
|
||||
} => {
|
||||
let raw = read_register(width, register, state);
|
||||
let shifted = match width {
|
||||
Width::W32 => {
|
||||
let val = raw as u32;
|
||||
let out = if amount == 0 {
|
||||
val
|
||||
} else {
|
||||
match shift {
|
||||
Shift::Lsl => val.wrapping_shl(u32::from(amount)),
|
||||
Shift::Lsr => val.wrapping_shr(u32::from(amount)),
|
||||
Shift::Asr => ((val as i32).wrapping_shr(u32::from(amount))) as u32,
|
||||
Shift::Ror => val.rotate_right(u32::from(amount)),
|
||||
}
|
||||
};
|
||||
u64::from(out)
|
||||
}
|
||||
Width::X64 => {
|
||||
if amount == 0 {
|
||||
raw
|
||||
} else {
|
||||
match shift {
|
||||
Shift::Lsl => raw.wrapping_shl(u32::from(amount)),
|
||||
Shift::Lsr => raw.wrapping_shr(u32::from(amount)),
|
||||
Shift::Asr => ((raw as i64).wrapping_shr(u32::from(amount))) as u64,
|
||||
Shift::Ror => raw.rotate_right(u32::from(amount)),
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
mask_width(width, shifted)
|
||||
}
|
||||
ValueSource::ExtendedRegister {
|
||||
register,
|
||||
extend,
|
||||
amount,
|
||||
} => {
|
||||
let raw = read_register(Width::X64, register, state);
|
||||
let extended = match extend {
|
||||
RegisterExtend::Uxtb => u64::from(raw as u8),
|
||||
RegisterExtend::Uxth => u64::from(raw as u16),
|
||||
RegisterExtend::Uxtw => u64::from(raw as u32),
|
||||
RegisterExtend::Uxtx => raw,
|
||||
RegisterExtend::Sxtb => i64::from(raw as i8) as u64,
|
||||
RegisterExtend::Sxth => i64::from(raw as i16) as u64,
|
||||
RegisterExtend::Sxtw => i64::from(raw as i32) as u64,
|
||||
RegisterExtend::Sxtx => raw,
|
||||
};
|
||||
mask_width(width, extended.wrapping_shl(u32::from(amount)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{GuestAddress, Lifter, aarch64::Decoder};
|
||||
|
||||
fn decode(word: u32) -> Operation {
|
||||
Decoder.lift(GuestAddress(0x1000), word).unwrap().operation
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adds_adcs_sbcs_csel_explicit_effects_and_zero_register() {
|
||||
// ADDS X4, X0, X2 (0xab02_0004)
|
||||
let adds_x = semantics_of(&decode(0xab02_0004)).unwrap();
|
||||
assert_eq!(adds_x.width, Width::X64);
|
||||
assert_eq!(
|
||||
adds_x.gpr_reads,
|
||||
RegisterSet::from_registers([Register::X(0), Register::X(2)])
|
||||
);
|
||||
assert_eq!(adds_x.gpr_writes, RegisterSet::of(Register::X(4)));
|
||||
assert_eq!(adds_x.flag_reads, FlagMask::NONE);
|
||||
assert_eq!(adds_x.flag_writes, FlagMask::ALL);
|
||||
|
||||
// ADDS WZR, W1, #1 (CMN W1, #1: 0x3100_043f)
|
||||
let cmn_w = semantics_of(&decode(0x3100_043f)).unwrap();
|
||||
assert_eq!(cmn_w.width, Width::W32);
|
||||
assert_eq!(cmn_w.gpr_reads, RegisterSet::of(Register::X(1)));
|
||||
assert_eq!(cmn_w.gpr_writes, RegisterSet::NONE);
|
||||
assert_eq!(cmn_w.flag_reads, FlagMask::NONE);
|
||||
assert_eq!(cmn_w.flag_writes, FlagMask::ALL);
|
||||
|
||||
// ADCS X5, X1, X3 (0xba03_0025)
|
||||
let adcs_x = semantics_of(&decode(0xba03_0025)).unwrap();
|
||||
assert_eq!(adcs_x.flag_reads, FlagMask::C);
|
||||
assert_eq!(adcs_x.flag_writes, FlagMask::ALL);
|
||||
|
||||
// SBCS W6, W5, W4 (0x7a04_00a6)
|
||||
let sbcs_w = semantics_of(&decode(0x7a04_00a6)).unwrap();
|
||||
assert_eq!(sbcs_w.width, Width::W32);
|
||||
assert_eq!(sbcs_w.flag_reads, FlagMask::C);
|
||||
assert_eq!(sbcs_w.flag_writes, FlagMask::ALL);
|
||||
assert!(matches!(
|
||||
sbcs_w.kind,
|
||||
SemanticKind::AddWithCarry {
|
||||
invert_right: true,
|
||||
carry_in: CarryInput::CarryFlag,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
// CSEL X6, X4, X5, CS (0x9a85_2086)
|
||||
let csel_cs = semantics_of(&decode(0x9a85_2086)).unwrap();
|
||||
assert_eq!(csel_cs.flag_reads, FlagMask::C);
|
||||
assert_eq!(csel_cs.flag_writes, FlagMask::NONE);
|
||||
assert_eq!(
|
||||
csel_cs.gpr_reads,
|
||||
RegisterSet::from_registers([Register::X(4), Register::X(5)])
|
||||
);
|
||||
|
||||
// CSEL W0, W0, W1, AL (0x1a81_e000): unconditional ignores W1 and reads no flags
|
||||
let csel_al = semantics_of(&decode(0x1a81_e000)).unwrap();
|
||||
assert_eq!(csel_al.width, Width::W32);
|
||||
assert_eq!(csel_al.flag_reads, FlagMask::NONE);
|
||||
assert_eq!(csel_al.flag_writes, FlagMask::NONE);
|
||||
assert_eq!(csel_al.gpr_reads, RegisterSet::of(Register::X(0)));
|
||||
assert_eq!(csel_al.gpr_writes, RegisterSet::of(Register::X(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_with_carry_covers_carry_borrow_overflow_and_zero_edges() {
|
||||
// W32: 0xffff_ffff + 0 + C=1 -> 0, Z=1 C=1 N=0 V=0 (0x6000_0000)
|
||||
assert_eq!(
|
||||
add_with_carry(Width::W32, 0xffff_ffff, 0, true),
|
||||
(0, NZCV_Z | NZCV_C)
|
||||
);
|
||||
// X64: 0xffff_ffff + 0 + C=1 -> 0x1_0000_0000, all flags clear
|
||||
assert_eq!(
|
||||
add_with_carry(Width::X64, 0xffff_ffff, 0, true),
|
||||
(0x1_0000_0000, 0)
|
||||
);
|
||||
// W32 signed overflow from carry alone: 0x7fff_ffff + 0 + 1 -> 0x8000_0000, N=1 V=1
|
||||
assert_eq!(
|
||||
add_with_carry(Width::W32, 0x7fff_ffff, 0, true),
|
||||
(0x8000_0000, NZCV_N | NZCV_V)
|
||||
);
|
||||
// SBCS W32: INT_MIN - 0 with borrow (C=0): AddWithCarry(0x8000_0000, 0xffff_ffff, false)
|
||||
assert_eq!(
|
||||
add_with_carry(Width::W32, 0x8000_0000, !0u32 as u64, false),
|
||||
(0x7fff_ffff, NZCV_C | NZCV_V)
|
||||
);
|
||||
// SBCS X64: 0 - 0 with C=1 (no borrow): 0, Z=1 C=1
|
||||
assert_eq!(
|
||||
add_with_carry(Width::X64, 0, !0u64, true),
|
||||
(0, NZCV_Z | NZCV_C)
|
||||
);
|
||||
// SBCS X64: 0 - 0 with C=0 (borrow): u64::MAX, N=1
|
||||
assert_eq!(
|
||||
add_with_carry(Width::X64, 0, !0u64, false),
|
||||
(u64::MAX, NZCV_N)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
//! runtime helper when software PAuth is enabled.
|
||||
|
||||
mod analysis;
|
||||
pub mod effects;
|
||||
mod features;
|
||||
mod host_gprs;
|
||||
pub mod loop_budget;
|
||||
@@ -26,6 +27,7 @@ pub use analysis::{
|
||||
SuccessorKind, analyze, analyze_with_profile, source_bytes, source_bytes_with_profile,
|
||||
};
|
||||
use analysis::{ParsedBlock, analyze_parsed, parse_admitted, parse_with};
|
||||
pub use effects::{BlockEffects, analyze_block_effects, eval_instructions, summarize_instructions};
|
||||
pub use features::{BlockProfile, Features};
|
||||
pub use host_gprs::HostGprSnapshot;
|
||||
pub use memory::{
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
//! Basic-block architectural side-effect composition built from per-instruction semantics.
|
||||
use super::BlockProfile;
|
||||
use super::analysis::{BlockAnalysisError, parse};
|
||||
use crate::{
|
||||
GuestAddress, GuestState,
|
||||
aarch64::{
|
||||
Instruction, Operation, Register,
|
||||
semantics::{FlagMask, RegisterSet, eval_instruction, semantics_of},
|
||||
},
|
||||
};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// Composed register and NZCV side-effect summary across a basic block.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BlockEffects {
|
||||
pub instruction_count: usize,
|
||||
pub fully_modeled: bool,
|
||||
pub live_in_gprs: RegisterSet,
|
||||
pub written_gprs: RegisterSet,
|
||||
pub live_in_flags: FlagMask,
|
||||
pub written_flags: FlagMask,
|
||||
pub killed_flags: FlagMask,
|
||||
/// Indices of instructions whose `NZCV` write is overwritten by a later
|
||||
/// instruction that redefines `FlagMask::ALL` before any bit is read.
|
||||
pub dead_flag_defs: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Summarize architectural register reads/writes, `NZCV` live-ins, and intra-block
|
||||
/// dead flag definitions across `instructions`.
|
||||
pub fn summarize_instructions(instructions: &[Instruction]) -> BlockEffects {
|
||||
summarize_with_exit(instructions, FlagMask::NONE, RegisterSet::NONE)
|
||||
}
|
||||
|
||||
/// Parse `source` at `base` using the ordinary block parser and compose its
|
||||
/// body effects together with any architectural terminal flag/register read.
|
||||
pub fn analyze_block_effects(
|
||||
source: &[u8],
|
||||
base: GuestAddress,
|
||||
) -> Result<BlockEffects, BlockAnalysisError> {
|
||||
let parsed = parse(source, base, BlockProfile::ORDINARY)?;
|
||||
let (exit_flags, exit_gprs) = match parsed.terminal.as_ref().map(|(_, term)| term) {
|
||||
Some(super::Terminator::Branch(Operation::BranchCondition { condition, .. })) => {
|
||||
(FlagMask::condition_reads(*condition), RegisterSet::NONE)
|
||||
}
|
||||
Some(super::Terminator::Branch(
|
||||
Operation::BranchZero { source, .. } | Operation::BranchBit { source, .. },
|
||||
)) => (FlagMask::NONE, RegisterSet::of(*source)),
|
||||
Some(super::Terminator::Register { source, .. }) => {
|
||||
(FlagMask::NONE, RegisterSet::of(*source))
|
||||
}
|
||||
Some(super::Terminator::DirectCall(_)) => (FlagMask::NONE, RegisterSet::NONE),
|
||||
Some(super::Terminator::Trap(_))
|
||||
| Some(super::Terminator::System(_))
|
||||
| Some(super::Terminator::PointerAuthentication(_))
|
||||
| Some(super::Terminator::Clock(_))
|
||||
| Some(super::Terminator::ThreadRegister(_))
|
||||
| Some(super::Terminator::FloatingPoint { .. })
|
||||
| Some(super::Terminator::Amx(_)) => (FlagMask::ALL, RegisterSet::NONE),
|
||||
_ => (FlagMask::NONE, RegisterSet::NONE),
|
||||
};
|
||||
let mut effects = summarize_with_exit(&parsed.instructions, exit_flags, exit_gprs);
|
||||
if matches!(
|
||||
parsed.terminal.as_ref().map(|(_, term)| term),
|
||||
Some(super::Terminator::Trap(_))
|
||||
| Some(super::Terminator::System(_))
|
||||
| Some(super::Terminator::PointerAuthentication(_))
|
||||
| Some(super::Terminator::Clock(_))
|
||||
| Some(super::Terminator::ThreadRegister(_))
|
||||
| Some(super::Terminator::FloatingPoint { .. })
|
||||
| Some(super::Terminator::Amx(_))
|
||||
) {
|
||||
effects.fully_modeled = false;
|
||||
}
|
||||
Ok(effects)
|
||||
}
|
||||
|
||||
fn summarize_with_exit(
|
||||
instructions: &[Instruction],
|
||||
exit_flag_reads: FlagMask,
|
||||
exit_gpr_reads: RegisterSet,
|
||||
) -> BlockEffects {
|
||||
let mut fully_modeled = true;
|
||||
let mut written_gprs = RegisterSet::NONE;
|
||||
let mut live_in_gprs = RegisterSet::NONE;
|
||||
let mut defined_all_flags = false;
|
||||
let mut written_flags = FlagMask::NONE;
|
||||
let mut live_in_flags = FlagMask::NONE;
|
||||
let mut live_before_write_flags = FlagMask::NONE;
|
||||
|
||||
for instruction in instructions {
|
||||
let Some(sem) = semantics_of(&instruction.operation) else {
|
||||
fully_modeled = false;
|
||||
continue;
|
||||
};
|
||||
let uncovered_gprs = sem.gpr_reads.difference(written_gprs);
|
||||
live_in_gprs = live_in_gprs.union(uncovered_gprs);
|
||||
written_gprs = written_gprs.union(sem.gpr_writes);
|
||||
|
||||
if !defined_all_flags {
|
||||
let unread_entry_flags = sem.flag_reads.difference(live_before_write_flags);
|
||||
live_in_flags = live_in_flags.union(unread_entry_flags);
|
||||
}
|
||||
written_flags = written_flags.union(sem.flag_writes);
|
||||
if sem.flag_writes == FlagMask::ALL {
|
||||
defined_all_flags = true;
|
||||
live_before_write_flags = FlagMask::ALL;
|
||||
}
|
||||
}
|
||||
|
||||
if !defined_all_flags {
|
||||
live_in_flags = live_in_flags.union(exit_flag_reads);
|
||||
}
|
||||
live_in_gprs = live_in_gprs.union(exit_gpr_reads.difference(written_gprs));
|
||||
|
||||
// Backward pass for intra-block dead flag definitions: NZCV is architecturally
|
||||
// live-out at block exit (`FlagMask::ALL`), so an instruction's flag write
|
||||
// is dead only if a later instruction in the same block overwrites every bit
|
||||
// it wrote before any intervening reader (or exit) observes them.
|
||||
let _ = exit_flag_reads;
|
||||
let mut live_flags_after = FlagMask::ALL;
|
||||
let mut dead_flag_defs = Vec::new();
|
||||
for (index, instruction) in instructions.iter().enumerate().rev() {
|
||||
let Some(sem) = semantics_of(&instruction.operation) else {
|
||||
// Unknown instructions may observe NZCV on block exit/fallback.
|
||||
live_flags_after = FlagMask::ALL;
|
||||
continue;
|
||||
};
|
||||
if !sem.flag_writes.is_empty() && !live_flags_after.intersects(sem.flag_writes) {
|
||||
dead_flag_defs.push(index);
|
||||
}
|
||||
live_flags_after = live_flags_after
|
||||
.difference(sem.flag_writes)
|
||||
.union(sem.flag_reads);
|
||||
}
|
||||
dead_flag_defs.reverse();
|
||||
|
||||
let killed_flags = if defined_all_flags {
|
||||
written_flags.difference(live_in_flags)
|
||||
} else {
|
||||
FlagMask::NONE
|
||||
};
|
||||
|
||||
BlockEffects {
|
||||
instruction_count: instructions.len(),
|
||||
fully_modeled,
|
||||
live_in_gprs,
|
||||
written_gprs,
|
||||
live_in_flags,
|
||||
written_flags,
|
||||
killed_flags,
|
||||
dead_flag_defs,
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate a slice of modeled instructions sequentially on `state`. Returns `None`
|
||||
/// if any instruction falls outside [`semantics_of`].
|
||||
pub fn eval_instructions(instructions: &[Instruction], state: &mut GuestState) -> Option<()> {
|
||||
for instruction in instructions {
|
||||
let sem = semantics_of(&instruction.operation)?;
|
||||
eval_instruction(&sem, state);
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Convenience helper for callers inspecting which `Register::X(i)` indices are in `set`.
|
||||
pub fn gpr_indices(set: RegisterSet) -> Vec<u8> {
|
||||
(0..31u8)
|
||||
.filter(|&i| set.contains(Register::X(i)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Lifter, aarch64::Decoder};
|
||||
|
||||
fn lift_words(words: &[u32]) -> Vec<Instruction> {
|
||||
words
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &w)| {
|
||||
Decoder
|
||||
.lift(GuestAddress(0x1000 + i as u64 * 4), w)
|
||||
.unwrap()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_carry_chain_and_dead_flag_kill() {
|
||||
// adds x4, x0, x2; adcs x5, x1, x3; csel x6, x4, x5, cs
|
||||
let u128_chain = lift_words(&[0xab02_0004, 0xba03_0025, 0x9a85_2086]);
|
||||
let effects = summarize_instructions(&u128_chain);
|
||||
assert!(effects.fully_modeled);
|
||||
assert_eq!(effects.live_in_flags, FlagMask::NONE);
|
||||
assert_eq!(effects.written_flags, FlagMask::ALL);
|
||||
assert_eq!(effects.killed_flags, FlagMask::ALL);
|
||||
// ADCS reads C from ADDS, CSEL reads C from ADCS, and NZCV is live-out at exit.
|
||||
assert!(effects.dead_flag_defs.is_empty());
|
||||
assert_eq!(
|
||||
effects.live_in_gprs,
|
||||
RegisterSet::from_registers([
|
||||
Register::X(0),
|
||||
Register::X(1),
|
||||
Register::X(2),
|
||||
Register::X(3),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
effects.written_gprs,
|
||||
RegisterSet::from_registers([Register::X(4), Register::X(5), Register::X(6)])
|
||||
);
|
||||
|
||||
// ADDS -> CSEL AL -> ADDS: CSEL AL reads no flags, so index 0 is dead.
|
||||
let al_kill = lift_words(&[0xab01_0004, 0x9a85_e086, 0xab03_0045]);
|
||||
let al_effects = summarize_instructions(&al_kill);
|
||||
assert_eq!(al_effects.live_in_flags, FlagMask::NONE);
|
||||
assert_eq!(al_effects.dead_flag_defs, vec![0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adcs_leading_block_requires_only_carry_in() {
|
||||
// adcs x4, x0, x2; sbcs x5, x1, x3; csel x6, x4, x5, hi
|
||||
let instructions = lift_words(&[0xba02_0004, 0xfa03_0025, 0x9a85_8086]);
|
||||
let effects = summarize_instructions(&instructions);
|
||||
assert_eq!(effects.live_in_flags, FlagMask::C);
|
||||
// Flipping N, Z, or V in entry NZCV must not change the output state.
|
||||
let mut s1 = GuestState::default();
|
||||
s1.x[0] = 0xffff_ffff_ffff_ffff;
|
||||
s1.x[1] = 10;
|
||||
s1.x[2] = 0;
|
||||
s1.x[3] = 4;
|
||||
s1.nzcv = crate::aarch64::flags::NZCV_C;
|
||||
|
||||
let mut s2 = s1.clone();
|
||||
s2.nzcv |= crate::aarch64::flags::NZCV_N
|
||||
| crate::aarch64::flags::NZCV_Z
|
||||
| crate::aarch64::flags::NZCV_V;
|
||||
|
||||
eval_instructions(&instructions, &mut s1).unwrap();
|
||||
eval_instructions(&instructions, &mut s2).unwrap();
|
||||
assert_eq!(s1.x, s2.x);
|
||||
assert_eq!(s1.nzcv, s2.nzcv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmodeled_trailing_instruction_keeps_flags_live_after_last_writer() {
|
||||
// adds x4, x0, x1; adds x5, x2, x3; csel x6, x4, x5, eq; branch exit
|
||||
let bytes: Vec<u8> = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086, 0x5400_0040]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let effects = analyze_block_effects(&bytes, GuestAddress(0x1000)).unwrap();
|
||||
assert!(effects.fully_modeled);
|
||||
assert_eq!(effects.live_in_flags, FlagMask::NONE);
|
||||
// First ADDS is dead because second ADDS overwrites all flags before CSEL EQ & B.EQ.
|
||||
assert_eq!(effects.dead_flag_defs, vec![0]);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ pub mod masked;
|
||||
pub mod pauth;
|
||||
pub mod processor;
|
||||
pub mod refusal;
|
||||
pub mod reims_hosted;
|
||||
pub mod tag_storage;
|
||||
pub mod uuid;
|
||||
|
||||
|
||||
@@ -1,445 +0,0 @@
|
||||
//! Guest-physical apertures for a copy-only hosted Reims device.
|
||||
//!
|
||||
//! The host transport owns the outer PCI resources. The inner guest sees the
|
||||
//! graphics registers below MSI-X, the command region and the doorbell pages.
|
||||
//! MSI-X and the guest's own RAM have separate ownership and are not forwarded.
|
||||
use alloc::boxed::Box;
|
||||
|
||||
use crate::{
|
||||
Refusal,
|
||||
bus::{self, Access, AdvancePolicy, Bus, DeviceId, Direction, MapError, MmioDevice, MmioError, Width},
|
||||
interrupt::{AicInput, Wire},
|
||||
};
|
||||
|
||||
/// Values from Reims graphics wire version 2 and its C transport header.
|
||||
const MAGIC: u64 = 1481000786;
|
||||
const VERSION: u64 = 2;
|
||||
const SURFACE_PAGES: u64 = 1;
|
||||
const POOL_FEATURES_HI: u64 = (1 << 25) | (1 << 27);
|
||||
const DOORBELL_PAGES_HI: u64 = 1 << (46 - 32);
|
||||
pub const REGISTER_BYTES: u64 = 2048;
|
||||
pub const REGION_BYTES: u64 = 1 << 30;
|
||||
pub const DOORBELL_BYTES: u64 = 4 << 20;
|
||||
/// Outer QEMU's hosted-only interrupt readouts in BAR4.
|
||||
pub const HOST_IRQ_SIGNATURE_OFFSET: u64 = DOORBELL_BYTES - 8;
|
||||
pub const HOST_IRQ_GENERATION_OFFSET: u64 = DOORBELL_BYTES - 4;
|
||||
pub const HOST_IRQ_SIGNATURE: u32 = 0x5249_5251;
|
||||
/// Guest read returns the observed generation. A matching write acknowledges it.
|
||||
pub const GUEST_IRQ_TOKEN: u64 = REGISTER_BYTES - 4;
|
||||
const ARM_PAGE: u64 = 16 << 10;
|
||||
// 250 us in the guest system counter's 24 MHz ticks.
|
||||
const IRQ_POLL_TICKS: u64 = 6000;
|
||||
|
||||
// Separate device offsets distinguish the three guest-physical mappings.
|
||||
const REGION_OFFSET: u64 = 1 << 32;
|
||||
const DOORBELL_OFFSET: u64 = 2 << 32;
|
||||
const NAME: &str = "Reims hosted graphics";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Bar {
|
||||
Registers,
|
||||
Region,
|
||||
Doorbells,
|
||||
}
|
||||
|
||||
/// The service that owns the outer device's three BARs. Values occupy the low
|
||||
/// bytes in little-endian order. Implementations must preserve the order in
|
||||
/// which the bus calls them and use the publication semantics of the wire.
|
||||
pub trait Transport {
|
||||
fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result<u64, Refusal>;
|
||||
fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal>;
|
||||
|
||||
/// A wrapping counter published by the host after it writes completion
|
||||
/// data. None means the transport has no notification channel.
|
||||
fn interrupt_generation(&mut self) -> Result<Option<u32>, Refusal> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// The ARM guest's physical bases, aligned to its 16 KiB page.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Apertures {
|
||||
pub registers: u64,
|
||||
pub region: u64,
|
||||
pub doorbells: u64,
|
||||
}
|
||||
|
||||
impl Apertures {
|
||||
/// Place the 1 GiB region first, followed by the registers and doorbells.
|
||||
pub fn at(base: u64) -> Option<Self> {
|
||||
if base == 0 || !base.is_multiple_of(REGION_BYTES) {
|
||||
return None;
|
||||
}
|
||||
let registers = base.checked_add(REGION_BYTES)?;
|
||||
let doorbells = registers.checked_add(DOORBELL_BYTES)?;
|
||||
doorbells.checked_add(DOORBELL_BYTES)?;
|
||||
Some(Self { registers, region: base, doorbells })
|
||||
}
|
||||
|
||||
/// Whether any of the device's three mappings intersects a RAM range.
|
||||
pub fn overlaps(self, start: u64, bytes: u64) -> bool {
|
||||
bytes != 0
|
||||
&& [
|
||||
(self.registers, REGISTER_BYTES),
|
||||
(self.region, REGION_BYTES),
|
||||
(self.doorbells, DOORBELL_BYTES),
|
||||
]
|
||||
.into_iter()
|
||||
.any(|(base, size)| {
|
||||
base < start.saturating_add(bytes) && start < base.saturating_add(size)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum InstallError {
|
||||
Alignment,
|
||||
WireVersion,
|
||||
GuestRamFeatures,
|
||||
ControlGeometry,
|
||||
InterruptUnavailable,
|
||||
InterruptInput,
|
||||
Transport(Refusal),
|
||||
Mapping(MapError),
|
||||
}
|
||||
|
||||
/// Check the outer device's protocol before exposing it to the ARM guest.
|
||||
pub fn validate_wire(transport: &mut impl Transport) -> Result<(), InstallError> {
|
||||
let mut register =
|
||||
|offset| transport.read(Bar::Registers, offset, Width::Word).map_err(InstallError::Transport);
|
||||
if register(0)? != MAGIC || register(4)? != VERSION {
|
||||
return Err(InstallError::WireVersion);
|
||||
}
|
||||
let lo = register(8)?;
|
||||
let hi = register(12)?;
|
||||
if lo & SURFACE_PAGES != 0 || hi & POOL_FEATURES_HI != 0 {
|
||||
return Err(InstallError::GuestRamFeatures);
|
||||
}
|
||||
if hi & DOORBELL_PAGES_HI == 0 || register(20)? != REGION_BYTES || register(24)? != 0 {
|
||||
return Err(InstallError::ControlGeometry);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Install the three ranges as one bus owner. The outer device must advertise
|
||||
/// the command region and doorbells without importing the inner guest's RAM.
|
||||
pub fn install(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, None, false)
|
||||
}
|
||||
|
||||
/// Install the device with a level AIC input serviced through GUEST_IRQ_TOKEN.
|
||||
pub fn install_with_interrupt(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
input: AicInput,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, Some(input), false)
|
||||
}
|
||||
|
||||
/// Install only registers and doorbells on the MMIO bus when BAR2 (the command
|
||||
/// and allocation region) is mapped directly in guest physical RAM.
|
||||
pub fn install_direct_region(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, None, true)
|
||||
}
|
||||
|
||||
/// [`install_direct_region`] with a level AIC input serviced through GUEST_IRQ_TOKEN.
|
||||
pub fn install_direct_region_with_interrupt(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
input: AicInput,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, Some(input), true)
|
||||
}
|
||||
|
||||
fn install_inner(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
mut transport: impl Transport + 'static,
|
||||
input: Option<AicInput>,
|
||||
direct_region: bool,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
if [addresses.registers, addresses.region, addresses.doorbells]
|
||||
.into_iter()
|
||||
.any(|address| !address.is_multiple_of(ARM_PAGE))
|
||||
{
|
||||
return Err(InstallError::Alignment);
|
||||
}
|
||||
validate_wire(&mut transport)?;
|
||||
let irq = if let Some(input) = input {
|
||||
let seen = transport
|
||||
.interrupt_generation()
|
||||
.map_err(InstallError::Transport)?
|
||||
.ok_or(InstallError::InterruptUnavailable)?;
|
||||
Some(Interrupt { input, seen, next_poll: 0 })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let device = Box::new(Device { transport, irq });
|
||||
if direct_region {
|
||||
bus.install(
|
||||
device,
|
||||
&[
|
||||
(addresses.registers, REGISTER_BYTES, 0),
|
||||
(addresses.doorbells, DOORBELL_BYTES, DOORBELL_OFFSET),
|
||||
],
|
||||
)
|
||||
.map_err(InstallError::Mapping)
|
||||
} else {
|
||||
bus.install(
|
||||
device,
|
||||
&[
|
||||
(addresses.registers, REGISTER_BYTES, 0),
|
||||
(addresses.region, REGION_BYTES, REGION_OFFSET),
|
||||
(addresses.doorbells, DOORBELL_BYTES, DOORBELL_OFFSET),
|
||||
],
|
||||
)
|
||||
.map_err(InstallError::Mapping)
|
||||
}
|
||||
}
|
||||
|
||||
struct Device<T> {
|
||||
transport: T,
|
||||
irq: Option<Interrupt>,
|
||||
}
|
||||
|
||||
struct Interrupt {
|
||||
input: AicInput,
|
||||
seen: u32,
|
||||
next_poll: u64,
|
||||
}
|
||||
|
||||
fn register(offset: u64, width: Width, direction: Direction) -> Result<(Bar, u64), MmioError> {
|
||||
if (REGION_OFFSET..REGION_OFFSET + REGION_BYTES).contains(&offset) {
|
||||
return Ok((Bar::Region, offset - REGION_OFFSET));
|
||||
}
|
||||
if width == Width::Word {
|
||||
if offset < REGISTER_BYTES {
|
||||
return Ok((Bar::Registers, offset));
|
||||
}
|
||||
if (DOORBELL_OFFSET..DOORBELL_OFFSET + DOORBELL_BYTES).contains(&offset) {
|
||||
return Ok((Bar::Doorbells, offset - DOORBELL_OFFSET));
|
||||
}
|
||||
}
|
||||
Err(bus::refuse(
|
||||
NAME,
|
||||
offset,
|
||||
width,
|
||||
direction,
|
||||
"graphics registers and doorbells take 32-bit accesses",
|
||||
))
|
||||
}
|
||||
|
||||
impl<T: Transport + 'static> MmioDevice for Device<T> {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn advance_policy(&self) -> AdvancePolicy {
|
||||
if self.irq.is_some() {
|
||||
AdvancePolicy::Always
|
||||
} else {
|
||||
AdvancePolicy::Passive
|
||||
}
|
||||
}
|
||||
|
||||
fn advance(&mut self, access: &mut Access<'_>) -> Result<Option<u64>, MmioError> {
|
||||
let Some(irq) = &mut self.irq else {
|
||||
return Ok(None);
|
||||
};
|
||||
if access.now >= irq.next_poll {
|
||||
let generation = self.transport.interrupt_generation().map_err(|error| {
|
||||
bus::refuse(NAME, GUEST_IRQ_TOKEN, Width::Word, Direction::Read, error)
|
||||
})?;
|
||||
let Some(generation) = generation else {
|
||||
return Err(bus::refuse(
|
||||
NAME, GUEST_IRQ_TOKEN, Width::Word, Direction::Read,
|
||||
"the host notification channel disappeared",
|
||||
));
|
||||
};
|
||||
if generation != irq.seen {
|
||||
irq.seen = generation;
|
||||
access.interrupts.set_level(Wire::Aic(irq.input), true);
|
||||
}
|
||||
irq.next_poll = access.now.saturating_add(IRQ_POLL_TICKS);
|
||||
}
|
||||
Ok(Some(irq.next_poll))
|
||||
}
|
||||
|
||||
fn read(&mut self, offset: u64, width: Width, _: &mut Access<'_>) -> Result<u64, MmioError> {
|
||||
let (bar, at) = register(offset, width, Direction::Read)?;
|
||||
if let Some(irq) = &self.irq
|
||||
&& bar == Bar::Registers
|
||||
&& at == GUEST_IRQ_TOKEN
|
||||
{
|
||||
return Ok(u64::from(irq.seen));
|
||||
}
|
||||
self.transport
|
||||
.read(bar, at, width)
|
||||
.map_err(|error| bus::refuse(NAME, offset, width, Direction::Read, error))
|
||||
}
|
||||
|
||||
fn write(
|
||||
&mut self,
|
||||
offset: u64,
|
||||
width: Width,
|
||||
value: u64,
|
||||
access: &mut Access<'_>,
|
||||
) -> Result<(), MmioError> {
|
||||
let (bar, at) = register(offset, width, Direction::Write)?;
|
||||
if let Some(irq) = &self.irq
|
||||
&& bar == Bar::Registers
|
||||
&& at == GUEST_IRQ_TOKEN
|
||||
{
|
||||
if value as u32 == irq.seen {
|
||||
access.interrupts.set_level(Wire::Aic(irq.input), false);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.transport
|
||||
.write(bar, at, width, value)
|
||||
.map_err(|error| bus::refuse(NAME, offset, width, Direction::Write, error))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::interrupt::InterruptLatch;
|
||||
use alloc::{rc::Rc, vec::Vec};
|
||||
use core::cell::{Cell, RefCell};
|
||||
|
||||
const ADDRESSES: Apertures = Apertures {
|
||||
registers: 0x2000_0000,
|
||||
region: 0x4000_0000,
|
||||
doorbells: 0x8040_0000,
|
||||
};
|
||||
|
||||
type Writes = Rc<RefCell<Vec<(Bar, u64, Width, u64)>>>;
|
||||
|
||||
struct FakeHost {
|
||||
surface_pages: bool,
|
||||
writes: Writes,
|
||||
generation: Option<Rc<Cell<u32>>>,
|
||||
}
|
||||
|
||||
impl Transport for FakeHost {
|
||||
fn read(&mut self, bar: Bar, offset: u64, _: Width) -> Result<u64, Refusal> {
|
||||
Ok(match (bar, offset) {
|
||||
(Bar::Registers, 0) => MAGIC,
|
||||
(Bar::Registers, 4) => VERSION,
|
||||
(Bar::Registers, 8) => u64::from(self.surface_pages),
|
||||
(Bar::Registers, 12) => DOORBELL_PAGES_HI,
|
||||
(Bar::Registers, 20) => REGION_BYTES,
|
||||
(Bar::Region, 256) => 0x4433_2211,
|
||||
_ => 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> {
|
||||
self.writes.borrow_mut().push((bar, offset, width, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn interrupt_generation(&mut self) -> Result<Option<u32>, Refusal> {
|
||||
Ok(self.generation.as_deref().map(Cell::get))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwards_the_three_graphics_apertures_excluding_outer_msix() {
|
||||
let writes = Writes::default();
|
||||
let mut bus = Bus::new();
|
||||
let host = FakeHost {
|
||||
surface_pages: false,
|
||||
writes: Rc::clone(&writes),
|
||||
generation: None,
|
||||
};
|
||||
install(&mut bus, ADDRESSES, host).unwrap();
|
||||
let mut interrupts = InterruptLatch::new();
|
||||
let mut access = Access::new(0, 0, &mut interrupts);
|
||||
assert_eq!(bus.read(ADDRESSES.registers, Width::Word, &mut access), Ok(MAGIC));
|
||||
assert_eq!(bus.read(ADDRESSES.region + 256, Width::Word, &mut access), Ok(0x4433_2211));
|
||||
assert!(bus.write(ADDRESSES.registers + 32, Width::Word, 0, &mut access).is_ok());
|
||||
assert!(bus.write(ADDRESSES.region + 8, Width::Double, 16, &mut access).is_ok());
|
||||
assert!(bus.write(ADDRESSES.doorbells + ARM_PAGE, Width::Word, 5, &mut access).is_ok());
|
||||
assert!(matches!(
|
||||
bus.write(ADDRESSES.registers + REGISTER_BYTES, Width::Word, 0, &mut access),
|
||||
Err(MmioError::Unmapped { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
bus.write(ADDRESSES.doorbells, Width::Byte, 1, &mut access),
|
||||
Err(MmioError::Unsupported { .. })
|
||||
));
|
||||
assert_eq!(
|
||||
&*writes.borrow(),
|
||||
&[
|
||||
(Bar::Registers, 32, Width::Word, 0),
|
||||
(Bar::Region, 8, Width::Double, 16),
|
||||
(Bar::Doorbells, ARM_PAGE, Width::Word, 5),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_outer_ram_features_and_conflicts_before_mapping_any_aperture() {
|
||||
let mut bus = Bus::new();
|
||||
let host = |surface_pages| FakeHost {
|
||||
surface_pages,
|
||||
writes: Writes::default(),
|
||||
generation: None,
|
||||
};
|
||||
assert_eq!(install(&mut bus, ADDRESSES, host(true)), Err(InstallError::GuestRamFeatures));
|
||||
assert_eq!(bus.name_at(ADDRESSES.registers), None);
|
||||
let conflict = Apertures { doorbells: ADDRESSES.region, ..ADDRESSES };
|
||||
assert_eq!(
|
||||
install(&mut bus, conflict, host(false)),
|
||||
Err(InstallError::Mapping(MapError::ProposedOverlap))
|
||||
);
|
||||
assert_eq!(bus.name_at(ADDRESSES.registers), None);
|
||||
assert_eq!(bus.name_at(ADDRESSES.region), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_irq_ack_keeps_an_observed_completion_pending() {
|
||||
let generation = Rc::new(Cell::new(u32::MAX));
|
||||
let mut bus = Bus::new();
|
||||
let input = AicInput::new(0, 740);
|
||||
let host = FakeHost {
|
||||
surface_pages: false,
|
||||
writes: Writes::default(),
|
||||
generation: Some(Rc::clone(&generation)),
|
||||
};
|
||||
install_with_interrupt(&mut bus, ADDRESSES, host, input).unwrap();
|
||||
let mut latch = InterruptLatch::new();
|
||||
let token = ADDRESSES.registers + GUEST_IRQ_TOKEN;
|
||||
let mut access = Access::new(0, 0, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(IRQ_POLL_TICKS)));
|
||||
assert!(latch.take_aic_inputs().is_empty());
|
||||
|
||||
generation.set(0);
|
||||
let mut access = Access::new(0, IRQ_POLL_TICKS, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(2 * IRQ_POLL_TICKS)));
|
||||
assert_eq!(bus.read(token, Width::Word, &mut access), Ok(0));
|
||||
assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, true)]);
|
||||
|
||||
generation.set(1);
|
||||
let mut access = Access::new(0, 2 * IRQ_POLL_TICKS, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(3 * IRQ_POLL_TICKS)));
|
||||
bus.write(token, Width::Word, 0, &mut access).unwrap();
|
||||
assert!(latch.take_aic_inputs().is_empty());
|
||||
|
||||
let mut access = Access::new(0, 2 * IRQ_POLL_TICKS, &mut latch);
|
||||
bus.write(token, Width::Word, 1, &mut access).unwrap();
|
||||
assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, false)]);
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
//! A manual integration fixture for a realized, paused x86 QEMU Reims device.
|
||||
#![cfg(feature = "std")]
|
||||
|
||||
use std::{
|
||||
env,
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::{SocketAddr, TcpStream},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use stela_contracts::{
|
||||
Refusal,
|
||||
bus::{Access, Bus, Width},
|
||||
interrupt::InterruptLatch,
|
||||
reims_hosted::{self, Apertures, Bar, Transport},
|
||||
};
|
||||
|
||||
struct Qtest {
|
||||
stream: BufReader<TcpStream>,
|
||||
bases: [u64; 3],
|
||||
}
|
||||
|
||||
impl Qtest {
|
||||
fn address(&self, bar: Bar, offset: u64) -> Result<u64, Refusal> {
|
||||
let index = match bar {
|
||||
Bar::Registers => 0,
|
||||
Bar::Region => 1,
|
||||
Bar::Doorbells => 2,
|
||||
};
|
||||
self.bases[index]
|
||||
.checked_add(offset)
|
||||
.ok_or_else(|| Refusal::new("QTest address overflow"))
|
||||
}
|
||||
|
||||
fn request(&mut self, command: &str) -> Result<Option<u64>, Refusal> {
|
||||
writeln!(self.stream.get_mut(), "{command}")
|
||||
.map_err(|_| Refusal::new("could not write QTest command"))?;
|
||||
let mut line = String::new();
|
||||
loop {
|
||||
line.clear();
|
||||
if self.stream.read_line(&mut line).map_err(|_| Refusal::new("QTest response failed"))? == 0
|
||||
{
|
||||
return Err(Refusal::new("QTest connection closed"));
|
||||
}
|
||||
let mut words = line.split_whitespace();
|
||||
match words.next() {
|
||||
Some("IRQ") => continue,
|
||||
Some("OK") => {
|
||||
return words
|
||||
.next()
|
||||
.map(|word| {
|
||||
u64::from_str_radix(word.trim_start_matches("0x"), 16)
|
||||
.map_err(|_| Refusal::new("invalid QTest value"))
|
||||
})
|
||||
.transpose();
|
||||
}
|
||||
_ => return Err(stela_contracts::refuse!("QTest rejected the request", command, line)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn suffix(width: Width) -> &'static str {
|
||||
match width {
|
||||
Width::Byte => "b",
|
||||
Width::Half => "w",
|
||||
Width::Word => "l",
|
||||
Width::Double => "q",
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Qtest {
|
||||
fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result<u64, Refusal> {
|
||||
let addr = self.address(bar, offset)?;
|
||||
self.request(&format!("read{} {addr:#x}", suffix(width)))?
|
||||
.ok_or_else(|| Refusal::new("QTest read returned no value"))
|
||||
}
|
||||
|
||||
fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> {
|
||||
let addr = self.address(bar, offset)?;
|
||||
self.request(&format!("write{} {addr:#x} {value:#x}", suffix(width))).map(drop)
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_env(name: &str) -> u64 {
|
||||
u64::from_str_radix(env::var(name).unwrap().trim_start_matches("0x"), 16).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a paused hosted Reims QEMU fixture"]
|
||||
fn arm_guest_apertures_carry_a_display_query_to_reims() {
|
||||
let addr: SocketAddr = env::var("STELA_REIMS_QTEST").unwrap().parse().unwrap();
|
||||
assert!(addr.ip().is_loopback());
|
||||
let stream = TcpStream::connect_timeout(&addr, Duration::from_secs(3)).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut host = Qtest {
|
||||
stream: BufReader::new(stream),
|
||||
bases: [
|
||||
hex_env("STELA_REIMS_PCI_BAR0"),
|
||||
hex_env("STELA_REIMS_PCI_BAR2"),
|
||||
hex_env("STELA_REIMS_PCI_BAR4"),
|
||||
],
|
||||
};
|
||||
let pci_config = 0x8000_2000u32;
|
||||
host.request(&format!("outl 0xcf8 {pci_config:#x}")).unwrap();
|
||||
assert_eq!(host.request("inl 0xcfc").unwrap(), Some(0x5247_1234));
|
||||
let [bar0, bar2, bar4] = host.bases;
|
||||
for (offset, value) in [(0x10, bar0), (0x18, bar2 & 0xffff_ffff), (0x1c, bar2 >> 32), (0x20, bar4)] {
|
||||
host.request(&format!("outl 0xcf8 {:#x}", pci_config + offset)).unwrap();
|
||||
host.request(&format!("outl 0xcfc {value:#x}")).unwrap();
|
||||
}
|
||||
host.request(&format!("outl 0xcf8 {:#x}", pci_config + 4)).unwrap();
|
||||
host.request("outw 0xcfc 0x2").unwrap();
|
||||
// These ARM physical addresses are intentionally different from the host's BARs.
|
||||
let arm = Apertures {
|
||||
registers: 0x2000_0000,
|
||||
region: 0x4000_0000,
|
||||
doorbells: 0x8040_0000,
|
||||
};
|
||||
let mut bus = Bus::new();
|
||||
reims_hosted::install(&mut bus, arm, host).unwrap();
|
||||
let mut interrupts = InterruptLatch::new();
|
||||
let mut access = Access::new(0, 0, &mut interrupts);
|
||||
assert_eq!(bus.read(arm.registers, Width::Word, &mut access).unwrap(), 1481000786);
|
||||
assert!(bus.read(arm.registers + 2048, Width::Word, &mut access).is_err());
|
||||
assert_eq!(bus.read(arm.doorbells, Width::Word, &mut access).unwrap(), 0);
|
||||
|
||||
// Wire v2: a 16-byte GET_DISPLAYS header, then publish its ring producer.
|
||||
let submit = arm.region + 256;
|
||||
let complete = arm.region + 65536;
|
||||
assert_eq!(bus.read(complete, Width::Double, &mut access).unwrap(), 0);
|
||||
bus.write(arm.registers + 16, Width::Word, 1, &mut access).unwrap();
|
||||
bus.write(submit, Width::Word, 1, &mut access).unwrap();
|
||||
bus.write(submit + 4, Width::Word, 16, &mut access).unwrap();
|
||||
bus.write(submit + 8, Width::Double, 1, &mut access).unwrap();
|
||||
bus.write(arm.region, Width::Double, 16, &mut access).unwrap();
|
||||
bus.write(arm.registers + 32, Width::Word, 0, &mut access).unwrap();
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while bus.read(complete, Width::Double, &mut access).unwrap() == 0 {
|
||||
assert!(Instant::now() < until, "Reims did not reply to GET_DISPLAYS");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(bus.read(complete + 256, Width::Word, &mut access).unwrap(), 257);
|
||||
assert_eq!(bus.read(complete + 264, Width::Double, &mut access).unwrap(), 1);
|
||||
assert_eq!(bus.read(complete + 272, Width::Word, &mut access).unwrap(), 1);
|
||||
println!("ARM guest addresses carried GET_DISPLAYS to the hosted device and received one display");
|
||||
}
|
||||
@@ -320,13 +320,12 @@ impl Linux {
|
||||
common_environment.profile(&mut common_build, None, &[], None);
|
||||
let mut common_build = upstream_build(&common_build, Path::new("src/compat"));
|
||||
upstream_warnings(&mut common_build);
|
||||
let registration = Path::new("src/compat").join("stela/registration.h");
|
||||
let common_profiles = COMMON
|
||||
.iter()
|
||||
.map(|spec| {
|
||||
linux_capture::profile(
|
||||
&common_build,
|
||||
®istration,
|
||||
Path::new("src/compat/stela/registration.h"),
|
||||
*spec,
|
||||
Path::new("../stela-linux"),
|
||||
)
|
||||
|
||||
@@ -40,7 +40,6 @@ mod power;
|
||||
#[cfg(feature = "native-acpi")]
|
||||
pub use power::{EmbeddedControllerInstallation, Power, install_embedded_controller};
|
||||
pub mod native;
|
||||
pub mod reims_hosted;
|
||||
#[cfg(any(test, feature = "native-acpi"))]
|
||||
mod platform;
|
||||
pub mod services;
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
//! Host PCI access for the copy-only Reims ARM64 transport.
|
||||
use super::{NativeServices, services::claim_unmastered};
|
||||
use crate::bus::{
|
||||
mmio::owned::Mapping,
|
||||
pci::{self, Address, Function, owned::OwnedConfig},
|
||||
};
|
||||
use core::ptr::NonNull;
|
||||
use stela_contracts::{
|
||||
Refusal,
|
||||
bus::Width,
|
||||
refuse,
|
||||
reims_hosted::{
|
||||
self, Bar, DOORBELL_BYTES, HOST_IRQ_GENERATION_OFFSET, HOST_IRQ_SIGNATURE,
|
||||
HOST_IRQ_SIGNATURE_OFFSET, REGION_BYTES, REGISTER_BYTES, Transport,
|
||||
},
|
||||
};
|
||||
|
||||
pub const VENDOR: u16 = 0x1234;
|
||||
pub const DEVICE: u16 = 0x5247;
|
||||
// The physical BAR includes MSI-X data above the wire's register window.
|
||||
const REGISTER_BAR_BYTES: u64 = 4096;
|
||||
|
||||
/// The host function and its uncached BAR mappings. The original PCI owner
|
||||
/// keeps bus mastering sealed off. MSI-X is not part of this transport.
|
||||
pub struct PciTransport {
|
||||
registers: Mapping,
|
||||
region: Option<Mapping>,
|
||||
region_base: u64,
|
||||
doorbells: Mapping,
|
||||
hosted_irq: bool,
|
||||
_function: Function<OwnedConfig>,
|
||||
}
|
||||
|
||||
impl PciTransport {
|
||||
pub fn open(services: &dyn NativeServices, address: Address) -> Result<Self, Refusal> {
|
||||
Self::open_inner(services, address, None)
|
||||
}
|
||||
|
||||
/// Open the host PCI function while leaving BAR2 unmapped in the uncached
|
||||
/// MMIO aperture because the loader already mapped BAR2 write-back into
|
||||
/// guest physical RAM at `expected_region`.
|
||||
pub fn open_direct_region(
|
||||
services: &dyn NativeServices,
|
||||
address: Address,
|
||||
expected_region: u64,
|
||||
) -> Result<Self, Refusal> {
|
||||
Self::open_inner(services, address, Some(expected_region))
|
||||
}
|
||||
|
||||
fn open_inner(
|
||||
services: &dyn NativeServices,
|
||||
address: Address,
|
||||
direct_region: Option<u64>,
|
||||
) -> Result<Self, Refusal> {
|
||||
let requester = claim_unmastered(services, address)
|
||||
.map_err(|error| refuse!("Reims PCI ownership: {error}", %error))?;
|
||||
let mut function = requester.into_function();
|
||||
if function.vendor != VENDOR || function.device != DEVICE {
|
||||
return Err(refuse!("Reims PCI identity changed after enumeration"));
|
||||
}
|
||||
let bars = function.bars().map_err(|error| refuse!("Reims PCI BARs: {error}", %error))?;
|
||||
let memory = |index: usize, bytes: u64| {
|
||||
let Some(bar @ pci::Bar::Memory { .. }) = bars[index] else {
|
||||
return Err(refuse!("Reims PCI BAR {index} is not memory", index));
|
||||
};
|
||||
let span = bar
|
||||
.memory()
|
||||
.ok_or_else(|| refuse!("Reims PCI BAR {index} is unassigned", index))?;
|
||||
if span.start == 0 || span.end - span.start != bytes {
|
||||
return Err(refuse!("Reims PCI BAR {index} has unexpected geometry", index));
|
||||
}
|
||||
Ok((bar, span.start))
|
||||
};
|
||||
let (registers, _) = memory(0, REGISTER_BAR_BYTES)?;
|
||||
let (region_bar, region_base) = memory(2, REGION_BYTES)?;
|
||||
let (doorbells, _) = memory(4, DOORBELL_BYTES)?;
|
||||
let map = |index, bar| {
|
||||
services
|
||||
.map_bar(address, bar)
|
||||
.map_err(|error| refuse!("Reims PCI BAR {index}: {error}", index, %error))
|
||||
};
|
||||
let registers = map(0, registers)?;
|
||||
let region = match direct_region {
|
||||
Some(expected) => {
|
||||
if region_base != expected {
|
||||
return Err(refuse!(
|
||||
"Reims PCI BAR 2 moved after firmware capture ({region_base:#x} != {expected:#x})",
|
||||
region_base,
|
||||
expected
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
None => Some(map(2, region_bar)?),
|
||||
};
|
||||
let doorbells = map(4, doorbells)?;
|
||||
function
|
||||
.enable_polled_decode()
|
||||
.map_err(|error| refuse!("Reims PCI memory decoding: {error}", ?error))?;
|
||||
let hosted_irq = doorbells
|
||||
.read32(HOST_IRQ_SIGNATURE_OFFSET as usize)
|
||||
.map_err(|error| refuse!("Reims host IRQ signature: {error}", ?error))?
|
||||
== HOST_IRQ_SIGNATURE;
|
||||
let mut transport = Self {
|
||||
registers,
|
||||
region,
|
||||
region_base,
|
||||
doorbells,
|
||||
hosted_irq,
|
||||
_function: function,
|
||||
};
|
||||
reims_hosted::validate_wire(&mut transport)
|
||||
.map_err(|error| refuse!("Reims graphics wire: {error}", ?error))?;
|
||||
Ok(transport)
|
||||
}
|
||||
|
||||
/// Verify the mapped wire and report its host apertures in a diagnostic boot.
|
||||
pub fn probe(services: &dyn NativeServices, address: Address) -> Result<[u64; 3], Refusal> {
|
||||
let mut transport = Self::open(services, address)?;
|
||||
let bases = transport.bases();
|
||||
if let Some(region) = &mut transport.region {
|
||||
// SAFETY: this transport has only read its wire registers; no
|
||||
// driver, callback or raw pointer can still access the mapping.
|
||||
unsafe { region.retire() }
|
||||
.map_err(|error| refuse!("retire Reims PCI BAR: {error}", ?error))?;
|
||||
}
|
||||
for mapping in [&mut transport.doorbells, &mut transport.registers] {
|
||||
// SAFETY: this transport has only read its wire registers; no
|
||||
// driver, callback or raw pointer can still access the mapping.
|
||||
unsafe { mapping.retire() }
|
||||
.map_err(|error| refuse!("retire Reims PCI BAR: {error}", ?error))?;
|
||||
}
|
||||
bases
|
||||
}
|
||||
|
||||
pub fn bases(&self) -> Result<[u64; 3], Refusal> {
|
||||
let base = |mapping: &Mapping| {
|
||||
mapping
|
||||
.physical_span()
|
||||
.map(|span| span.start())
|
||||
.map_err(|error| refuse!("Reims PCI BAR mapping: {error}", ?error))
|
||||
};
|
||||
let region = match &self.region {
|
||||
Some(mapping) => base(mapping)?,
|
||||
None => self.region_base,
|
||||
};
|
||||
Ok([base(&self.registers)?, region, base(&self.doorbells)?])
|
||||
}
|
||||
|
||||
fn address(&self, bar: Bar, offset: u64, width: Width) -> Result<NonNull<u8>, Refusal> {
|
||||
let (mapping, limit) = match bar {
|
||||
Bar::Registers => (&self.registers, REGISTER_BYTES),
|
||||
Bar::Region => (
|
||||
self.region
|
||||
.as_ref()
|
||||
.ok_or_else(|| refuse!("Reims PCI BAR 2 is direct-mapped RAM"))?,
|
||||
REGION_BYTES,
|
||||
),
|
||||
Bar::Doorbells => (&self.doorbells, DOORBELL_BYTES),
|
||||
};
|
||||
let bytes = width.bytes();
|
||||
if !offset.is_multiple_of(bytes)
|
||||
|| offset.checked_add(bytes).is_none_or(|end| end > limit)
|
||||
|| (bar != Bar::Region && width != Width::Word)
|
||||
{
|
||||
return Err(refuse!("Reims PCI access outside its aligned aperture"));
|
||||
}
|
||||
mapping
|
||||
.address(offset as usize, bytes as usize)
|
||||
.map_err(|error| refuse!("Reims PCI BAR access: {error}", ?error))
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for PciTransport {
|
||||
fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result<u64, Refusal> {
|
||||
let address = self.address(bar, offset, width)?;
|
||||
if bar == Bar::Doorbells && offset >= HOST_IRQ_SIGNATURE_OFFSET {
|
||||
return Ok(0);
|
||||
}
|
||||
// SAFETY: the live uncached mapping covers this naturally aligned
|
||||
// access. The transport has the only owner that can access the BAR.
|
||||
Ok(unsafe {
|
||||
match width {
|
||||
Width::Byte => u64::from(address.read_volatile()),
|
||||
Width::Half => u64::from(u16::from_le(address.cast::<u16>().read_volatile())),
|
||||
Width::Word => u64::from(u32::from_le(address.cast::<u32>().read_volatile())),
|
||||
Width::Double => u64::from_le(address.cast::<u64>().read_volatile()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> {
|
||||
let address = self.address(bar, offset, width)?;
|
||||
// SAFETY: as for read; the uncached x86 mapping orders the accesses
|
||||
// to the ring before a subsequent MMIO doorbell.
|
||||
unsafe {
|
||||
match width {
|
||||
Width::Byte => address.write_volatile(value as u8),
|
||||
Width::Half => address.cast::<u16>().write_volatile((value as u16).to_le()),
|
||||
Width::Word => address.cast::<u32>().write_volatile((value as u32).to_le()),
|
||||
Width::Double => address.cast::<u64>().write_volatile(value.to_le()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn interrupt_generation(&mut self) -> Result<Option<u32>, Refusal> {
|
||||
if !self.hosted_irq {
|
||||
return Ok(None);
|
||||
}
|
||||
self.doorbells
|
||||
.read32(HOST_IRQ_GENERATION_OFFSET as usize)
|
||||
.map(Some)
|
||||
.map_err(|error| refuse!("Reims host IRQ generation: {error}", ?error))
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//! The boot kernel collection an auxiliary collection links against: its
|
||||
//! identity, its base and the symbols each of its fileset entries defines.
|
||||
use alloc::{collections::BTreeMap, vec::Vec};
|
||||
use alloc::collections::BTreeMap;
|
||||
|
||||
use super::{fit, fixups::Signature};
|
||||
use super::fit;
|
||||
use crate::{Result, Within};
|
||||
use object::{
|
||||
LittleEndian as LE, macho,
|
||||
@@ -15,13 +15,6 @@ use crate::kernel_collection::KernelCollection;
|
||||
/// The kernel's entry, which defines every `com.apple.kpi.*` interface.
|
||||
pub const KERNEL: &str = "com.apple.kernel";
|
||||
|
||||
/// A virtual method in the boot collection, before XNU applies its fixup.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Method {
|
||||
pub address: u64,
|
||||
pub signature: Signature,
|
||||
}
|
||||
|
||||
pub struct BootCollection<'a> {
|
||||
data: &'a [u8],
|
||||
collection: KernelCollection,
|
||||
@@ -62,13 +55,15 @@ impl<'a> BootCollection<'a> {
|
||||
self.collection.fileset_entry(entry).is_some()
|
||||
}
|
||||
|
||||
fn span(&self, address: u64, size: u64) -> Result<&'a [u8]> {
|
||||
/// The target of the pointer the collection holds at `address`, which
|
||||
/// its chained fixups encode, or `None` for a null slot.
|
||||
pub fn pointer(&self, address: u64) -> Result<Option<u64>> {
|
||||
let segment = self
|
||||
.collection
|
||||
.segment_containing(address)
|
||||
.ok_or_else(|| refuse!("{address:#x} lies outside the boot collection", address))?;
|
||||
require!(
|
||||
size <= segment.file_size.saturating_sub(address - segment.vm_address),
|
||||
address + 8 <= segment.vm_address + segment.file_size,
|
||||
"{address:#x} has no bytes in the boot collection",
|
||||
address
|
||||
);
|
||||
@@ -76,16 +71,15 @@ impl<'a> BootCollection<'a> {
|
||||
segment.file_offset + (address - segment.vm_address),
|
||||
"a boot collection file offset",
|
||||
)?;
|
||||
let size: usize = fit(size, "a boot collection span size")?;
|
||||
self.data
|
||||
.get(offset..offset + size)
|
||||
.ok_or_else(|| refuse!("a boot collection span {address:#x} past the file", address).into())
|
||||
}
|
||||
|
||||
/// The target of the pointer the collection holds at `address`, which
|
||||
/// its chained fixups encode, or `None` for a null slot.
|
||||
pub fn pointer(&self, address: u64) -> Result<Option<u64>> {
|
||||
let raw = u64::from_le_bytes(self.span(address, 8)?.try_into().unwrap());
|
||||
let raw = u64::from_le_bytes(
|
||||
self.data
|
||||
.get(offset..offset + 8)
|
||||
.and_then(|bytes| bytes.try_into().ok())
|
||||
.ok_or(refuse!(
|
||||
"a boot collection pointer {address:#x} past the file",
|
||||
address
|
||||
))?,
|
||||
);
|
||||
if raw == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -97,89 +91,6 @@ impl<'a> BootCollection<'a> {
|
||||
Ok(Some(self.base() + (raw & 0x3fff_ffff)))
|
||||
}
|
||||
|
||||
/// Read a named C++ vtable from its own fileset member, including methods
|
||||
/// that are private to that member. This never adds them to its exports.
|
||||
pub(super) fn methods(&self, entry: &str, name: &str) -> Result<Vec<Method>> {
|
||||
let offset = self
|
||||
.collection
|
||||
.fileset_entry(entry)
|
||||
.ok_or_else(|| refuse!("the boot collection has no {entry}", entry))?
|
||||
.file_offset;
|
||||
let header = macho::MachHeader64::<LE>::parse(self.data, offset)?;
|
||||
let mut commands = header.load_commands(LE, self.data, offset)?;
|
||||
while let Some(command) = commands.next()? {
|
||||
let Some(symtab) = command.symtab()? else {
|
||||
continue;
|
||||
};
|
||||
let table = symtab.symbols::<macho::MachHeader64<LE>, _>(LE, self.data)?;
|
||||
let defined = |symbol: &&macho::Nlist64<LE>| {
|
||||
symbol.n_type() & (macho::N_STAB | macho::N_TYPE) == macho::N_SECT
|
||||
};
|
||||
for symbol in table.iter().filter(defined) {
|
||||
if symbol.name(LE, table.strings())? != name.as_bytes() {
|
||||
continue;
|
||||
}
|
||||
let start = symbol.n_value(LE);
|
||||
let end = table
|
||||
.iter()
|
||||
.filter(defined)
|
||||
.filter(|candidate| candidate.n_sect() == symbol.n_sect())
|
||||
.map(|candidate| candidate.n_value(LE))
|
||||
.filter(|&address| address > start)
|
||||
.min()
|
||||
.ok_or(refuse!("no boundary for {entry}'s {name}", entry, name))?;
|
||||
let size = end - start;
|
||||
require!(
|
||||
(24..=32768).contains(&size) && size.is_multiple_of(8),
|
||||
"{entry}'s {name} has an invalid size {size}",
|
||||
entry, name, size
|
||||
);
|
||||
let words = self.span(start, size)?;
|
||||
require!(
|
||||
words[..16] == [0; 16],
|
||||
"{entry}'s {name} has a nonzero C++ vtable header",
|
||||
entry, name
|
||||
);
|
||||
let methods = words[16..]
|
||||
.chunks_exact(8)
|
||||
.map(|word| u64::from_le_bytes(word.try_into().unwrap()));
|
||||
let mut methods = methods.collect::<Vec<_>>();
|
||||
while methods.last() == Some(&0) {
|
||||
methods.pop();
|
||||
}
|
||||
require!(!methods.is_empty(), "{entry}'s {name} has no methods", entry, name);
|
||||
return methods
|
||||
.into_iter()
|
||||
.map(|word| {
|
||||
require!(
|
||||
word >> 63 == 1 && (word >> 30 & 3) == 0 && (word >> 48 & 7) == 1,
|
||||
"{entry}'s {name} does not contain only authenticated boot methods",
|
||||
entry, name
|
||||
);
|
||||
let address = self.base() + (word & 0x3fff_ffff);
|
||||
require!(
|
||||
self.collection.segment_containing(address).is_some_and(|segment| {
|
||||
segment.initial_protection & 4 != 0
|
||||
&& address - segment.vm_address < segment.file_size
|
||||
}),
|
||||
"{entry}'s {name} points outside boot code",
|
||||
entry, name
|
||||
);
|
||||
Ok(Method {
|
||||
address,
|
||||
signature: Signature {
|
||||
key: 0,
|
||||
address_diversity: true,
|
||||
diversity: (word >> 32) as u16,
|
||||
},
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
Err(refuse!("no {name} in {entry}", name, entry).into())
|
||||
}
|
||||
|
||||
/// The external symbols `entry` defines, by name, at their unslid
|
||||
/// addresses.
|
||||
pub fn exports(&self, entry: &str) -> Result<BTreeMap<&'a str, u64>> {
|
||||
|
||||
@@ -25,8 +25,6 @@ use super::{
|
||||
relocatable::{self, Definition, Kind, Object, Target},
|
||||
};
|
||||
|
||||
mod vtable;
|
||||
|
||||
/// A kext's segments, in the order its Mach-O header lists them.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Region {
|
||||
@@ -113,13 +111,6 @@ struct Vtable {
|
||||
end: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct VtableBinding {
|
||||
value: Value,
|
||||
/// None keeps the object's discriminator for ordinary inheritance.
|
||||
signature: Option<Signature>,
|
||||
}
|
||||
|
||||
/// What a pointer-sized slot holds.
|
||||
enum Slot {
|
||||
Fixup(Pointer),
|
||||
@@ -160,7 +151,7 @@ pub struct Unit<'a> {
|
||||
stub_sections: Option<(usize, usize)>,
|
||||
/// Vtable slots bound to the superclass's entry rather than the symbol
|
||||
/// the object names, by (object, section, relocation offset).
|
||||
inherited: BTreeMap<(usize, usize, u64), VtableBinding>,
|
||||
inherited: BTreeMap<(usize, usize, u64), Value>,
|
||||
/// Each region's addresses, assigned by the collection's layout; the
|
||||
/// `__TEXT` region starts with the kext's Mach-O header.
|
||||
pub ranges: [Range<u64>; 4],
|
||||
@@ -618,20 +609,18 @@ impl<'a> Unit<'a> {
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let (value, addend, signature) = match relocation.target {
|
||||
let (value, addend) = match relocation.target {
|
||||
// The bytes in place hold the target's object address.
|
||||
Target::Section(target) => {
|
||||
(self.locate(object, target, relocation.addend as u64)?, 0, signature)
|
||||
(self.locate(object, target, relocation.addend as u64)?, 0)
|
||||
}
|
||||
Target::Symbol(_) => {
|
||||
match self.inherited.get(&(object, input, relocation.offset)) {
|
||||
Some(binding) => (
|
||||
binding.value,
|
||||
relocation.addend,
|
||||
binding.signature.or(signature),
|
||||
),
|
||||
None => (self.resolve(object, relocation.target)?, relocation.addend, signature),
|
||||
}
|
||||
let inherited = self.inherited.get(&(object, input, relocation.offset));
|
||||
let value = match inherited {
|
||||
Some(&value) => value,
|
||||
None => self.resolve(object, relocation.target)?,
|
||||
};
|
||||
(value, relocation.addend)
|
||||
}
|
||||
};
|
||||
let slot = self.slot(value, addend, boot, signature)?;
|
||||
@@ -705,9 +694,6 @@ impl<'a> Unit<'a> {
|
||||
fn inherit(&mut self, boot: &BootCollection<'_>) -> Result<()> {
|
||||
let vtables = self.vtables();
|
||||
let mut done = BTreeSet::new();
|
||||
if let Some(binding) = self.info.remove(vtable::INFO_KEY) {
|
||||
done.insert(self.bind_vtable(binding, &vtables, boot)?);
|
||||
}
|
||||
let mut names: Vec<&String> = vtables.keys().collect();
|
||||
names.sort();
|
||||
for name in names {
|
||||
@@ -844,10 +830,7 @@ impl<'a> Unit<'a> {
|
||||
}
|
||||
self.inherited.insert(
|
||||
(vtable.object, vtable.section, relocation.offset),
|
||||
VtableBinding {
|
||||
value: inherited,
|
||||
signature: None,
|
||||
},
|
||||
inherited,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
@@ -908,7 +891,7 @@ impl<'a> Unit<'a> {
|
||||
};
|
||||
let key = (vtable.object, vtable.section, relocation.offset);
|
||||
match self.inherited.get(&key) {
|
||||
Some(binding) => Ok(Some(binding.value)),
|
||||
Some(&value) => Ok(Some(value)),
|
||||
None => self.resolve(vtable.object, relocation.target).map(Some),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
//! Rebind a consumer's own vtable during AuxKC linking. The recorded
|
||||
//! override slots belong to one BootKC. Inherited methods are read from that
|
||||
//! collection's parent table, and their signatures come from the oldest
|
||||
//! declared ancestor that has each slot.
|
||||
use alloc::{borrow::ToOwned, collections::BTreeMap, string::String, vec::Vec};
|
||||
|
||||
use stela_contracts::{refuse, require};
|
||||
|
||||
use super::{
|
||||
BootCollection, Dictionary, Kind, Region, Target, Unit, Value, Vtable, VtableBinding,
|
||||
plist, vtable_class,
|
||||
};
|
||||
use crate::Result;
|
||||
|
||||
pub(super) const INFO_KEY: &str = "StelaVtableBindings";
|
||||
|
||||
fn field<'a>(dict: &'a Dictionary, key: &str) -> Result<&'a plist::Value> {
|
||||
dict.get(key)
|
||||
.ok_or_else(|| refuse!("{INFO_KEY} has no {key}", INFO_KEY, key).into())
|
||||
}
|
||||
|
||||
fn text<'a>(dict: &'a Dictionary, key: &str) -> Result<&'a str> {
|
||||
field(dict, key)?
|
||||
.as_string()
|
||||
.ok_or_else(|| refuse!("{key} must be a string", key).into())
|
||||
}
|
||||
|
||||
fn array<'a>(dict: &'a Dictionary, key: &str) -> Result<&'a [plist::Value]> {
|
||||
match field(dict, key)? {
|
||||
plist::Value::Array(values) => Ok(values),
|
||||
_ => Err(refuse!("{key} must be an array", key).into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn method_index(dict: &Dictionary, key: &str) -> Result<u64> {
|
||||
match field(dict, key)? {
|
||||
plist::Value::Integer(slot) if (2..4096).contains(slot) => Ok(*slot - 2),
|
||||
_ => Err(refuse!("{key} must name a method slot", key).into()),
|
||||
}
|
||||
}
|
||||
|
||||
impl Unit<'_> {
|
||||
pub(super) fn bind_vtable(
|
||||
&mut self,
|
||||
binding: plist::Value,
|
||||
vtables: &BTreeMap<String, Vtable>,
|
||||
boot: &BootCollection<'_>,
|
||||
) -> Result<String> {
|
||||
let binding = binding
|
||||
.as_dictionary()
|
||||
.ok_or(refuse!("{INFO_KEY} must be a dictionary", INFO_KEY))?;
|
||||
require!(
|
||||
matches!(field(binding, "BootUUID")?, plist::Value::Data(uuid) if uuid.as_slice() == boot.uuid),
|
||||
"a vtable binding belongs to a different BootKC"
|
||||
);
|
||||
let name = text(binding, "Class")?;
|
||||
let library = text(binding, "Library")?;
|
||||
require!(
|
||||
self.info
|
||||
.get("OSBundleLibraries")
|
||||
.and_then(plist::Value::as_dictionary)
|
||||
.is_some_and(|libraries| libraries.contains_key(library)),
|
||||
"{name}'s vtable library {library} is not declared",
|
||||
name, library
|
||||
);
|
||||
let vtable = vtables
|
||||
.get(name)
|
||||
.ok_or(refuse!("the kext does not define vtable {name}", name))?;
|
||||
let class = vtable_class(name).ok_or(refuse!("invalid consumer vtable {name}", name))?;
|
||||
let donors = array(binding, "Donors")?
|
||||
.iter()
|
||||
.map(|donor| {
|
||||
donor
|
||||
.as_string()
|
||||
.filter(|name| vtable_class(name).is_some())
|
||||
.ok_or_else(|| refuse!("a donor must name a C++ vtable").into())
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let parent = self.parent(name)?;
|
||||
require!(
|
||||
(1..=8).contains(&donors.len()) && donors.first().copied() == parent.as_deref(),
|
||||
"{name}'s first vtable donor must be its superclass",
|
||||
name
|
||||
);
|
||||
let tables = donors
|
||||
.iter()
|
||||
.map(|donor| boot.methods(library, donor))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let methods = &tables[0];
|
||||
require!(
|
||||
tables.windows(2).all(|pair| pair[0].len() >= pair[1].len())
|
||||
&& (methods.len() as u64 + 2) * 8 <= vtable.end - vtable.start,
|
||||
"{name}'s compiled vtable cannot hold the BootKC method layout",
|
||||
name
|
||||
);
|
||||
|
||||
let object = &self.objects[vtable.object];
|
||||
let input = &object.sections[vtable.section];
|
||||
let first = vtable.start - input.address + 16;
|
||||
let mut slots = BTreeMap::new();
|
||||
for relocation in &input.relocations {
|
||||
if relocation.offset < first || input.address + relocation.offset >= vtable.end {
|
||||
continue;
|
||||
}
|
||||
let offset = relocation.offset - first;
|
||||
let Target::Symbol(index) = relocation.target else {
|
||||
return Err(refuse!("{name} has a vtable slot without a symbol", name).into());
|
||||
};
|
||||
require!(
|
||||
offset.is_multiple_of(8)
|
||||
&& relocation.addend == 0
|
||||
&& matches!(relocation.kind, Kind::Authenticated { .. })
|
||||
&& slots.insert(offset / 8, (relocation, index)).is_none(),
|
||||
"{name} has an unsupported vtable relocation",
|
||||
name
|
||||
);
|
||||
}
|
||||
|
||||
let owns = |symbol: &str| {
|
||||
symbol
|
||||
.strip_prefix("__ZN")
|
||||
.is_some_and(|rest| rest.strip_prefix('K').unwrap_or(rest).starts_with(class))
|
||||
};
|
||||
let mut overrides = BTreeMap::new();
|
||||
let mut sources = BTreeMap::new();
|
||||
for spec in array(binding, "Overrides")? {
|
||||
let spec = spec
|
||||
.as_dictionary()
|
||||
.ok_or(refuse!("a vtable override must be a dictionary"))?;
|
||||
let source = method_index(spec, "ObjectSlot")?;
|
||||
let target = method_index(spec, "BootSlot")?;
|
||||
let method = text(spec, "Method")?;
|
||||
let (relocation, index) = slots
|
||||
.get(&source)
|
||||
.ok_or(refuse!("{name} has no compiled method {source}", name, source))?;
|
||||
require!(
|
||||
owns(method) && object.symbols[*index].name == method,
|
||||
"{method} is not {name}'s compiled method at slot {source}",
|
||||
method, name, source
|
||||
);
|
||||
let value = self.resolve(vtable.object, relocation.target)?;
|
||||
require!(
|
||||
matches!(value, Value::Local { section, .. } if self.sections[section].region == Region::TextExec)
|
||||
&& target < methods.len() as u64
|
||||
&& sources.insert(source, ()).is_none()
|
||||
&& overrides.insert(target, value).is_none(),
|
||||
"{method} has an invalid or duplicate vtable binding",
|
||||
method
|
||||
);
|
||||
}
|
||||
require!(
|
||||
slots
|
||||
.iter()
|
||||
.all(|(slot, (_, index))| !owns(&object.symbols[*index].name) || sources.contains_key(slot)),
|
||||
"{name} has a compiled override without a binding",
|
||||
name
|
||||
);
|
||||
for (slot, method) in methods.iter().enumerate() {
|
||||
let (relocation, _) = slots
|
||||
.get(&(slot as u64))
|
||||
.ok_or(refuse!("{name} has no relocation for vtable method {slot}", name, slot))?;
|
||||
let signature = tables
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|table| table.get(slot))
|
||||
.unwrap()
|
||||
.signature;
|
||||
let value = overrides
|
||||
.get(&(slot as u64))
|
||||
.copied()
|
||||
.unwrap_or(Value::Boot(method.address));
|
||||
self.inherited.insert(
|
||||
(vtable.object, vtable.section, relocation.offset),
|
||||
VtableBinding {
|
||||
value,
|
||||
signature: Some(signature),
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(name.to_owned())
|
||||
}
|
||||
}
|
||||
@@ -477,37 +477,6 @@ pub fn hide_agx(tree: &mut DeviceTree) -> Vec<String> {
|
||||
hidden
|
||||
}
|
||||
|
||||
/// Hides the board's DCP external display outputs (`dcpext`, its expert and
|
||||
/// pipe) when a hosted display driver (such as ReimsGraphics) owns the sole
|
||||
/// primary display, and marks `/product artwork-display-gamut` as sRGB so
|
||||
/// QuartzCore / SkyLight match the sRGB display attributes published by
|
||||
/// ReimsGraphics instead of selecting extended-range 2-plane XR10 surfaces.
|
||||
pub fn hide_external_outputs(tree: &mut DeviceTree) -> Vec<String> {
|
||||
let mut hidden = Vec::new();
|
||||
for profile in board::EXTERNAL_OUTPUTS {
|
||||
for name in [profile.controller, profile.expert, profile.pipe] {
|
||||
let path = format!("/arm-io/{name}");
|
||||
if let Some(node) = tree.node_mut(&path) {
|
||||
retire(node, &path, &mut hidden);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(product) = tree.node_mut("/product")
|
||||
&& product.property("artwork-display-gamut").is_some()
|
||||
{
|
||||
product
|
||||
.set_property("artwork-display-gamut", b"sRGB\0".to_vec())
|
||||
.expect("sRGB gamut property");
|
||||
}
|
||||
if let Some(defaults) = tree.node_mut(DEFAULTS) {
|
||||
defaults
|
||||
.set_property("vmm-present", 1u32.to_le_bytes().to_vec())
|
||||
.expect("vmm-present property");
|
||||
}
|
||||
retire_hidden_service_identities(tree, &hidden);
|
||||
hidden
|
||||
}
|
||||
|
||||
/// Removes `compatible` from `node` and everything under it.
|
||||
fn retire(node: &mut Node, path: &str, hidden: &mut Vec<String>) {
|
||||
if node.property(COMPATIBLE).is_some() {
|
||||
|
||||
@@ -9,7 +9,6 @@ use crate::Result;
|
||||
use crate::apple_device_tree::{DeviceTree, Node};
|
||||
use alloc::{format, string::String, vec::Vec};
|
||||
use stela_contracts::{refuse, require};
|
||||
use stela_contracts::reims_hosted::{Apertures, DOORBELL_BYTES, REGION_BYTES, REGISTER_BYTES};
|
||||
|
||||
const ARM_IO: &str = "/arm-io";
|
||||
const COMPATIBLE: &[u8] = b"gpu,stela\0";
|
||||
@@ -17,9 +16,6 @@ const COMPATIBLE: &[u8] = b"gpu,stela\0";
|
||||
const AIC: &str = "/arm-io/aic";
|
||||
const PHANDLE: &str = "AAPL,phandle";
|
||||
const INTERRUPT_PARENT: &str = "interrupt-parent";
|
||||
const REIMS_NODE: &str = "reims-graphics";
|
||||
const REIMS_DISPLAY_NODE: &str = "reims-display0";
|
||||
const ARM_PAGE: u64 = 16 << 10;
|
||||
|
||||
/// Where the gate's node places it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -63,7 +59,12 @@ pub fn place_gpu_gate(tree: &mut DeviceTree, index: usize, bytes: u64) -> Result
|
||||
.map(|offset| (offset, range[1] + (offset - range[0])))
|
||||
})
|
||||
.ok_or(refuse!("/arm-io has no gap for the StelaGPU gate"))?;
|
||||
let (aic, used) = aic_inputs(tree)?;
|
||||
let aic = tree
|
||||
.property(AIC, PHANDLE)
|
||||
.and_then(|phandle| phandle.as_u32())
|
||||
.ok_or(refuse!("/arm-io/aic has no phandle"))?;
|
||||
let mut used = Vec::new();
|
||||
interrupts_of(&tree.root, aic, &mut used);
|
||||
let irq = used
|
||||
.into_iter()
|
||||
.max()
|
||||
@@ -82,113 +83,6 @@ pub fn place_gpu_gate(tree: &mut DeviceTree, index: usize, bytes: u64) -> Result
|
||||
Ok(Placement { physical, irq })
|
||||
}
|
||||
|
||||
/// The board's device vectors attached to its primary AIC.
|
||||
pub fn aic_vectors_in_use(tree: &DeviceTree) -> Result<Vec<u32>> {
|
||||
aic_inputs(tree).map(|(_, used)| used)
|
||||
}
|
||||
|
||||
/// Describe the same apertures the engine will install on the guest bus.
|
||||
/// Reg order is registers, command region, doorbells.
|
||||
pub fn place_hosted_reims(tree: &mut DeviceTree, apertures: Apertures, irq: u32) -> Result<()> {
|
||||
let (aic, vectors) = aic_inputs(tree)?;
|
||||
require!(!vectors.contains(&irq), "AIC vector {irq} is already assigned", irq);
|
||||
let arm_io = tree.node(ARM_IO).ok_or(refuse!("DeviceTree has no /arm-io"))?;
|
||||
require!(arm_io.child(REIMS_NODE).is_none(), "/arm-io already has a Reims device");
|
||||
require!(
|
||||
arm_io.child(REIMS_DISPLAY_NODE).is_none(),
|
||||
"/arm-io already has a Reims display node"
|
||||
);
|
||||
for cells in ["#address-cells", "#size-cells"] {
|
||||
require!(word(arm_io, cells) == Some(2), "/arm-io {cells} is not 2", cells);
|
||||
}
|
||||
let mut ranges = quads(arm_io, "ranges", 3).ok_or(refuse!("/arm-io has no ranges"))?;
|
||||
let mut used: Vec<_> = arm_io
|
||||
.children
|
||||
.iter()
|
||||
.filter_map(|child| quads(child, "reg", 2))
|
||||
.flatten()
|
||||
.map(|reg| (reg[0], reg[0].saturating_add(reg[1])))
|
||||
.collect();
|
||||
let mut regs = Vec::new();
|
||||
for (physical, bytes) in [
|
||||
(apertures.registers, REGISTER_BYTES),
|
||||
(apertures.region, REGION_BYTES),
|
||||
(apertures.doorbells, DOORBELL_BYTES),
|
||||
] {
|
||||
let offset = describe_io_range(&mut ranges, &used, physical, bytes)?;
|
||||
regs.extend_from_slice(&offset.to_le_bytes());
|
||||
regs.extend_from_slice(&bytes.to_le_bytes());
|
||||
used.push((offset, offset + bytes));
|
||||
}
|
||||
|
||||
let mut node = Node::named(REIMS_NODE)?;
|
||||
node.set_property("compatible", b"reims,hosted-graphics\0".to_vec())?;
|
||||
node.set_property("device_type", b"reims-graphics\0".to_vec())?;
|
||||
node.set_property("reg", regs)?;
|
||||
node.set_property("reg-names", b"registers\0region\0doorbells\0".to_vec())?;
|
||||
node.set_property(INTERRUPT_PARENT, aic.to_le_bytes().to_vec())?;
|
||||
node.set_property("interrupts", irq.to_le_bytes().to_vec())?;
|
||||
|
||||
let mut display_node = Node::named(REIMS_DISPLAY_NODE)?;
|
||||
display_node.set_property("device_type", b"display-subsystem\0".to_vec())?;
|
||||
|
||||
let ranges = ranges.into_iter().flatten().flat_map(u64::to_le_bytes).collect();
|
||||
let arm_io = tree.node_mut(ARM_IO).ok_or(refuse!("DeviceTree has no /arm-io"))?;
|
||||
arm_io.set_property("ranges", ranges)?;
|
||||
arm_io.children.push(node);
|
||||
arm_io.children.push(display_node);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn describe_io_range(
|
||||
ranges: &mut Vec<Vec<u64>>,
|
||||
used: &[(u64, u64)],
|
||||
physical: u64,
|
||||
bytes: u64,
|
||||
) -> Result<u64> {
|
||||
let end = physical.checked_add(bytes).ok_or(refuse!("Reims physical range overflow"))?;
|
||||
let mut offset = None;
|
||||
let mut local_end = used.iter().map(|&(_, end)| end).max().unwrap_or_default();
|
||||
for range in ranges.iter() {
|
||||
let [local, start, length] = [range[0], range[1], range[2]];
|
||||
let physical_end = start.checked_add(length).ok_or(refuse!("arm-io physical range overflow"))?;
|
||||
local_end = local_end.max(
|
||||
local.checked_add(length).ok_or(refuse!("arm-io child range overflow"))?,
|
||||
);
|
||||
if physical < physical_end && start < end {
|
||||
require!(
|
||||
offset.is_none() && start <= physical && end <= physical_end,
|
||||
"Reims aperture crosses an existing arm-io range"
|
||||
);
|
||||
offset = local.checked_add(physical - start);
|
||||
}
|
||||
}
|
||||
if let Some(offset) = offset {
|
||||
let end = offset.checked_add(bytes).ok_or(refuse!("Reims child range overflow"))?;
|
||||
require!(
|
||||
used.iter().all(|&(first, past)| past <= offset || end <= first),
|
||||
"Reims aperture overlaps an arm-io device"
|
||||
);
|
||||
return Ok(offset);
|
||||
}
|
||||
let offset = local_end
|
||||
.checked_next_multiple_of(ARM_PAGE)
|
||||
.and_then(|offset| offset.checked_add(bytes).map(|_| offset))
|
||||
.ok_or(refuse!("Reims child range overflow"))?;
|
||||
ranges.push(alloc::vec![offset, physical, bytes]);
|
||||
Ok(offset)
|
||||
}
|
||||
|
||||
fn aic_inputs(tree: &DeviceTree) -> Result<(u32, Vec<u32>)> {
|
||||
let aic = tree
|
||||
.property(AIC, PHANDLE)
|
||||
.and_then(|phandle| phandle.as_u32())
|
||||
.ok_or(refuse!("/arm-io/aic has no phandle"))?;
|
||||
let mut used = Vec::new();
|
||||
interrupts_of(&tree.root, aic, &mut used);
|
||||
Ok((aic, used))
|
||||
}
|
||||
|
||||
/// Collects the AIC inputs of `node` and its descendants whose interrupt
|
||||
/// parent is the AIC with phandle `aic`. A node's `interrupt-parent` is one
|
||||
/// phandle for all its interrupts, or one per interrupt cell: T6050's
|
||||
@@ -394,35 +288,6 @@ mod tests {
|
||||
DeviceTree { root }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_reims_node_translates_each_mmio_register_and_declares_its_interrupt() {
|
||||
let mut tree = tree(Vec::new());
|
||||
let apertures = Apertures::at(0x3_0000_0000).unwrap();
|
||||
place_hosted_reims(&mut tree, apertures, 740).unwrap();
|
||||
let arm_io = tree.node(ARM_IO).unwrap();
|
||||
let ranges = quads(arm_io, "ranges", 3).unwrap();
|
||||
let node = arm_io.child(REIMS_NODE).unwrap();
|
||||
assert_eq!(word(node, INTERRUPT_PARENT), Some(AIC_PHANDLE));
|
||||
assert_eq!(word(node, "interrupts"), Some(740));
|
||||
let regs = quads(node, "reg", 2).unwrap();
|
||||
let physical: Vec<_> = regs
|
||||
.iter()
|
||||
.map(|reg| {
|
||||
let range = ranges
|
||||
.iter()
|
||||
.find(|range| range[0] <= reg[0] && reg[0] + reg[1] <= range[0] + range[2])
|
||||
.unwrap();
|
||||
(range[1] + reg[0] - range[0], reg[1])
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(physical, [
|
||||
(apertures.registers, REGISTER_BYTES),
|
||||
(apertures.region, REGION_BYTES),
|
||||
(apertures.doorbells, DOORBELL_BYTES),
|
||||
]);
|
||||
assert!(place_hosted_reims(&mut tree, apertures, 740).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gate_takes_the_last_aligned_gap_no_device_uses() {
|
||||
let mut tree = tree(vec![
|
||||
|
||||
@@ -116,19 +116,6 @@ impl AicLayout {
|
||||
Self::V2 { dies, .. } => dies,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pick an unassigned input inside the controller's implemented banks.
|
||||
pub fn free_vector(self, inputs: u16, occupied: &[u32]) -> Option<u32> {
|
||||
let Self::V2 { max_irq, dies, .. } = self else {
|
||||
return None;
|
||||
};
|
||||
let per_die = u32::from(max_irq);
|
||||
let count = u32::from(inputs.min(max_irq));
|
||||
(0..u32::from(dies))
|
||||
.rev()
|
||||
.flat_map(|die| (die * per_die..die * per_die + count).rev())
|
||||
.find(|vector| !occupied.contains(vector))
|
||||
}
|
||||
}
|
||||
|
||||
/// Hardware facts of one AICv2 instance. NR_IRQ and MAX_IRQ come from the
|
||||
|
||||
@@ -381,11 +381,6 @@ impl Aic2 {
|
||||
pub fn span(&self) -> u64 {
|
||||
self.span
|
||||
}
|
||||
pub(crate) fn input_for_vector(&self, vector: u32) -> Option<AicInput> {
|
||||
AicInput::from_vector(vector, self.config.max_irq).filter(|input| {
|
||||
usize::from(input.die) < self.layout.dies.len() && input.irq < self.config.nr_irq
|
||||
})
|
||||
}
|
||||
/// Sets the level of one hardware input, as wired by the engine from the
|
||||
/// device models' `Wire::Aic` outputs.
|
||||
pub fn set_input(
|
||||
|
||||
@@ -4,64 +4,6 @@ use super::*;
|
||||
use alloc::sync::Arc;
|
||||
|
||||
impl AppleDevices {
|
||||
/// Mount the copy-only Reims windows for a hosted ARM64 guest.
|
||||
pub fn add_hosted_reims(
|
||||
&mut self,
|
||||
addresses: stela_contracts::reims_hosted::Apertures,
|
||||
transport: impl stela_contracts::reims_hosted::Transport + 'static,
|
||||
) -> Result<DeviceId, stela_contracts::reims_hosted::InstallError> {
|
||||
stela_contracts::reims_hosted::install(&mut self.bus, addresses, transport)
|
||||
}
|
||||
|
||||
/// Connect the transport's completion notification to a guest AIC vector.
|
||||
pub fn add_hosted_reims_with_interrupt(
|
||||
&mut self,
|
||||
addresses: stela_contracts::reims_hosted::Apertures,
|
||||
transport: impl stela_contracts::reims_hosted::Transport + 'static,
|
||||
vector: u32,
|
||||
) -> Result<DeviceId, stela_contracts::reims_hosted::InstallError> {
|
||||
use stela_contracts::reims_hosted::{self, InstallError};
|
||||
let Some(Controller::V2(id)) = self.aic else {
|
||||
return Err(InstallError::InterruptInput);
|
||||
};
|
||||
let input = self.bus.device::<Aic2>(id)
|
||||
.and_then(|aic| aic.input_for_vector(vector))
|
||||
.ok_or(InstallError::InterruptInput)?;
|
||||
reims_hosted::install_with_interrupt(&mut self.bus, addresses, transport, input)
|
||||
}
|
||||
|
||||
/// Mount only registers and doorbells on the MMIO bus when BAR2 is mapped
|
||||
/// directly in guest physical RAM.
|
||||
pub fn add_hosted_reims_direct_region(
|
||||
&mut self,
|
||||
addresses: stela_contracts::reims_hosted::Apertures,
|
||||
transport: impl stela_contracts::reims_hosted::Transport + 'static,
|
||||
) -> Result<DeviceId, stela_contracts::reims_hosted::InstallError> {
|
||||
stela_contracts::reims_hosted::install_direct_region(&mut self.bus, addresses, transport)
|
||||
}
|
||||
|
||||
/// [`Self::add_hosted_reims_direct_region`] with a guest AIC vector.
|
||||
pub fn add_hosted_reims_direct_region_with_interrupt(
|
||||
&mut self,
|
||||
addresses: stela_contracts::reims_hosted::Apertures,
|
||||
transport: impl stela_contracts::reims_hosted::Transport + 'static,
|
||||
vector: u32,
|
||||
) -> Result<DeviceId, stela_contracts::reims_hosted::InstallError> {
|
||||
use stela_contracts::reims_hosted::{self, InstallError};
|
||||
let Some(Controller::V2(id)) = self.aic else {
|
||||
return Err(InstallError::InterruptInput);
|
||||
};
|
||||
let input = self.bus.device::<Aic2>(id)
|
||||
.and_then(|aic| aic.input_for_vector(vector))
|
||||
.ok_or(InstallError::InterruptInput)?;
|
||||
reims_hosted::install_direct_region_with_interrupt(
|
||||
&mut self.bus,
|
||||
addresses,
|
||||
transport,
|
||||
input,
|
||||
)
|
||||
}
|
||||
|
||||
/// A StelaGPU call gate over `service`, its window at `physical` and
|
||||
/// its completion interrupt at `irq`.
|
||||
pub fn add_gpu_gate(
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>ReimsHostedDevice</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.stela.ReimsHostedDevice</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>KEXT</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1.0.0</string>
|
||||
<key>IOKitPersonalities</key>
|
||||
<dict>
|
||||
<key>ReimsHostedDevice</key>
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.stela.ReimsHostedDevice</string>
|
||||
<key>IOClass</key>
|
||||
<string>ReimsHostedDevice</string>
|
||||
<key>IONameMatch</key>
|
||||
<array>
|
||||
<string>reims-graphics</string>
|
||||
<string>reims,hosted-graphics</string>
|
||||
</array>
|
||||
<key>IOProviderClass</key>
|
||||
<string>AppleARMIODevice</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>OSBundleLibraries</key>
|
||||
<dict>
|
||||
<key>com.apple.kpi.iokit</key>
|
||||
<string>8.0.0</string>
|
||||
<key>com.apple.kpi.libkern</key>
|
||||
<string>8.0.0</string>
|
||||
</dict>
|
||||
<key>OSBundleRequired</key>
|
||||
<string>Root</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,209 +0,0 @@
|
||||
#include <IOKit/IODeviceMemory.h>
|
||||
#include <IOKit/IOInterruptEventSource.h>
|
||||
#include <IOKit/IOLib.h>
|
||||
#include <IOKit/IOService.h>
|
||||
#include <IOKit/IOWorkLoop.h>
|
||||
|
||||
namespace {
|
||||
|
||||
// Reims graphics wire v2 and Stela's hosted IRQ token.
|
||||
constexpr unsigned kMagic = 0x58464752;
|
||||
constexpr unsigned kVersion = 2;
|
||||
constexpr unsigned kRegisterBytes = 2048;
|
||||
constexpr unsigned kRegionBytes = 1U << 30;
|
||||
constexpr unsigned kDoorbellBytes = 4U << 20;
|
||||
constexpr unsigned kRingSpan = 65536;
|
||||
constexpr unsigned kRingData = 256;
|
||||
constexpr unsigned kProducer = 0;
|
||||
constexpr unsigned kConsumer = 64;
|
||||
constexpr unsigned kArmed = 192;
|
||||
constexpr unsigned kStatus = 16;
|
||||
constexpr unsigned kRingDoorbell = 32;
|
||||
constexpr unsigned kIrqToken = kRegisterBytes - 4;
|
||||
constexpr unsigned kGetDisplays = 1;
|
||||
constexpr unsigned kDisplaysReply = 257;
|
||||
constexpr unsigned kMessageBytes = 16;
|
||||
|
||||
template<typename T>
|
||||
T read(volatile unsigned char *base, unsigned offset)
|
||||
{
|
||||
return *reinterpret_cast<volatile T *>(base + offset);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void write(volatile unsigned char *base, unsigned offset, T value)
|
||||
{
|
||||
*reinterpret_cast<volatile T *>(base + offset) = value;
|
||||
}
|
||||
|
||||
void deviceBarrier()
|
||||
{
|
||||
__asm__ volatile("dmb sy" ::: "memory");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
class ReimsHostedDevice final : public IOService {
|
||||
OSDeclareDefaultStructors(ReimsHostedDevice);
|
||||
|
||||
public:
|
||||
bool start(IOService *provider) override;
|
||||
void stop(IOService *provider) override;
|
||||
void free() override;
|
||||
|
||||
private:
|
||||
static void interruptOccurred(OSObject *owner, IOInterruptEventSource *, int);
|
||||
void complete();
|
||||
void releaseTransport();
|
||||
|
||||
IOMemoryMap *registerMap = nullptr;
|
||||
IOMemoryMap *controlMap = nullptr;
|
||||
IOWorkLoop *workLoop = nullptr;
|
||||
IOInterruptEventSource *interrupt = nullptr;
|
||||
volatile unsigned char *registers = nullptr;
|
||||
volatile unsigned char *control = nullptr;
|
||||
bool started = false;
|
||||
};
|
||||
|
||||
OSDefineMetaClassAndStructors(ReimsHostedDevice, IOService);
|
||||
|
||||
__attribute__((constructor))
|
||||
static void
|
||||
logModuleInitialization()
|
||||
{
|
||||
IOLog("ReimsHostedDevice: module initialized\n");
|
||||
}
|
||||
|
||||
bool
|
||||
ReimsHostedDevice::start(IOService *provider)
|
||||
{
|
||||
IOLog("ReimsHostedDevice: matching provider %s\n", provider->getName());
|
||||
if (!IOService::start(provider))
|
||||
return false;
|
||||
auto registersMemory = provider->getDeviceMemoryWithIndex(0);
|
||||
auto region = provider->getDeviceMemoryWithIndex(1);
|
||||
auto doorbells = provider->getDeviceMemoryWithIndex(2);
|
||||
if (!registersMemory || registersMemory->getLength() != kRegisterBytes ||
|
||||
!region || region->getLength() != kRegionBytes ||
|
||||
!doorbells || doorbells->getLength() != kDoorbellBytes) {
|
||||
IOLog("ReimsHostedDevice: provider memory layout differs\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
registerMap = registersMemory->map(kIOMapInhibitCache);
|
||||
if (!registerMap) {
|
||||
IOLog("ReimsHostedDevice: cannot map registers\n");
|
||||
return false;
|
||||
}
|
||||
registers = reinterpret_cast<volatile unsigned char *>(registerMap->getVirtualAddress());
|
||||
if (read<unsigned>(registers, 0) != kMagic ||
|
||||
read<unsigned>(registers, 4) != kVersion ||
|
||||
read<unsigned>(registers, kStatus) != 0) {
|
||||
IOLog("ReimsHostedDevice: wire mismatch, magic=%x version=%u status=%u\n",
|
||||
read<unsigned>(registers, 0), read<unsigned>(registers, 4),
|
||||
read<unsigned>(registers, kStatus));
|
||||
goto fail;
|
||||
}
|
||||
|
||||
if (auto memory = IODeviceMemory::withSubRange(region, 0, 2 * kRingSpan)) {
|
||||
controlMap = memory->map(kIOMapInhibitCache);
|
||||
memory->release();
|
||||
}
|
||||
if (!controlMap) {
|
||||
IOLog("ReimsHostedDevice: cannot map control rings\n");
|
||||
goto fail;
|
||||
}
|
||||
control = reinterpret_cast<volatile unsigned char *>(controlMap->getVirtualAddress());
|
||||
if (read<UInt64>(control, kProducer) || read<UInt64>(control, kRingSpan + kProducer))
|
||||
goto fail;
|
||||
workLoop = IOWorkLoop::workLoop();
|
||||
if (!workLoop)
|
||||
goto fail;
|
||||
interrupt = IOInterruptEventSource::interruptEventSource(this, interruptOccurred, provider, 0);
|
||||
if (!interrupt || workLoop->addEventSource(interrupt) != kIOReturnSuccess) {
|
||||
IOLog("ReimsHostedDevice: cannot enable provider interrupt\n");
|
||||
OSSafeReleaseNULL(interrupt);
|
||||
goto fail;
|
||||
}
|
||||
interrupt->enable();
|
||||
setProperty("ReimsWireVersion", kVersion, 32);
|
||||
started = true;
|
||||
write<unsigned>(registers, kStatus, 1);
|
||||
write<unsigned>(control, kRingData, kGetDisplays);
|
||||
write<unsigned>(control, kRingData + 4, kMessageBytes);
|
||||
write<UInt64>(control, kRingData + 8, 1);
|
||||
write<unsigned>(control, kRingSpan + kArmed, 1);
|
||||
deviceBarrier();
|
||||
write<UInt64>(control, kProducer, kMessageBytes);
|
||||
deviceBarrier();
|
||||
write<unsigned>(registers, kRingDoorbell, 0);
|
||||
IOLog("ReimsHostedDevice: display query submitted\n");
|
||||
registerService();
|
||||
return true;
|
||||
|
||||
fail:
|
||||
releaseTransport();
|
||||
return false;
|
||||
}
|
||||
|
||||
void
|
||||
ReimsHostedDevice::interruptOccurred(OSObject *owner, IOInterruptEventSource *, int)
|
||||
{
|
||||
static_cast<ReimsHostedDevice *>(owner)->complete();
|
||||
}
|
||||
|
||||
void
|
||||
ReimsHostedDevice::complete()
|
||||
{
|
||||
auto token = read<unsigned>(registers, kIrqToken);
|
||||
deviceBarrier();
|
||||
auto producer = read<UInt64>(control, kRingSpan + kProducer);
|
||||
if (producer >= kMessageBytes + sizeof(unsigned) && producer <= kRingSpan - kRingData) {
|
||||
auto reply = control + kRingSpan + kRingData;
|
||||
auto kind = read<unsigned>(reply, 0);
|
||||
auto bytes = read<unsigned>(reply, 4);
|
||||
auto sequence = read<UInt64>(reply, 8);
|
||||
auto count = read<unsigned>(reply, kMessageBytes);
|
||||
if (kind == kDisplaysReply && sequence == 1 && bytes >= kMessageBytes + sizeof(unsigned) &&
|
||||
bytes <= producer && count > 0 && count <= 4) {
|
||||
setProperty("ReimsDisplayCount", count, 32);
|
||||
setProperty("ReimsReplySequence", sequence, 64);
|
||||
setProperty("ReimsInterruptToken", token, 32);
|
||||
IOLog("ReimsHostedDevice: display query completed through AIC, displays=%u\n", count);
|
||||
}
|
||||
write<UInt64>(control, kRingSpan + kConsumer, producer);
|
||||
}
|
||||
deviceBarrier();
|
||||
write<unsigned>(registers, kIrqToken, token);
|
||||
}
|
||||
|
||||
void
|
||||
ReimsHostedDevice::releaseTransport()
|
||||
{
|
||||
if (interrupt) {
|
||||
interrupt->disable();
|
||||
workLoop->removeEventSource(interrupt);
|
||||
OSSafeReleaseNULL(interrupt);
|
||||
}
|
||||
if (started) {
|
||||
write<unsigned>(registers, kStatus, 0);
|
||||
started = false;
|
||||
}
|
||||
OSSafeReleaseNULL(workLoop);
|
||||
OSSafeReleaseNULL(controlMap);
|
||||
OSSafeReleaseNULL(registerMap);
|
||||
}
|
||||
|
||||
void
|
||||
ReimsHostedDevice::stop(IOService *provider)
|
||||
{
|
||||
releaseTransport();
|
||||
IOService::stop(provider);
|
||||
}
|
||||
|
||||
void
|
||||
ReimsHostedDevice::free()
|
||||
{
|
||||
releaseTransport();
|
||||
IOService::free();
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
#include "../../stela-gpu/kext/runtime.cpp"
|
||||
Vendored
+4
-1
@@ -76,7 +76,10 @@
|
||||
/COPYING
|
||||
/README
|
||||
/Makefile
|
||||
/kernel/locking/
|
||||
/kernel/locking/mutex.c
|
||||
/kernel/locking/percpu-rwsem.c
|
||||
/kernel/locking/mutex.h
|
||||
/kernel/locking/ww_mutex.h
|
||||
/kernel/sched/core.c
|
||||
/kernel/sched/sched.h
|
||||
/kernel/sched/sched_class_bounds.c
|
||||
|
||||
+68
-14
@@ -11,11 +11,13 @@ use clap::Args;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io::{Read, Write},
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
mod corpus;
|
||||
mod record;
|
||||
mod semantics_verify;
|
||||
mod stela;
|
||||
|
||||
use record::{Case, Ending, INPUT_BYTES, OUTPUT_BYTES};
|
||||
@@ -62,17 +64,41 @@ pub struct CpuReference {
|
||||
/// Rewrite the recorded table from this Mac run.
|
||||
#[arg(long)]
|
||||
record: bool,
|
||||
/// Recorded table path to read or write (default: `xtask/src/cpu_reference/apple-m1-pro.tsv`).
|
||||
#[arg(long)]
|
||||
table: Option<PathBuf>,
|
||||
/// Only the cases whose name contains this text.
|
||||
#[arg(long)]
|
||||
only: Option<String>,
|
||||
/// List the case names and exit.
|
||||
#[arg(long)]
|
||||
list: bool,
|
||||
/// Verify explicit Arm instruction semantics, block side effects, and
|
||||
/// multi-tier Stela compilation against the M4 corpus.
|
||||
#[arg(long)]
|
||||
verify_semantics: bool,
|
||||
}
|
||||
|
||||
impl CpuReference {
|
||||
pub fn run(self) -> Result<()> {
|
||||
let cases: Vec<Case> = corpus::all()
|
||||
if self.verify_semantics {
|
||||
semantics_verify::verify_m4_semantics()?;
|
||||
if self.only.is_none()
|
||||
&& self.mac.is_none()
|
||||
&& !self.recorded
|
||||
&& !self.record
|
||||
&& !self.list
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let using_m1_default = self.table.is_none();
|
||||
let all_cases = if self.recorded && using_m1_default {
|
||||
corpus::m1_baseline()
|
||||
} else {
|
||||
corpus::all()
|
||||
};
|
||||
let cases: Vec<Case> = all_cases
|
||||
.into_iter()
|
||||
.filter(|case| {
|
||||
self.only
|
||||
@@ -89,16 +115,16 @@ impl CpuReference {
|
||||
}
|
||||
ensure!(!cases.is_empty(), "no case matches");
|
||||
let (reference, source) = if self.recorded {
|
||||
let table = recorded()?;
|
||||
let table = match &self.table {
|
||||
Some(path) => recorded_from_path(path)?,
|
||||
None => recorded()?,
|
||||
};
|
||||
let outcomes = cases
|
||||
.iter()
|
||||
.map(|case| {
|
||||
table
|
||||
.get(case.name.as_str())
|
||||
.map(|outcome| outcome.to_string())
|
||||
.with_context(|| {
|
||||
format!("{} is not recorded; run with --record", case.name)
|
||||
})
|
||||
table.get(case.name.as_str()).cloned().with_context(|| {
|
||||
format!("{} is not recorded; run with --record", case.name)
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
(outcomes, "recorded")
|
||||
@@ -112,7 +138,11 @@ impl CpuReference {
|
||||
.collect();
|
||||
if self.record {
|
||||
ensure!(self.only.is_none(), "--record keeps every case");
|
||||
write_table(&host, &cases, &outcomes)?;
|
||||
let target_path = self
|
||||
.table
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from(TABLE_PATH));
|
||||
write_table(&host, &target_path, &cases, &outcomes)?;
|
||||
}
|
||||
(outcomes, "mac")
|
||||
};
|
||||
@@ -203,21 +233,41 @@ fn ssh(host: &str, script: &str) -> Command {
|
||||
}
|
||||
|
||||
/// The recorded table: case name to outcome.
|
||||
fn recorded() -> Result<BTreeMap<&'static str, &'static str>> {
|
||||
fn recorded() -> Result<BTreeMap<String, String>> {
|
||||
parse_table(TABLE)
|
||||
}
|
||||
|
||||
fn recorded_from_path(path: &std::path::Path) -> Result<BTreeMap<String, String>> {
|
||||
let resolved = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
crate::tools::root().join(path)
|
||||
};
|
||||
let text = std::fs::read_to_string(&resolved)
|
||||
.with_context(|| format!("cannot read table {}", resolved.display()))?;
|
||||
parse_table(&text)
|
||||
}
|
||||
|
||||
fn parse_table(text: &str) -> Result<BTreeMap<String, String>> {
|
||||
let mut table = BTreeMap::new();
|
||||
for line in TABLE
|
||||
for line in text
|
||||
.lines()
|
||||
.filter(|line| !line.starts_with('#') && !line.is_empty())
|
||||
{
|
||||
let Some((name, outcome)) = line.split_once('\t') else {
|
||||
bail!("malformed recorded line {line:?}");
|
||||
};
|
||||
table.insert(name, outcome);
|
||||
table.insert(name.to_string(), outcome.to_string());
|
||||
}
|
||||
Ok(table)
|
||||
}
|
||||
|
||||
fn write_table(host: &str, cases: &[Case], outcomes: &[String]) -> Result<()> {
|
||||
fn write_table(
|
||||
host: &str,
|
||||
target: &std::path::Path,
|
||||
cases: &[Case],
|
||||
outcomes: &[String],
|
||||
) -> Result<()> {
|
||||
let identity = Command::new("ssh")
|
||||
.args([
|
||||
"-o",
|
||||
@@ -235,7 +285,11 @@ fn write_table(host: &str, cases: &[Case], outcomes: &[String]) -> Result<()> {
|
||||
for (case, outcome) in cases.iter().zip(outcomes) {
|
||||
text.push_str(&format!("{}\t{outcome}\n", case.name));
|
||||
}
|
||||
let path = crate::tools::root().join(TABLE_PATH);
|
||||
let path = if target.is_absolute() {
|
||||
target.to_path_buf()
|
||||
} else {
|
||||
crate::tools::root().join(target)
|
||||
};
|
||||
std::fs::write(&path, text)?;
|
||||
println!("recorded {}", path.display());
|
||||
Ok(())
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -862,8 +862,8 @@ fn register_overlaps(cases: &mut Vec<Case>) {
|
||||
.push(Case::new("overlap.control.ldp.post", &[0xa8c1_1043]).memory(2, 16, &MEMORY_PATTERN));
|
||||
}
|
||||
|
||||
/// Every case, in a fixed order.
|
||||
pub fn all() -> Vec<Case> {
|
||||
/// The existing Apple M1 Pro baseline corpus, in fixed order.
|
||||
pub fn m1_baseline() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
fp_conversions(&mut cases);
|
||||
fp_rounding(&mut cases);
|
||||
@@ -880,6 +880,343 @@ pub fn all() -> Vec<Case> {
|
||||
cases
|
||||
}
|
||||
|
||||
/// Apple M4 differential corpus covering ADDS, ADCS, SBCS, CSEL, and
|
||||
/// multi-instruction basic blocks.
|
||||
pub fn m4_flags_csel() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
m4_adds(&mut cases);
|
||||
m4_carry_arith(&mut cases);
|
||||
m4_csel(&mut cases);
|
||||
m4_blocks(&mut cases);
|
||||
cases
|
||||
}
|
||||
|
||||
fn m4_adds(cases: &mut Vec<Case>) {
|
||||
let imm_forms: [(&str, u32); 9] = [
|
||||
("w.imm0", 0x3100_0020), // adds w0, w1, #0
|
||||
("w.imm1", 0x3100_0420), // adds w0, w1, #1
|
||||
("w.imm_fff", 0x313f_fc20), // adds w0, w1, #0xfff
|
||||
("w.imm1_lsl12", 0x3140_0420), // adds w0, w1, #1, lsl #12
|
||||
("w.imm_fff_lsl12", 0x317f_fc20), // adds w0, w1, #0xfff, lsl #12
|
||||
("w.cmn_fff", 0x313f_fc3f), // cmn w1, #0xfff (rd=wzr)
|
||||
("x.imm1", 0xb100_0420), // adds x0, x1, #1
|
||||
("x.imm_fff_lsl12", 0xb17f_fc20), // adds x0, x1, #0xfff, lsl #12
|
||||
("x.cmn_fff", 0xb13f_fc3f), // cmn x1, #0xfff (rd=xzr)
|
||||
];
|
||||
let inputs = [
|
||||
0u64,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0xffff_ffff,
|
||||
0xdead_beef_ffff_ffff,
|
||||
0xfeed_face_7fff_ffff,
|
||||
0x7fff_ffff_ffff_ffff,
|
||||
0xffff_ffff_ffff_ffff,
|
||||
];
|
||||
for (form, word) in imm_forms {
|
||||
for (i, &val) in inputs.iter().enumerate() {
|
||||
cases.push(
|
||||
Case::new(format!("m4.adds.{form}.{i}"), &[word])
|
||||
.x(0, 0xaaaa_bbbb_cccc_dddd)
|
||||
.x(1, val)
|
||||
.nzcv(0xf000_0000),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let shift_forms: [(&str, u32); 8] = [
|
||||
("w.lsl3", 0x2b02_0c20), // adds w0, w1, w2, lsl #3
|
||||
("w.lsr1", 0x2b42_0420), // adds w0, w1, w2, lsr #1
|
||||
("w.asr31", 0x2b82_7c20), // adds w0, w1, w2, asr #31
|
||||
("w.cmn_lsl3", 0x2b02_0c3f), // cmn w1, w2, lsl #3
|
||||
("x.lsl3", 0xab02_0c20), // adds x0, x1, x2, lsl #3
|
||||
("x.lsr1", 0xab42_0420), // adds x0, x1, x2, lsr #1
|
||||
("x.asr63", 0xab82_fc20), // adds x0, x1, x2, asr #63
|
||||
("x.cmn_lsl3", 0xab02_0c3f), // cmn x1, x2, lsl #3
|
||||
];
|
||||
let pairs = [
|
||||
(0u64, 0u64),
|
||||
(0x7fff_ffff, 1),
|
||||
(0xdead_beef_ffff_ffff, 0xfeed_face_2000_0000),
|
||||
(0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff),
|
||||
];
|
||||
for (form, word) in shift_forms {
|
||||
for (i, &(a, b)) in pairs.iter().enumerate() {
|
||||
cases.push(
|
||||
Case::new(format!("m4.adds.{form}.{i}"), &[word])
|
||||
.x(0, 0x1234_5678_9abc_def0)
|
||||
.x(1, a)
|
||||
.x(2, b)
|
||||
.nzcv(0xf000_0000),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn m4_carry_arith(cases: &mut Vec<Case>) {
|
||||
// Non-C flags (N,Z,V) are set in `c0` to prove carry ops read only `C`.
|
||||
let carry_states = [("c0", 0xd000_0000u64), ("c1", 0x2000_0000u64)];
|
||||
|
||||
let adcs_pairs = [
|
||||
("zero", 0u64, 0u64),
|
||||
("w32_carry_zero", 0xdead_beef_ffff_ffff, 0),
|
||||
("w32_ovf_carry", 0xfeed_face_7fff_ffff, 0),
|
||||
("x64_ovf_carry", 0x7fff_ffff_ffff_ffff, 0),
|
||||
("x64_max_max", u64::MAX, u64::MAX),
|
||||
(
|
||||
"x64_sign_wrap",
|
||||
0x8000_0000_0000_0000,
|
||||
0x8000_0000_0000_0000,
|
||||
),
|
||||
];
|
||||
for (wlabel, word) in [("w", 0x3a02_0020u32), ("x", 0xba02_0020)] {
|
||||
for (plabel, a, b) in adcs_pairs {
|
||||
for (clabel, nzcv) in carry_states {
|
||||
cases.push(
|
||||
Case::new(format!("m4.adcs.{wlabel}.{plabel}.{clabel}"), &[word])
|
||||
.x(0, 0x5555_5555_5555_5555)
|
||||
.x(1, a)
|
||||
.x(2, b)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (label, word) in [
|
||||
("w.alias_all", 0x3a00_0000u32), // adcs w0, w0, w0
|
||||
("x.alias_all", 0xba00_0000), // adcs x0, x0, x0
|
||||
("x.alias_rd_rm", 0xba01_0041), // adcs x1, x2, x1
|
||||
("w.alias_rd_rm", 0x3a01_0041), // adcs w1, w2, w1
|
||||
("x.rd_zr", 0xba02_003f), // adcs xzr, x1, x2
|
||||
("x.rn_rm_zr", 0xba1f_03e0), // adcs x0, xzr, xzr
|
||||
] {
|
||||
for (clabel, nzcv) in carry_states {
|
||||
cases.push(
|
||||
Case::new(format!("m4.adcs.{label}.{clabel}"), &[word])
|
||||
.x(0, 0xfeed_face_7fff_ffff)
|
||||
.x(1, 0x8000_0000_0000_0001)
|
||||
.x(2, 0x7fff_ffff_ffff_ffff)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let sbcs_pairs = [
|
||||
("zero_zero", 0u64, 0u64),
|
||||
("zero_one", 0, 1),
|
||||
("w32_intmin_zero", 0xdead_beef_8000_0000, 0),
|
||||
("w32_intmax_neg1", 0x0000_0001_7fff_ffff, 0xffff_ffff),
|
||||
(
|
||||
"w32_dirty_cancel",
|
||||
0xdead_beef_0000_0005,
|
||||
0xfeed_face_0000_0005,
|
||||
),
|
||||
("x64_intmin_zero", 0x8000_0000_0000_0000, 0),
|
||||
("x64_zero_intmin", 0, 0x8000_0000_0000_0000),
|
||||
("x64_intmax_neg1", 0x7fff_ffff_ffff_ffff, u64::MAX),
|
||||
];
|
||||
for (wlabel, word) in [("w", 0x7a02_0020u32), ("x", 0xfa02_0020)] {
|
||||
for (plabel, a, b) in sbcs_pairs {
|
||||
for (clabel, nzcv) in carry_states {
|
||||
cases.push(
|
||||
Case::new(format!("m4.sbcs.{wlabel}.{plabel}.{clabel}"), &[word])
|
||||
.x(0, 0x5555_5555_5555_5555)
|
||||
.x(1, a)
|
||||
.x(2, b)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (label, word) in [
|
||||
("w.alias_all", 0x7a00_0000u32), // sbcs w0, w0, w0
|
||||
("x.alias_all", 0xfa00_0000), // sbcs x0, x0, x0
|
||||
("x.alias_rd_rm", 0xfa01_0041), // sbcs x1, x2, x1
|
||||
("w.rd_zr", 0x7a02_003f), // sbcs wzr, w1, w2
|
||||
("x.ngcs", 0xfa01_03e0), // ngcs x0, x1
|
||||
] {
|
||||
for (clabel, nzcv) in carry_states {
|
||||
cases.push(
|
||||
Case::new(format!("m4.sbcs.{label}.{clabel}"), &[word])
|
||||
.x(0, 0xfeed_face_8000_0000)
|
||||
.x(1, 0x8000_0000_0000_0001)
|
||||
.x(2, 0x0000_0000_0000_0001)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn m4_csel(cases: &mut Vec<Case>) {
|
||||
// Full 16x16 matrix: every condition 0..16 x every NZCV nibble 0..16 for CSEL X0, X1, X2, cond
|
||||
for condition in 0..16u32 {
|
||||
let word = 0x9a82_0020 | (condition << 12);
|
||||
for nibble in 0..16u64 {
|
||||
cases.push(
|
||||
Case::new(format!("m4.csel.x.c{condition}.{nibble:x}"), &[word])
|
||||
.x(0, 0x0123_4567_89ab_cdef)
|
||||
.x(1, 0x1111_2222_3333_4444)
|
||||
.x(2, 0x8888_9999_aaaa_bbbb)
|
||||
.nzcv(nibble << 28),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// W32 upper-bit truncation, aliasing (`keep_false`), unconditional AL/NV, and XZR/WZR.
|
||||
let w_variants = [
|
||||
("w.alias_rn", 0x1a81_0000u32), // csel w0, w0, w1, eq
|
||||
("w.alias_rm", 0x1a80_0020), // csel w0, w1, w0, eq
|
||||
("w.al", 0x1a81_e000), // csel w0, w0, w1, al
|
||||
("w.nv", 0x1a81_f000), // csel w0, w0, w1, nv
|
||||
("x.rn_zr", 0x9a81_23e0), // csel x0, xzr, x1, hs
|
||||
("x.rm_zr", 0x9a9f_3020), // csel x0, x1, xzr, lo
|
||||
("x.rd_zr", 0x9a82_003f), // csel xzr, x1, x2, eq
|
||||
];
|
||||
for (label, word) in w_variants {
|
||||
for (nlabel, nzcv) in [
|
||||
("zero", 0u64),
|
||||
("z", 0x4000_0000),
|
||||
("c", 0x2000_0000),
|
||||
("all", 0xf000_0000),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.csel.{label}.{nlabel}"), &[word])
|
||||
.x(0, 0xdead_beef_1111_2222)
|
||||
.x(1, 0xcafe_babe_3333_4444)
|
||||
.x(2, 0xbaad_f00d_5555_6666)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn m4_blocks(cases: &mut Vec<Case>) {
|
||||
// 1. 128-bit ADDS + ADCS carry propagation into CSEL CS
|
||||
let u128_add = [0xab02_0004u32, 0xba03_0025, 0x9a85_2086];
|
||||
for (label, x0, x1, x2, x3, nzcv) in [
|
||||
(
|
||||
"c_low",
|
||||
0xffff_ffff_ffff_ffff,
|
||||
0x7fff_ffff_ffff_ffff,
|
||||
1,
|
||||
0,
|
||||
0xf000_0000u64,
|
||||
),
|
||||
("no_carry", 10, 0xffff_ffff_ffff_ffff, 20, 0, 0x2000_0000),
|
||||
("double_carry", u64::MAX, u64::MAX, 1, 0, 0),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.u128_add_csel.{label}"), &u128_add)
|
||||
.x(0, x0)
|
||||
.x(1, x1)
|
||||
.x(2, x2)
|
||||
.x(3, x3)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
|
||||
// 2. 128-bit SUBS + SBCS borrow propagation into CSEL LT
|
||||
let u128_sub = [0xeb02_0004u32, 0xfa03_0025, 0x9a85_b086];
|
||||
for (label, x0, x1, x2, x3) in [
|
||||
("borrow", 0u64, 0u64, 1u64, 0u64),
|
||||
("no_borrow", 5, 0x8000_0000_0000_0000, 3, 1),
|
||||
("signed_lt", 0, 0x8000_0000_0000_0000, 1, 0),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.u128_sub_csel.{label}"), &u128_sub)
|
||||
.x(0, x0)
|
||||
.x(1, x1)
|
||||
.x(2, x2)
|
||||
.x(3, x3),
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Mixed ADDS carry-out -> SBCS -> CSEL VS
|
||||
let mixed_adds_sbcs = [0xab02_0004u32, 0xfa03_0025, 0x9a85_6086];
|
||||
for (label, x0, x1, x2, x3) in [
|
||||
(
|
||||
"no_borrow_ovf",
|
||||
1u64,
|
||||
0x7fff_ffff_ffff_ffffu64,
|
||||
0xffff_ffff_ffff_ffffu64,
|
||||
u64::MAX,
|
||||
),
|
||||
("borrow_ovf", 1, 0x8000_0000_0000_0000, 2, 0),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(
|
||||
format!("m4.block.mixed_adds_sbcs.{label}"),
|
||||
&mixed_adds_sbcs,
|
||||
)
|
||||
.x(0, x0)
|
||||
.x(1, x1)
|
||||
.x(2, x2)
|
||||
.x(3, x3),
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Consecutive AddSubCarry chain: ADCS -> SBCS -> ADCS -> CSEL HI
|
||||
let carry_run = [0xba02_0004u32, 0xfa03_0025, 0xba05_0086, 0x9a86_80a7];
|
||||
for (label, nzcv) in [("c0", 0xd000_0000u64), ("c1", 0x2000_0000)] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.carry_run_mixed.{label}"), &carry_run)
|
||||
.x(0, u64::MAX)
|
||||
.x(1, 10)
|
||||
.x(2, 0)
|
||||
.x(3, 5)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
|
||||
// 5. Intra-block dead flag kill: ADDS -> ADDS -> CSEL EQ
|
||||
let dead_kill = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086];
|
||||
for (label, x2, x3, nzcv) in [
|
||||
("zero_final", 5u64, 0xffff_ffff_ffff_fffbu64, 0xf000_0000u64),
|
||||
("nonzero_final", 5, 6, 0x4000_0000),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.dead_flags_kill.{label}"), &dead_kill)
|
||||
.x(0, 1)
|
||||
.x(1, 2)
|
||||
.x(2, x2)
|
||||
.x(3, x3)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
|
||||
// 6. 32-bit dirty-upper-bits multi-step chain: ADDS W -> ADCS W -> SBCS W -> CSEL W GE
|
||||
let w32_chain = [0x2b01_0004u32, 0x3a1f_0045, 0x7a04_00a6, 0x1a86_a087];
|
||||
for (label, w0, w1, w2) in [
|
||||
(
|
||||
"carry_ge",
|
||||
0xdead_beef_ffff_ffffu64,
|
||||
0xfeed_face_0000_0001u64,
|
||||
0xbaad_f00d_7fff_ffffu64,
|
||||
),
|
||||
(
|
||||
"borrow_lt",
|
||||
0x1234_5678_8000_0000,
|
||||
0x9abc_def0_0000_0001,
|
||||
0x0000_0001_0000_0000,
|
||||
),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.w32_chain.{label}"), &w32_chain)
|
||||
.x(0, w0)
|
||||
.x(1, w1)
|
||||
.x(2, w2)
|
||||
.nzcv(0xf000_0000),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every case, in a fixed order.
|
||||
pub fn all() -> Vec<Case> {
|
||||
let mut cases = m1_baseline();
|
||||
cases.extend(m4_flags_csel());
|
||||
cases
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Three-way verification of explicit instruction semantics, basic-block
|
||||
//! side effects, Stela LEAF / BlockRuntime / SYSTEM_MODE compilation, and
|
||||
//! native Apple M4 outcomes.
|
||||
use super::corpus;
|
||||
use super::record::{self, Ending, MEMORY};
|
||||
use super::stela;
|
||||
use anyhow::{Result, ensure};
|
||||
use stela_compiler::{
|
||||
GuestAddress, GuestState, Lifter, Options, TargetCpu,
|
||||
aarch64::{
|
||||
Decoder, Register, Width,
|
||||
flags::{NZCV_C, NZCV_N, NZCV_V, NZCV_Z},
|
||||
semantics::{FlagMask, RegisterSet, add_with_carry, semantics_of},
|
||||
},
|
||||
block::{
|
||||
BlockProfile, Features, analyze_block_effects, eval_instructions, summarize_instructions,
|
||||
},
|
||||
compile,
|
||||
};
|
||||
|
||||
const RET_ENCODING: u32 = 0xd65f_03c0;
|
||||
|
||||
/// Execute all explicit semantic checks, block side-effect invariants,
|
||||
/// Stela LEAF vs BlockRuntime vs semantic-oracle equivalence checks across the
|
||||
/// full `m4_flags_csel` suite.
|
||||
pub fn verify_m4_semantics() -> Result<()> {
|
||||
verify_instruction_contracts()?;
|
||||
verify_block_contracts()?;
|
||||
verify_corpus_three_way()?;
|
||||
println!(
|
||||
"semantics verification: 100% passed (instruction contracts, block effects, 480 m4 cases x semantic oracle x LEAF x BlockRuntime x SYSTEM_MODE compile)"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lift(words: &[u32]) -> Result<Vec<stela_compiler::aarch64::Instruction>> {
|
||||
words
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &w)| {
|
||||
Decoder
|
||||
.lift(GuestAddress(0x10_0000 + i as u64 * 4), w)
|
||||
.map_err(|e| anyhow::anyhow!("decode failed at #{i} ({w:#010x}): {e:?}"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn verify_instruction_contracts() -> Result<()> {
|
||||
// 1. ADDS imm & shifted reg: reads GPR(s), reads no flags, writes ALL flags.
|
||||
let adds_imm = lift(&[0x3100_0420])?;
|
||||
let s = semantics_of(&adds_imm[0].operation).expect("adds w0, w1, #1");
|
||||
ensure!(s.width == Width::W32);
|
||||
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
|
||||
ensure!(s.gpr_writes == RegisterSet::of(Register::X(0)));
|
||||
ensure!(s.flag_reads == FlagMask::NONE && s.flag_writes == FlagMask::ALL);
|
||||
|
||||
// CMN W1, #0xfff -> writes ZERO architectural GPR while writing all flags.
|
||||
let cmn = lift(&[0x313f_fc3f])?;
|
||||
let s = semantics_of(&cmn[0].operation).expect("cmn w1, #0xfff");
|
||||
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
|
||||
ensure!(s.gpr_writes == RegisterSet::NONE);
|
||||
ensure!(s.flag_writes == FlagMask::ALL);
|
||||
|
||||
// 2. ADCS & SBCS: read C flag ONLY, write ALL flags.
|
||||
let carry_ops = lift(&[0xba02_0020, 0xfa02_0020])?;
|
||||
for insn in &carry_ops {
|
||||
let s = semantics_of(&insn.operation).expect("adcs/sbcs");
|
||||
ensure!(s.flag_reads == FlagMask::C);
|
||||
ensure!(s.flag_writes == FlagMask::ALL);
|
||||
}
|
||||
|
||||
// 3. CSEL: condition-specific flag reads, NO flag writes, AL/NV unconditional.
|
||||
for cond in 0..16u32 {
|
||||
let word = 0x9a82_0020 | (cond << 12);
|
||||
let insn = lift(&[word])?;
|
||||
let s = semantics_of(&insn[0].operation).expect("csel");
|
||||
ensure!(s.flag_writes == FlagMask::NONE);
|
||||
ensure!(s.flag_reads == FlagMask::condition_reads(cond as u8));
|
||||
if cond >= 14 {
|
||||
ensure!(s.flag_reads == FlagMask::NONE);
|
||||
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
|
||||
} else {
|
||||
ensure!(s.gpr_reads == RegisterSet::from_registers([Register::X(1), Register::X(2)]));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Arm AddWithCarry edge values.
|
||||
ensure!(add_with_carry(Width::W32, 0xffff_ffff, 0, true) == (0, NZCV_Z | NZCV_C));
|
||||
ensure!(add_with_carry(Width::W32, 0x7fff_ffff, 0, true) == (0x8000_0000, NZCV_N | NZCV_V));
|
||||
ensure!(
|
||||
add_with_carry(Width::X64, 0x8000_0000_0000_0000, !0u64, false)
|
||||
== (0x7fff_ffff_ffff_ffff, NZCV_C | NZCV_V)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_block_contracts() -> Result<()> {
|
||||
// ADDS -> ADCS -> CSEL CS: live_in_flags == NONE, X0..X3 live-in, X4..X6 written.
|
||||
// Neither flag write is dead because ADCS consumes C and block exit keeps NZCV live.
|
||||
let u128_words = [0xab02_0004u32, 0xba03_0025, 0x9a85_2086];
|
||||
let u128_bytes: Vec<u8> = u128_words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let e = analyze_block_effects(&u128_bytes, GuestAddress(0x10_0000))?;
|
||||
ensure!(e.fully_modeled && e.live_in_flags == FlagMask::NONE);
|
||||
ensure!(e.written_flags == FlagMask::ALL && e.killed_flags == FlagMask::ALL);
|
||||
ensure!(e.live_in_gprs.contains(Register::X(0)) && e.live_in_gprs.contains(Register::X(3)));
|
||||
ensure!(!e.live_in_gprs.contains(Register::X(4)));
|
||||
ensure!(e.dead_flag_defs.is_empty());
|
||||
|
||||
// ADCS -> SBCS -> ADCS -> CSEL HI: live_in_flags == C (N,Z,V entry bits ignored).
|
||||
let run_words = [0xba02_0004u32, 0xfa03_0025, 0xba05_0086, 0x9a86_80a7];
|
||||
let run_insns = lift(&run_words)?;
|
||||
let e_run = summarize_instructions(&run_insns);
|
||||
ensure!(e_run.live_in_flags == FlagMask::C);
|
||||
ensure!(e_run.dead_flag_defs.is_empty());
|
||||
|
||||
// Dead-flag kill: ADDS -> ADDS -> CSEL EQ (first ADDS flags dead).
|
||||
let kill_words = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086];
|
||||
let kill_bytes: Vec<u8> = kill_words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let e_kill = analyze_block_effects(&kill_bytes, GuestAddress(0x10_0000))?;
|
||||
ensure!(e_kill.live_in_flags == FlagMask::NONE);
|
||||
ensure!(e_kill.dead_flag_defs == vec![0]);
|
||||
|
||||
// ADDS -> CSEL AL -> ADDS: unconditional CSEL AL reads no flags, so first ADDS is dead.
|
||||
let al_words = [0xab01_0004u32, 0x9a85_e086, 0xab03_0045];
|
||||
let al_bytes: Vec<u8> = al_words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let e_al = analyze_block_effects(&al_bytes, GuestAddress(0x10_0000))?;
|
||||
ensure!(e_al.live_in_flags == FlagMask::NONE);
|
||||
ensure!(e_al.dead_flag_defs == vec![0]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_corpus_three_way() -> Result<()> {
|
||||
let cases = corpus::m4_flags_csel();
|
||||
ensure!(!cases.is_empty(), "m4_flags_csel must be non-empty");
|
||||
let block_runtime_endings = stela::run(&cases)?;
|
||||
let leaf_options = Options::new(BlockProfile::new(Features::LEAF), TargetCpu::detect());
|
||||
let system_options = Options::new(
|
||||
BlockProfile::new(Features::SYSTEM_MODE),
|
||||
TargetCpu::detect(),
|
||||
);
|
||||
|
||||
for (case, br_ending) in cases.iter().zip(&block_runtime_endings) {
|
||||
// 1. Lift and verify semantic model + side effects.
|
||||
let insns = lift(&case.words)?;
|
||||
let effects = summarize_instructions(&insns);
|
||||
ensure!(effects.fully_modeled, "{} was not modeled", case.name);
|
||||
|
||||
let mut oracle_state = GuestState {
|
||||
x: case.state.x,
|
||||
nzcv: case.state.nzcv as u32,
|
||||
..Default::default()
|
||||
};
|
||||
eval_instructions(&insns, &mut oracle_state)
|
||||
.ok_or_else(|| anyhow::anyhow!("oracle failed on {}", case.name))?;
|
||||
|
||||
// 2. Non-interference: architectural registers outside `written_gprs` stay identical,
|
||||
// and unread entry flag bits do not affect register outputs (or flags if overwritten).
|
||||
for idx in 0..31u8 {
|
||||
if !effects.written_gprs.contains(Register::X(idx)) {
|
||||
ensure!(
|
||||
oracle_state.x[usize::from(idx)] == case.state.x[usize::from(idx)],
|
||||
"{}: unmodeled write to X{idx}",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
}
|
||||
let unread_flags = FlagMask::ALL
|
||||
.difference(effects.live_in_flags)
|
||||
.to_nzcv_mask();
|
||||
if unread_flags != 0 {
|
||||
let mut perturbed = GuestState {
|
||||
x: case.state.x,
|
||||
nzcv: (case.state.nzcv as u32) ^ unread_flags,
|
||||
..Default::default()
|
||||
};
|
||||
eval_instructions(&insns, &mut perturbed).unwrap();
|
||||
ensure!(
|
||||
perturbed.x == oracle_state.x,
|
||||
"{}: unread NZCV bits altered GPRs",
|
||||
case.name
|
||||
);
|
||||
if effects.written_flags == FlagMask::ALL {
|
||||
ensure!(
|
||||
perturbed.nzcv == oracle_state.nzcv,
|
||||
"{}: unread NZCV bits altered final NZCV",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Compare semantic oracle against BlockRuntime (`optimize: true`).
|
||||
let oracle_ending = Ending::Completed {
|
||||
state: Box::new(super::record::State {
|
||||
x: oracle_state.x,
|
||||
nzcv: u64::from(oracle_state.nzcv),
|
||||
fpcr: case.state.fpcr,
|
||||
fpsr: case.state.fpsr,
|
||||
v: case.state.v,
|
||||
}),
|
||||
memory: Box::new([0u8; MEMORY]),
|
||||
};
|
||||
let oracle_out = record::outcome(case, &oracle_ending);
|
||||
let br_out = record::outcome(case, br_ending);
|
||||
ensure!(
|
||||
oracle_out == br_out,
|
||||
"{}: semantic oracle ({oracle_out}) != BlockRuntime ({br_out})",
|
||||
case.name
|
||||
);
|
||||
|
||||
// 4. Compile & execute through Stela `Features::LEAF` (frame emitter).
|
||||
let mut leaf_words = case.words.clone();
|
||||
leaf_words.push(RET_ENCODING);
|
||||
let leaf_bytes: Vec<u8> = leaf_words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let compiled_leaf = compile(&leaf_bytes, GuestAddress(0x10_0000), &leaf_options)?;
|
||||
ensure!(
|
||||
compiled_leaf.source_bytes == leaf_bytes.len(),
|
||||
"{}: LEAF truncated block",
|
||||
case.name
|
||||
);
|
||||
let mut leaf_state = GuestState {
|
||||
x: case.state.x,
|
||||
nzcv: case.state.nzcv as u32,
|
||||
..Default::default()
|
||||
};
|
||||
run_native_leaf(&compiled_leaf.native.x86_64_code, &mut leaf_state)?;
|
||||
ensure!(
|
||||
leaf_state.x == oracle_state.x && leaf_state.nzcv == oracle_state.nzcv,
|
||||
"{}: LEAF mismatch: leaf(nzcv={:#x}) vs oracle(nzcv={:#x})",
|
||||
case.name,
|
||||
leaf_state.nzcv,
|
||||
oracle_state.nzcv
|
||||
);
|
||||
|
||||
// 5. Compile through Stela `Features::SYSTEM_MODE` (pinned + carry runs + dead-flag elimination).
|
||||
let block_bytes: Vec<u8> = case.words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let compiled_sys = compile(&block_bytes, GuestAddress(0x10_0000), &system_options)?;
|
||||
ensure!(
|
||||
compiled_sys.source_bytes == block_bytes.len(),
|
||||
"{}: SYSTEM_MODE did not cover full block",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn run_native_leaf(code: &[u8], state: &mut GuestState) -> Result<()> {
|
||||
use core::ffi::c_void;
|
||||
unsafe extern "system" {
|
||||
fn GetCurrentProcess() -> *mut c_void;
|
||||
fn VirtualAlloc(
|
||||
lp_address: *mut c_void,
|
||||
dw_size: usize,
|
||||
fl_allocation_type: u32,
|
||||
fl_protect: u32,
|
||||
) -> *mut c_void;
|
||||
fn VirtualProtect(
|
||||
lp_address: *mut c_void,
|
||||
dw_size: usize,
|
||||
fl_new_protect: u32,
|
||||
lpfl_old_protect: *mut u32,
|
||||
) -> i32;
|
||||
fn VirtualFree(lp_address: *mut c_void, dw_size: usize, dw_free_type: u32) -> i32;
|
||||
fn FlushInstructionCache(
|
||||
h_process: *mut c_void,
|
||||
lp_base_address: *const c_void,
|
||||
dw_size: usize,
|
||||
) -> i32;
|
||||
}
|
||||
let bytes = code.len().max(1).next_multiple_of(4096);
|
||||
// SAFETY: allocates a private RW buffer, copies Stela's generated leaf
|
||||
// x86-64 code (ending in RET), transitions it to RX, flushes I-cache,
|
||||
// executes with SysV64 ABI (`RDI = state`), and frees it.
|
||||
unsafe {
|
||||
let page = VirtualAlloc(core::ptr::null_mut(), bytes, 0x3000, 0x04);
|
||||
ensure!(!page.is_null(), "VirtualAlloc failed for leaf");
|
||||
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
|
||||
let mut old = 0u32;
|
||||
ensure!(
|
||||
VirtualProtect(page, bytes, 0x20, &mut old) != 0,
|
||||
"VirtualProtect failed"
|
||||
);
|
||||
ensure!(
|
||||
FlushInstructionCache(GetCurrentProcess(), page, bytes) != 0,
|
||||
"FlushInstructionCache failed"
|
||||
);
|
||||
let func: unsafe extern "sysv64" fn(*mut GuestState) = core::mem::transmute(page);
|
||||
func(state as *mut GuestState);
|
||||
ensure!(VirtualFree(page, 0, 0x8000) != 0, "VirtualFree failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn run_native_leaf(code: &[u8], state: &mut GuestState) -> Result<()> {
|
||||
use core::ffi::c_void;
|
||||
unsafe extern "C" {
|
||||
fn mmap(
|
||||
addr: *mut c_void,
|
||||
len: usize,
|
||||
prot: i32,
|
||||
flags: i32,
|
||||
fd: i32,
|
||||
off: i64,
|
||||
) -> *mut c_void;
|
||||
fn mprotect(addr: *mut c_void, len: usize, prot: i32) -> i32;
|
||||
fn munmap(addr: *mut c_void, len: usize) -> i32;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
const MAP_ANON: i32 = 0x1000;
|
||||
#[cfg(target_os = "linux")]
|
||||
const MAP_ANON: i32 = 0x20;
|
||||
let bytes = code.len().max(1).next_multiple_of(4096);
|
||||
// SAFETY: private RX mapping containing valid compiled leaf code.
|
||||
unsafe {
|
||||
let page = mmap(core::ptr::null_mut(), bytes, 3, 2 | MAP_ANON, -1, 0);
|
||||
ensure!(page as usize != usize::MAX, "mmap failed");
|
||||
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
|
||||
ensure!(mprotect(page, bytes, 5) == 0, "mprotect failed");
|
||||
let func: unsafe extern "sysv64" fn(*mut GuestState) = core::mem::transmute(page);
|
||||
func(state as *mut GuestState);
|
||||
ensure!(munmap(page, bytes) == 0, "munmap failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,9 +5,119 @@ use super::record::{Case, Ending, MEMORY, State};
|
||||
use anyhow::{Context, Result};
|
||||
use stela_compiler::{GuestAddress, GuestState};
|
||||
use stela_engine::blocks::{BlockRuntime, StopReason, ThreadState};
|
||||
#[cfg(unix)]
|
||||
use stela_engine::memory::{MemoryRegionSpec, OwnedMemory};
|
||||
use stela_engine::pauth::{self, Keys};
|
||||
|
||||
#[cfg(unix)]
|
||||
struct CaseBuffer(OwnedMemory);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl CaseBuffer {
|
||||
fn allocate() -> Result<Self> {
|
||||
let memory = OwnedMemory::map(vec![MemoryRegionSpec {
|
||||
guest_address: MEMORY_BASE,
|
||||
virtual_bytes: 4096,
|
||||
initial_bytes: vec![0; 4096],
|
||||
readable: true,
|
||||
writable: true,
|
||||
executable: false,
|
||||
}])
|
||||
.context("cannot map the case buffer")?;
|
||||
Ok(Self(memory))
|
||||
}
|
||||
|
||||
fn write(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
// Re-zero first so shrinking or untouched regions never leak prior case bytes.
|
||||
self.0.write(MEMORY_BASE, &[0u8; 4096])?;
|
||||
self.0.write(MEMORY_BASE, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_snapshot(&self, len: usize) -> Result<Vec<u8>> {
|
||||
self.0.read_snapshot(MEMORY_BASE, len)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
struct CaseBuffer {
|
||||
ptr: *mut core::ffi::c_void,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl CaseBuffer {
|
||||
const ALLOCATION_BYTES: usize = 0x1_0000;
|
||||
const MEM_COMMIT: u32 = 0x1000;
|
||||
const MEM_RESERVE: u32 = 0x2000;
|
||||
const MEM_RELEASE: u32 = 0x8000;
|
||||
const PAGE_READWRITE: u32 = 0x04;
|
||||
|
||||
fn allocate() -> Result<Self> {
|
||||
unsafe extern "system" {
|
||||
fn VirtualAlloc(
|
||||
lp_address: *mut core::ffi::c_void,
|
||||
dw_size: usize,
|
||||
fl_allocation_type: u32,
|
||||
fl_protect: u32,
|
||||
) -> *mut core::ffi::c_void;
|
||||
}
|
||||
// SAFETY: reserves and commits a fresh 64 KiB read-write buffer at the
|
||||
// fixed 64 KiB-aligned guest address used by the differential harness.
|
||||
let ptr = unsafe {
|
||||
VirtualAlloc(
|
||||
MEMORY_BASE as *mut core::ffi::c_void,
|
||||
Self::ALLOCATION_BYTES,
|
||||
Self::MEM_COMMIT | Self::MEM_RESERVE,
|
||||
Self::PAGE_READWRITE,
|
||||
)
|
||||
};
|
||||
anyhow::ensure!(!ptr.is_null(), "VirtualAlloc failed for case buffer");
|
||||
anyhow::ensure!(
|
||||
ptr as u64 == MEMORY_BASE,
|
||||
"VirtualAlloc returned {:#x}, expected {MEMORY_BASE:#x}",
|
||||
ptr as u64
|
||||
);
|
||||
Ok(Self { ptr })
|
||||
}
|
||||
|
||||
fn write(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
anyhow::ensure!(bytes.len() <= 4096, "case memory exceeds 4096 bytes");
|
||||
// SAFETY: `ptr` points to `ALLOCATION_BYTES` uniquely owned writable bytes.
|
||||
unsafe {
|
||||
core::ptr::write_bytes(self.ptr.cast::<u8>(), 0, 4096);
|
||||
core::ptr::copy_nonoverlapping(bytes.as_ptr(), self.ptr.cast::<u8>(), bytes.len());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_snapshot(&self, len: usize) -> Result<Vec<u8>> {
|
||||
anyhow::ensure!(len <= 4096, "snapshot exceeds 4096 bytes");
|
||||
let mut out = vec![0u8; len];
|
||||
// SAFETY: `ptr` points to at least 4096 initialized readable bytes.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(self.ptr.cast::<u8>(), out.as_mut_ptr(), len);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Drop for CaseBuffer {
|
||||
fn drop(&mut self) {
|
||||
unsafe extern "system" {
|
||||
fn VirtualFree(
|
||||
lp_address: *mut core::ffi::c_void,
|
||||
dw_size: usize,
|
||||
dw_free_type: u32,
|
||||
) -> i32;
|
||||
}
|
||||
// SAFETY: `self.ptr` was allocated with `VirtualAlloc(MEM_RESERVE | MEM_COMMIT)`.
|
||||
unsafe {
|
||||
let _ = VirtualFree(self.ptr, 0, Self::MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ADDRESS_SPACE: u64 = 0x5ce1;
|
||||
/// Guest addresses equal host addresses in the direct profile: the buffer
|
||||
/// is mapped here, at a 64-byte-aligned address as the runner's.
|
||||
@@ -32,15 +142,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
|
||||
),
|
||||
stela_compiler::TargetCpu::detect(),
|
||||
);
|
||||
let mut memory = OwnedMemory::map(vec![MemoryRegionSpec {
|
||||
guest_address: MEMORY_BASE,
|
||||
virtual_bytes: 4096,
|
||||
initial_bytes: vec![0; 4096],
|
||||
readable: true,
|
||||
writable: true,
|
||||
executable: false,
|
||||
}])
|
||||
.context("cannot map the case buffer")?;
|
||||
let mut memory = CaseBuffer::allocate().context("cannot map the case buffer")?;
|
||||
let pauth = pauth::Context::new(
|
||||
ADDRESS_SPACE,
|
||||
Keys::from_words(KEY, KEY, KEY, KEY).with_generic_words(KEY),
|
||||
@@ -52,7 +154,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
|
||||
words.push(BRANCH_NEXT);
|
||||
let source = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
runtime.register_code(GuestAddress(base), source)?;
|
||||
memory.write(MEMORY_BASE, &case.memory)?;
|
||||
memory.write(&case.memory)?;
|
||||
let mut thread = ThreadState {
|
||||
registers: guest_state(case),
|
||||
pc: GuestAddress(base),
|
||||
@@ -71,7 +173,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
|
||||
state.x[register] = state.x[register].wrapping_sub(MEMORY_BASE);
|
||||
}
|
||||
}
|
||||
let bytes = memory.read_snapshot(MEMORY_BASE, MEMORY)?;
|
||||
let bytes = memory.read_snapshot(MEMORY)?;
|
||||
Ending::Completed {
|
||||
state: Box::new(state),
|
||||
memory: Box::new(bytes.try_into().unwrap()),
|
||||
|
||||
@@ -3,32 +3,68 @@ use super::*;
|
||||
#[test]
|
||||
fn every_case_is_recorded() {
|
||||
let table = recorded().unwrap();
|
||||
let cases = corpus::all();
|
||||
let cases = corpus::m1_baseline();
|
||||
assert_eq!(table.len(), cases.len());
|
||||
for case in &cases {
|
||||
assert!(table.contains_key(case.name.as_str()), "{}", case.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The regression check: every case through Stela gives the outcome
|
||||
/// recorded on the Mac, except the known differences, which still differ.
|
||||
/// Stela runs the cases in exact guest mappings, which only an x86-64 Linux
|
||||
/// or macOS host has.
|
||||
#[test]
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "linux", target_os = "macos")))]
|
||||
fn m4_semantics_and_tiers_match() {
|
||||
semantics_verify::verify_m4_semantics().unwrap();
|
||||
}
|
||||
|
||||
/// The regression check: every case through Stela gives the outcome
|
||||
/// recorded on the M1 Pro, except the known differences, which still differ.
|
||||
#[test]
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
any(target_os = "linux", target_os = "macos", target_os = "windows")
|
||||
))]
|
||||
fn stela_matches_the_recorded_mac() {
|
||||
let table = recorded().unwrap();
|
||||
let cases = corpus::all();
|
||||
let cases = corpus::m1_baseline();
|
||||
let endings = stela::run(&cases).unwrap();
|
||||
let mut unexpected = Vec::new();
|
||||
for (case, ending) in cases.iter().zip(&endings) {
|
||||
let stela = record::outcome(case, ending);
|
||||
let mac = table[case.name.as_str()];
|
||||
let mac = &table[case.name.as_str()];
|
||||
match known_difference(&case.name) {
|
||||
None if stela != mac => {
|
||||
None if &stela != mac => {
|
||||
unexpected.push(format!("{}: mac {mac}, stela {stela}", case.name))
|
||||
}
|
||||
Some(_) if stela == mac => unexpected.push(format!("{}: no longer differs", case.name)),
|
||||
Some(_) if &stela == mac => {
|
||||
unexpected.push(format!("{}: no longer differs", case.name))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(unexpected.is_empty(), "{}", unexpected.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
any(target_os = "linux", target_os = "macos", target_os = "windows")
|
||||
))]
|
||||
fn stela_matches_recorded_apple_m4() {
|
||||
let table =
|
||||
recorded_from_path(std::path::Path::new("xtask/src/cpu_reference/apple-m4.tsv")).unwrap();
|
||||
let cases = corpus::all();
|
||||
assert_eq!(table.len(), cases.len());
|
||||
let endings = stela::run(&cases).unwrap();
|
||||
let mut unexpected = Vec::new();
|
||||
for (case, ending) in cases.iter().zip(&endings) {
|
||||
let stela = record::outcome(case, ending);
|
||||
let mac = &table[case.name.as_str()];
|
||||
match known_difference(&case.name) {
|
||||
None if &stela != mac => {
|
||||
unexpected.push(format!("{}: m4 {mac}, stela {stela}", case.name))
|
||||
}
|
||||
Some(_) if &stela == mac => {
|
||||
unexpected.push(format!("{}: no longer differs", case.name))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
+10
-44
@@ -11,7 +11,6 @@
|
||||
use crate::tools::{self, exec};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use std::{
|
||||
env,
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
@@ -50,39 +49,12 @@ pub fn run() -> Result<()> {
|
||||
fs::write(include.join("stela/bundle.h"), bundle_header(&bundle)?)?;
|
||||
fs::write(include.join("stela/app.h"), app_header(root)?)?;
|
||||
fs::write(include.join("stela/compression.h"), compression::header()?)?;
|
||||
let kext = build_kext(&component, &output.join("StelaGPU.kext"), &xnu, &include)?;
|
||||
let kext = build_kext(&component, &output, &xnu, &include)?;
|
||||
let code = stela_loader::plugin::code_hashes(&fs::read(bundle.join(BUNDLE_EXECUTABLE))?)?;
|
||||
fs::write(kext.join(TRUSTED_CODE_FILE), code.concat())?;
|
||||
embed_kext(&kext, &code, &output.join("StelaGPU.kext.rs"))?;
|
||||
stela_cli::gpu::Payload::write(&output)?;
|
||||
println!("StelaGPU kext: {}", kext.display());
|
||||
let hosted = build_kext(
|
||||
&root.join("guest/reims-hosted"),
|
||||
&output.join("ReimsHostedDevice.kext"),
|
||||
&xnu,
|
||||
&include,
|
||||
)?;
|
||||
embed_kext(&hosted, &[], &output.join("ReimsHostedDevice.kext.rs"))?;
|
||||
println!("ReimsHostedDevice kext: {}", hosted.display());
|
||||
if let Some(bundle) = env::var_os("STELA_REIMS_GRAPHICS_KEXT") {
|
||||
let bundle = std::path::absolute(bundle)?;
|
||||
let trusted = bundle.join(TRUSTED_CODE_FILE);
|
||||
let code = match fs::read(&trusted) {
|
||||
Ok(bytes) => stela_loader::trust_cache::code_hashes(&bytes)
|
||||
.with_context(|| format!("{}: invalid trusted code", trusted.display()))?,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
|
||||
Err(error) => {
|
||||
return Err(error)
|
||||
.with_context(|| format!("cannot read {}", trusted.display()));
|
||||
}
|
||||
};
|
||||
embed_kext(&bundle, &code, &output.join("ReimsGraphics.kext.rs"))?;
|
||||
println!(
|
||||
"ReimsGraphics kext: {} ({} trusted code hashes)",
|
||||
bundle.display(),
|
||||
code.len()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -226,12 +198,13 @@ fn selector_stub_flags(clang: &Path) -> &'static [&'static str] {
|
||||
|
||||
/// Compiles each source of `<component>/kext` into `<output>/StelaGPU.kext`
|
||||
/// beside its `Info.plist`.
|
||||
fn build_kext(component: &Path, bundle: &Path, xnu: &Path, include: &Path) -> Result<PathBuf> {
|
||||
fn build_kext(component: &Path, output: &Path, xnu: &Path, include: &Path) -> Result<PathBuf> {
|
||||
let source = component.join("kext");
|
||||
let bundle = output.join("StelaGPU.kext");
|
||||
if bundle.exists() {
|
||||
fs::remove_dir_all(bundle)?;
|
||||
fs::remove_dir_all(&bundle)?;
|
||||
}
|
||||
fs::create_dir_all(bundle)?;
|
||||
fs::create_dir_all(&bundle)?;
|
||||
let info = fs::read_to_string(source.join("Info.plist"))?;
|
||||
let (identifier, version) = identity(&info)?;
|
||||
fs::write(bundle.join("Info.plist"), &info)?;
|
||||
@@ -256,7 +229,7 @@ fn build_kext(component: &Path, bundle: &Path, xnu: &Path, include: &Path) -> Re
|
||||
command.arg("-isystem").arg(include);
|
||||
exec(command.arg("-c").arg(&path).arg("-o").arg(&object))?;
|
||||
}
|
||||
Ok(bundle.to_path_buf())
|
||||
Ok(bundle)
|
||||
}
|
||||
|
||||
/// `stela/bundle.h`: the Metal plugin `bundle` as the kext installs it, each
|
||||
@@ -288,10 +261,8 @@ fn bundle_header(bundle: &Path) -> Result<String> {
|
||||
.map(|path| {
|
||||
let name = path
|
||||
.strip_prefix(bundle)?
|
||||
.iter()
|
||||
.map(|component| component.to_str().context("a file name is not UTF-8"))
|
||||
.collect::<Result<Vec<_>>>()?
|
||||
.join("/");
|
||||
.to_str()
|
||||
.context("a file name is not UTF-8")?;
|
||||
ensure!(
|
||||
name.bytes()
|
||||
.all(|byte| byte.is_ascii_graphic() && byte != b'"' && byte != b'\\'),
|
||||
@@ -303,7 +274,7 @@ fn bundle_header(bundle: &Path) -> Result<String> {
|
||||
);
|
||||
let bytes = fs::read(&path)?;
|
||||
ensure!(!bytes.is_empty(), "{name} is empty");
|
||||
Ok((name, bytes))
|
||||
Ok((name.to_owned(), bytes))
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
files.sort();
|
||||
@@ -373,16 +344,11 @@ fn embed_kext(kext: &Path, code: &[CodeHash], source: &Path) -> Result<()> {
|
||||
.collect::<Result<_>>()?;
|
||||
objects.retain(|path| path.extension().is_some_and(|extension| extension == "o"));
|
||||
objects.sort();
|
||||
let info = kext.join("Info.plist");
|
||||
ensure!(
|
||||
info.is_file() && !objects.is_empty(),
|
||||
"{} needs Info.plist and relocatable objects",
|
||||
kext.display()
|
||||
);
|
||||
let includes: String = objects
|
||||
.iter()
|
||||
.map(|path| format!(" include_bytes!({:?}),\n", path.display().to_string()))
|
||||
.collect();
|
||||
let info = kext.join("Info.plist");
|
||||
fs::write(
|
||||
source,
|
||||
format!(
|
||||
|
||||
Reference in new issue
Block a user