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
45 changed files with 363 additions and 4134 deletions

No files matched your search

+2 -2
View File
@@ -1,4 +1,4 @@
[submodule "vendor/qemu"]
path = vendor/qemu
url = https://github.com/yxc0915/qemu-reims-vgpu.git
branch = codex/intel-vm-suspend
url = https://github.com/steelbrain/qemu-reims-vgpu
branch = steelbrain/reims-vgpu-rebase-2
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?)",
);
+39 -48
View File
@@ -195,33 +195,6 @@ pub fn opt(s: &str) -> String {
s.replace(',', ",,")
}
/// Compute the qcow2 L2 cache size in MiB needed to cover the full virtual disk
/// (`virtual_size / cluster_size * 8` bytes), clamped to `..=32 MiB`, returning `Some(mib)` only
/// when the image needs more than QEMU's 8 MiB non-Linux default.
fn qcow2_l2_cache_mib(path: &Path) -> Option<u64> {
use std::io::Read;
let mut hdr = [0u8; 32];
let mut f = std::fs::File::open(path).ok()?;
f.read_exact(&mut hdr).ok()?;
if &hdr[0..4] != b"QFI\xfb" {
return None;
}
let version = u32::from_be_bytes(hdr[4..8].try_into().ok()?);
if version < 2 || version > 3 {
return None;
}
let cluster_bits = u32::from_be_bytes(hdr[20..24].try_into().ok()?);
if !(9..=21).contains(&cluster_bits) {
return None;
}
let virtual_size = u64::from_be_bytes(hdr[24..32].try_into().ok()?);
let cluster_size = 1u64 << cluster_bits;
let clusters = virtual_size.div_ceil(cluster_size);
let l2_bytes = clusters.saturating_mul(8);
let mib = l2_bytes.div_ceil(1024 * 1024).min(32);
(mib > 8).then_some(mib)
}
fn optp(p: &Path) -> String {
opt(&p.to_string_lossy())
}
@@ -405,13 +378,6 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
c.disk_format.as_str(),
optp(&vm.disk())
);
// QEMU caps default qcow2 L2 cache at 8 MiB on non-Linux hosts (covering only 64 GiB at 64 KiB
// clusters). Size l2-cache-size to cover the image's virtual capacity (capped at 32 MiB).
if matches!(c.disk_format, crate::vm::ImageFormat::Qcow2) {
if let Some(mib) = qcow2_l2_cache_mib(&vm.disk()) {
disk.push_str(&format!(",l2-cache-size={mib}M"));
}
}
// An install's flushes, which the module's doc measures, are dropped while the installer is
// attached.
if q.installer.is_some() {
@@ -432,15 +398,12 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
"-device",
&format!("ide-hd,bus=sata.{},drive=disk,rotation_rate=1", q.disk_port),
]),
// Pass guest TRIMs (`discard=unmap`) like NVMe and offload block handling to a dedicated
// iothread so disk completions do not contend with QEMU's main event loop.
// SATA's drive options, at the first slot no other device takes.
DiskController::Virtio => push(&[
"-object",
"iothread,id=io0",
"-drive",
&format!("{disk},discard=unmap"),
&disk,
"-device",
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
"virtio-blk-pci,drive=disk,addr=0x6",
]),
}
// The installer, on port 4, past OpenCore's, or on 5 past an AHCI disk on 4.
@@ -574,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) {
@@ -581,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()]);
@@ -987,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]
@@ -1791,12 +1786,10 @@ pub(crate) mod tests {
assert!(has(
&a,
&[
"-object",
"iothread,id=io0",
"-drive",
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,discard=unmap",
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2",
"-device",
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
"virtio-blk-pci,drive=disk,addr=0x6",
]
));
assert!(
@@ -1821,12 +1814,10 @@ pub(crate) mod tests {
assert!(has(
&a,
&[
"-object",
"iothread,id=io0",
"-drive",
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on,discard=unmap",
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on",
"-device",
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
"virtio-blk-pci,drive=disk,addr=0x6",
]
));
}
+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 -39
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
@@ -942,45 +946,6 @@ RvgStatus rvg_graphics_device_read_display_at(RvgGraphicsDevice *device,
RvgDisplayCoord rvg_graphics_device_cursor_position_at(const RvgGraphicsDevice *device,
uint32_t display);
// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
// and waits for GPU idle.
//
// # Safety
// `device` is a live graphics device handle.
RvgStatus rvg_graphics_device_quiesce(RvgGraphicsDevice *device);
// Resumes VBLANK and ring threads after a snapshot finishes or fails.
//
// # Safety
// `device` is a live graphics device handle.
RvgStatus rvg_graphics_device_unquiesce(RvgGraphicsDevice *device);
// Serializes the full graphics device state into a heap-allocated buffer owned by the caller
// and released with [`rvg_graphics_snapshot_free`].
//
// # Safety
// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers.
RvgStatus rvg_graphics_device_snapshot_save(RvgGraphicsDevice *device,
uint8_t **out_data,
size_t *out_len);
// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`].
//
// # Safety
// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not
// be freed more than once.
void rvg_graphics_snapshot_free(uint8_t *data, size_t len);
// Restores the full graphics device state from a snapshot buffer produced by
// [`rvg_graphics_device_snapshot_save`].
//
// # Safety
// `device` is a live graphics device handle; `data` points to `len` readable bytes.
RvgStatus rvg_graphics_device_snapshot_load(RvgGraphicsDevice *device,
const uint8_t *data,
size_t len);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
+26 -119
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(|| {
@@ -1180,124 +1206,5 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position_at(
})
}
/// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
/// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
/// and waits for GPU idle.
///
/// # Safety
/// `device` is a live graphics device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_quiesce(
device: *mut RvgGraphicsDevice,
) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_quiesce") };
match d.device.quiesce() {
Ok(()) => RVG_OK,
Err(e) => status(e),
}
})
}
/// Resumes VBLANK and ring threads after a snapshot finishes or fails.
///
/// # Safety
/// `device` is a live graphics device handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_unquiesce(
device: *mut RvgGraphicsDevice,
) -> RvgStatus {
ffi::export(|| {
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_unquiesce") };
d.device.unquiesce();
RVG_OK
})
}
/// Serializes the full graphics device state into a heap-allocated buffer owned by the caller
/// and released with [`rvg_graphics_snapshot_free`].
///
/// # Safety
/// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_snapshot_save(
device: *mut RvgGraphicsDevice,
out_data: *mut *mut u8,
out_len: *mut usize,
) -> RvgStatus {
ffi::export(|| {
if out_data.is_null() || out_len.is_null() {
return RVG_ERR_INVALID_ARGUMENT;
}
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_snapshot_save") };
match d.device.snapshot_save() {
Ok(bytes) => {
let mut boxed = bytes.into_boxed_slice();
let len = boxed.len();
let ptr = boxed.as_mut_ptr();
std::mem::forget(boxed);
// SAFETY: non-null checked above.
unsafe {
*out_data = ptr;
*out_len = len;
}
RVG_OK
}
Err(e) => status(e),
}
})
}
/// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`].
///
/// # Safety
/// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not
/// be freed more than once.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_snapshot_free(data: *mut u8, len: usize) {
ffi::export(|| {
if !data.is_null() {
// SAFETY: matches Box::<[u8]>::into_raw layout above.
unsafe {
let _ = Box::from_raw(std::ptr::slice_from_raw_parts_mut(data, len));
}
}
})
}
/// Restores the full graphics device state from a snapshot buffer produced by
/// [`rvg_graphics_device_snapshot_save`].
///
/// # Safety
/// `device` is a live graphics device handle; `data` points to `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rvg_graphics_device_snapshot_load(
device: *mut RvgGraphicsDevice,
data: *const u8,
len: usize,
) -> RvgStatus {
ffi::export(|| {
if data.is_null() && len > 0 {
return RVG_ERR_INVALID_ARGUMENT;
}
// SAFETY: the caller's contract.
let d = unsafe { live(device, "rvg_graphics_device_snapshot_load") };
let slice = if len == 0 {
&[]
} else {
// SAFETY: caller's contract.
unsafe { std::slice::from_raw_parts(data, len) }
};
match d.device.snapshot_load(slice) {
Ok(()) => RVG_OK,
Err(e) => status(e),
}
})
}
#[cfg(test)]
mod tests;
-5
View File
@@ -241,11 +241,6 @@ static void check_graphics(void) {
CHECK(wait_for(&graphics_moved, 2));
at = rvg_graphics_device_cursor_position(d);
CHECK(at.x == 0 && at.y == 0);
CHECK_STATUS(rvg_graphics_device_quiesce(d), RVG_OK);
CHECK_STATUS(rvg_graphics_device_snapshot_save(d, NULL, NULL), RVG_ERR_INVALID_ARGUMENT);
CHECK_STATUS(rvg_graphics_device_snapshot_load(d, NULL, 1), RVG_ERR_INVALID_ARGUMENT);
rvg_graphics_snapshot_free(NULL, 0);
CHECK_STATUS(rvg_graphics_device_unquiesce(d), RVG_OK);
rvg_graphics_device_release(d);
#if defined(_WIN32)
CloseHandle(bell);
+1 -1
View File
@@ -242,7 +242,7 @@ fn c_harness_calls_every_function() {
// A function with a form of each OS's (Windows's under `#if defined(_WIN32)`, the others'
// under `#if !defined(_WIN32)`) is declared once per form, one after the other.
declared.dedup();
assert_eq!(declared.len(), 24, "{declared:?}");
assert_eq!(declared.len(), 19, "{declared:?}");
let missing: Vec<&str> = declared
.iter()
.copied()
-264
View File
@@ -1104,8 +1104,6 @@ pub(crate) struct Shared {
reset_owed: AtomicBool,
/// Set at the device's end.
ending: AtomicBool,
/// Set while quiesced for checkpointing.
quiesced: AtomicBool,
/// The control thread's own wake.
wake: Wake,
/// The host's doorbell file for ring 0, once given.
@@ -1876,7 +1874,6 @@ impl Device {
epoch: AtomicU64::new(0),
reset_owed: AtomicBool::new(false),
ending: AtomicBool::new(false),
quiesced: AtomicBool::new(false),
wake: Wake::new()?,
doorbell: OnceLock::new(),
submit: Mutex::new(Submit {
@@ -2122,26 +2119,6 @@ impl Device {
pub fn reset(&self) {
self.shared.reset();
}
/// Quiesces the device for stopped-VM checkpointing.
pub fn quiesce(&self) {
self.shared.quiesce();
}
/// Resumes VBLANK ticks and ring consumption after quiesce.
pub fn unquiesce(&self) {
self.shared.unquiesce();
}
/// Exports the quiescent device's BAR0/ring/display/queue/region state.
pub fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot {
self.shared.export_snapshot()
}
/// Restores device state on a freshly created device (after QEMU restored BAR2).
pub fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> {
self.shared.import_snapshot(snap)
}
}
/// The `COMPLETE` a ring-0 command owes, which the host gives from any thread once it has carried
@@ -2600,219 +2577,6 @@ impl Shared {
/// The reset (the module doc). It waits for the message the control thread is taking, and
/// for a take of a queue's ring or a post onto one under way, none of which waits for the
/// host; the host is told on the control thread ([`Self::tell_reset`]).
fn quiesce(&self) {
self.quiesced.store(true, Ordering::Release);
self.wake.wake();
let active_queues: Vec<Arc<QueueShared>> = {
self.queues.lock().by_obj.values().cloned().collect()
};
for q in &active_queues {
q.wake.wake();
}
{
let _taking = self.taking.lock();
}
self.take_messages();
self.lanes.wait_idle();
if self.control_handing.load(Ordering::Acquire) {
self.post_behind_control_handed(None);
}
for q in &active_queues {
let poster = self.queue_poster(q);
self.take_queue_messages(q, &poster);
if q.handing.load(Ordering::Acquire) {
self.post_handed(q);
}
}
self.lanes.wait_idle();
}
fn unquiesce(&self) {
self.quiesced.store(false, Ordering::Release);
self.wake.wake();
let active_queues: Vec<Arc<QueueShared>> = {
self.queues.lock().by_obj.values().cloned().collect()
};
for q in &active_queues {
q.wake.wake();
}
}
fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot {
use crate::snapshot::{DeviceSnapshot, DisplaySnapshot, QueueSnapshot};
let status = self.status.load(Ordering::Acquire);
let driver_features = self.driver_features.load(Ordering::Acquire);
let control_done = self.control_done.load(Ordering::Acquire);
let (control_submit_count, control_submit_broken) = {
let s = self.submit.lock();
(s.consumer.consumed(), s.broken)
};
let control_completion_count = self.completion.lock().produced();
let vt_ring_count = self.vt_ring.lock().produced();
let pages: Vec<u32> = self.pages.iter().map(|p| p.load(Ordering::Acquire)).collect();
let displays: Vec<DisplaySnapshot> = self
.displays
.iter()
.map(|d| {
let st = d.state.lock();
DisplaySnapshot {
scanout: st.scanout,
vblank: st.vblank,
asleep: st.asleep,
refreshes: st.refreshes,
told: st.told,
changed: st.changed,
cursor_image: st.cursor_image.clone(),
}
})
.collect();
let region_blocks = self.region.export_blocks();
let mut queue_list: Vec<Arc<QueueShared>> =
self.queues.lock().by_obj.values().cloned().collect();
queue_list.sort_by_key(|q| q.obj_id);
let queues: Vec<QueueSnapshot> = queue_list
.iter()
.map(|q| {
let s = q.submit.lock();
let c = q.complete.lock();
QueueSnapshot {
create_bytes: q.create.as_bytes().to_vec(),
flags: q.flags,
taken_seqno: q.taken_seqno.load(Ordering::Acquire),
taken_buffer_seqno: q.taken_buffer_seqno.load(Ordering::Acquire),
submit_count: s.consumer.consumed(),
submit_broken: s.broken,
complete_count: c.produced(),
}
})
.collect();
DeviceSnapshot {
status,
driver_features,
control_done,
control_submit_count,
control_submit_broken,
control_completion_count,
vt_ring_count,
pages,
displays,
region_blocks,
queues,
}
}
fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> {
self.quiesced.store(true, Ordering::Release);
self.region.import_blocks(&snap.region_blocks);
self.driver_features.store(snap.driver_features, Ordering::Release);
if snap.driver_features != 0 {
self.host.driver_ready(snap.driver_features);
}
let mut any_page = false;
for (dst, &val) in self.pages.iter().zip(snap.pages.iter()) {
dst.store(val, Ordering::Release);
if val != 0 {
any_page = true;
}
}
if any_page {
self.pages_bound.store(true, Ordering::Release);
}
{
let mut submit = self.submit.lock();
submit.consumer.set_count(snap.control_submit_count);
submit.broken = snap.control_submit_broken;
submit.backlog.clear();
}
self.control_done.store(snap.control_done, Ordering::Release);
self.completion.lock().set_count(snap.control_completion_count);
self.vt_ring.lock().set_count(snap.vt_ring_count);
self.reset_owed.store(false, Ordering::Release);
for (display, ds) in self.displays.iter().zip(snap.displays.iter()) {
{
let mut st = display.state.lock();
st.scanout = ds.scanout;
st.vblank = ds.vblank;
st.asleep = ds.asleep;
st.refreshes = ds.refreshes;
st.told = ds.told;
st.changed = ds.changed;
st.cursor_image = ds.cursor_image.clone();
}
display.screen.scanout(ds.scanout);
display.screen.cursor_image(ds.cursor_image.clone());
display.screen.power(!ds.asleep);
}
self.status.store(snap.status, Ordering::Release);
let epoch = self.epoch.load(Ordering::Acquire);
for qs in &snap.queues {
let Ok(q) = RgfxQueueCreate::read_from_bytes(&qs.create_bytes) else {
return Err("malformed RgfxQueueCreate in snapshot");
};
let Some((submit_at, complete_at)) = self.validate_rings(&q) else {
return Err("queue rings invalid against restored BAR2 block ledger");
};
let Some(me) = self.weak_self.get().and_then(Weak::upgrade) else {
return Err("device weak_self missing");
};
let Some(wake) = Wake::new() else {
return Err("queue wake allocation failed");
};
let bell = if self.driver_took(RGFX_FEATURE_DOORBELL_ASKS) {
wake::bell()
} else {
None
};
let mut consumer = Consumer::new(submit_at);
consumer.set_count(qs.submit_count);
let mut producer = Producer::new(complete_at);
producer.set_count(qs.complete_count);
let queue = Arc::new(QueueShared {
obj_id: q.obj_id,
context: (q.obj_id >> RGFX_CONTEXT_OBJ_ID_SHIFT) as u32,
create: q,
flags: qs.flags,
epoch,
ring_id: q.submit_offset,
vector: q.vector,
submit: Mutex::new(Submit {
consumer,
broken: qs.submit_broken,
backlog: Backlog::default(),
asleep: false,
}),
taken_seqno: AtomicU64::new(qs.taken_seqno),
taken_buffer_seqno: AtomicU64::new(qs.taken_buffer_seqno),
consuming: Mutex::new(None),
complete: Mutex::new(producer),
room: Room::default(),
full: AtomicBool::new(false),
untold: Mutex::new(Untold::default()),
handed: Mutex::new(Handed::default()),
handing: AtomicBool::new(false),
wake,
bell,
route: AtomicU64::new(0),
route_page: AtomicU32::new(u32::MAX),
ending: AtomicBool::new(false),
trip: trip::Queue::default(),
});
{
let mut queues = self.queues.lock();
queues.by_obj.insert(q.obj_id, Arc::clone(&queue));
queues.by_ring.insert(q.submit_offset, Arc::clone(&queue));
}
let service = Arc::clone(&queue);
std::thread::Builder::new()
.name(format!("reims-vgpu.graphics-queue-{:#x}", q.obj_id))
.spawn(move || me.queue_service_restored(&service))
.map_err(|_| "failed to spawn restored queue thread")?;
self.route(&queue);
self.host.queue_made(&self.queue_poster(&queue));
}
Ok(())
}
fn reset(&self) {
self.status.store(RGFX_STATUS_RESET, Ordering::Release);
self.driver_features.store(0, Ordering::Release);
@@ -3490,10 +3254,6 @@ impl Shared {
/// The control thread (the module doc).
fn control_thread(&self) {
while !self.ending() {
if self.quiesced.load(Ordering::Acquire) {
self.wake.sleep_for(None, Some(Duration::from_millis(20)));
continue;
}
// The answers handed over to it, posted first, as a post onto the ring would.
if self.control_handing.load(Ordering::Acquire) {
self.post_behind_control_handed(None);
@@ -4678,23 +4438,6 @@ impl Shared {
/// A queue's service thread (the module doc): it takes the queue's submission ring with the
/// control thread's `consumer_idle` handshake, hands each message to the host, and sleeps on
/// the queue's own wake, woken by its doorbell or its end.
fn queue_service_restored(&self, queue: &Arc<QueueShared>) {
let poster = self.queue_poster(queue);
self.queue_loop(queue, &poster);
self.close_handed(queue);
if !self.ending() && self.epoch.load(Ordering::Acquire) == queue.epoch {
let destroy = RgfxObjectDestroy {
header: RgfxMsgHeader {
r#type: RGFX_CMD_OBJECT_DESTROY,
size: size_of::<RgfxObjectDestroy>() as u32,
seqno: 0,
},
obj_id: queue.obj_id,
};
self.host.stage3_message(&poster, destroy.as_bytes());
}
}
fn queue_service(&self, queue: &Arc<QueueShared>) {
let poster = self.queue_poster(queue);
// The host makes the queue's handle first, so a command buffer on it can name it.
@@ -4721,10 +4464,6 @@ impl Shared {
/// The loop of a queue's service thread: take, then sleep, until the queue or the device ends.
fn queue_loop(&self, queue: &Arc<QueueShared>, poster: &CompletionPoster) {
while !self.ending() && !queue.ended() {
if self.quiesced.load(Ordering::Acquire) {
queue.wake.sleep_for(None, Some(Duration::from_millis(20)));
continue;
}
// The records handed over to it, posted first, as far as its ring has room: those
// left wait for its next look, while it takes the guest's buffers meanwhile.
if queue.handing.load(Ordering::Acquire) {
@@ -5335,9 +5074,6 @@ impl Shared {
/// that sees it ([`Self::displays_seen`]) alone: a guest that did not take
/// [`RGFX_FEATURE_MULTI_DISPLAY`] gets none of a display but 0's.
pub(crate) fn refresh(&self, id: u32, now: u64) {
if self.quiesced.load(Ordering::Acquire) {
return;
}
let Some(display) = self.displays.get(id as usize) else {
return;
};
@@ -1035,19 +1035,6 @@ impl Lanes {
}
}
/// Waits until no lane is running or has queued jobs (or the device ends).
pub(super) fn wait_idle(&self) {
let mut state = self.state.lock();
while !state.ended
&& state
.lanes
.values()
.any(|lane| lane.running.is_some() || !lane.jobs.is_empty())
{
self.moved.wait(&mut state);
}
}
/// The device ended: the lanes' threads go at their next look, and so do those that wait for
/// a lane.
pub(super) fn end(&self) {
-1
View File
@@ -31,7 +31,6 @@ pub mod keep;
pub mod managed;
pub mod ops;
pub mod region;
pub mod snapshot;
mod ring;
// The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header.
/// cbindgen:ignore
-44
View File
@@ -60,19 +60,6 @@ pub struct Region {
}
/// A block's size and who holds it.
/// Serializable snapshot of a granted or shared BAR2 region block.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RegionBlockSnapshot {
/// Byte offset inside BAR2.
pub offset: u64,
/// Block size in bytes.
pub size: u64,
/// Context IDs holding this block.
pub holders: Vec<u32>,
/// Whether this block was shared (`BLOCK_SHARE`).
pub shared: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Held {
size: u64,
@@ -226,37 +213,6 @@ impl Region {
}
/// No block is anyone's any more (the device's reset): the kext grants them again.
/// Exports all currently granted/shared BAR2 blocks for checkpointing.
pub fn export_blocks(&self) -> Vec<RegionBlockSnapshot> {
let blocks = self.blocks.lock();
blocks
.iter()
.map(|(&offset, held)| RegionBlockSnapshot {
offset,
size: held.size,
holders: held.holders.clone(),
shared: held.shared,
})
.collect()
}
/// Replaces the BAR2 block ledger from a checkpoint.
pub fn import_blocks(&self, snap: &[RegionBlockSnapshot]) {
let mut blocks = self.blocks.lock();
blocks.clear();
for b in snap {
blocks.insert(
b.offset,
Held {
size: b.size,
holders: b.holders.clone(),
shared: b.shared,
},
);
}
}
/// Revokes all active BAR2 region grants prior to snapshot restore.
pub fn revoke_all(&self) {
self.blocks.lock().clear();
}
-15
View File
@@ -202,11 +202,6 @@ impl Consumer {
self.count
}
/// Restores the host's consumed byte count from a checkpoint (BAR2 already holds header).
pub(crate) fn set_count(&mut self, count: u64) {
self.count = count;
}
/// The guest's published count (the ring's producer), read with an acquire load.
pub(crate) fn published_count(&self, region: &Region) -> u64 {
region
@@ -560,16 +555,6 @@ impl Producer {
}
/// Back to a ring nothing has passed through ([`RingAt::initialize`]), `consumer_idle` 0.
/// Returns the host's published byte count.
pub(crate) fn produced(&self) -> u64 {
self.count
}
/// Restores the host's published byte count from a checkpoint (BAR2 already holds header).
pub(crate) fn set_count(&mut self, count: u64) {
self.count = count;
}
pub(crate) fn reset(&mut self, region: &Region) {
self.count = 0;
self.at.initialize(region, false);
-293
View File
@@ -1,293 +0,0 @@
//! Binary snapshot codec for [`Device`](crate::Device) state (Layer B).
use crate::display::{CursorImage, Mode, Scanout};
use crate::region::RegionBlockSnapshot;
/// Serializable display state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DisplaySnapshot {
/// Active BAR2 scanout, if any.
pub scanout: Option<Scanout>,
/// Whether VBLANK delivery is enabled.
pub vblank: bool,
/// Whether the panel is off (`SET_DISPLAY_POWER`).
pub asleep: bool,
/// Refresh counter since reset.
pub refreshes: u64,
/// Last mode told to the guest.
pub told: Option<Mode>,
/// Whether a `DISPLAY_CHANGED` event is owed.
pub changed: bool,
/// Current guest cursor image, if any.
pub cursor_image: Option<CursorImage>,
}
/// Serializable per-command-queue ring state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueueSnapshot {
/// Raw `RgfxQueueCreate` wire message bytes.
pub create_bytes: Vec<u8>,
/// Accepted `RGFX_QUEUE_*` flags.
pub flags: u32,
/// Highest message seqno taken off the queue's submission ring.
pub taken_seqno: u64,
/// Highest command-buffer seqno taken off the queue's submission ring.
pub taken_buffer_seqno: u64,
/// Host consumer byte count on the queue's submission ring.
pub submit_count: u64,
/// Whether the queue's submission ring was marked broken.
pub submit_broken: bool,
/// Host producer byte count on the queue's completion ring.
pub complete_count: u64,
}
/// Complete serializable snapshot of `reims_vgpu_graphics::Device` (BAR0/rings/displays/queues).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeviceSnapshot {
/// `STATUS` register value.
pub status: u32,
/// Negotiated `DRIVER_FEATURES` bitmask.
pub driver_features: u64,
/// Control submission ring `control_done` count.
pub control_done: u64,
/// Control submission ring consumer byte count.
pub control_submit_count: u64,
/// Whether control submission ring is broken.
pub control_submit_broken: bool,
/// Control completion ring producer byte count.
pub control_completion_count: u64,
/// VideoToolbox ring producer byte count.
pub vt_ring_count: u64,
/// Doorbell page context bindings (`RGFX_REG_DOORBELL_PAGE_BIND`).
pub pages: Vec<u32>,
/// Per-display state.
pub displays: Vec<DisplaySnapshot>,
/// Active BAR2 granted/shared blocks.
pub region_blocks: Vec<RegionBlockSnapshot>,
/// Active per-queue rings.
pub queues: Vec<QueueSnapshot>,
}
fn put_u8(o: &mut Vec<u8>, v: u8) { o.push(v); }
fn put_u32(o: &mut Vec<u8>, v: u32) { o.extend_from_slice(&v.to_le_bytes()); }
fn put_u64(o: &mut Vec<u8>, v: u64) { o.extend_from_slice(&v.to_le_bytes()); }
fn put_bytes(o: &mut Vec<u8>, b: &[u8]) {
put_u64(o, b.len() as u64);
o.extend_from_slice(b);
}
fn get_u8(i: &mut &[u8]) -> Option<u8> {
let (&b, rest) = i.split_first()?;
*i = rest;
Some(b)
}
fn get_u32(i: &mut &[u8]) -> Option<u32> {
if i.len() < 4 { return None; }
let (a, rest) = i.split_at(4);
*i = rest;
Some(u32::from_le_bytes(a.try_into().ok()?))
}
fn get_u64(i: &mut &[u8]) -> Option<u64> {
if i.len() < 8 { return None; }
let (a, rest) = i.split_at(8);
*i = rest;
Some(u64::from_le_bytes(a.try_into().ok()?))
}
fn get_bytes(i: &mut &[u8]) -> Option<Vec<u8>> {
let n = usize::try_from(get_u64(i)?).ok()?;
if i.len() < n { return None; }
let (a, rest) = i.split_at(n);
*i = rest;
Some(a.to_vec())
}
fn checked_count(i: &mut &[u8], min_item_bytes: usize) -> Option<usize> {
let count = usize::try_from(get_u32(i)?).ok()?;
let min_bytes = min_item_bytes.max(1);
if count > i.len() / min_bytes {
return None;
}
Some(count)
}
fn read_vec<T>(
i: &mut &[u8],
min_item_bytes: usize,
mut f: impl FnMut(&mut &[u8]) -> Option<T>,
) -> Option<Vec<T>> {
let count = checked_count(i, min_item_bytes)?;
let mut out = Vec::with_capacity(count);
for _ in 0..count {
out.push(f(i)?);
}
Some(out)
}
impl DeviceSnapshot {
/// Encodes this device snapshot into `out`.
pub fn encode(&self, o: &mut Vec<u8>) {
put_u32(o, 1);
put_u32(o, self.status);
put_u64(o, self.driver_features);
put_u64(o, self.control_done);
put_u64(o, self.control_submit_count);
put_u8(o, u8::from(self.control_submit_broken));
put_u64(o, self.control_completion_count);
put_u64(o, self.vt_ring_count);
put_u32(o, self.pages.len() as u32);
for &p in &self.pages { put_u32(o, p); }
put_u32(o, self.displays.len() as u32);
for d in &self.displays {
match d.scanout {
Some(s) => {
put_u8(o, 1);
put_u32(o, s.width); put_u32(o, s.height);
put_u32(o, s.stride); put_u64(o, s.offset);
}
None => put_u8(o, 0),
}
put_u8(o, u8::from(d.vblank));
put_u8(o, u8::from(d.asleep));
put_u64(o, d.refreshes);
match d.told {
Some(m) => {
put_u8(o, 1);
put_u32(o, m.width); put_u32(o, m.height);
put_u32(o, m.refresh_mhz); put_u32(o, m.scale_120ths);
}
None => put_u8(o, 0),
}
put_u8(o, u8::from(d.changed));
match &d.cursor_image {
Some(c) => {
put_u8(o, 1);
put_u32(o, c.width); put_u32(o, c.height);
put_u32(o, c.hot_spot.0); put_u32(o, c.hot_spot.1);
put_bytes(o, &c.rgba);
}
None => put_u8(o, 0),
}
}
put_u32(o, self.region_blocks.len() as u32);
for b in &self.region_blocks {
put_u64(o, b.offset); put_u64(o, b.size);
put_u8(o, u8::from(b.shared));
put_u32(o, b.holders.len() as u32);
for &h in &b.holders { put_u32(o, h); }
}
put_u32(o, self.queues.len() as u32);
for q in &self.queues {
put_bytes(o, &q.create_bytes);
put_u32(o, q.flags);
put_u64(o, q.taken_seqno);
put_u64(o, q.taken_buffer_seqno);
put_u64(o, q.submit_count);
put_u8(o, u8::from(q.submit_broken));
put_u64(o, q.complete_count);
}
}
/// Decodes a device snapshot from `i`.
pub fn decode(i: &mut &[u8]) -> Option<Self> {
if get_u32(i)? != 1 { return None; }
let status = get_u32(i)?;
let driver_features = get_u64(i)?;
let control_done = get_u64(i)?;
let control_submit_count = get_u64(i)?;
let control_submit_broken = get_u8(i)? != 0;
let control_completion_count = get_u64(i)?;
let vt_ring_count = get_u64(i)?;
let pages = read_vec(i, 4, get_u32)?;
let displays = read_vec(i, 14, |i| {
let scanout = if get_u8(i)? != 0 {
Some(Scanout {
width: get_u32(i)?, height: get_u32(i)?,
stride: get_u32(i)?, offset: get_u64(i)?,
})
} else { None };
let vblank = get_u8(i)? != 0;
let asleep = get_u8(i)? != 0;
let refreshes = get_u64(i)?;
let told = if get_u8(i)? != 0 {
Some(Mode {
width: get_u32(i)?, height: get_u32(i)?,
refresh_mhz: get_u32(i)?, scale_120ths: get_u32(i)?,
})
} else { None };
let changed = get_u8(i)? != 0;
let cursor_image = if get_u8(i)? != 0 {
Some(CursorImage {
width: get_u32(i)?, height: get_u32(i)?,
hot_spot: (get_u32(i)?, get_u32(i)?),
rgba: get_bytes(i)?,
})
} else { None };
Some(DisplaySnapshot { scanout, vblank, asleep, refreshes, told, changed, cursor_image })
})?;
let region_blocks = read_vec(i, 21, |i| {
let offset = get_u64(i)?;
let size = get_u64(i)?;
let shared = get_u8(i)? != 0;
let holders = read_vec(i, 4, get_u32)?;
Some(RegionBlockSnapshot { offset, size, holders, shared })
})?;
let queues = read_vec(i, 45, |i| {
Some(QueueSnapshot {
create_bytes: get_bytes(i)?,
flags: get_u32(i)?,
taken_seqno: get_u64(i)?,
taken_buffer_seqno: get_u64(i)?,
submit_count: get_u64(i)?,
submit_broken: get_u8(i)? != 0,
complete_count: get_u64(i)?,
})
})?;
Some(DeviceSnapshot {
status, driver_features, control_done,
control_submit_count, control_submit_broken,
control_completion_count, vt_ring_count,
pages, displays, region_blocks, queues,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decode_rejects_oversized_counts_without_allocating() {
// Minimal valid header (version=1 + fixed scalar fields = 49 bytes).
let mut base = Vec::new();
let empty = DeviceSnapshot {
status: 1,
driver_features: 2,
control_done: 3,
control_submit_count: 4,
control_submit_broken: false,
control_completion_count: 5,
vt_ring_count: 6,
pages: vec![],
displays: vec![],
region_blocks: vec![],
queues: vec![],
};
empty.encode(&mut base);
let mut s = base.as_slice();
assert_eq!(DeviceSnapshot::decode(&mut s), Some(empty));
assert!(s.is_empty());
// Overwrite each of the 4 top-level collection counts with u32::MAX.
// Header length before pages count: 4 + 4 + 8 + 8 + 8 + 1 + 8 + 8 = 49.
for offset in [49usize, 53, 57, 61] {
let mut bad = base.clone();
bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes());
let mut sl = bad.as_slice();
assert!(DeviceSnapshot::decode(&mut sl).is_none(), "offset {offset} must fail");
}
}
}
@@ -564,44 +564,4 @@ pub trait GpuDevice<P: Platform>: Handle {
&self,
desc: &FullComputePipelineDesc<'_, P>,
) -> Result<Option<P::ComputePipeline>, NsErrorText>;
/// Waits for all submitted GPU work on this device to complete without tearing down the device.
fn wait_idle(&self) {}
/// Reads the current timeline value of a non-shared `MTLEvent` (0 if unsupported).
fn event_signaled_value(&self, _event: &P::Event) -> u64 {
0
}
/// Restores a non-shared `MTLEvent`'s timeline value across host process restart.
fn event_restore_signaled_value(&self, _event: &P::Event, _value: u64) -> bool {
true
}
/// Reads the contents of a standalone GPU buffer (Shared/Managed/Private) for snapshotting.
/// Returns `Ok(None)` if the buffer has no backed contents or this platform does not support
/// readback; returns `Err(...)` if a GPU transfer fails.
fn read_standalone_buffer(&self, _buffer: &P::Buffer) -> Result<Option<Vec<u8>>, &'static str> {
Ok(None)
}
/// Restores the contents of a standalone GPU buffer from snapshot bytes.
fn write_standalone_buffer(&self, _buffer: &P::Buffer, _data: &[u8]) -> bool {
false
}
/// Reads all mip levels and array/cube slices of a standalone GPU texture into packed bytes.
/// Returns `Ok(None)` for non-transferable formats (MSAA, Memoryless, depth/stencil) or on
/// platforms without readback; returns `Err(...)` if a GPU transfer fails.
fn read_standalone_texture(
&self,
_texture: &P::Texture,
) -> Result<Option<Vec<u8>>, &'static str> {
Ok(None)
}
/// Uploads packed mip/slice bytes back into a standalone GPU texture.
fn write_standalone_texture(&self, _texture: &P::Texture, _data: &[u8]) -> bool {
false
}
}
@@ -2625,327 +2625,6 @@ impl GpuDevice<RtPlatform> for RtObj<RtDevice> {
crate::recorder::rec_done!(recorded_call, recorded_answer);
recorded_answer
}
fn wait_idle(&self) {
let _ = self.rt().wait_idle();
}
fn event_signaled_value(&self, event: &<RtPlatform as Platform>::Event) -> u64 {
event.signaled_value()
}
fn event_restore_signaled_value(
&self,
event: &<RtPlatform as Platform>::Event,
value: u64,
) -> bool {
if value > 0 {
event.restore_signaled_value(value).is_ok()
} else {
true
}
}
fn read_standalone_buffer(
&self,
buffer: &<RtPlatform as Platform>::Buffer,
) -> Result<Option<Vec<u8>>, &'static str> {
let Some(rt_buf) = buffer.made_rt() else {
return Ok(None);
};
let len = rt_buf.length();
if len == 0 {
return Ok(Some(Vec::new()));
}
if let Some(ptr) = rt_buf.contents() {
return Ok(Some(unsafe {
std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec()
}));
}
let rt = self.rt();
let alloc_len = (len.max(4096) + 4095) & !4095;
let stage = rt
.take_block(rt::MemoryClass::Shared, alloc_len)
.map_err(|_| "standalone buffer readback: staging take_block failed")?;
let res = (|| -> Result<Vec<u8>, &'static str> {
let dst_buf = rt
.new_buffer(stage.id, 0, len, None)
.map_err(|_| "standalone buffer readback: staging new_buffer failed")?;
let q = rt
.new_command_queue(4)
.map_err(|_| "standalone buffer readback: new_command_queue failed")?;
let cb = q
.command_buffer()
.map_err(|_| "standalone buffer readback: command_buffer failed")?;
let mut blit = cb
.blit_command_encoder()
.map_err(|_| "standalone buffer readback: blit_command_encoder failed")?;
blit.copy_from_buffer_to_buffer(rt_buf, 0, &dst_buf, 0, len)
.map_err(|_| "standalone buffer readback: copy_from_buffer_to_buffer failed")?;
blit.end_encoding();
cb.commit()
.map_err(|_| "standalone buffer readback: commit failed")?;
cb.wait_until_completed()
.map_err(|_| "standalone buffer readback: wait_until_completed failed")?;
let ptr = stage
.contents
.ok_or("standalone buffer readback: staging block not host-mapped")?;
let out = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec() };
drop(dst_buf);
Ok(out)
})();
let _ = rt.release_block(stage);
res.map(Some)
}
fn write_standalone_buffer(
&self,
buffer: &<RtPlatform as Platform>::Buffer,
data: &[u8],
) -> bool {
let Some(rt_buf) = buffer.made_rt() else {
return false;
};
let len = rt_buf.length();
if data.len() as u64 != len {
return false;
}
if len == 0 {
return true;
}
if let Some(ptr) = rt_buf.contents() {
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize);
}
let _ = rt_buf.did_modify_range(0, len);
return true;
}
let rt = self.rt();
let alloc_len = (len.max(4096) + 4095) & !4095;
let Ok(stage) = rt.take_block(rt::MemoryClass::Shared, alloc_len) else {
return false;
};
if let Some(ptr) = stage.contents {
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize);
}
} else {
let _ = rt.release_block(stage);
return false;
}
let ok = (|| -> Result<(), rt::Error> {
let src_buf = rt.new_buffer(stage.id, 0, len, None)?;
let q = rt.new_command_queue(4)?;
let cb = q.command_buffer()?;
let mut blit = cb.blit_command_encoder()?;
blit.copy_from_buffer_to_buffer(&src_buf, 0, rt_buf, 0, len)?;
blit.end_encoding();
cb.commit()?;
cb.wait_until_completed()?;
drop(src_buf);
Ok(())
})()
.is_ok();
let _ = rt.release_block(stage);
ok
}
fn read_standalone_texture(
&self,
texture: &<RtPlatform as Platform>::Texture,
) -> Result<Option<Vec<u8>>, &'static str> {
let rt_tex = texture.rt();
let desc = rt_tex.descriptor();
let Some((plan, total)) = texture_copy_plan(self.rt(), desc) else {
return Ok(None);
};
if total == 0 {
return Ok(Some(Vec::new()));
}
let rt = self.rt();
let alloc_len = (total.max(4096) + 4095) & !4095;
let stage = rt
.take_block(rt::MemoryClass::Shared, alloc_len)
.map_err(|_| "standalone texture readback: staging take_block failed")?;
let res = (|| -> Result<Vec<u8>, &'static str> {
let dst_buf = rt
.new_buffer(stage.id, 0, total, None)
.map_err(|_| "standalone texture readback: staging new_buffer failed")?;
let q = rt
.new_command_queue(4)
.map_err(|_| "standalone texture readback: new_command_queue failed")?;
let cb = q
.command_buffer()
.map_err(|_| "standalone texture readback: command_buffer failed")?;
let mut blit = cb
.blit_command_encoder()
.map_err(|_| "standalone texture readback: blit_command_encoder failed")?;
for step in &plan {
blit.copy_from_texture_to_buffer(
rt_tex,
rt::TexturePlace {
slice: step.slice,
level: step.level,
origin: [0, 0, 0],
},
step.size,
&dst_buf,
rt::BufferLayout {
offset: step.offset,
bytes_per_row: step.bytes_per_row,
bytes_per_image: step.bytes_per_image,
},
)
.map_err(|_| "standalone texture readback: copy_from_texture_to_buffer failed")?;
}
blit.end_encoding();
cb.commit()
.map_err(|_| "standalone texture readback: commit failed")?;
cb.wait_until_completed()
.map_err(|_| "standalone texture readback: wait_until_completed failed")?;
let ptr = stage
.contents
.ok_or("standalone texture readback: staging block not host-mapped")?;
let out = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), total as usize).to_vec() };
drop(dst_buf);
Ok(out)
})();
let _ = rt.release_block(stage);
res.map(Some)
}
fn write_standalone_texture(
&self,
texture: &<RtPlatform as Platform>::Texture,
data: &[u8],
) -> bool {
let rt_tex = texture.rt();
let desc = rt_tex.descriptor();
let Some((plan, total)) = texture_copy_plan(self.rt(), desc) else {
return false;
};
if data.len() as u64 != total {
return false;
}
if total == 0 {
return true;
}
let rt = self.rt();
let alloc_len = (total.max(4096) + 4095) & !4095;
let Ok(stage) = rt.take_block(rt::MemoryClass::Shared, alloc_len) else {
return false;
};
if let Some(ptr) = stage.contents {
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), total as usize);
}
} else {
let _ = rt.release_block(stage);
return false;
}
let ok = (|| -> Result<(), rt::Error> {
let src_buf = rt.new_buffer(stage.id, 0, total, None)?;
let q = rt.new_command_queue(4)?;
let cb = q.command_buffer()?;
let mut blit = cb.blit_command_encoder()?;
for step in &plan {
blit.copy_from_buffer(
&src_buf,
rt::BufferLayout {
offset: step.offset,
bytes_per_row: step.bytes_per_row,
bytes_per_image: step.bytes_per_image,
},
step.size,
rt_tex,
rt::TexturePlace {
slice: step.slice,
level: step.level,
origin: [0, 0, 0],
},
)?;
}
blit.end_encoding();
cb.commit()?;
cb.wait_until_completed()?;
drop(src_buf);
Ok(())
})()
.is_ok();
let _ = rt.release_block(stage);
ok
}
}
struct TextureCopyStep {
slice: u32,
level: u32,
size: [u32; 3],
offset: u64,
bytes_per_row: u64,
bytes_per_image: u64,
}
fn texture_copy_plan(
rt: &rt::Device,
desc: &rt::TextureDescriptor,
) -> Option<(Vec<TextureCopyStep>, u64)> {
if desc.sample_count > 1 || desc.storage_mode == rt::StorageMode::Memoryless {
return None;
}
let raw_fmt = u64::from(desc.pixel_format.as_raw());
if (250..=262).contains(&raw_fmt) {
return None;
}
let info = rt.pixel_format_info(u64::from(desc.pixel_format.as_raw()));
let block_bytes = info.words[0];
if block_bytes == 0 {
return None;
}
let (block_w, block_h, block_d) = if info.flags & 0x400 != 0 {
(info.words[1].max(1), info.words[2].max(1), info.words[3].max(1))
} else {
(1, 1, 1)
};
let slices = match desc.texture_type {
rt::TextureType::Cube | rt::TextureType::CubeArray => desc.array_length.checked_mul(6)?,
rt::TextureType::Type3D => 1,
_ => desc.array_length.max(1),
};
let levels = desc.mipmap_level_count.max(1);
let mut plan = Vec::with_capacity((slices as usize).saturating_mul(levels as usize));
let mut offset: u64 = 0;
for slice in 0..slices {
for level in 0..levels {
let w = (desc.width >> level).max(1);
let h = match desc.texture_type {
rt::TextureType::Type1D | rt::TextureType::Type1DArray => 1,
_ => (desc.height >> level).max(1),
};
let d = match desc.texture_type {
rt::TextureType::Type3D => (desc.depth >> level).max(1),
_ => 1,
};
let bx = u64::from(w).div_ceil(block_w);
let by = u64::from(h).div_ceil(block_h);
let bz = u64::from(d).div_ceil(block_d);
let raw_bpr = bx.checked_mul(block_bytes)?;
let bpr = (raw_bpr + 15) & !15;
let bpi = bpr.checked_mul(by)?;
let step_bytes = bpi.checked_mul(bz)?;
offset = (offset + 15) & !15;
plan.push(TextureCopyStep {
slice,
level,
size: [w, h, d],
offset,
bytes_per_row: bpr,
bytes_per_image: bpi,
});
offset = offset.checked_add(step_bytes)?;
}
}
Some((plan, offset))
}
/// The identity of `device` ([`answers::identity`]): rt's linear and texture-buffer alignments
-15
View File
@@ -14,10 +14,6 @@
//! no window ever captures the keyboard or the pointer ([`crate::capture`]). `1`, `true`,
//! `yes` or `on` turns it on. Default: [`CAPTURE_DEFAULT`]. reims-ctl sets it from a VM's
//! settings.
//! - `REIMS_VGPU_WINDOW_FIXED_MODE`: `1`, `true`, `yes` or `on`, in any case, decouples the
//! guest's display mode from the window's pixel size so the display keeps offering the
//! configured resolution (e.g. 5120x2880 HiDPI supersampled into a 4K borderless window) and
//! scales the frame on the GPU. Default: off.
use std::sync::OnceLock;
@@ -29,8 +25,6 @@ pub const SCREENS_VAR: &str = "REIMS_VGPU_WINDOW_SCREENS";
pub const IMPL_VAR: &str = "REIMS_VGPU_WINDOW_IMPL";
/// The capture switch's variable.
pub const CAPTURE_VAR: &str = "REIMS_VGPU_WINDOW_CAPTURE";
/// The fixed guest mode switch's variable.
pub const FIXED_MODE_VAR: &str = "REIMS_VGPU_WINDOW_FIXED_MODE";
/// Whether a click into the image captures input where the capture switch is unset.
pub const CAPTURE_DEFAULT: bool = true;
@@ -46,8 +40,6 @@ pub struct Settings {
pub window_impl: WindowImpl,
/// Whether a click into the image captures input; off, nothing ever does.
pub capture: bool,
/// Keep offering the configured guest resolution instead of following the window's pixels.
pub fixed_mode: bool,
}
impl Default for Settings {
@@ -57,7 +49,6 @@ impl Default for Settings {
screens: Vec::new(),
window_impl: WindowImpl::AppKit,
capture: CAPTURE_DEFAULT,
fixed_mode: false,
}
}
}
@@ -125,11 +116,6 @@ fn parse_screens(value: &str) -> Option<Vec<usize>> {
.collect()
}
/// Whether fixed guest mode is on (`1`, `true`, `yes` or `on`, in any case); default off.
pub fn parse_fixed_mode(value: Option<&str>) -> bool {
value.is_some_and(parse_switch)
}
/// The process's settings, read from its environment the first time they are asked for. A
/// value that is not UTF-8 counts as unset.
pub fn settings() -> &'static Settings {
@@ -140,7 +126,6 @@ pub fn settings() -> &'static Settings {
Settings {
window_impl: parse_impl(var(IMPL_VAR).as_deref()),
capture: parse_capture(var(CAPTURE_VAR).as_deref()),
fixed_mode: parse_fixed_mode(var(FIXED_MODE_VAR).as_deref()),
..parse(borderless.as_deref(), screens.as_deref())
}
})
+15 -20
View File
@@ -79,9 +79,9 @@ struct Win32Msg {
/// WPARAM.
w_param: usize,
/// LPARAM.
l_param: isize,
_l_param: isize,
/// Message timestamp (GetMessageTime).
_time: u32,
time: u32,
/// Cursor position (POINT).
_pt: [i32; 2],
}
@@ -109,6 +109,8 @@ 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.
@@ -174,27 +176,20 @@ unsafe extern "C" fn unicode_message_hook(_userdata: *mut c_void, raw_msg: *mut
match msg.message {
WM_KEYDOWN | WM_SYSKEYDOWN => {
let vk = (msg.w_param & 0xFFFF) as u16;
LAST_KEY_UNMAPPED.set(vk == VK_PACKET || vk == VK_PROCESSKEY);
true
}
WM_CHAR => {
let unit = (msg.w_param & 0xFFFF) as u16;
let scan_code = (msg.l_param.cast_unsigned() >> 16) & 0xFF;
// Any WM_CHAR carrying a hardware scan code came from TranslateMessage on
// a physical WM_KEYDOWN that SDL already forwarded as a USB HID key.
// Never compare msg.time against WM_KEYDOWN.time: TranslateMessage stamps
// WM_CHAR with the current GetTickCount(), not the keydown's time.
let non_physical = scan_code == 0
&& (LAST_KEY_UNMAPPED.get() || unit >= 0x80 || msg.l_param == 0);
if non_physical && (unit >= 0x20 || unit == 0x0D || unit == 0x09) {
enqueue_utf16(unit);
return false;
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_IME_CHAR => {
WM_CHAR | WM_IME_CHAR => {
let unit = (msg.w_param & 0xFFFF) as u16;
if unit >= 0x20 || unit == 0x0D || unit == 0x09 {
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;
}
@@ -252,7 +247,7 @@ fn forward_unicode_loop(rx: mpsc::Receiver<u16>, addr: SocketAddr, path: String,
}
}
/// Sends a minimal HTTP/1.1 POST with UTF-8 text to the local host bridge.
/// 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;
+100 -506
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;
@@ -93,8 +93,7 @@ use reims_vgpu_graphics::wire::{
RGFX_FEATURE_TEXTURE_DID_MODIFY_DATA, RGFX_FEATURE_UNCHANGING_PAGES,
RGFX_FEATURE_UNSHARED_QUEUES, RGFX_FEATURE_UPLOADS_WRITTEN, RGFX_FEATURE_VT_MESSAGES,
RGFX_RESOURCE_ID_CHUNK, RGFX_RESOURCE_ID_CHUNKS, RGFX_STATUS_INVALID_ARGUMENT,
RGFX_STATUS_CACHE, RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED,
RGFX_VIDEO_CAPS_CODECS,
RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED, RGFX_VIDEO_CAPS_CODECS,
RGFX_VIDEO_CAPS_OFFSET, RGFX_VIDEO_CAPS_OUTPUT_CACHED, RGFX_VIDEO_CAPS_VERSION,
RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_CODEC_VP9, RGFX_VIDEO_DECODE,
RGFX_VIDEO_H264_BASELINE, RGFX_VIDEO_H264_HIGH, RGFX_VIDEO_H264_MAIN, RGFX_VIDEO_HEVC_MAIN,
@@ -191,7 +190,6 @@ mod present;
mod read;
mod rt_window;
mod sink;
mod snapshot;
mod slow_answers;
mod summary;
mod trip;
@@ -502,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")
}
}
}
@@ -523,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>>,
@@ -614,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(
@@ -1037,7 +1051,6 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
let clock = Arc::clone(&platform);
create_waits::CreateWaits::new(Box::new(move || clock.clock().now_mono()))
},
live_log: snapshot::LiveLog::new(count),
});
let cursors: Vec<Arc<HostCursor>> = (0..count)
.map(|display| {
@@ -1045,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(),
@@ -1131,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,
@@ -1142,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.
@@ -1353,242 +1416,6 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
(self.cursors.get(display as usize)).map_or((0, 0), |cursor| cursor.position())
})
}
fn quiesce_device(&self) -> Option<Arc<GraphicsControl<P>>> {
self.device.quiesce();
if let Some(pool) = &self.pool {
pool.quiesce();
}
let control = self.ending.upgrade()?;
control.pool.wait_idle();
control.icb_worker.flush();
let decoder = control.decoder();
decoder.flush_workers();
decoder.flush_all_surface_caches(&control.device);
control.device.wait_idle();
Some(control)
}
/// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
/// drains pending compiles and workers, flushes dirty device-cached IOSurfaces back to Guest
/// RAM, and waits for GPU idle.
pub fn quiesce(&self) -> Result<(), Error> {
entry::run(|_| {
let _ = self.quiesce_device();
Ok(())
})
}
/// Resumes VBLANK and ring service threads after a snapshot completes or aborts.
pub fn unquiesce(&self) {
entry::run(|_| {
self.device.unquiesce();
});
}
/// Serializes the full graphics device state (device rings/displays/queues, Shared Pool,
/// Private Blocks + VRAM, live Metal/Vulkan objects, timeline events, and standalone GPU
/// buffers/textures) into a portable byte blob for suspend-to-disk.
pub fn snapshot_save(&self) -> Result<Vec<u8>, Error> {
entry::run(|_| {
let t0 = std::time::Instant::now();
let control = self.quiesce_device().ok_or(Error::HostResources)?;
let decoder = control.decoder();
let mut device_snapshot = Vec::new();
self.device.export_snapshot().encode(&mut device_snapshot);
let shared_pool = self.pool.as_ref().map(|p| p.export_snapshot()).transpose()?;
let private_blocks = control.private_blocks.export_snapshot()?;
let id_chunks = decoder.export_id_chunks();
let (live_records, surface_pages, standalone_tex_set, presented_surfaces) =
control.live_log.export();
let mut known_ranges: Vec<(u64, u64)> = Vec::new();
if let Some(sp) = &shared_pool {
for piece in &sp.pieces {
if piece.gpu_address != 0 {
known_ranges.push((piece.gpu_address, piece.len));
}
}
}
for pb in &private_blocks.blocks {
if pb.gpu_address != 0 {
known_ranges.push((pb.gpu_address, pb.len));
}
}
let live_values = decoder
.export_live_values(&control.device, &known_ranges, &standalone_tex_set)
.map_err(|_| Error::HostResources)?;
let mut standalone_textures: Vec<u64> = standalone_tex_set.into_iter().collect();
standalone_textures.sort_unstable();
let snap = snapshot::VgpuSnapshot {
device_snapshot,
shared_pool,
private_blocks,
id_chunks,
surface_pages,
live_records,
standalone_textures,
presented_surfaces,
live_values,
};
let t_exp = t0.elapsed();
let n_tex = snap.live_values.textures.len();
let tex_bytes: usize = snap.live_values.textures.iter().map(|(_, b)| b.len()).sum();
let n_caches = snap.live_values.surface_caches.len();
let cache_bytes: usize = snap
.live_values
.surface_caches
.iter()
.map(|(_, b)| b.len())
.sum();
let encoded = snap.encode();
log::info!(
target: "reims_vgpu::graphics",
"snapshot_save done in {:.2}s (export={:.2}s): total={} B, textures={} ({:.1} MiB), unattached_caches={} ({:.1} MiB)",
t0.elapsed().as_secs_f64(),
t_exp.as_secs_f64(),
encoded.len(),
n_tex,
tex_bytes as f64 / (1024.0 * 1024.0),
n_caches,
cache_bytes as f64 / (1024.0 * 1024.0),
);
Ok(encoded)
})
}
/// Restores the full graphics device state from a snapshot produced by [`Self::snapshot_save`]
/// in a fresh host process.
pub fn snapshot_load(&self, data: &[u8]) -> Result<(), Error> {
entry::run(|_| {
let snap = snapshot::VgpuSnapshot::decode(data).ok_or(Error::InvalidArgument)?;
let mut dev_slice: &[u8] = &snap.device_snapshot;
let dev_snap = reims_vgpu_graphics::snapshot::DeviceSnapshot::decode(&mut dev_slice)
.ok_or(Error::InvalidArgument)?;
if !dev_slice.is_empty() {
return Err(Error::InvalidArgument);
}
let control = self.ending.upgrade().ok_or(Error::HostResources)?;
// Keep device rings and VBLANK paused until full object table replay finishes.
// Any error below returns without unquiescing so partial restores never report success.
self.device.quiesce();
match (&self.pool, &snap.shared_pool) {
(Some(pool), Some(ps)) => pool.import_snapshot(ps)?,
(None, Some(ps)) if !ps.pieces.is_empty() => return Err(Error::HostResources),
_ => {}
}
control.private_blocks.import_snapshot(&snap.private_blocks)?;
self.device.import_snapshot(&dev_snap).map_err(|_| Error::InvalidArgument)?;
control
.decoder()
.set_managed_at_copy(dev_snap.driver_features & RGFX_FEATURE_MANAGED_AT_COPY != 0);
{
let decoder = control.decoder();
decoder.import_id_chunks(&snap.id_chunks);
for sp in &snap.surface_pages {
decoder
.replay_surface_pages(
&control.device,
&sp.pages,
&sp.runs,
sp.flags,
sp.layout,
)
.map_err(|_| Error::HostResources)?;
}
}
let mut records = snap.live_records;
records.sort_by_key(|r| r.seq);
for rec in &records {
control.replay_record(rec)?;
}
let n_surface_pages = snap.surface_pages.len();
let n_records = records.len();
let standalone_set: std::collections::HashSet<u64> =
snap.standalone_textures.into_iter().collect();
control.live_log.restore(
records,
snap.surface_pages,
standalone_set,
snap.presented_surfaces.clone(),
);
// Wait for any replay-time buffer zeroing to finish, then upload exact saved memory!
control.device.wait_idle();
if let (Some(pool), Some(ps)) = (&self.pool, &snap.shared_pool) {
pool.restore_bytes(ps)?;
}
control.private_blocks.restore_bytes(&snap.private_blocks)?;
{
let decoder = control.decoder();
decoder
.import_live_values(&control.device, &snap.live_values)
.map_err(|_| Error::HostResources)?;
for qs in &dev_snap.queues {
let q = reims_vgpu_graphics::wire::RgfxQueueCreate::read_from_bytes(
&qs.create_bytes,
)
.map_err(|_| Error::InvalidArgument)?;
let watermark = qs.taken_seqno.max(qs.taken_buffer_seqno);
if watermark > 0 {
log::info!(
target: "reims_vgpu::graphics",
"restoring queue {:#x} watermark={watermark} (taken={} buf={})",
q.obj_id, qs.taken_seqno, qs.taken_buffer_seqno
);
decoder.restore_queue_watermark(q.obj_id, watermark);
control.presents.restore_finished(q.obj_id, watermark);
}
}
for (display, &iosurface_id) in snap.presented_surfaces.iter().enumerate() {
if iosurface_id == 0 {
continue;
}
let presented = control.presented.get(display).ok_or(Error::InvalidArgument)?;
let found = decoder.surface_present(iosurface_id).ok_or_else(|| {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_load: presented surface {iosurface_id} for display {display} missing after replay"
);
Error::HostResources
})?;
let shown = presented.hold(
found.texture,
found.view,
found.span,
found.queued,
);
let _ = presented.swap(iosurface_id, Some(shown));
}
}
log::info!(
target: "reims_vgpu::graphics",
"snapshot_load summary: dev_queues={} surface_pages={} records={} presented={:?} events={} shared_events={} bufs={} texs={} caches={}",
dev_snap.queues.len(),
n_surface_pages,
n_records,
snap.presented_surfaces,
snap.live_values.events.len(),
snap.live_values.shared_events.len(),
snap.live_values.buffers.len(),
snap.live_values.textures.len(),
snap.live_values.surface_caches.len(),
);
control.device.wait_idle();
self.device.unquiesce();
Ok(())
})
}
}
impl<P: ApiPlatform> Drop for GraphicsDevice<P> {
@@ -1782,7 +1609,6 @@ struct GraphicsControl<P: ApiPlatform> {
/// The pipeline creates waiting for their replies, timed for the counts line
/// (`create_waits`): from their take ([`Self::handle_stage3`]) to their reply's post.
create_waits: create_waits::CreateWaits,
live_log: snapshot::LiveLog,
}
/// The longest `COMMAND_BUFFER` message, in bytes, that is walked and committed on its queue's
@@ -2436,7 +2262,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
self.pending.cancel_context(context);
let (dropped, closed) = decoder.close_tables(&self.device, context);
self.pool.context_closed(context);
self.live_log.close_context(context);
self.presents.context_gone(context);
self.queue_sinks
.write()
@@ -2527,7 +2352,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
}
// And every Private block, the objects in them dropped.
self.private_blocks.reset();
self.live_log.reset();
self.presents.reset();
self.queue_sinks.write().clear();
for color in &self.colors {
@@ -2590,7 +2414,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
answer.answer(RGFX_STATUS_REFUSED);
return;
}
self.live_log.forget_surface_pages(release.offset);
// Once no display shows or draws a surface over the block, with what was in flight then.
let m = Arc::clone(&marks);
let in_flight = decoder.in_flight_read(release.context);
@@ -2891,10 +2714,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
let _carried = me.reset_gate.read_recursive();
let status = (me.decoder())
.carry_out_surface_pages(&me.device, &pages, &runs, flags, layout, &settle);
if matches!(status, Some(RGFX_STATUS_OK | RGFX_STATUS_CACHE)) {
me.live_log
.record_surface_pages(pages, runs.clone(), flags, layout);
}
// Where the guest took IMPORT_ADDRESSES_LATER, answered now, with no address,
// before the view is made and given one below.
let answer = match status {
@@ -2993,197 +2812,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
/// ([`Host::command_buffer`]), which goes to the buffer's lane as it is, with `claim`, its
/// queue's claim on its messages, which a buffer carried out here lets go once begun
/// ([`Self::carry_out`]).
/// Synchronously replays one recorded stage-3 object creation or persistent mutation
/// during [`GraphicsDevice::snapshot_load`] without emitting wire completion replies.
fn replay_record(&self, rec: &snapshot::LogRecord) -> Result<(), Error> {
let mut decoder = self
.decoders
.sender(Some(rec.context), Sinks::default());
match rec.msg_type {
snapshot::LOG_TAG_ASSEMBLED_LIBRARY => {
let guest_key: Option<decode::LibraryKey> = if rec.bytes.is_empty() {
None
} else {
Some(
rec.bytes
.as_slice()
.try_into()
.map_err(|_| Error::InvalidArgument)?,
)
};
let job = decoder.prepare_library_bytes(
rec.obj_id,
rec.inline_bytes.clone(),
guest_key,
);
let made = refusing(|| make_library::<P>(&self.device, &job)).map_err(|raise| {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: library seq={} obj={:#x} raised: {raise}",
rec.seq, rec.obj_id
);
Error::HostResources
})?;
let status = decoder.finish_library(made);
if status != RGFX_STATUS_OK {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: library seq={} obj={:#x} failed status={status}",
rec.seq, rec.obj_id
);
return Err(Error::HostResources);
}
Ok(())
}
RGFX_CMD_LIBRARY_LOOKUP => {
let (_, status) = decoder.lookup_library(&rec.bytes);
if status != RGFX_STATUS_OK {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: library lookup seq={} obj={:#x} failed status={status}",
rec.seq, rec.obj_id
);
return Err(Error::HostResources);
}
Ok(())
}
RGFX_CMD_RENDER_PIPELINE_CREATE
| RGFX_CMD_MESH_RENDER_PIPELINE_CREATE
| RGFX_CMD_COMPUTE_PIPELINE_CREATE => {
let job = decoder.prepare_pipeline(&rec.bytes).map_err(|e| {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: prepare_pipeline seq={} obj={:#x} failed: {e:?}",
rec.seq, rec.obj_id
);
Error::HostResources
})?;
let seen_from = job.seen_from;
let (compiled, _) =
stage::making(|| compile_refusing::<P>(&self.device, job));
let _ = compiled.finish(0);
let ok = compiled.is_made();
decoder.finish_pipeline_if(compiled, Some(seen_from), || true);
if !ok {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: pipeline compile seq={} type={:#x} obj={:#x} refused",
rec.seq, rec.msg_type, rec.obj_id
);
return Err(Error::HostResources);
}
Ok(())
}
RGFX_CMD_RATE_MAP_CREATE | RGFX_CMD_RATE_MAP_RESET => {
let reset = rec.msg_type == RGFX_CMD_RATE_MAP_RESET;
match refusing(|| decoder.rate_map_state(&self.device, &rec.bytes, reset)) {
Ok(Some(st)) if st.status == RGFX_STATUS_OK => Ok(()),
other => {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: rate_map seq={} obj={:#x} failed: {other:?}",
rec.seq, rec.obj_id
);
Err(Error::HostResources)
}
}
}
RGFX_CMD_FUNCTION_HANDLE_CREATE | RGFX_CMD_FUNCTION_TABLE_CREATE => {
match refusing(|| decoder.function_pointer_state(&rec.bytes)) {
Ok(Some(st)) if st.status == RGFX_STATUS_OK => Ok(()),
other => {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: function_pointer seq={} obj={:#x} failed: {other:?}",
rec.seq, rec.obj_id
);
Err(Error::HostResources)
}
}
}
RGFX_CMD_DYNAMIC_LIBRARY_CREATE => {
match refusing(|| decoder.dynamic_library_create(&self.device, &rec.bytes)) {
Ok(Some((_, RGFX_STATUS_OK))) => Ok(()),
other => {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: dynamic_library seq={} obj={:#x} failed: {other:?}",
rec.seq, rec.obj_id
);
Err(Error::HostResources)
}
}
}
RGFX_CMD_SHARED_EVENT_NAME => {
let listen_queue = RgfxSharedEventName::read_from_prefix(&rec.bytes)
.map_err(|_| Error::InvalidArgument)?
.0
.listen_queue_obj_id;
let listen = self.presents.queue_poster(listen_queue).map(|ring| {
Arc::new(move |m: &RgfxEventSignalled| ring.try_post(m.as_bytes()))
as ListenSink
});
let (_, status) = decoder.name_shared_event(&rec.bytes, listen);
if status != RGFX_STATUS_OK {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: shared_event_name seq={} obj={:#x} failed status={status}",
rec.seq, rec.obj_id
);
return Err(Error::HostResources);
}
Ok(())
}
RGFX_CMD_SHARED_EVENT_IMPORT => {
let listen_queue = RgfxSharedEventName::read_from_prefix(&rec.bytes)
.map_err(|_| Error::InvalidArgument)?
.0
.listen_queue_obj_id;
let listen = self.presents.queue_poster(listen_queue).map(|ring| {
Arc::new(move |m: &RgfxEventSignalled| ring.try_post(m.as_bytes()))
as ListenSink
});
match decoder.import_shared_event(&rec.bytes, listen) {
Some(v) if v.status == RGFX_STATUS_OK => Ok(()),
other => {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: shared_event_import seq={} obj={:#x} failed: {other:?}",
rec.seq, rec.obj_id
);
Err(Error::HostResources)
}
}
}
_ => match refusing(|| decoder.decode(&self.device, &rec.bytes)) {
Ok(Ok(())) => {
log::debug!(
target: "reims_vgpu::graphics",
"replay_record: seq={} ctx={} type={:#x} obj={:#x} -> Ok",
rec.seq, rec.context, rec.msg_type, rec.obj_id
);
Ok(())
}
Ok(Err(e)) => {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: seq={} ctx={} type={:#x} obj={:#x} decode error: {e:?}",
rec.seq, rec.context, rec.msg_type, rec.obj_id
);
Err(Error::HostResources)
}
Err(raise) => {
log::error!(
target: "reims_vgpu::graphics",
"replay_record: seq={} ctx={} type={:#x} obj={:#x} raised: {raise}",
rec.seq, rec.context, rec.msg_type, rec.obj_id
);
Err(Error::HostResources)
}
},
}
}
fn handle_stage3(
self: &Arc<Self>,
poster: &CompletionPoster,
@@ -3191,7 +2819,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
claim: Option<&mut QueueClaim<'_>>,
) {
let message: &[u8] = &bytes;
self.live_log.record_stage3(sender_context(poster, message), message);
let r#type = RgfxMsgHeader::read_from_prefix(message).map_or(0, |(h, _)| h.r#type);
// A queue's command buffer taken from its ring: the presents' late-show lines keep when
// the host first saw it (`present`).
@@ -4071,10 +3698,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
"library lookup (object {obj_id:#x}, {size} bytes): {}",
if status == RGFX_STATUS_OK { "hit" } else { "miss" }
);
if status == RGFX_STATUS_OK {
self.live_log
.record_library_lookup(sender_context(poster, message), message);
}
if let Some(seqno) = seqno {
poster.post(complete(seqno, status).as_bytes());
}
@@ -4584,15 +4207,7 @@ impl<P: ApiPlatform> GraphicsControl<P> {
.prepare_library(message)
});
let job = match start {
LibraryStart::Make(job) => {
self.live_log.record_library(
sender_context(poster, message),
job.obj_id,
job.bytes.clone(),
job.guest_key,
);
job
}
LibraryStart::Make(job) => job,
LibraryStart::Chunk => return,
LibraryStart::Refused { error, answer } => {
let (ty, seqno, obj_id) = message_identity(message);
@@ -4665,7 +4280,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
return;
};
if iosurface_id == 0 {
self.live_log.record_present(display, 0);
let color = staging.lock().take();
self.presents
.present(display, 0, None, color, answer, Vec::new(), None);
@@ -4697,7 +4311,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
owner,
queued,
}) => {
self.live_log.record_present(display, iosurface_id);
// The process that made the texture over the surface the display shows owns the
// scanout (WindowServer): its compiles go first.
self.pool.favour(owner);
@@ -4779,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
@@ -4933,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(
@@ -5241,7 +4852,6 @@ fn vt_decoders(caps: &RgfxVideoCaps) -> Vec<paravirt::Decoder> {
/// gate's ([`reims_vgpu_vulkan::exit_gate`]): the process's exit waits for it, and one called
/// once the exit began parks its thread for good, on any thread but the exiting one (as an entry
/// does, [`entry`]'s module doc).
#[track_caller]
fn stepped<T>(f: impl FnOnce() -> T) -> T {
let Some(_step) = reims_vgpu_vulkan::exit_gate::step() else {
reims_vgpu_vulkan::exit_gate::stay()
@@ -5775,35 +5385,19 @@ impl Screen for WindowScreen {
/// draw).
fn mode(&self) -> Mode {
let drawn = *self.shown.drawable.lock();
let fixed = reims_vgpu_window::env::settings().fixed_mode;
let offered = self
.window
.offered()
.map(|(w, h)| (u64::from(w), u64::from(h)));
let raw = if fixed {
offered
.or_else(|| drawn.map(|d| d.pixels))
.unwrap_or((1920, 1080))
} else {
drawn.map_or_else(|| offered.unwrap_or((1920, 1080)), |d| d.pixels)
};
let (width, height) = geometry::offered_mode(raw);
let (width, height) = geometry::offered_mode(drawn.map_or_else(
|| {
let (w, h) = self.window.offered().unwrap_or((1920, 1080));
(u64::from(w), u64::from(h))
},
|d| d.pixels,
));
let clamp = |v: u64| u32::try_from(v.max(1)).unwrap_or(u32::MAX);
let clamped_w = clamp(width);
let clamped_h = clamp(height);
let scale_120ths = drawn.map_or(0, |d| {
let eff = if fixed && d.pixels.0 > 0 {
d.scale * (f64::from(clamped_w) / f64::from(clamp(d.pixels.0)))
} else {
d.scale
};
scale_in_120ths(eff)
});
Mode {
width: clamped_w,
height: clamped_h,
width: clamp(width),
height: clamp(height),
refresh_mhz: self.refresh_mhz,
scale_120ths,
scale_120ths: drawn.map_or(0, |d| scale_in_120ths(d.scale)),
}
}
+4 -13
View File
@@ -582,17 +582,6 @@ impl CompilePool {
self.close();
}
/// Waits until all queued and running compile jobs have finished.
pub(crate) fn wait_idle(&self) {
let mut state = self.shared.state.lock();
while state.waiting() > 0
|| state.running.values().copied().sum::<usize>() > 0
|| state.prepasses_running > 0
{
self.shared.waiting.wait(&mut state);
}
}
/// Ends the threads once nothing waits; later compiles run where they are handed over.
fn close(&self) {
self.shared.state.lock().closed = true;
@@ -683,8 +672,10 @@ fn run(shared: &Shared, queued: Queued) {
ms(ended.saturating_duration_since(started)),
);
shared.state.lock().ended(of.context(), of.kind);
// Wake waiters (pre-pass limit or snapshot quiesce wait_idle).
shared.waiting.notify_all();
// A thread that found the pre-passes' makes at their most may take the next now.
if of.kind == CompileKind::Prepass {
shared.waiting.notify_one();
}
reims_vgpu_vulkan::os::make_ended(ended.saturating_duration_since(started));
}
@@ -402,9 +402,9 @@ pub(crate) struct LibraryJob<P: Platform> {
pub(crate) obj_id: u64,
/// The create's seqno, which its `COMPLETE` carries.
pub(crate) seqno: u64,
pub(crate) bytes: Vec<u8>,
bytes: Vec<u8>,
/// The key the guest sent with the bytes.
pub(crate) guest_key: Option<LibraryKey>,
guest_key: Option<LibraryKey>,
slot: Arc<LibrarySlot<P>>,
/// The device's resets when it was prepared.
resets: u64,
@@ -697,29 +697,6 @@ impl<P: Platform> GraphicsDecoder<P> {
})
}
/// Prepares a [`LibraryJob`] directly from snapshotted library bytes for silent replay.
pub(crate) fn prepare_library_bytes(
&self,
obj_id: u64,
bytes: Vec<u8>,
guest_key: Option<LibraryKey>,
) -> LibraryJob<P> {
let slot = LibrarySlot::new();
let resets = {
let mut libraries = self.shared.libraries.lock();
libraries.making.insert(obj_id, Arc::clone(&slot));
libraries.resets
};
LibraryJob {
obj_id,
seqno: 0,
bytes,
guest_key,
slot,
resets,
}
}
/// One `LIBRARY_FROM_REGION` chunk: its bytes are copied out once (so the platform parses
/// memory the guest cannot change under it), its ack is written so the guest may reuse the
/// block, and the library's whole bytes are handed back once the chunks reach its length. A
@@ -220,7 +220,6 @@ mod helpers;
mod icb;
mod lane;
mod library;
pub(crate) use library::whole_key as whole_library_key;
mod managed;
mod pipeline_key;
pub(crate) mod prepass;
@@ -265,7 +264,6 @@ pub(crate) use library::verified_key as test_key;
#[cfg(test)]
pub(crate) use library::whole_key as test_whole_key;
use library::{Libraries, LibraryRef};
pub(crate) use library::LibraryKey;
pub(crate) use library::{LibraryJob, LibraryStart, MadeLibrary, complete, make_library};
use managed::{STORAGE_MODE_MANAGED, storage_mode};
pub(crate) use pipeline_key::PipelineKey;
@@ -610,16 +608,6 @@ fn new_sampler<P: Platform>(
/// A host handle for one guest object, by kind. Later increments read these to
/// bind resources into command buffers; this slice only inserts them on a create
/// and drops them on a destroy.
/// Live dynamic values captured from active GPU objects during a snapshot.
#[derive(Clone, Debug, Default)]
pub(crate) struct LiveValues {
pub(crate) events: Vec<(u64, u64)>,
pub(crate) shared_events: Vec<(u64, u64)>,
pub(crate) buffers: Vec<(u64, Vec<u8>)>,
pub(crate) textures: Vec<(u64, Vec<u8>)>,
pub(crate) surface_caches: Vec<(u64, Vec<u8>)>,
}
enum ObjHandle<P: Platform> {
Event(P::Event),
Fence(P::Fence),
@@ -3550,285 +3538,6 @@ impl<P: Platform> GraphicsDecoder<P> {
}
/// The objects the tables hold (for the tests).
/// Flushes all background decoder workers (surface, let-go, close, video) for quiesce.
pub(crate) fn flush_workers(&self) {
self.shared.surface_worker.flush();
self.shared.close_worker.flush();
self.shared.let_go_worker.flush();
self.shared.video_worker.flush();
}
/// Synchronously downloads every live device-cached IOSurface back to Guest RAM.
pub(crate) fn flush_all_surface_caches(&self, device: &P::Device) {
use reims_vgpu_vulkan::core::sync::Condvar;
let blocks = self.surface_caches.attached_live_blocks();
for block in blocks {
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let p_done = Arc::clone(&pair);
let p_fail = Arc::clone(&pair);
self.surface_download(
device,
block,
Box::new(move || {
*p_done.0.lock() = true;
p_done.1.notify_all();
}),
Box::new(move |_| {
*p_fail.0.lock() = true;
p_fail.1.notify_all();
}),
);
let mut done = pair.0.lock();
while !*done {
pair.1.wait(&mut done);
}
}
}
/// Exports the resource-ID small-chunk grant table (0 = ungranted, ctx + 1 = granted to ctx).
pub(crate) fn export_id_chunks(&self) -> Vec<u32> {
self.shared
.id_chunks
.lock()
.iter()
.map(|c| c.map_or(0, |ctx| ctx.wrapping_add(1)))
.collect()
}
/// Restores the resource-ID small-chunk grant table.
pub(crate) fn import_id_chunks(&self, chunks: &[u32]) {
let mut guard = self.shared.id_chunks.lock();
let n = guard.len().min(chunks.len());
for i in 0..n {
guard[i] = if chunks[i] == 0 {
None
} else {
Some(chunks[i].wrapping_sub(1))
};
}
}
/// Replays a `SURFACE_PAGES` registration synchronously without sending a wire reply.
/// Restores pre-suspend seqno watermarks for a restored command queue.
pub(crate) fn restore_queue_watermark(&self, queue: u64, seqno: u64) {
self.shared
.surface_order
.lock()
.restore_queue_watermark(queue, seqno);
}
pub(crate) fn replay_surface_pages(
&self,
device: &P::Device,
pages: &reims_vgpu_graphics::wire::RgfxSurfacePages,
runs: &[reims_vgpu_graphics::wire::RgfxPageRun],
flags: u32,
layout: Option<reims_vgpu_graphics::wire::RgfxSurfacePagesLayout>,
) -> Result<(), &'static str> {
let settle = self.begin_surface_pages(pages.block_offset);
let status = self.carry_out_surface_pages(device, pages, runs, flags, layout, &settle);
drop(settle);
match status {
Some(RGFX_STATUS_OK | RGFX_STATUS_CACHE) => Ok(()),
other => {
log::error!(
target: "reims_vgpu::graphics",
"snapshot replay: SURFACE_PAGES block {:#x} failed with status={other:?}",
pages.block_offset
);
Err("surface_pages replay failed")
}
}
}
/// Exports live GPU values (Events, SharedEvents, standalone Buffers & Textures) while quiesced.
pub(crate) fn export_live_values(
&self,
device: &P::Device,
known_ranges: &[(u64, u64)],
standalone_tex_ids: &std::collections::HashSet<u64>,
) -> Result<LiveValues, &'static str> {
let mut values = LiveValues::default();
let mut first_err: Option<&'static str> = None;
let mut contexts: Vec<Arc<Context<P>>> =
self.shared.contexts.lock().values().cloned().collect();
contexts.sort_by_key(|c| c.id);
let in_known = |addr: u64| -> bool {
addr != 0
&& known_ranges
.iter()
.any(|&(base, len)| addr >= base && addr < base.saturating_add(len))
};
for ctx in contexts {
ctx.for_each_live(|id, entry| {
if first_err.is_some() {
return;
}
match &entry.handle {
ObjHandle::Event(ev) => {
let val = device.event_signaled_value(ev);
if val > 0 {
values.events.push((id, val));
}
}
ObjHandle::SharedEvent(se) => {
let val = se.signaled_value();
if val > 0 {
values.shared_events.push((id, val));
}
}
ObjHandle::Buffer(buf) => {
if entry.span.is_none()
&& entry.ram.is_none()
&& !entry.over_cache
&& !entry.over_view
&& !in_known(buf.gpu_address())
{
match device.read_standalone_buffer(buf) {
Ok(Some(bytes)) => values.buffers.push((id, bytes)),
Ok(None) => {}
Err(e) => {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_save: buffer {id:#x} readback failed: {e}"
);
first_err = Some(e);
}
}
}
}
ObjHandle::Texture(tex) => {
let is_deferred_cache = (entry.over_cache || entry.shape.is_some())
&& !entry.over_view
&& entry
.span
.is_some_and(|(at, _)| self.surface_caches.lock().has(at));
let is_standalone = standalone_tex_ids.contains(&id)
&& !entry.over_cache
&& !entry.over_view;
if is_standalone || is_deferred_cache {
match device.read_standalone_texture(tex) {
Ok(Some(bytes)) => values.textures.push((id, bytes)),
Ok(None) => {}
Err(e) => {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_save: texture {id:#x} readback failed: {e}"
);
first_err = Some(e);
}
}
}
}
_ => {}
}
});
if let Some(e) = first_err {
return Err(e);
}
}
values.surface_caches = self.surface_caches.export_unattached(device)?;
Ok(values)
}
/// Restores live GPU values onto objects previously replayed into the decoder tables.
pub(crate) fn import_live_values(
&self,
device: &P::Device,
values: &LiveValues,
) -> Result<(), &'static str> {
for &(id, val) in &values.events {
let ctx = self
.context_state(context_of(id))
.ok_or("snapshot_load: missing context for event")?;
let ok = ctx
.with_live(id, |entry| match &entry.handle {
ObjHandle::Event(ev) => device.event_restore_signaled_value(ev, val),
_ => false,
})
.unwrap_or(false);
if !ok {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_load: failed to restore event {id:#x} value={val}"
);
return Err("snapshot_load: event value restore failed");
}
}
for &(id, val) in &values.shared_events {
let ctx = self
.context_state(context_of(id))
.ok_or("snapshot_load: missing context for shared event")?;
let ok = ctx
.with_live(id, |entry| match &entry.handle {
ObjHandle::SharedEvent(se) => se.set_signaled_value(val).is_ok(),
_ => false,
})
.unwrap_or(false);
if !ok {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_load: failed to restore shared event {id:#x} value={val}"
);
return Err("snapshot_load: shared event value restore failed");
}
}
for (id, bytes) in &values.buffers {
let ctx = self
.context_state(context_of(*id))
.ok_or("snapshot_load: missing context for buffer")?;
let ok = ctx
.with_live(*id, |entry| match &entry.handle {
ObjHandle::Buffer(buf) => device.write_standalone_buffer(buf, bytes),
_ => false,
})
.unwrap_or(false);
if !ok {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_load: failed to restore buffer {id:#x} ({} bytes)",
bytes.len()
);
return Err("snapshot_load: buffer upload failed");
}
}
self.surface_caches
.import_unattached(device, &values.surface_caches)?;
for (id, bytes) in &values.textures {
let ctx = self
.context_state(context_of(*id))
.ok_or("snapshot_load: missing context for texture")?;
let ok = ctx
.with_live(*id, |entry| match &entry.handle {
ObjHandle::Texture(tex) => {
if !device.write_standalone_texture(tex, bytes) {
return false;
}
if let Some((block, _)) = entry.span
&& (entry.over_cache || entry.shape.is_some())
{
let shape_id = entry.shape.as_ref().map(|s| s.reference.id());
self.surface_caches
.lock()
.mark_restored_texture(block, shape_id);
}
true
}
_ => false,
})
.unwrap_or(false);
if !ok {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_load: failed to restore texture {id:#x} ({} bytes)",
bytes.len()
);
return Err("snapshot_load: texture upload failed");
}
}
Ok(())
}
#[cfg(any(test, feature = "testkit"))]
pub fn object_count(&self) -> usize {
let contexts: Vec<Arc<Context<P>>> =
@@ -6830,11 +6539,6 @@ impl<P: Platform> CompiledPipeline<P> {
}
}
/// Whether compilation produced a live pipeline handle (not refused).
pub(crate) fn is_made(&self) -> bool {
self.handle.is_some()
}
/// A made pipeline and its reflection.
fn made(obj_id: u64, handle: ObjHandle<P>, reflection: RgfxPipelineReflection) -> Self {
CompiledPipeline {
@@ -3589,18 +3589,6 @@ impl<P: Platform> SurfaceCaches<P> {
.map(|c| c.length)
}
/// Marks a deferred cache (and optional shape) as populated after snapshot texture restore.
pub(crate) fn mark_restored_texture(&mut self, block: u64, shape_id: Option<u64>) {
if let Some(cache) = self.by_block.get_mut(&block) {
cache.written = true;
cache.first_fill = None;
cache.zeros = false;
if let Some(id) = shape_id {
cache.shapes.mark_restored(id);
}
}
}
/// The cache of the block `m` names where the block has no view: a deferred block's while its
/// pages are not named, or where they are copied, and a cache made with its pages copied
/// ([`Caches::make_copied`]); where the block's size holds the `m.block_size` bytes `m` names
@@ -8349,171 +8337,6 @@ impl<P: Platform> Caches<P> {
/// `trace`: `done` once the pages hold the cache, or `failed` where the platform raised at
/// the copy.
#[allow(clippy::too_many_arguments)] // the download's, and its trace
/// Returns all currently tracked surface cache block offsets for pre-snapshot flushing.
pub(crate) fn attached_live_blocks(&self) -> Vec<u64> {
self.lock()
.by_block
.iter()
.filter(|(_, c)| c.pages.is_some())
.map(|(&block, _)| block)
.collect()
}
/// Exports GPU buffer contents for deferred IOSurface device caches whose guest pages
/// are not named (`pages.is_none()`), flushing any dirty per-shape textures into the
/// cache's backing buffer first so VA-API decoded video frames and unattached WindowServer
/// surfaces survive suspend/resume intact.
pub(crate) fn export_unattached(
&self,
device: &P::Device,
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
let need_mem: Vec<P::Buffer> = {
let state = self.lock();
state
.by_block
.values()
.filter(|c| {
c.pages.is_none()
&& !c.device.memory_made()
&& c.shapes.iter().any(|s| s.dirty)
})
.map(|c| c.device.clone_ref())
.collect()
};
self.make_memory(need_mem, MemoryFor::WriteBack);
let mut flushed_any = false;
{
let mut state = self.lock();
let dirty_blocks: Vec<u64> = state
.by_block
.iter()
.filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty))
.map(|(&b, _)| b)
.collect();
if !dirty_blocks.is_empty() {
if !state
.make_transfer(device)
.map_err(|_| "snapshot_save: surface cache transfer init failed")?
{
return Err("snapshot_save: surface cache transfer queue unavailable");
}
for block in dirty_blocks {
let cb_opt = {
let transfer = state
.transfer
.as_mut()
.ok_or("snapshot_save: surface cache transfer missing")?;
transfer
.queue
.command_buffer(ON)
.map_err(|_| "snapshot_save: surface cache command buffer failed")?
};
let Some(cb) = cb_opt else {
return Err("snapshot_save: surface cache command buffer unavailable");
};
let Some(cache) = state.by_block.get_mut(&block) else {
continue;
};
if !cache.copy_through(MemoryFor::WriteBack) {
return Err("snapshot_save: deferred surface cache allocation failed");
}
let back = shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| {
s.dirty
})
.map_err(|_| "snapshot_save: surface cache shape write_back failed")?;
cache.wrote_shapes(&back);
state.owed_commits.push(cb);
flushed_any = true;
}
}
}
if flushed_any {
device.wait_idle();
}
let mut to_read: Vec<(u64, P::Buffer)> = {
let state = self.lock();
state
.by_block
.iter()
.filter(|(_, c)| c.pages.is_none() && c.device.memory_made())
.map(|(&block, c)| (block, c.device.clone_ref()))
.collect()
};
to_read.sort_by_key(|(block, _)| *block);
let mut out = Vec::with_capacity(to_read.len());
for (block, buf) in to_read {
match device.read_standalone_buffer(&buf)? {
Some(bytes) => out.push((block, bytes)),
None => return Err("snapshot_save: unattached surface cache buffer unreadable"),
}
}
Ok(out)
}
/// Restores GPU buffer contents for deferred unattached IOSurface device caches.
pub(crate) fn import_unattached(
&self,
device: &P::Device,
entries: &[(u64, Vec<u8>)],
) -> Result<(), &'static str> {
if entries.is_empty() {
return Ok(());
}
let targets: Vec<(u64, P::Buffer)> = {
let state = self.lock();
let mut out = Vec::with_capacity(entries.len());
for (block, _) in entries {
let cache = state
.by_block
.get(block)
.ok_or("snapshot_load: missing unattached surface cache")?;
out.push((*block, cache.device.clone_ref()));
}
out
};
let need_mem: Vec<P::Buffer> = targets
.iter()
.filter(|(_, b)| !b.memory_made())
.map(|(_, b)| b.clone_ref())
.collect();
self.make_memory(need_mem, MemoryFor::Fill);
for ((block, buf), (_, bytes)) in targets.iter().zip(entries.iter()) {
if !buf.memory_made() {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_load: failed to allocate memory for unattached surface cache {block:#x}"
);
return Err("snapshot_load: surface cache memory allocation failed");
}
if !device.write_standalone_buffer(buf, bytes) {
log::error!(
target: "reims_vgpu::graphics",
"snapshot_load: failed to upload unattached surface cache {block:#x} ({} bytes)",
bytes.len()
);
return Err("snapshot_load: surface cache upload failed");
}
}
let mut state = self.lock();
for (block, _) in entries {
if let Some(cache) = state.by_block.get_mut(block) {
let _ = cache.copy_through(MemoryFor::Fill);
cache.written = true;
cache.first_fill = None;
cache.zeros = false;
cache.lacks = false;
cache.changed = Changed::All;
cache.shapes.mark_owed_all();
}
}
Ok(())
}
pub(crate) fn download(
&self,
device: &P::Device,
@@ -914,23 +914,6 @@ impl<T> ShapeTable<T> {
shape.map(|s| s.dirty = true).is_some()
}
/// Marks a shape whose pixels were directly uploaded during snapshot restore as valid & dirty.
pub(crate) fn mark_restored(&mut self, id: u64) {
if let Some(s) = self.shapes.iter_mut().find(|s| s.id() == id) {
s.owed = false;
s.dirty = true;
s.cleared = false;
}
}
pub(crate) fn mark_owed_all(&mut self) {
for s in &mut self.shapes {
s.owed = true;
s.cleared = false;
s.clean();
}
}
/// A video command buffer wrote the buffer, its decodes' pictures, not the images: every
/// shape owes a fill from it, its own write before the buffer's lost (the decode writes its
/// planes whole, and a write it does not cover was copied into the buffer before it ran);
@@ -292,17 +292,6 @@ impl Marks {
self.done.load(Ordering::Acquire),
)
}
/// Advances all per-queue watermarks to `seqno` after snapshot restore (all pre-suspend work
/// finished during quiesce).
pub(crate) fn restore_watermark(&self, seqno: u64) {
self.taken.fetch_max(seqno, Ordering::SeqCst);
self.signalled.fetch_max(seqno, Ordering::SeqCst);
self.committed.fetch_max(seqno, Ordering::SeqCst);
self.done.fetch_max(seqno, Ordering::SeqCst);
self.commit.begin(seqno);
self.commit.raise(seqno);
}
}
/// A signal a command buffer carries: its queue's `done` rises to `seqno` once it finishes.
@@ -873,19 +862,6 @@ impl<P: Platform> SurfaceOrder<P> {
q.buffers = Some(buffers);
}
/// Restores a queue's commit/surface-order watermarks and timeline event value after snapshot load.
pub(crate) fn restore_queue_watermark(&mut self, queue: u64, seqno: u64) {
if seqno == 0 {
return;
}
if let Some(q) = self.queues.get(&queue) {
q.marks.restore_watermark(seqno);
if let Some(ev) = &q.event {
let _ = ev.set_signaled_value(seqno);
}
}
}
/// What a removal from context `context`'s table waits for before its entry is let go of
/// ([`super::tables`], "After the buffers posted before it"): each queue of the context the
/// decoder made and that has not ended, whose ring published a command buffer its commit mark
-10
View File
@@ -272,16 +272,6 @@ impl<P: Platform> PresentQueue<P> {
self.state.lock().queues.insert(queue, poster);
}
/// Advances the finished watermark for a restored queue so pre-suspend surface writers never stall.
pub(crate) fn restore_finished(&self, queue: u64, seqno: u64) {
if seqno == 0 {
return;
}
let mut st = self.state.lock();
let done = st.finished.entry(queue).or_insert(0);
*done = (*done).max(seqno);
}
/// Shows IOSurface `id`'s `texture` (`None`: the scanout) on display `display`, with the
/// colour stages `color` sets, once each command buffer in `writers` has finished, and
/// `fill`, its surface's device cache's fill, where it has one, and every present of the
+3 -86
View File
@@ -239,8 +239,6 @@ pub(crate) struct ScanoutDraw<P: Platform> {
ramps: Mutex<Vec<(u64, P::Texture)>>,
/// The scanout's ramp, made at its first use; `None` inside where the platform refused it.
scanout_ramp: Kept<ScanoutRead<P>>,
/// Staging texture used to GPU-scale a raw scanout whose size differs from the window's image.
scanout_stage: Mutex<Option<P::Texture>>,
/// What draws the guest's cursor where the window draws it (`cursor`): its pipelines and its
/// glyph's texture, made at their first use.
cursor: Mutex<CursorPass<P>>,
@@ -570,7 +568,6 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
color_table: Mutex::new(None),
ramps: Mutex::default(),
scanout_ramp: Kept::new(),
scanout_stage: Mutex::new(None),
cursor: Mutex::new(CursorPass::cursor()),
overlay: Mutex::new(CursorPass::overlay()),
#[cfg(test)]
@@ -610,7 +607,6 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
*self.color_table.lock() = None;
self.ramps.lock().clear();
self.scanout_ramp.forget();
*self.scanout_stage.lock() = None;
*self.cursor.lock() = CursorPass::cursor();
*self.overlay.lock() = CursorPass::overlay();
}
@@ -904,8 +900,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
if let Some((surface, view, hold)) = self.presented.shown() {
let (from, to) = (surface.pixel_format(), texture.pixel_format());
self.presented.seen_format(from, to);
let same_size = surface.width() == region.width && surface.height() == region.height;
let copied = same_size && BGRA8_FORMATS.contains(&from) && BGRA8_FORMATS.contains(&to);
let copied = BGRA8_FORMATS.contains(&from) && BGRA8_FORMATS.contains(&to);
let drawn = if color.is_none() && copied {
self.encode_surface(&surface, texture, region)
} else {
@@ -1468,15 +1463,6 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
fn encode_scanout(&self, texture: &P::Texture, region: PixelRect) -> Option<P::CommandBuffer> {
let scanout = (*self.shown.scanout.lock())?;
let (buffer, source_offset) = self.scanout_buffer(&scanout)?;
let (sw, sh) = (u64::from(scanout.width), u64::from(scanout.height));
if sw > 0
&& sh > 0
&& (sw != region.width || sh != region.height)
&& let Some(cb) =
self.encode_scanout_scaled(&scanout, &buffer, source_offset, texture, region)
{
return Some(cb);
}
let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?;
let (texture_width, texture_height) = (texture.width(), texture.height());
let x = region.x.min(texture_width);
@@ -1583,62 +1569,6 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
})
}
/// Stages `scanout` into a `BGRA8Unorm` texture and scales it into `texture` at `region` via
/// the linear-filtered display present shader (used when guest mode != window pixels, e.g.
/// `REIMS_VGPU_WINDOW_FIXED_MODE=1` during boot/Recovery).
fn encode_scanout_scaled(
&self,
scanout: &Scanout,
buffer: &P::Buffer,
source_offset: u64,
texture: &P::Texture,
region: PixelRect,
) -> Option<P::CommandBuffer> {
let (sw, sh) = (u64::from(scanout.width), u64::from(scanout.height));
let stage = {
let mut slot = self.scanout_stage.lock();
let reuse = slot
.as_ref()
.is_some_and(|t| t.width() == sw && t.height() == sh);
if !reuse {
let desc = self.platform.texture_descriptor(&TextureDesc {
pixel_format: 80,
width: sw,
height: sh,
usage: RAMP_USAGE,
resource_options: Some(PRIVATE),
..TextureDesc::default()
});
let made = no_catch(self.device.new_texture(OnFault::Die, &desc))?;
*slot = Some(made);
}
slot.as_ref()?.clone_ref()
};
let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?;
let blit = Open::new(
no_catch(command_buffer.blit_encoder(OnFault::Die))?,
end_blit::<P>,
);
let stride = u64::from(scanout.stride);
no_catch(blit.get().encode(
OnFault::Die,
BlitCmd::CopyBufferToTexture {
source_buffer: buffer,
source_offset,
source_bytes_per_row: stride,
source_bytes_per_image: stride * sh,
source_size: MtlSize::new(sw, sh, 1),
destination_texture: &stage,
destination_slice: 0,
destination_level: 0,
destination_origin: MtlOrigin::new(0, 0, 0),
},
));
blit.end();
self.encode_converted_into(&command_buffer, &stage, texture, region)?;
Some(command_buffer)
}
/// A command buffer of the sink's queue with the presented `surface` drawn into `texture` at
/// `region` by the display's present shaders, which convert its format to the drawable's,
/// after a clear of the drawable to black where `region` does not cover it ([`pass_load`]);
@@ -1650,25 +1580,12 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
texture: &P::Texture,
region: PixelRect,
) -> Option<P::CommandBuffer> {
let command_buffer = self.surface_command_buffer()?;
self.encode_converted_into(&command_buffer, surface, texture, region)?;
Some(command_buffer)
}
/// Encodes the linear-filtered display present shader drawing `surface` into `texture` at
/// `region` on `command_buffer`.
fn encode_converted_into(
&self,
command_buffer: &P::CommandBuffer,
surface: &P::Texture,
texture: &P::Texture,
region: PixelRect,
) -> Option<()> {
let converter = self.converter()?;
let pipeline = converter.pipelines.pipeline_for(PipelineKey {
format: texture.pixel_format(),
gamma: false,
})?;
let command_buffer = self.surface_command_buffer()?;
let (texture_width, texture_height) = (texture.width(), texture.height());
let x = region.x.min(texture_width);
let y = region.y.min(texture_height);
@@ -1740,7 +1657,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
}
}
encoder.end();
Some(())
Some(command_buffer)
}
/// Clears all of `texture` to opaque black, in a render pass of `command_buffer` with no
File diff suppressed because it is too large. Load diff
+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();
-203
View File
@@ -85,7 +85,6 @@
mod addresses;
mod host_blocks;
mod private_blocks;
pub(crate) use private_blocks::{PrivateBlockSnapshot, PrivateBlocksSnapshot};
mod rt_blocks;
mod takes;
@@ -310,47 +309,6 @@ pub enum BlockError {
/// Where the pool's blocks come from (metal2vulkan-runtime's `Device::take_block` and
/// `release_block`).
/// Capture/replay address metadata for a pool or private block.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockCapture {
pub class: MemoryClass,
pub alloc_len: u64,
pub offset: u64,
pub len: u64,
pub gpu_address: u64,
pub opaque_buffer_address: u64,
pub opaque_memory_address: u64,
}
/// Snapshot of a single live Shared Pool piece mapped into Guest GPA.
#[derive(Clone, Debug)]
pub struct PoolPieceSnapshot {
pub gpa: u64,
pub len: u64,
pub gpu_address: u64,
pub capture: Option<BlockCapture>,
pub bytes: Vec<u8>,
}
/// Snapshot of a context's carved sub-block inside a Shared Pool piece.
#[derive(Clone, Debug)]
pub struct PoolCarveSnapshot {
pub gpa: u64,
pub context: u32,
pub len: u64,
pub serial: u64,
pub gpu_address: u64,
pub picked_address: bool,
}
/// Complete snapshot of the Shared Pool.
#[derive(Clone, Debug, Default)]
pub struct PoolSnapshot {
pub serial: u64,
pub pieces: Vec<PoolPieceSnapshot>,
pub carves: Vec<PoolCarveSnapshot>,
}
pub trait BlockSource: Send + Sync {
/// A block of `class` at least `len` long ([`BlockInfo::len`]). Waits only when no block is
/// ready.
@@ -359,27 +317,6 @@ pub trait BlockSource: Send + Sync {
/// any more: it goes back to the ready set, with its id, address and host mapping, or is
/// freed.
fn release_block(&self, block: BlockId) -> Result<(), BlockError>;
/// Returns capture/replay metadata for a live block, if supported.
fn capture_block(&self, _block: BlockId) -> Option<BlockCapture> {
None
}
/// Replays a previously captured block at its exact Vulkan device address.
fn take_block_replayed(&self, _cap: BlockCapture) -> Result<BlockInfo, BlockError> {
Err(BlockError::OutOfMemory)
}
/// Reads back raw VRAM bytes of a Private block (via GPU staging blit).
/// Returns `Ok(None)` when the source has no GPU-backed VRAM (unit-test fakes).
fn read_private_block(&self, _block: BlockId) -> Result<Option<Vec<u8>>, BlockError> {
Ok(None)
}
/// Uploads raw VRAM bytes into a Private block (via GPU staging blit).
fn write_private_block(&self, _block: BlockId, _data: &[u8]) -> Result<(), BlockError> {
Ok(())
}
}
/// The guest physical range the host reserved for the pool, with no RAM under it.
@@ -1150,146 +1087,6 @@ impl Pool {
dead_code,
reason = "the guest's side of the pool (its ring messages) calls it once it lands"
)]
/// Waits until in-flight pool take workers and zeroer are idle.
pub(crate) fn quiesce(&self) {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
loop {
let busy = {
let st = self.shared.state.lock();
st.workers > 0 || st.zeroer || st.serving > 0 || !st.asks.is_empty()
};
if !busy || std::time::Instant::now() >= deadline {
break;
}
std::thread::sleep(Duration::from_millis(2));
}
}
/// Exports all live Shared Pool pieces (with raw bytes & BDA capture metadata) and carves.
pub(crate) fn export_snapshot(&self) -> Result<PoolSnapshot, Error> {
self.quiesce();
let st = self.shared.state.lock();
let source = st.source.clone();
let mut pieces = Vec::new();
for (&gpa, p) in &st.pieces {
if !matches!(p.mapped, Mapped::Live | Mapped::Adding) {
continue;
}
let cap = source.as_ref().and_then(|s| s.capture_block(p.block.id));
let ptr = p.block.contents.ok_or(Error::HostResources)?;
let bytes = unsafe {
std::slice::from_raw_parts(ptr.as_ptr(), p.block.len as usize).to_vec()
};
pieces.push(PoolPieceSnapshot {
gpa,
len: p.block.len,
gpu_address: p.block.gpu_address,
capture: cap,
bytes,
});
}
let carves = takes::export_carves(&st.carves);
Ok(PoolSnapshot {
serial: st.serial,
pieces,
carves,
})
}
/// Restores Shared Pool pieces at their exact GPAs and Vulkan BDAs, and asks host to map them.
pub(crate) fn import_snapshot(&self, snap: &PoolSnapshot) -> Result<(), Error> {
self.quiesce();
let source = {
let st = self.shared.state.lock();
st.source.clone()
};
let Some(source) = source else {
return if snap.pieces.is_empty() {
Ok(())
} else {
Err(Error::HostResources)
};
};
// First release any pre-existing empty pieces if any (fresh device has none).
let mut restored_pieces: Vec<(u64, BlockInfo)> = Vec::with_capacity(snap.pieces.len());
for ps in &snap.pieces {
let blk = if let Some(cap) = ps.capture {
source
.take_block_replayed(cap)
.map_err(|_| Error::HostResources)?
} else {
source
.take_block(MemoryClass::Shared, ps.len)
.map_err(|_| Error::HostResources)?
};
let ptr = blk.contents.ok_or(Error::HostResources)?;
if ps.bytes.len() as u64 != blk.len {
return Err(Error::InvalidArgument);
}
unsafe {
std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len());
}
restored_pieces.push((ps.gpa, blk));
}
{
let mut st = self.shared.state.lock();
st.serial = st.serial.max(snap.serial);
for (gpa, blk) in &restored_pieces {
let piece_carves = snap
.carves
.iter()
.filter(|c| c.gpa >= *gpa && c.gpa < *gpa + blk.len)
.count() as u64;
st.by_block.insert(blk.id, *gpa);
st.pieces.insert(
*gpa,
Piece {
block: *blk,
mapped: Mapped::Adding,
empty_since: if piece_carves == 0 {
Some((self.shared.now)())
} else {
None
},
holds: 0,
kept: Arc::new(()),
carves: piece_carves,
zeros: takes::Ranges::new(),
zero_pending: false,
going: None,
},
);
}
let state = &mut *st;
takes::import_carves(&mut state.carves, &mut state.addresses, &snap.carves);
}
for (gpa, blk) in &restored_pieces {
if let Some(ptr) = blk.contents {
(self.shared.host.add)(*gpa, ptr.as_ptr(), blk.len);
}
}
self.shared.wake();
Ok(())
}
/// Re-copies snapshotted Shared Pool piece bytes after LiveLog replay (so any `new_buffer`
/// zero-initialization during replay cannot clobber saved guest/GPU contents).
pub(crate) fn restore_bytes(&self, snap: &PoolSnapshot) -> Result<(), Error> {
let st = self.shared.state.lock();
for ps in &snap.pieces {
let piece = st.pieces.get(&ps.gpa).ok_or(Error::HostResources)?;
let ptr = piece.block.contents.ok_or(Error::HostResources)?;
if ps.bytes.len() as u64 != piece.block.len {
return Err(Error::InvalidArgument);
}
unsafe {
std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len());
}
}
Ok(())
}
#[cfg(any(test, feature = "testkit"))]
pub fn live(&self) -> Vec<(u64, u64)> {
let st = self.shared.state.lock();
(st.pieces.iter())
@@ -139,24 +139,6 @@ pub(crate) struct HeldRef {
}
/// A context's block.
/// Serializable snapshot of a single Private GPU-address block and its VRAM contents.
#[derive(Clone, Debug)]
pub(crate) struct PrivateBlockSnapshot {
pub(crate) gpu_address: u64,
pub(crate) context: u32,
pub(crate) len: u64,
pub(crate) serial: u64,
pub(crate) capture: Option<super::BlockCapture>,
pub(crate) bytes: Vec<u8>,
}
/// Complete snapshot of all contexts' Private blocks.
#[derive(Clone, Debug, Default)]
pub(crate) struct PrivateBlocksSnapshot {
pub(crate) serial: u64,
pub(crate) blocks: Vec<PrivateBlockSnapshot>,
}
#[derive(Debug)]
struct Held {
context: u32,
@@ -455,128 +437,6 @@ impl PrivateBlocks {
/// The device's reset: every take not yet answered ends unanswered, and every block is freed
/// at once, its objects already dropped.
/// Waits until in-flight private take workers are idle, then exports all held Private blocks + VRAM.
pub(crate) fn export_snapshot(&self) -> Result<PrivateBlocksSnapshot, super::Error> {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
loop {
let busy = {
let st = self.inner.state.lock();
st.takers.values().any(|t| t.busy || !t.jobs.is_empty())
};
if !busy {
break;
}
if std::time::Instant::now() >= deadline {
return Err(super::Error::HostResources);
}
std::thread::sleep(Duration::from_millis(2));
}
let entries: Vec<(u64, u32, u64, u64, Option<BlockId>)> = {
let st = self.inner.state.lock();
st.held
.iter()
.filter(|(_, h)| !h.going)
.map(|(&addr, h)| (addr, h.context, h.len, h.serial, h.block))
.collect()
};
let serial = self.inner.state.lock().serial;
let mut blocks = Vec::with_capacity(entries.len());
for (gpu_address, context, len, bserial, block_id) in entries {
let (capture, bytes) = match (&self.inner.source, block_id) {
(Some(src), Some(bid)) => {
let cap = src.capture_block(bid);
let raw = src
.read_private_block(bid)
.map_err(|_| super::Error::HostResources)?
.unwrap_or_default();
(cap, raw)
}
(Some(_), None) => return Err(super::Error::HostResources),
(None, _) => (None, Vec::new()),
};
blocks.push(PrivateBlockSnapshot {
gpu_address,
context,
len,
serial: bserial,
capture,
bytes,
});
}
Ok(PrivateBlocksSnapshot { serial, blocks })
}
/// Restores Private blocks at their exact Vulkan BDAs and uploads saved VRAM contents.
pub(crate) fn import_snapshot(&self, snap: &PrivateBlocksSnapshot) -> Result<(), super::Error> {
let mut restored = Vec::with_capacity(snap.blocks.len());
for b in &snap.blocks {
let block_id = if let Some(src) = &self.inner.source {
let info = if let Some(cap) = b.capture {
src.take_block_replayed(cap)
.map_err(|_| super::Error::HostResources)?
} else {
src.take_block(MemoryClass::Private, b.len)
.map_err(|_| super::Error::HostResources)?
};
Some(info.id)
} else {
None
};
restored.push((b, block_id));
}
let mut st = self.inner.state.lock();
st.serial = st.serial.max(snap.serial);
st.held.clear();
for (b, block_id) in restored {
st.held.insert(
b.gpu_address,
Held {
context: b.context,
len: b.len,
serial: b.serial,
going: false,
block: block_id,
},
);
}
Ok(())
}
/// Uploads snapshotted Private Block VRAM bytes after LiveLog object replay (so `new_buffer`
/// zeroing during replay never clobbers restored Private VRAM).
pub(crate) fn restore_bytes(&self, snap: &PrivateBlocksSnapshot) -> Result<(), super::Error> {
let Some(src) = &self.inner.source else {
if snap.blocks.iter().any(|b| !b.bytes.is_empty()) {
return Err(super::Error::HostResources);
}
return Ok(());
};
let ids: Vec<(BlockId, &[u8])> = {
let st = self.inner.state.lock();
let mut out = Vec::with_capacity(snap.blocks.len());
for b in &snap.blocks {
if b.bytes.is_empty() {
continue;
}
let held = st
.held
.get(&b.gpu_address)
.ok_or(super::Error::HostResources)?;
if b.bytes.len() as u64 != held.len {
return Err(super::Error::InvalidArgument);
}
let id = held.block.ok_or(super::Error::HostResources)?;
out.push((id, b.bytes.as_slice()));
}
out
};
for (id, bytes) in ids {
src.write_private_block(id, bytes)
.map_err(|_| super::Error::HostResources)?;
}
Ok(())
}
pub(crate) fn reset(&self) {
let (released, ended) = {
let mut state = self.inner.state.lock();
+1 -148
View File
@@ -42,7 +42,7 @@ use parking_lot::Mutex;
use reims_vgpu_vulkan::core::trace;
use reims_vgpu_vulkan::rt_platform::{RtDevice, RtObj};
use super::{BlockCapture, BlockError, BlockId, BlockInfo, BlockSource, MemoryClass};
use super::{BlockError, BlockId, BlockInfo, BlockSource, MemoryClass};
/// The pool's blocks from an rt device, with the handle of each one handed out.
pub(crate) struct RtBlocks {
@@ -144,153 +144,6 @@ impl BlockSource for RtBlocks {
// be; rt drops the handle all the same.
(self.device.rt().release_block(handle)).map_err(|_| BlockError::NotHeld)
}
fn capture_block(&self, block: BlockId) -> Option<BlockCapture> {
let held = self.held.lock();
let h = held.get(&block)?;
let cap = h.capture_info()?;
Some(BlockCapture {
class: match cap.class {
rt::MemoryClass::Private => MemoryClass::Private,
rt::MemoryClass::Shared => MemoryClass::Shared,
},
alloc_len: cap.alloc_len,
offset: cap.offset,
len: cap.len,
gpu_address: cap.gpu_address,
opaque_buffer_address: cap.opaque_buffer_address,
opaque_memory_address: cap.opaque_memory_address,
})
}
fn take_block_replayed(&self, cap: BlockCapture) -> Result<BlockInfo, BlockError> {
let rt_cap = rt::BlockCaptureInfo {
class: match cap.class {
MemoryClass::Private => rt::MemoryClass::Private,
MemoryClass::Shared => rt::MemoryClass::Shared,
},
alloc_len: cap.alloc_len,
offset: cap.offset,
len: cap.len,
gpu_address: cap.gpu_address,
opaque_buffer_address: cap.opaque_buffer_address,
opaque_memory_address: cap.opaque_memory_address,
};
let block = self
.device
.rt()
.take_block_replayed(rt_cap)
.map_err(|_| BlockError::OutOfMemory)?;
let Some(gpu_address) = block.gpu_address else {
let _ = self.device.rt().release_block(block);
return Err(BlockError::OutOfMemory);
};
let info = BlockInfo {
id: BlockId(block.id.get()),
class: cap.class,
len: block.len,
gpu_address,
contents: block.contents,
};
self.known.know(block.clone());
self.held.lock().insert(info.id, block);
Ok(info)
}
fn read_private_block(&self, block: BlockId) -> Result<Option<Vec<u8>>, BlockError> {
let handle = self
.held
.lock()
.get(&block)
.cloned()
.ok_or(BlockError::NotHeld)?;
let len = handle.len;
if len == 0 {
return Ok(Some(Vec::new()));
}
let rt = self.device.rt();
let stage = rt
.take_block(rt::MemoryClass::Shared, len)
.map_err(|_| BlockError::OutOfMemory)?;
let res = (|| -> Result<Vec<u8>, BlockError> {
let src_buf = rt
.new_buffer(handle.id, 0, len, None)
.map_err(|_| BlockError::OutOfMemory)?;
let dst_buf = rt
.new_buffer(stage.id, 0, len, None)
.map_err(|_| BlockError::OutOfMemory)?;
let q = rt
.new_command_queue(4)
.map_err(|_| BlockError::OutOfMemory)?;
let cb = q.command_buffer().map_err(|_| BlockError::OutOfMemory)?;
let mut blit = cb
.blit_command_encoder()
.map_err(|_| BlockError::OutOfMemory)?;
blit.copy_from_buffer_to_buffer(&src_buf, 0, &dst_buf, 0, len)
.map_err(|_| BlockError::OutOfMemory)?;
blit.end_encoding();
cb.commit().map_err(|_| BlockError::OutOfMemory)?;
cb.wait_until_completed()
.map_err(|_| BlockError::OutOfMemory)?;
let ptr = stage.contents.ok_or(BlockError::OutOfMemory)?;
let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec() };
drop(dst_buf);
drop(src_buf);
Ok(bytes)
})();
let _ = rt.release_block(stage);
res.map(Some)
}
fn write_private_block(&self, block: BlockId, data: &[u8]) -> Result<(), BlockError> {
let handle = self
.held
.lock()
.get(&block)
.cloned()
.ok_or(BlockError::NotHeld)?;
let len = handle.len;
if data.len() as u64 != len {
return Err(BlockError::OutOfMemory);
}
if len == 0 {
return Ok(());
}
let rt = self.device.rt();
let stage = rt
.take_block(rt::MemoryClass::Shared, len)
.map_err(|_| BlockError::OutOfMemory)?;
let res = (|| -> Result<(), BlockError> {
let ptr = stage.contents.ok_or(BlockError::OutOfMemory)?;
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize);
}
let src_buf = rt
.new_buffer(stage.id, 0, len, None)
.map_err(|_| BlockError::OutOfMemory)?;
let dst_buf = rt
.new_buffer(handle.id, 0, len, None)
.map_err(|_| BlockError::OutOfMemory)?;
let q = rt
.new_command_queue(4)
.map_err(|_| BlockError::OutOfMemory)?;
let cb = q.command_buffer().map_err(|_| BlockError::OutOfMemory)?;
let mut blit = cb
.blit_command_encoder()
.map_err(|_| BlockError::OutOfMemory)?;
blit.copy_from_buffer_to_buffer(&src_buf, 0, &dst_buf, 0, len)
.map_err(|_| BlockError::OutOfMemory)?;
blit.end_encoding();
cb.commit().map_err(|_| BlockError::OutOfMemory)?;
cb.wait_until_completed()
.map_err(|_| BlockError::OutOfMemory)?;
drop(dst_buf);
drop(src_buf);
Ok(())
})();
let _ = rt.release_block(stage);
res
}
}
impl Drop for RtBlocks {
-41
View File
@@ -191,47 +191,6 @@ enum GpuAddress {
Picked(u64),
}
pub(super) fn export_carves(carves: &BTreeMap<u64, Carve>) -> Vec<super::PoolCarveSnapshot> {
carves
.iter()
.filter(|(_, c)| matches!(c.state, Carving::Held))
.map(|(&gpa, c)| super::PoolCarveSnapshot {
gpa,
context: c.context,
len: c.len,
serial: c.serial,
gpu_address: c.gpu_address.get(),
picked_address: matches!(c.gpu_address, GpuAddress::Picked(_)),
})
.collect()
}
pub(super) fn import_carves(
carves: &mut BTreeMap<u64, Carve>,
_addresses: &mut super::addresses::HostAddresses,
snap: &[super::PoolCarveSnapshot],
) {
carves.clear();
for c in snap {
let gpu_address = if c.picked_address {
GpuAddress::Picked(c.gpu_address)
} else {
GpuAddress::OfBlock(c.gpu_address)
};
carves.insert(
c.gpa,
Carve {
context: c.context,
len: c.len,
serial: c.serial,
state: Carving::Held,
gpu_address,
zero: Vec::new(),
},
);
}
}
impl GpuAddress {
fn get(self) -> u64 {
match self {
-11
View File
@@ -1,11 +0,0 @@
{
"capabilities": [
"display-fixed-mode",
"nested-virt-nonfatal",
"vm-suspend",
"win10-compat",
"win10-startup-ipis",
"win32-coroutine-fiber",
"win32-unicode-input"
]
}
Vendored
+1 -1
Submodule vendor/qemu updated: c67660108a...4571bc5fec.