Compare commits

...
Author SHA1 Message Date
YXC0915 82c62d4253 Snapshot Reims vGPU source for the hosted Stambha ARM preview
Recover the tested source overlay at 3731afd9. Normalize Windows line endings for Git.
2026-12-05 22:27:53 +08:00
20 changed files with 531 additions and 74 deletions

No files matched your search

Generated
+3
View File
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "metal2vulkan"
version = "0.2.0"
source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"ash",
"metal2vulkan-air",
@@ -223,6 +224,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-air"
version = "0.2.0"
source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"sha2 0.11.1",
]
@@ -230,6 +232,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-runtime"
version = "0.2.0"
source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699"
dependencies = [
"ash",
"libc",
+3
View File
@@ -13,6 +13,9 @@ description = "Create, boot and manage macOS VMs on QEMU with reims-vgpu"
[workspace]
[features]
windows-arm64-guest = []
[dependencies]
anyhow = "1.0.104"
clap = { version = "4.6.7", features = ["derive", "env", "wrap_help"] }
+8 -4
View File
@@ -13,8 +13,7 @@
//! `ld.lld`), so the build needs clang and no lld of the host's. Where clang can't build it,
//! reims-ctl carries no module, says so as it builds, and refuses to start an arm64 VM.
//!
//! A reims-ctl for Windows, which runs no arm64 VM (src/host.rs), carries neither the arm64 set
//! nor the module.
//! The optional Windows arm64 guest build embeds the same assets as other arm64 guest hosts.
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
@@ -24,9 +23,8 @@ fn main() {
let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets it"));
let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").expect("cargo sets it"));
let out = out_dir.join("set.rs");
// A reims-ctl for Windows runs no arm64 VM (src/host.rs), and carries no arm64 guest.
let windows = std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "windows");
let (set_arm64e, module) = if windows {
let (set_arm64e, module) = if windows && !cfg!(feature = "windows-arm64-guest") {
("None".to_string(), "None".to_string())
} else {
(
@@ -37,6 +35,12 @@ fn main() {
module_code(&crate_dir.join("../../firmware/ambrosia"), &out_dir),
)
};
if windows && cfg!(feature = "windows-arm64-guest") {
assert!(
set_arm64e != "None" && module != "None",
"windows-arm64-guest needs the arm64 guest set and the Ambrosia graphics module"
);
}
let set = format!(
"/// guest/prebuilt/set.toml's set, in its order.\n\
pub static SET: Option<&[Kext]> = {};\n\
+4 -5
View File
@@ -367,11 +367,11 @@ fn create_examples_on(host: Host) -> String {
# Or with the OpenCore image it booted from, copied, which keeps its Mac too
reims-ctl create mac --disk {disk} --opencore {opencore}
An arm64 guest on an arm64 Mac, arm64 Linux or x86-64 Linux:
An arm64 guest on a host with the arm64 guest runtime:
# Download the current macOS's IPSW from Apple (about 25 GB, kept for the next VM; a
# stopped download continues), restore it onto a new 128G disk, with tickets Apple
# signs for the VM, and start it. On x86-64 Linux the VM runs emulated (QEMU's TCG),
# signs for the VM, and start it. On x86-64 the VM runs emulated (QEMU's TCG),
# far slower than on an arm64 host
reims-ctl create mac --ipsw latest --start
@@ -494,8 +494,7 @@ pub struct CreateArgs {
/// image's BaseSystem.img, or a DMG, converted to a raw image in the VM's directory
#[arg(long)]
pub installer: Option<PathBuf>,
/// On an arm64 Mac, arm64 Linux or x86-64 Linux: the IPSW to restore an arm64 VM's macOS
/// from: latest,
/// Restore an arm64 guest on a host with the arm64 guest runtime. Use latest for
/// the current macOS, downloaded from Apple once and kept (reims-ctl downloads lists it),
/// or an IPSW's path, read where it is. The VM needs one boot, which makes its Data volume,
/// and then `reims-restore finish-eacs DIR`
@@ -2245,7 +2244,7 @@ mod tests {
"{e}"
);
assert!(
e.contains("An arm64 guest on an arm64 Mac, arm64 Linux or x86-64 Linux:"),
e.contains("An arm64 guest on a host with the arm64 guest runtime:"),
"{e}"
);
}
+2 -2
View File
@@ -1670,7 +1670,7 @@ mod tests {
..arm64_spec(&env)
});
assert!(e.contains("not an existing one"), "{e}");
// An IPSW makes no x86-64 VM, and a Windows host runs no arm64 one.
// An IPSW selects an arm64 VM, which needs a host that supports it.
let x86 = Host {
os: crate::host::Os::Linux,
arch: crate::host::Arch::X86_64,
@@ -1685,7 +1685,7 @@ mod tests {
assert!(e.starts_with("an IPSW makes an arm64 VM"), "{e}");
let win = Host {
os: crate::host::Os::Windows,
arch: crate::host::Arch::X86_64,
arch: crate::host::Arch::Aarch64,
};
let e = create_with(arm64_spec(&env), win, &mut |_| {}, &Fake::Succeeds, &cancel)
.unwrap_err()
+23 -7
View File
@@ -12,8 +12,8 @@
//! several times slower than on an arm64 host. On Linux on x86-64 it is the second profile, an
//! IPSW's, and q35 the default.
//!
//! Any other host runs none ([`UNSUPPORTED`]). Windows on x86-64 runs no arm64 VM: its QEMU is
//! built for x86-64 guests alone (scripts/install-ctl.sh).
//! A Windows x86-64 build with the optional arm64 guest runtime also offers vmapple under TCG.
//! Any other host runs none ([`UNSUPPORTED`]).
//!
//! Another host or guest architecture is another profile (x86-64 guests on an Intel Mac would be
//! `q35` on HVF, without the memfd RAM only Linux has): add it here and in `qemu.rs`.
@@ -23,8 +23,13 @@ use std::collections::BTreeMap;
use std::fmt;
/// What reims-ctl tells a host it runs no VMs on, for a create or a start there.
pub const UNSUPPORTED: &str = "reims-ctl runs x86-64 VMs on Linux and Windows x86-64 hosts, \
and arm64 VMs on arm64 Macs, arm64 Linux and Linux on x86-64";
pub const UNSUPPORTED: &str = if cfg!(feature = "windows-arm64-guest") {
"reims-ctl runs x86-64 VMs on Linux and Windows x86-64 hosts, and arm64 VMs on arm64 Macs, \
arm64 Linux, and x86-64 Linux and Windows"
} else {
"reims-ctl runs x86-64 VMs on Linux and Windows x86-64 hosts, \
and arm64 VMs on arm64 Macs, arm64 Linux and Linux on x86-64"
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Os {
@@ -156,6 +161,9 @@ impl Profile {
pub fn supported_on(host: Host) -> &'static [Profile] {
match (host.os, host.arch) {
(Os::Linux, Arch::X86_64) => &[Profile::Q35X86_64, Profile::VmappleArm64],
(Os::Windows, Arch::X86_64) if cfg!(feature = "windows-arm64-guest") => {
&[Profile::Q35X86_64, Profile::VmappleArm64]
}
(Os::Windows, Arch::X86_64) => &[Profile::Q35X86_64],
(Os::Mac | Os::Linux, Arch::Aarch64) => &[Profile::VmappleArm64],
_ => &[],
@@ -187,6 +195,7 @@ impl Profile {
match self {
Profile::Q35X86_64 if cfg!(windows) => "qemu-system-x86_64.exe",
Profile::Q35X86_64 => "qemu-system-x86_64",
Profile::VmappleArm64 if cfg!(windows) => "qemu-system-aarch64.exe",
Profile::VmappleArm64 => "qemu-system-aarch64",
}
}
@@ -233,7 +242,7 @@ impl Profile {
/// [`crate::qemu`]'s module doc), and its section committed whole on Windows. The arm64
/// machine's memfd is allocated as the guest touches it.
pub fn ram_whole_at_start(self, host: Host) -> bool {
self == Profile::Q35X86_64 && (self.memfd_ram(host) || self.section_ram(host))
self.section_ram(host) || (self == Profile::Q35X86_64 && self.memfd_ram(host))
}
/// Whether a Vulkan GPU can be chosen: the library runs on the host's Vulkan GPUs on Linux
@@ -307,7 +316,10 @@ mod tests {
assert_eq!(arm.accel_arg(arm_linux), "kvm");
assert!(arm.memfd_ram(arm_linux) && arm.gpu_choice(arm_linux));
assert!(arm.describe(arm_linux).ends_with("KVM)"));
assert_eq!(arm.qemu_binary(), "qemu-system-aarch64");
assert_eq!(
arm.qemu_binary(),
format!("qemu-system-aarch64{}", std::env::consts::EXE_SUFFIX)
);
for (os, arch) in [
(Os::Mac, Arch::X86_64),
(Os::Windows, Arch::Aarch64),
@@ -326,7 +338,11 @@ mod tests {
arch: Arch::X86_64,
};
let q35 = Profile::Q35X86_64;
assert_eq!(Profile::supported_on(windows), [q35]);
assert_eq!(windows.default_profile(), Some(q35));
assert_eq!(
Profile::supported_on(windows).contains(&Profile::VmappleArm64),
cfg!(feature = "windows-arm64-guest")
);
assert_eq!(q35.accel(windows), "whpx");
assert!(q35.section_ram(windows) && !q35.memfd_ram(windows));
assert!(q35.ram_whole_at_start(windows));
+23 -1
View File
@@ -13,6 +13,8 @@
//!
//! `REIMS_CTL_QEMU` names a QEMU binary to use instead (a build tree's, such as `make qemu`'s
//! `build/qemu/qemu-system-x86_64`); `qemu-img` is taken from beside it.
//! `REIMS_CTL_QEMU_AARCH64` overrides the arm64 emulator. On Windows its default is the
//! arm64 executable beside the x86 emulator in the same portable runtime.
use crate::host::Profile;
use crate::paths;
@@ -83,8 +85,28 @@ impl Install {
/// The QEMU binary for `profile`.
pub fn qemu_binary(profile: Profile) -> Result<PathBuf> {
if profile == Profile::VmappleArm64
&& let Some(p) = std::env::var_os("REIMS_CTL_QEMU_AARCH64")
{
let arm = paths::native(PathBuf::from(p));
if !arm.is_file() {
bail!("{} is missing: check REIMS_CTL_QEMU_AARCH64", arm.display());
}
return Ok(arm);
}
if let Some(p) = std::env::var_os("REIMS_CTL_QEMU") {
return Ok(paths::native(PathBuf::from(p)));
let bin = paths::native(PathBuf::from(p));
if cfg!(windows) && profile == Profile::VmappleArm64 {
let arm = bin.with_file_name(profile.qemu_binary());
if !arm.is_file() {
bail!(
"{} is missing: install the arm64 guest runtime or set REIMS_CTL_QEMU_AARCH64",
arm.display()
);
}
return Ok(arm);
}
return Ok(bin);
}
let bin = paths::qemu_root()
.join("current")
+3 -2
View File
@@ -836,7 +836,7 @@ mod tests {
/// A reims-ctl for Windows, which runs no arm64 VM, carries neither the arm64 set nor the
/// module (build.rs).
#[cfg(windows)]
#[cfg(all(windows, not(feature = "windows-arm64-guest")))]
#[test]
fn a_reims_ctl_for_windows_carries_no_arm64_guest() {
assert!(super::SET_ARM64E.is_none());
@@ -845,9 +845,10 @@ mod tests {
/// The module build.rs built is an aarch64 ELF static PIE, the module format Ambrosia loads:
/// a checkout whose clang can't build it fails here, not at an arm64 VM's start.
#[cfg(not(windows))]
#[cfg(any(not(windows), feature = "windows-arm64-guest"))]
#[test]
fn the_module_is_built() {
assert!(!super::SET_ARM64E.expect("the arm64 guest set").is_empty());
let elf = AMBROSIA_MODULE.expect(
"build.rs built no module for Ambrosia: its warning says why (is clang installed?)",
);
+32
View File
@@ -537,6 +537,8 @@ fn vmapple(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
let mut machine = format!("vmapple,uuid=0x{:016x}", v.ecid);
if c.profile.memfd_ram(ctx.host) {
machine.push_str(",memory-backend=ram,dump-guest-core=off");
} else if c.profile.section_ram(ctx.host) {
machine.push_str(",memory-backend=ram");
}
push(&["-machine", &machine, "-m", &mem]);
if c.profile.memfd_ram(ctx.host) {
@@ -544,6 +546,11 @@ fn vmapple(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
"-object",
&format!("memory-backend-memfd,id=ram,size={mem},share=on"),
]);
} else if c.profile.section_ram(ctx.host) {
push(&[
"-object",
&format!("memory-backend-ram,id=ram,size={mem},share=on"),
]);
}
push(&["-smp", &c.cpus.to_string()]);
push(&["-bios", &boot.ambrosia.to_string_lossy()]);
@@ -950,6 +957,31 @@ pub(crate) mod tests {
.collect()
}
#[cfg(feature = "windows-arm64-guest")]
#[test]
fn arm64_on_x86_64_windows_runs_on_tcg_with_a_shared_section() {
let host = Host {
os: Os::Windows,
arch: Arch::X86_64,
};
let inv = invocation(&arm64_vm(), &arm64_ctx(host)).unwrap();
assert!(
inv.args
.windows(2)
.any(|a| a == ["-accel", "tcg,thread=multi"])
);
assert!(
inv.args
.windows(2)
.any(|a| a == ["-object", "memory-backend-ram,id=ram,size=8192M,share=on"])
);
assert!(inv.args.windows(2).any(|a| a
== [
"-machine",
"vmapple,uuid=0x9e35f01edc0c5536,memory-backend=ram"
]));
}
/// An arm64 VM on an x86-64 Linux host: vmapple under TCG, a thread for each vCPU, in memfd
/// RAM, which the library on Linux needs.
#[test]
+13 -3
View File
@@ -853,12 +853,22 @@ fn random_bytes<const N: usize>() -> [u8; N] {
.and_then(|mut f| f.read_exact(&mut b))
.is_err()
{
// Windows has no /dev/urandom. The clock alone is no random source there: it counts
// 100 ns, so its low bytes hold some 22 bits, the first of them a multiple of 4, and the
// pid, shifted past them, changes none. std's RandomState is keyed from the OS's random
// source (ProcessPrng on Windows), so a hash it keys is unpredictable; the clock and the
// pid are hashed in too.
use std::hash::{BuildHasher, Hasher};
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
let seed = t.as_nanos() ^ (std::process::id() as u128) << 64;
for (i, x) in b.iter_mut().enumerate() {
*x = (seed >> (i * 8)) as u8;
let keys = std::collections::hash_map::RandomState::new();
for (i, chunk) in b.chunks_mut(8).enumerate() {
let mut h = keys.build_hasher();
h.write_usize(i);
h.write_u128(t.as_nanos());
h.write_u32(std::process::id());
chunk.copy_from_slice(&h.finish().to_le_bytes()[..chunk.len()]);
}
}
b
+1 -1
View File
@@ -64,7 +64,7 @@ zip = { version = "9.5.1", default-features = false, features = ["deflate-flate2
# The space free on a volume (src/sys/windows.rs).
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl"] }
[dev-dependencies]
# Writes the tests' synthetic IPSWs.
+24 -9
View File
@@ -475,6 +475,8 @@ impl Files {
for (name, size) in [(DISK, disk_size), (AUX_TRIMMED, AUX_SIZE)] {
let p = self.part(name);
let f = File::create(&p).with_context(|| format!("make {}", p.display()))?;
#[cfg(windows)]
crate::sys::set_sparse(&f)?;
f.set_len(size)
.with_context(|| format!("size {} to {size} bytes", p.display()))?;
}
@@ -501,7 +503,7 @@ impl Files {
}
let f = File::open(&from).context("open the disk")?;
let m = f.metadata()?;
let used = crate::sys::allocated(&m);
let used = crate::sys::allocated(&from, &m);
check_space(&self.dir, free_space(&self.dir)?, used)?;
copy_sparse(&f, 0, m.len(), &to, 0)?;
Ok(Some(used))
@@ -530,9 +532,7 @@ impl Files {
if name == EACS_DISK && !p.exists() {
continue;
}
File::open(&p)
.and_then(|f| f.sync_all())
.with_context(|| format!("flush {}", p.display()))?;
sync_image(&p)?;
}
// The machine identifier goes last; a failed move takes back those made before it.
let mut moved = Vec::new();
@@ -625,6 +625,8 @@ fn clone_file(from: &Path, to: &Path) -> bool {
fn copy_sparse(from: &File, at: u64, len: u64, to: &Path, to_at: u64) -> Result<()> {
use reims_apfs::file_at::FileAt as _;
let out = File::create(to).with_context(|| format!("make {}", to.display()))?;
#[cfg(windows)]
crate::sys::set_sparse(&out)?;
out.set_len(to_at + len)?;
let mut buf = vec![0u8; 1 << 20];
let mut done = 0;
@@ -759,9 +761,7 @@ fn start_again(dir: &Path) -> Result<()> {
let f = File::open(&pre).with_context(|| format!("open {}", pre.display()))?;
copy_sparse(&f, 0, f.metadata()?.len(), &part, 0)?;
}
File::open(&part)
.and_then(|f| f.sync_all())
.with_context(|| format!("flush {}", part.display()))?;
sync_image(&part)?;
std::fs::rename(&part, dir.join(DISK)).context("move the restored disk back into place")?;
let restored = std::fs::read(dir.join(EACS_AUX))
.with_context(|| format!("read {}", dir.join(EACS_AUX).display()))?;
@@ -783,13 +783,28 @@ fn put_aux(dir: &Path, trimmed: &[u8]) -> Result<()> {
for (name, bytes) in [(AUX_TRIMMED, trimmed), (AUX, &h[..])] {
let p = dir.join(name);
let tmp = dir.join(format!("{name}.part"));
std::fs::write(&tmp, bytes).with_context(|| format!("write {}", tmp.display()))?;
File::open(&tmp)?.sync_all()?;
{
let mut file =
File::create(&tmp).with_context(|| format!("create {}", tmp.display()))?;
file.write_all(bytes)
.with_context(|| format!("write {}", tmp.display()))?;
file.sync_all()
.with_context(|| format!("flush {}", tmp.display()))?;
}
std::fs::rename(&tmp, &p).with_context(|| format!("move {} into place", p.display()))?;
}
Ok(())
}
/// FlushFileBuffers on Windows requires a writable handle even when no further writes are due.
fn sync_image(path: &Path) -> Result<()> {
OpenOptions::new()
.write(true)
.open(path)
.and_then(|file| file.sync_all())
.with_context(|| format!("flush {}", path.display()))
}
/// Virtualization.framework's machine identifier: `{ECID: n}`.
fn machine_identifier(ecid: u64) -> Value {
let mut d = Dictionary::new();
+1 -1
View File
@@ -19,6 +19,6 @@ pub fn free_space(dir: &Path) -> Result<u64> {
/// The space the file `m` describes takes on its file system: its 512-byte blocks, fewer than
/// its length where it is sparse.
pub fn allocated(m: &std::fs::Metadata) -> u64 {
pub fn allocated(_path: &Path, m: &std::fs::Metadata) -> u64 {
m.blocks() * 512
}
+49 -6
View File
@@ -1,8 +1,8 @@
//! [`super`] on Windows, where reims-ctl makes no arm64 VM (its host.rs), so no restore runs:
//! these answer as reims-ctl's code that the restore shares with x86-64 VMs needs them.
//! Storage for a restore on Windows.
use anyhow::{Context, Result};
use std::os::windows::ffi::OsStrExt as _;
use std::os::windows::io::AsRawHandle as _;
use std::path::Path;
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
@@ -26,8 +26,51 @@ pub fn free_space(dir: &Path) -> Result<u64> {
Ok(free)
}
/// The space the file `m` describes takes on its volume, counted as its length: a sparse file's
/// holes count as written, so a check of room for its copy asks for more than the copy takes.
pub fn allocated(m: &std::fs::Metadata) -> u64 {
m.len()
/// Mark the empty image before extending it. Volumes without sparse files retain dense images.
pub fn set_sparse(file: &std::fs::File) -> Result<()> {
use windows_sys::Win32::Foundation::{ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED};
use windows_sys::Win32::System::{IO::DeviceIoControl, Ioctl::FSCTL_SET_SPARSE};
let mut returned = 0;
// SAFETY: the synchronous file handle is live and this control takes no buffers.
let ok = unsafe {
DeviceIoControl(
file.as_raw_handle(),
FSCTL_SET_SPARSE,
std::ptr::null(),
0,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
};
if ok == 0 {
let error = std::io::Error::last_os_error();
if !matches!(
error.raw_os_error().map(|c| c as u32),
Some(ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED)
) {
return Err(error).context("mark restore image sparse");
}
}
Ok(())
}
/// The disk space its backup needs. Fall back to the logical size if the query fails.
pub fn allocated(path: &Path, m: &std::fs::Metadata) -> u64 {
use windows_sys::Win32::Foundation::{GetLastError, SetLastError};
use windows_sys::Win32::Storage::FileSystem::{GetCompressedFileSizeW, INVALID_FILE_SIZE};
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let mut high = 0;
// SAFETY: the string is NUL-terminated and high is writable. Clearing the thread's last
// error distinguishes a legitimate all-ones low word from a failed query.
unsafe {
SetLastError(0);
let low = GetCompressedFileSizeW(wide.as_ptr(), &mut high);
if low == INVALID_FILE_SIZE && GetLastError() != 0 {
m.len()
} else {
(u64::from(high) << 32) | u64::from(low)
}
}
}
+4
View File
@@ -881,6 +881,10 @@ RvgStatus rvg_graphics_device_set_doorbell(RvgGraphicsDevice *device, void *even
//
// # Safety
// `device` is a live graphics device handle.
RvgStatus rvg_graphics_device_set_memory_map(RvgGraphicsDevice *device,
const RvgMemoryMap *map,
const RvgMemoryRangeFile *files);
void rvg_graphics_device_reset(RvgGraphicsDevice *device);
// What the device's display shows now, read back into `dst`: the guest's scanout, or the
+26
View File
@@ -1023,6 +1023,32 @@ unsafe fn set_doorbell(device: *mut RvgGraphicsDevice, doorbell: RawDoorbell) ->
///
/// # Safety
/// `device` is a live graphics device handle.
/// Installs the guest RAM map on a live graphics device (used by hosted ARM64 translators whose
/// inner physical address layout is established after PCI realize and before driver handshake).
///
/// # Safety
/// `device` is a live graphics device handle; `map` and `files` obey the same contract as
/// `RvgGraphicsDeviceConfig.memory_map` and `memory_files`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_set_memory_map(
device: *mut RvgGraphicsDevice,
map: *const RvgMemoryMap,
files: *const RvgMemoryRangeFile,
) -> RvgStatus {
ffi::export(|| {
let d = unsafe { live(device, "rvg_graphics_device_set_memory_map") };
let parsed = match unsafe { memory_map(map, files) } {
Ok(Some(m)) => m,
Ok(None) => return RVG_ERR_INVALID_ARGUMENT,
Err(status) => return status,
};
match d.device.set_memory_map(parsed) {
Ok(()) => RVG_OK,
Err(err) => status(err),
}
})
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_reset(device: *mut RvgGraphicsDevice) {
ffi::export(|| {
@@ -183,6 +183,8 @@ fn start_video() -> bool {
);
return false;
}
#[cfg(target_os = "windows")]
super::super::windows::install_unicode_input_hook();
// SAFETY: SDL's video runs.
let kind = unsafe { SDL_RegisterEvents(1) };
WAKE.store(kind, Ordering::Release);
+201 -2
View File
@@ -42,12 +42,19 @@
//! taskbar then goes to the bottom of the z-order while the window is active, and that taking
//! the mark away leaves the window to the shell's own detection.
use std::cell::Cell;
use std::ffi::c_void;
use std::io::Write;
use std::net::{SocketAddr, TcpStream};
use std::ptr::{NonNull, null, null_mut};
use std::sync::OnceLock;
use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
use std::time::Duration;
use sdl3_sys::everything::{
SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties,
SDL_PROP_WINDOW_WIN32_HWND_POINTER, SDL_WINDOW_FULLSCREEN, SDL_Window,
MSG as SDL_MSG, SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties,
SDL_PROP_WINDOW_WIN32_HWND_POINTER, SDL_SetWindowsMessageHook, SDL_WINDOW_FULLSCREEN,
SDL_Window,
};
use windows_sys::Win32::Foundation::{FALSE, HWND, RPC_E_CHANGED_MODE, S_FALSE, S_OK, TRUE};
use windows_sys::Win32::System::Com::{
@@ -62,6 +69,198 @@ use crate::capture::HostOs;
/// The OS whose names the title gives the release chord's keys: Ctrl+Alt+Win (the module doc).
pub(super) const HOST_OS: HostOs = HostOs::Windows;
/// Win32 MSG layout matching winuser.h for SDL_SetWindowsMessageHook.
#[repr(C)]
struct Win32Msg {
/// Target window handle.
_hwnd: HWND,
/// Message identifier (WM_*).
message: u32,
/// WPARAM.
w_param: usize,
/// LPARAM.
_l_param: isize,
/// Message timestamp (GetMessageTime).
time: u32,
/// Cursor position (POINT).
_pt: [i32; 2],
}
/// WM_KEYDOWN.
const WM_KEYDOWN: u32 = 0x0100;
/// WM_CHAR.
const WM_CHAR: u32 = 0x0102;
/// WM_SYSKEYDOWN.
const WM_SYSKEYDOWN: u32 = 0x0104;
/// WM_UNICHAR.
const WM_UNICHAR: u32 = 0x0109;
/// WM_IME_CHAR.
const WM_IME_CHAR: u32 = 0x0286;
/// UNICODE_NOCHAR.
const UNICODE_NOCHAR: usize = 0xFFFF;
/// VK_PROCESSKEY (host IME intercepted key).
const VK_PROCESSKEY: u16 = 0x00E5;
/// VK_PACKET (SendInput with KEYEVENTF_UNICODE).
const VK_PACKET: u16 = 0x00E7;
/// Non-blocking channel carrying UTF-16 code units from the SDL UI thread to the HTTP forwarder.
static UNICODE_TX: OnceLock<SyncSender<u16>> = OnceLock::new();
thread_local! {
/// Whether the most recent WM_KEYDOWN was unmapped (VK_PACKET or VK_PROCESSKEY).
static LAST_KEY_UNMAPPED: Cell<bool> = const { Cell::new(false) };
/// Timestamp of the most recent normal WM_KEYDOWN that SDL translates to a USB key.
static LAST_MAPPED_KEY_TIME: Cell<u32> = const { Cell::new(0) };
}
/// Parses a loopback http://127.0.0.1:<port><path> endpoint from REIMS_GO_INPUT_URL.
fn parse_loopback_input_url(raw: &str) -> Option<(SocketAddr, String)> {
let rest = raw.trim().strip_prefix("http://127.0.0.1:")?;
let (port_str, path) = match rest.find('/') {
Some(idx) => (&rest[..idx], &rest[idx..]),
None => (rest, "/v1/host-text"),
};
let port: u16 = port_str.parse().ok()?;
if port == 0 || path.contains(['\r', '\n', ' ']) {
return None;
}
let addr = SocketAddr::from(([127, 0, 0, 1], port));
Some((addr, path.to_owned()))
}
/// Installs a Win32 message hook on SDL's UI thread when REIMS_GO_INPUT_URL and
/// REIMS_GO_INPUT_TOKEN are set, forwarding non-keyboard WM_CHAR / WM_UNICHAR /
/// WM_IME_CHAR text (remote IMEs, dictation, host IME commits) to the local host bridge.
pub(super) fn install_unicode_input_hook() {
let Ok(url) = std::env::var("REIMS_GO_INPUT_URL") else {
return;
};
let Ok(token) = std::env::var("REIMS_GO_INPUT_TOKEN") else {
return;
};
if token.is_empty() || token.contains(['\r', '\n']) {
return;
}
let Some((addr, path)) = parse_loopback_input_url(&url) else {
log::warn!(target: "reims_vgpu_window", "ignoring non-loopback REIMS_GO_INPUT_URL");
return;
};
let (tx, rx) = mpsc::sync_channel::<u16>(512);
if UNICODE_TX.set(tx).is_err() {
return;
}
let _ = std::thread::Builder::new()
.name("reims-vgpu.ime".into())
.spawn(move || forward_unicode_loop(rx, addr, path, token));
// SAFETY: called on SDL's UI thread right after SDL_Init(SDL_INIT_VIDEO).
unsafe { SDL_SetWindowsMessageHook(Some(unicode_message_hook), null_mut()) };
}
/// Enqueues a UTF-16 code unit without blocking the Win32 message loop.
fn enqueue_utf16(unit: u16) {
if unit != 0
&& let Some(tx) = UNICODE_TX.get()
{
let _ = tx.try_send(unit);
}
}
/// SDL Win32 message hook: forwards non-physical WM_CHAR / WM_UNICHAR / WM_IME_CHAR
/// events to the local input bridge while leaving all physical keyboard events untouched.
unsafe extern "C" fn unicode_message_hook(_userdata: *mut c_void, raw_msg: *mut SDL_MSG) -> bool {
if raw_msg.is_null() {
return true;
}
// SAFETY: SDL passes a valid pointer to Win32 MSG for the duration of the callback.
let msg = unsafe { &*raw_msg.cast::<Win32Msg>() };
match msg.message {
WM_KEYDOWN | WM_SYSKEYDOWN => {
let vk = (msg.w_param & 0xFFFF) as u16;
if vk == VK_PACKET || vk == VK_PROCESSKEY {
LAST_KEY_UNMAPPED.set(true);
} else {
LAST_KEY_UNMAPPED.set(false);
LAST_MAPPED_KEY_TIME.set(msg.time);
}
true
}
WM_CHAR | WM_IME_CHAR => {
let unit = (msg.w_param & 0xFFFF) as u16;
let non_physical = unit >= 0x80
|| LAST_KEY_UNMAPPED.get()
|| msg.time != LAST_MAPPED_KEY_TIME.get();
if non_physical && (unit >= 0x20 || unit == 0x0D || unit == 0x09) {
enqueue_utf16(unit);
return false;
}
true
}
WM_UNICHAR => {
if msg.w_param != UNICODE_NOCHAR
&& let Ok(code) = u32::try_from(msg.w_param)
&& let Some(ch) = char::from_u32(code)
&& (ch >= ' ' || ch == '\r' || ch == '\t')
{
let mut pair = [0u16; 2];
for &mut u in ch.encode_utf16(&mut pair) {
enqueue_utf16(u);
}
return false;
}
true
}
_ => true,
}
}
/// Decodes UTF-16 code units, coalesces bursts, and POSTs UTF-8 text to the loopback bridge.
fn forward_unicode_loop(rx: mpsc::Receiver<u16>, addr: SocketAddr, path: String, token: String) {
let mut units: Vec<u16> = Vec::with_capacity(64);
loop {
let first = match rx.recv() {
Ok(u) => u,
Err(_) => return,
};
units.clear();
units.push(first);
if first != 0x0D {
while units.len() < 128 {
match rx.recv_timeout(Duration::from_millis(35)) {
Ok(u) => {
units.push(u);
if u == 0x0D {
break;
}
}
Err(RecvTimeoutError::Timeout) => break,
Err(RecvTimeoutError::Disconnected) => break,
}
}
}
let text: String = char::decode_utf16(units.iter().copied())
.filter_map(Result::ok)
.map(|c| if c == '\r' { '\n' } else { c })
.collect();
if !text.is_empty() {
post_loopback_text(addr, &path, &token, &text);
}
}
}
/// Sends a minimal HTTP/1.1 POST with UTF-8 ext to the local host bridge.
fn post_loopback_text(addr: SocketAddr, path: &str, token: &str, text: &str) {
let Ok(mut stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else {
return;
};
let _ = stream.set_write_timeout(Some(Duration::from_millis(500)));
let req = format!(
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
text.len()
);
let _ = stream.write_all(req.as_bytes());
let _ = stream.write_all(text.as_bytes());
}
/// The GPU the compositor composites SDL's window on: none known on Windows (the module doc).
///
/// # Safety
+88 -24
View File
@@ -49,7 +49,7 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock, Weak};
use metal2vulkan_runtime::host_time;
@@ -500,13 +500,15 @@ fn pool_range(room: PoolConfig, heaps: u64) -> Option<PoolConfig> {
/// machine where no whole GiB of addresses lies from the end of the PCI host's 64-bit window to
/// the top quarter of the guest's physical addresses (under KVM and WHPX, to the host's at most)
/// (`reims_graphics_pool_room` and `reims_graphics_pool_room_machine` in
/// `hw/display/reims-graphics-pci.c`); a Windows host offers the pool to an x86-64 guest alone.
/// `hw/display/reims-graphics-pci.c`); Windows ARM64 guests require the pool opt-in.
fn no_pool(given: bool, ranged: bool, offered: bool) -> Option<&'static str> {
match (given, ranged, offered) {
(_, _, true) => None,
(false, _, false) => Some("the host gave the device no guest addresses for one"),
(true, false, false) => Some("the GPU answers no memory heap"),
(true, true, false) => Some("a Windows host offers one to an x86-64 guest alone"),
(true, true, false) => {
Some("the Shared pool is disabled for ARM64 guests on this Windows host")
}
}
}
@@ -521,8 +523,16 @@ pub struct GraphicsDevice<P: ApiPlatform = DefaultPlatform> {
cursors: Vec<Arc<HostCursor>>,
/// The stage-3 decoder and the device handle it drives, shared with the device's [`Host`],
/// which feeds it the control ring's stage-3 messages; held here for the tests' look at it.
#[cfg(any(test, feature = "testkit"))]
control: Arc<GraphicsControl<P>>,
/// Host feature/budget atomics shared with CallbackHost so hosted ARM64 translators can
/// install the guest RAM map before the guest graphics driver handshakes.
platform_ref: Arc<P>,
features_atom: Arc<AtomicU64>,
features_16k_atom: Arc<AtomicU64>,
deferred_budget_atom: Arc<AtomicU64>,
base_features: u64,
in_place_features: u64,
own_memory_budget: u64,
/// What display 0's window shows, where there is one: the tests draw it.
#[cfg(test)]
shown: Option<Arc<Shown>>,
@@ -612,11 +622,17 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
// The guest's processes take blocks of it for their buffers' slabs (`POOL`). An
// arm64 guest's processes use the blocks write-back, as an x86-64 guest's do: arm64
// boots under TCG and HVF ran on them with no fault (docs/graphics-kext/design.md,
// "The Shared pool"). A Windows host offers it to an x86-64 guest alone, whose cost
// under WHP was measured beside the region's (docs/qemu.md, "Windows hosts: the
// Shared pool"): an arm64 guest runs under TCG there, where it was not measured.
// "The Shared pool"). Windows offers it by default to x86-64 guests. Its cost under
// WHP was measured beside the region's (docs/qemu.md, "Windows hosts: the Shared
// pool"). Windows ARM64 guests can opt in to measure the TCG path.
let arm64_pool_opt_in = cfg!(windows)
&& config.guest_arch == GuestArch::Arm64
&& std::env::var_os("REIMS_VGPU_ARM64_SHARED_POOL")
.is_some_and(|value| value == "1");
let pool_ledger = (shared_pool.as_ref())
.filter(|_| !cfg!(windows) || config.guest_arch == GuestArch::X86_64)
.filter(|_| {
!cfg!(windows) || config.guest_arch == GuestArch::X86_64 || arm64_pool_opt_in
})
.map(Pool::ledger);
// The one line of a device with no pool, whatever kept it from one.
if let Some(why) = no_pool(
@@ -1042,11 +1058,16 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
Arc::new(HostCursor::new(&platform, glyph, show, moved))
})
.collect();
let vt_feats = vt_features(&vt);
let base_features = (features & !pages_features & !RGFX_FEATURE_PAGES_16K) | vt_feats;
let features_atom = Arc::new(AtomicU64::new(features | vt_feats));
let features_16k_atom = Arc::new(AtomicU64::new(features_16k));
let deferred_budget_atom = Arc::new(AtomicU64::new(deferred_budget));
let host = Box::new(CallbackHost {
callbacks: config.callbacks,
features: features | vt_features(&vt),
features_16k,
deferred_budget,
features: Arc::clone(&features_atom),
features_16k: Arc::clone(&features_16k_atom),
deferred_budget: Arc::clone(&deferred_budget_atom),
control: Arc::clone(&control),
vt,
vt_seen: Arc::default(),
@@ -1128,8 +1149,14 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
device,
cursors,
ending: Arc::downgrade(&control),
#[cfg(any(test, feature = "testkit"))]
control,
platform_ref: Arc::clone(&platform),
features_atom,
features_16k_atom,
deferred_budget_atom,
base_features,
in_place_features: in_place,
own_memory_budget: own_memory,
#[cfg(test)]
shown,
reads,
@@ -1139,6 +1166,45 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
})
}
/// Installs the guest RAM map after device creation (for hosted ARM64 translators whose
/// inner physical layout is established during guest boot, before the graphics driver
/// handshakes). Enables zero-copy `RGFX_FEATURE_SURFACE_PAGES` and page-backed buffers.
pub fn set_memory_map(&self, map: MemoryMap) -> Result<(), Error> {
entry::run(|_| {
if map.ranges().is_empty() {
return Err(Error::InvalidArgument);
}
let lease: GuestMemoryLease = Arc::from(self.platform_ref.guest_memory(&map));
let memory = CoreMemoryMap::new(Arc::clone(&self.platform_ref), &map.to_core())
.ok_or(Error::InvalidArgument)?;
let mut decoder = self.control.decoder();
decoder.set_guest_memory(memory, lease);
decoder.start_views_age();
let pages_features = if decoder.surface_pages_available() {
self.in_place_features
| u64::from(RGFX_FEATURE_SURFACE_CACHE)
| u64::from(RGFX_FEATURE_SURFACE_DEFERRED)
| RGFX_FEATURE_SURFACE_DEFERRED_CARRY
| cache_every(P::SURFACE_SHAPES, self.pool.is_some())
} else {
0
};
let (features, features_16k) =
if pages_features != 0 && decoder.surface_pages_need_16k() {
(self.base_features | RGFX_FEATURE_PAGES_16K, pages_features)
} else {
(self.base_features | pages_features, 0)
};
let offerable = features | features_16k;
let deferred = deferred_budget(offerable, self.own_memory_budget);
decoder.set_deferred_budget(deferred);
self.deferred_budget_atom.store(deferred, Ordering::Release);
self.features_16k_atom.store(features_16k, Ordering::Release);
self.features_atom.store(features, Ordering::Release);
Ok(())
})
}
/// The host mapped the pool's piece at `physical_address` it was asked to add
/// ([`GraphicsCallbacks::pool_add`]): the guest's address space has it from now on. Any
/// thread, the host's lock held or not; waits for nothing and calls back never.
@@ -4326,15 +4392,13 @@ impl<P: ApiPlatform> GraphicsControl<P> {
struct CallbackHost<P: ApiPlatform> {
/// The host's callbacks: the device raises its interrupt through them.
callbacks: GraphicsCallbacks,
/// The `RGFX_FEATURE_*` the decoder carries out, fixed at the device's make: the guest reads
/// them on a vCPU, which takes no lock of the decoder's.
features: u64,
/// Those it carries out only for a guest that takes `RGFX_FEATURE_PAGES_16K`, also fixed at
/// the make: the guest RAM's on a host of 16 KiB pages, else none.
features_16k: u64,
/// The deferred blocks' budget ([`deferred_budget`]), read once at the device's make, so the
/// kext's one read holds.
deferred_budget: u64,
/// The `RGFX_FEATURE_*` the decoder carries out: the guest reads them on a vCPU without
/// taking a decoder lock; updated atomically if hosted guest RAM is installed before handshake.
features: Arc<AtomicU64>,
/// Those it carries out only for a guest that takes `RGFX_FEATURE_PAGES_16K`.
features_16k: Arc<AtomicU64>,
/// The deferred blocks' budget ([`deferred_budget`]).
deferred_budget: Arc<AtomicU64>,
/// The stage-3 decoder, fed the stage-3 messages of ring 0 and of the queues' rings.
control: Arc<GraphicsControl<P>>,
/// The host's side of VideoToolbox's paravirtual messages ([`paravirt`]), over the decoders
@@ -4480,15 +4544,15 @@ impl<P: ApiPlatform> Host for CallbackHost<P> {
}
fn features(&self) -> u64 {
self.features
self.features.load(Ordering::Acquire)
}
fn features_with_16k_pages(&self) -> u64 {
self.features_16k
self.features_16k.load(Ordering::Acquire)
}
fn deferred_budget(&self) -> u64 {
self.deferred_budget
self.deferred_budget.load(Ordering::Acquire)
}
fn surface_pages(
+21 -7
View File
@@ -13729,7 +13729,7 @@ fn the_no_pool_line_names_why_the_device_offers_no_pool() {
);
assert_eq!(
no_pool(true, true, false),
Some("a Windows host offers one to an x86-64 guest alone")
Some("the Shared pool is disabled for ARM64 guests on this Windows host")
);
}
@@ -13878,8 +13878,13 @@ fn a_guest_s_pool_block_is_taken_held_by_its_heap_and_given_back() {
assert_eq!(device.decoder_object_count(), 0);
}
/// A guest of either architecture is offered the pool on a Linux or macOS host, an x86-64 guest on
/// a Windows host too, and a guest of a device with none is offered none
/// The test runner supplies the expected state in a separate process for each setting.
fn expect_windows_arm64_pool() -> bool {
cfg!(windows)
&& std::env::var_os("REIMS_VGPU_TEST_EXPECT_ARM64_POOL").is_some_and(|value| value == "1")
}
/// Hosts with a pool offer both pool features. On Windows, ARM64 guests require an opt-in.
#[test]
fn a_guest_of_either_architecture_is_offered_the_pool() {
let pool_of = |guest_arch: GuestArch| {
@@ -13900,11 +13905,16 @@ fn a_guest_of_either_architecture_is_offered_the_pool() {
let offered = u64::from(device.mmio_read(RGFX_REG_FEATURES_HI.into())) << 32;
(
offered & RGFX_FEATURE_POOL != 0,
offered & RGFX_FEATURE_POOL_ADDRESSES != 0,
device.control.shared_pool.is_some(),
)
};
assert_eq!(pool_of(GuestArch::Arm64), (!cfg!(windows), !cfg!(windows)));
assert_eq!(pool_of(GuestArch::X86_64), (true, true));
let arm64_pool_expected = !cfg!(windows) || expect_windows_arm64_pool();
assert_eq!(
pool_of(GuestArch::Arm64),
(arm64_pool_expected, arm64_pool_expected, arm64_pool_expected)
);
assert_eq!(pool_of(GuestArch::X86_64), (true, true, true));
let raised = Arc::new(AtomicU32::new(0));
assert!(headless(&raised).control.shared_pool.is_none());
}
@@ -14045,7 +14055,7 @@ fn managed_at_copy_is_offered_only_on_a_unified_gpu_of_rt_with_the_pool() {
assert_eq!(offered & RGFX_FEATURE_MANAGED_AT_COPY, 0);
}
/// An x86-64 guest that took `POOL_ADDRESSES` beside `POOL` is answered each block's GPU address:
/// A guest that took `POOL_ADDRESSES` beside `POOL` is answered each block's GPU address:
/// on a platform whose pool blocks have none, the host's picks from 2^45 up, each block's span
/// its pages and a guard page on the 32 KiB granule; a heap over the block at that address is
/// pinned there
@@ -14067,7 +14077,11 @@ fn a_guest_that_took_pool_addresses_is_answered_each_block_s_gpu_address() {
physical_address: BASE,
physical_length: 4 << 30,
}),
guest_arch: GuestArch::X86_64,
guest_arch: if expect_windows_arm64_pool() {
GuestArch::Arm64
} else {
GuestArch::X86_64
},
..GraphicsConfig::default()
};
let device = GraphicsDevice::with_platform(Arc::new(FakePlatform::new()), config).unwrap();