Author SHA1 Message Date
YXC0915 01c5e819a9 Snapshot local hosted Reims ARM integration 2026-12-05 22:26:08 +08:00
YXC0915 1cafb9a6ca 🆕 Route hosted Reims apertures on the ARM bus
Require the copy-only wire capabilities before publishing the three
windows. Exercise the address translation with a display query to a
paused hosted QEMU device.
2026-11-30 21:20:42 +08:00
41 changed files with 2440 additions and 120 deletions

No files matched your search

+30
View File
@@ -43,6 +43,27 @@ 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";
@@ -219,6 +240,9 @@ 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>,
@@ -374,6 +398,9 @@ 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,
@@ -803,6 +830,9 @@ 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,6 +26,8 @@ pub enum Error {
AudioMode,
DumpRegister,
Number,
HostedReimsBase,
HostedReimsIrq,
UrlScheme,
UrlPath,
UrlHost,
@@ -144,6 +146,12 @@ 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,6 +39,26 @@ 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,6 +137,45 @@ 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,6 +8,14 @@ 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));
}
+15
View File
@@ -19,6 +19,21 @@ 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);
+1
View File
@@ -1135,6 +1135,7 @@ dependencies = [
"stela-fingerprint",
"stela-formats",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
+4
View File
@@ -30,6 +30,10 @@ 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"]
+39 -6
View File
@@ -33,6 +33,20 @@ 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")]
@@ -2005,17 +2019,36 @@ pub(super) fn no_metal_device() -> Option<&'static str> {
Some("this stela.efi was built without GPU drivers (the `nvk` feature)")
}
/// 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>> {
/// 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();
#[cfg(feature = "nvk")]
return alloc::vec![stela_loader::aux_kc::Kext {
bundles.push(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(not(feature = "nvk"))]
Vec::new()
});
#[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
}
/// Takes the display for the GPUs [`open`] bound, in the monitor's own mode
+8 -1
View File
@@ -120,7 +120,14 @@ 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"));
}
@@ -130,7 +137,7 @@ impl Owner {
"guest RAM is placed before the guest's memory is registered"
));
}
super::ram::place(&mut state.ram, base);
super::ram::place_except_host(&mut state.ram, base, fixed_host);
Ok(())
}
+222 -10
View File
@@ -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();
let kexts = gpu::kexts(options.hosted_reims_irq.is_some());
let request = installed::Request {
volume: options.boot_volume,
kexts: &kexts,
@@ -157,6 +157,7 @@ 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}"));
@@ -396,6 +397,37 @@ 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]
@@ -572,15 +604,22 @@ fn open_host(
options.dram_base = base;
}
}
ram::place(&mut ram, options.dram_base);
ram::place_except_host(&mut ram, options.dram_base, fixed_reims_host);
host_owner
.place_ram(options.dram_base)
.place_ram_except_host(options.dram_base, fixed_reims_host)
.unwrap_or_else(|error| output::fatal(error));
for range in &ram {
output::arguments(format_args!(
"GUEST DRAM pa={:#x} bytes={:#x} host={:#x}\n",
range.guest, range.bytes, range.host
));
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
));
}
}
#[cfg(feature = "diagnostics")]
if let Some(url) = &options.network_check {
@@ -990,6 +1029,7 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
guest_network,
host_disks,
fdr: mut fdr_device,
hosted_reims,
..
},
ram: worker_ram,
@@ -1016,9 +1056,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();
let metal_device = !gpu_gates.is_empty() || hosted_reims.is_some();
#[cfg(not(feature = "nvk"))]
let metal_device = false;
let metal_device = hosted_reims.is_some();
if let Some(assigned) = &mut assigned
&& options.hides_agx(metal_device)
{
@@ -1039,6 +1079,19 @@ 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.
@@ -1069,6 +1122,35 @@ 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 {
@@ -1078,7 +1160,6 @@ 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()));
@@ -1137,6 +1218,33 @@ 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")]
@@ -3119,6 +3227,7 @@ 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
@@ -3142,6 +3251,7 @@ 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()
@@ -3152,6 +3262,8 @@ 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()
{
@@ -3333,6 +3445,11 @@ 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(
@@ -3499,5 +3616,100 @@ 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
}
+3
View File
@@ -141,6 +141,9 @@ 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
+9
View File
@@ -292,6 +292,15 @@ 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> {
+176 -1
View File
@@ -70,7 +70,13 @@ 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)));
@@ -96,6 +102,175 @@ 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.
+1
View File
@@ -26,6 +26,7 @@ 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
+21 -12
View File
@@ -23,6 +23,8 @@ 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
@@ -33,9 +35,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 page directory: its first `LEAVES` entries hold the
/// leaf tables, the rest map 2 MiB pages.
pub(super) directory: 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],
pub(super) leaves: [u64; LEAVES],
pub(super) virtual_base: u64,
pub(super) cores: u32,
@@ -361,19 +363,26 @@ impl Prepared {
}
*slot = leaf as u64;
}
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"));
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;
}
// 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"));
if wire.directories[0] == wire.directories[1] {
return Err(refuse!("MMIO aperture directories alias each other"));
}
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;
+30 -26
View File
@@ -15,7 +15,7 @@
use super::*;
use super::{
aliases::{aliases, owned_table},
capture::LEAVES,
capture::{DIRECTORIES, 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..ENTRIES,
Size::Large => LEAVES..DIRECTORIES * ENTRIES,
}
}
/// The size a request maps with: 2 MiB pages when it is 2 MiB aligned at
@@ -228,7 +228,9 @@ impl Platform {
Size::Page => {
owned_table(wire, wire.leaves[index / ENTRIES])?.wrapping_add(index % ENTRIES)
}
Size::Large => owned_table(wire, wire.directory)?.wrapping_add(index),
Size::Large => {
owned_table(wire, wire.directories[index / ENTRIES])?.wrapping_add(index % ENTRIES)
}
})
}
fn address(&self, size: Size, index: usize) -> u64 {
@@ -563,10 +565,10 @@ impl Source {
});
let mut written = Vec::new();
written
.try_reserve_exact(LEAVES + 1)
.try_reserve_exact(LEAVES + DIRECTORIES)
.map_err(refused("MMIO aperture: room for the aperture's table list"))?;
written.extend_from_slice(&wire.leaves);
written.push(wire.directory);
written.extend_from_slice(&wire.directories);
for &table in &written {
crate::native_memory::cache::verify_writeback(
crate::layout::physical(table),
@@ -586,32 +588,34 @@ impl Source {
platform.check_context(space).map_err(named(
"the boot processor's root does not share the aperture",
))?;
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 {
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 {
return Err(refuse(&alloc::format!(
"root {root:#x} has entry {entry:#x} at level {level} of the aperture's path"
"root {root:#x} reaches {table:#x}, not the aperture's directory {directory:#x}"
)));
}
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.directory).map_err(named(
let directory = owned_table(wire, wire.directories[0]).map_err(named(
"the aperture's directory is not a table page the capture owns",
))?;
for (index, &leaf) in wire.leaves.iter().enumerate() {
+13 -11
View File
@@ -142,17 +142,19 @@ unsafe fn reserve_with_limit(
.host
.checked_add(range.bytes)
.ok_or(refuse!("canonical guest RAM extent wraps"))?;
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)
})
{
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) {
return Err(refuse!(
"canonical guest RAM is outside actual loader ownership"
));
+46
View File
@@ -755,3 +755,49 @@ 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
}
+16 -1
View File
@@ -331,6 +331,8 @@ 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;
@@ -831,7 +833,19 @@ 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 image = memory::prepare_image(&snapshot)?;
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 mut memory = memory::reserve(cores, &image.ram)?;
let tsc_hz = crate::firmware::tsc_hz();
if !crate::cpu::INVARIANT_TSC.present() {
@@ -1183,6 +1197,7 @@ 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
+39 -3
View File
@@ -21,6 +21,7 @@ pub(super) struct EngineImage {
pub ram: Vec<(usize, usize)>,
pub screen: Option<Framebuffer>,
pub apic: u64,
pub hosted_reims_region: Region,
pub placement: Placement,
}
@@ -46,7 +47,10 @@ pub(super) struct EngineMemory {
}
/// Copy and relocate the pristine image into the selected host window.
pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
pub(super) fn prepare_image(
snapshot: &Snapshot,
hosted_reims_region: Region,
) -> 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"));
@@ -54,7 +58,26 @@ pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
let ram = firmware::ram()?;
let screen = Framebuffer::for_engine()?;
let apic_base = crate::apic::base_msr();
// The physmap reaches RAM, the framebuffer and the local APIC.
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.
let apic = apic_base & crate::apic::BASE_ADDRESS;
let top = ram
.iter()
@@ -66,6 +89,7 @@ pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
.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);
@@ -102,6 +126,7 @@ pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
ram,
screen,
apic,
hosted_reims_region,
placement,
})
}
@@ -274,6 +299,7 @@ pub(super) fn map(
ram,
screen,
apic,
hosted_reims_region,
..
} = image;
let EngineMemory {
@@ -429,7 +455,7 @@ pub(super) fn map(
code.bytes,
PRESENT | tables::GLOBAL,
)?;
// The physmap: all RAM, the framebuffer and the local APIC.
// The physmap: all RAM, any direct-mapped hosted Reims BAR2, the framebuffer and the local APIC.
for &(start, end) in ram {
let (start, end) = (start as u64, end as u64);
tables::map_range(
@@ -441,6 +467,16 @@ 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);
+21 -2
View File
@@ -311,6 +311,24 @@ 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")
@@ -430,13 +448,14 @@ pub fn compile(
.collect();
// System-header diagnostics are normally suppressed. Keep the original
// function prototypes checked before producing an object for any class.
crate::linux_build::check_declarations(&build, std::slice::from_ref(&placement.source));
let compiler_source = compiler_source(&placement.source).to_path_buf();
crate::linux_build::check_declarations(&build, std::slice::from_ref(&compiler_source));
let object = placement.output.join(format!("captured-{token}.o"));
let depfile = object.with_extension("d");
run(compiler
.to_command()
.arg("-c")
.arg(&placement.source)
.arg(&compiler_source)
.arg("-o")
.arg(&object)
.arg("-MD")
+1
View File
@@ -19,6 +19,7 @@ pub mod masked;
pub mod pauth;
pub mod processor;
pub mod refusal;
pub mod reims_hosted;
pub mod tag_storage;
pub mod uuid;
+445
View File
@@ -0,0 +1,445 @@
//! 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)]);
}
}
@@ -0,0 +1,147 @@
//! 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");
}
+2 -1
View File
@@ -320,12 +320,13 @@ 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,
Path::new("src/compat/stela/registration.h"),
&registration,
*spec,
Path::new("../stela-linux"),
)
+1
View File
@@ -40,6 +40,7 @@ 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;
@@ -0,0 +1,216 @@
//! 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))
}
}
+104 -15
View File
@@ -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;
use alloc::{collections::BTreeMap, vec::Vec};
use super::fit;
use super::{fit, fixups::Signature};
use crate::{Result, Within};
use object::{
LittleEndian as LE, macho,
@@ -15,6 +15,13 @@ 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,
@@ -55,15 +62,13 @@ impl<'a> BootCollection<'a> {
self.collection.fileset_entry(entry).is_some()
}
/// 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>> {
fn span(&self, address: u64, size: u64) -> Result<&'a [u8]> {
let segment = self
.collection
.segment_containing(address)
.ok_or_else(|| refuse!("{address:#x} lies outside the boot collection", address))?;
require!(
address + 8 <= segment.vm_address + segment.file_size,
size <= segment.file_size.saturating_sub(address - segment.vm_address),
"{address:#x} has no bytes in the boot collection",
address
);
@@ -71,15 +76,16 @@ impl<'a> BootCollection<'a> {
segment.file_offset + (address - segment.vm_address),
"a boot collection file offset",
)?;
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
))?,
);
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());
if raw == 0 {
return Ok(None);
}
@@ -91,6 +97,89 @@ 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>> {
+28 -11
View File
@@ -25,6 +25,8 @@ 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 {
@@ -111,6 +113,13 @@ 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),
@@ -151,7 +160,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), Value>,
inherited: BTreeMap<(usize, usize, u64), VtableBinding>,
/// 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],
@@ -609,18 +618,20 @@ impl<'a> Unit<'a> {
}),
_ => None,
};
let (value, addend) = match relocation.target {
let (value, addend, signature) = 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)
(self.locate(object, target, relocation.addend as u64)?, 0, signature)
}
Target::Symbol(_) => {
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)
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 slot = self.slot(value, addend, boot, signature)?;
@@ -694,6 +705,9 @@ 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 {
@@ -830,7 +844,10 @@ impl<'a> Unit<'a> {
}
self.inherited.insert(
(vtable.object, vtable.section, relocation.offset),
inherited,
VtableBinding {
value: inherited,
signature: None,
},
);
}
Ok(())
@@ -891,7 +908,7 @@ impl<'a> Unit<'a> {
};
let key = (vtable.object, vtable.section, relocation.offset);
match self.inherited.get(&key) {
Some(&value) => Ok(Some(value)),
Some(binding) => Ok(Some(binding.value)),
None => self.resolve(vtable.object, relocation.target).map(Some),
}
}
@@ -0,0 +1,182 @@
//! 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())
}
}
+31
View File
@@ -477,6 +477,37 @@ 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() {
+141 -6
View File
@@ -9,6 +9,7 @@ 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";
@@ -16,6 +17,9 @@ 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)]
@@ -59,12 +63,7 @@ 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 = 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 (aic, used) = aic_inputs(tree)?;
let irq = used
.into_iter()
.max()
@@ -83,6 +82,113 @@ 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
@@ -288,6 +394,35 @@ 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![
+13
View File
@@ -116,6 +116,19 @@ 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
+5
View File
@@ -381,6 +381,11 @@ 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,6 +4,64 @@ 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(
+42
View File
@@ -0,0 +1,42 @@
<?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>
@@ -0,0 +1,209 @@
#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
View File
@@ -0,0 +1 @@
#include "../../stela-gpu/kext/runtime.cpp"
+1 -4
View File
@@ -76,10 +76,7 @@
/COPYING
/README
/Makefile
/kernel/locking/mutex.c
/kernel/locking/percpu-rwsem.c
/kernel/locking/mutex.h
/kernel/locking/ww_mutex.h
/kernel/locking/
/kernel/sched/core.c
/kernel/sched/sched.h
/kernel/sched/sched_class_bounds.c
+44 -10
View File
@@ -11,6 +11,7 @@
use crate::tools::{self, exec};
use anyhow::{Context, Result, ensure};
use std::{
env,
fs,
path::{Path, PathBuf},
process::Command,
@@ -49,12 +50,39 @@ 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, &xnu, &include)?;
let kext = build_kext(&component, &output.join("StelaGPU.kext"), &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(())
}
@@ -198,13 +226,12 @@ 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, output: &Path, xnu: &Path, include: &Path) -> Result<PathBuf> {
fn build_kext(component: &Path, bundle: &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)?;
@@ -229,7 +256,7 @@ fn build_kext(component: &Path, output: &Path, xnu: &Path, include: &Path) -> Re
command.arg("-isystem").arg(include);
exec(command.arg("-c").arg(&path).arg("-o").arg(&object))?;
}
Ok(bundle)
Ok(bundle.to_path_buf())
}
/// `stela/bundle.h`: the Metal plugin `bundle` as the kext installs it, each
@@ -261,8 +288,10 @@ fn bundle_header(bundle: &Path) -> Result<String> {
.map(|path| {
let name = path
.strip_prefix(bundle)?
.to_str()
.context("a file name is not UTF-8")?;
.iter()
.map(|component| component.to_str().context("a file name is not UTF-8"))
.collect::<Result<Vec<_>>>()?
.join("/");
ensure!(
name.bytes()
.all(|byte| byte.is_ascii_graphic() && byte != b'"' && byte != b'\\'),
@@ -274,7 +303,7 @@ fn bundle_header(bundle: &Path) -> Result<String> {
);
let bytes = fs::read(&path)?;
ensure!(!bytes.is_empty(), "{name} is empty");
Ok((name.to_owned(), bytes))
Ok((name, bytes))
})
.collect::<Result<_>>()?;
files.sort();
@@ -344,11 +373,16 @@ 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!(