Compare commits
54
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7df96f018 | ||
|
|
011fe14323 | ||
|
|
c6e8df0463 | ||
|
|
f7f0af3500 | ||
|
|
6527829878 | ||
|
|
91c0ce917a | ||
|
|
5a2083b951 | ||
|
|
acd68ab830 | ||
|
|
82da699225 | ||
|
|
1adc8a59ce | ||
|
|
6a1f03f862 | ||
|
|
db0c7395f1 | ||
|
|
5f690a8165 | ||
|
|
410d4a3f59 | ||
|
|
66a66b8c26 | ||
|
|
79fdedd8f0 | ||
|
|
f71a03f37c | ||
|
|
01df95a4a4 | ||
|
|
f8f29ada50 | ||
|
|
e8a21294e6 | ||
|
|
2373afdd01 | ||
|
|
e68e3ce939 | ||
|
|
9324949b55 | ||
|
|
48dd6d2fad | ||
|
|
7c00df2c0b | ||
|
|
1bac132e21 | ||
|
|
d3ceaeaa0b | ||
|
|
64c0e9a32a | ||
|
|
914debd758 | ||
|
|
2df30ffea9 | ||
|
|
6b7e7d7cad | ||
|
|
1a6d1626ca | ||
|
|
1ac525f616 | ||
|
|
0427583422 | ||
|
|
0824c15d61 | ||
|
|
7e7b50364b | ||
|
|
9835066ce3 | ||
|
|
8ae206e06a | ||
|
|
bfea2dc988 | ||
|
|
3fdde46abd | ||
|
|
cf00aac721 | ||
|
|
e76060b02c | ||
|
|
9d9be66a68 | ||
|
|
c95335699c | ||
|
|
edd66dcc12 | ||
|
|
ff284bc497 | ||
|
|
e0cb092b03 | ||
|
|
9e0d1bc1a0 | ||
|
|
bcd18d6485 | ||
|
|
6aa417aef6 | ||
|
|
b1e8f45e9e | ||
|
|
53b6af7574 | ||
|
|
c8213cb933 | ||
|
|
d1637583ba |
No files matched your search
@@ -0,0 +1,25 @@
|
||||
name: Queue Runtime Alpha
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [intel-vm-suspend]
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
|
||||
concurrency:
|
||||
group: queue-runtime-alpha
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
alpha:
|
||||
if: github.repository == 'reims-go/reims-vgpu'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Queue Alpha for the pushed commit
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh workflow run runtime-preview.yml --repo "$GITHUB_REPOSITORY" --ref master \
|
||||
-f upstream_commit="$GITHUB_SHA" -f publish=true -f supersede=true
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
[submodule "vendor/qemu"]
|
||||
path = vendor/qemu
|
||||
url = https://github.com/steelbrain/qemu-reims-vgpu
|
||||
branch = steelbrain/reims-vgpu-rebase-2
|
||||
url = https://github.com/reims-go/qemu-reims-vgpu.git
|
||||
branch = intel-vm-suspend
|
||||
Generated
+3
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
[[package]]
|
||||
name = "metal2vulkan"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=8fd7fb5d9cf2df9164b121995b63187f95a3a191#8fd7fb5d9cf2df9164b121995b63187f95a3a191"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"metal2vulkan-air",
|
||||
@@ -223,6 +224,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metal2vulkan-air"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=8fd7fb5d9cf2df9164b121995b63187f95a3a191#8fd7fb5d9cf2df9164b121995b63187f95a3a191"
|
||||
dependencies = [
|
||||
"sha2 0.11.1",
|
||||
]
|
||||
@@ -230,6 +232,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metal2vulkan-runtime"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=8fd7fb5d9cf2df9164b121995b63187f95a3a191#8fd7fb5d9cf2df9164b121995b63187f95a3a191"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"libc",
|
||||
|
||||
+2
-2
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
|
||||
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
|
||||
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
|
||||
# from metal2vulkan's public repository at the commit both name.
|
||||
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "865592b96b791840b26dddb310f33561bfc7d564" }
|
||||
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "8fd7fb5d9cf2df9164b121995b63187f95a3a191" }
|
||||
# The Vulkan platform's runtime (architecture D1), metal2vulkan-runtime: a Metal-shaped API on
|
||||
# Vulkan, one path for every device, under reims-vgpu-vulkan's `rt_platform` and `seam` and
|
||||
# reims-vgpu's `pool::rt_blocks`.
|
||||
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "865592b96b791840b26dddb310f33561bfc7d564" }
|
||||
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "8fd7fb5d9cf2df9164b121995b63187f95a3a191" }
|
||||
# The hashes of the Vulkan platform's metallib sources (reims-vgpu-vulkan/build.rs).
|
||||
sha2 = "0.10.9"
|
||||
# A display window's swapchain on Linux (reims-vgpu-vulkan/src/swapchain.rs), at the runtime's
|
||||
|
||||
+40
-14
@@ -226,11 +226,10 @@ what to do, and so do reims-ctl show and the VM's pane in reims-ctl.
|
||||
An x86-64 VM's macOS sees this host's processor: sysctl machdep.cpu.brand_string reads its name \
|
||||
as the host gives it, and About This Mac shows the Intel family Apple has a name for: Core i3, \
|
||||
i5, i7 or i9 by the host's own (a Core Ultra 7 or a Ryzen 7 shows as Core i7), and Xeon for a \
|
||||
Xeon, Threadripper or EPYC. The start writes it into the VM's OpenCore image where the image \
|
||||
holds another, as after the VM moves to another host; a processor of no such family keeps \
|
||||
OpenCore's own pick. About This Mac counts the VM's CPUs rounded up to a power of two, so 5 CPUs \
|
||||
show as 8 cores, and says Unknown where Apple has no name for that many in the family: Core i5 \
|
||||
and i7 are named at 2 to 8 CPUs, Core i9 at 5 to 8, Core i3 at 2 to 4, and a Xeon at 1 to 16.";
|
||||
Xeon, Threadripper or EPYC. A cold start can set the display type where OpenCore uses automatic \
|
||||
SMBIOS, and Apple has a label for the host family and the VM's CPU count. About This Mac counts \
|
||||
the VM's CPUs rounded up to a power of two, so 5 CPUs show as 8 cores. Core i5 and i7 are named \
|
||||
at 2 to 8 CPUs, Core i9 at 5 to 8, Core i3 at 2 to 4, and a Xeon at 1 to 16.";
|
||||
|
||||
const VIEW_HELP: &str = "\
|
||||
For a VM started headless (reims-ctl start NAME --headless) or on a host with no screen, to \
|
||||
@@ -721,6 +720,9 @@ pub struct CreateArgs {
|
||||
/// directory are on one file system that makes them, else a full copy) or in-place
|
||||
#[arg(long, default_value = "copy")]
|
||||
pub disk_mode: String,
|
||||
/// Host I/O cache policy for the system disk: default, writeback, none or unsafe
|
||||
#[arg(long)]
|
||||
pub disk_cache: Option<String>,
|
||||
/// Download this macOS from Apple to install: a name (tahoe), a number (26) or latest; with
|
||||
/// --offline, also a release (26.6.2) or a build (25G83)
|
||||
#[arg(long, value_name = "VERSION", conflicts_with = "installer")]
|
||||
@@ -814,6 +816,9 @@ pub struct SetArgs {
|
||||
/// OpenCore may start it
|
||||
#[arg(long)]
|
||||
pub disk_controller: Option<String>,
|
||||
/// Host I/O cache policy for the system disk: default, writeback, none or unsafe
|
||||
#[arg(long)]
|
||||
pub disk_cache: Option<String>,
|
||||
/// The size each of reims-vgpu's windows opens at, WIDTHxHEIGHT in the desktop's points:
|
||||
/// one size for every display, or one for each display, comma-separated
|
||||
/// (2560x1440,1920x1080); on a headless start (start --headless), each display's mode
|
||||
@@ -1204,7 +1209,11 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
|
||||
size_mib: parse_size_mib(sz)?,
|
||||
}),
|
||||
(None, Some(p)) => Some(DiskSource::Existing {
|
||||
path: paths::absolute(&p.to_string_lossy()),
|
||||
path: if vm::is_windows_raw_device(p) {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
paths::absolute(&p.to_string_lossy())
|
||||
},
|
||||
mode: ImportMode::parse(&a.disk_mode)?,
|
||||
}),
|
||||
(None, None) => Some(DiskSource::New {
|
||||
@@ -1226,6 +1235,11 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
|
||||
}
|
||||
});
|
||||
s.mac = a.mac.clone();
|
||||
s.disk_cache = a
|
||||
.disk_cache
|
||||
.as_deref()
|
||||
.map(vm::DiskCache::parse)
|
||||
.transpose()?;
|
||||
s.graphics = a.graphics.as_deref().map(vm::Graphics::parse).transpose()?;
|
||||
if let Some(n) = a.displays {
|
||||
s.display.count = n;
|
||||
@@ -1447,14 +1461,19 @@ pub fn describe(vm: &Vm, host: Host, full: Option<&runtime::DiskFull>) -> Vec<(S
|
||||
Err(_) => paths::tilde(&disk),
|
||||
};
|
||||
match &c.q35 {
|
||||
Some(q) => add(
|
||||
"disk",
|
||||
format!(
|
||||
"{disk_name} ({}, {})",
|
||||
c.disk_format.as_str(),
|
||||
q.disk_controller.describe()
|
||||
),
|
||||
),
|
||||
Some(q) => {
|
||||
add(
|
||||
"disk",
|
||||
format!(
|
||||
"{disk_name} ({}, {})",
|
||||
c.disk_format.as_str(),
|
||||
q.disk_controller.describe()
|
||||
),
|
||||
);
|
||||
if !q.disk_cache.is_default() {
|
||||
add("disk cache", q.disk_cache.id().into());
|
||||
}
|
||||
}
|
||||
None => add("disk", format!("{disk_name} ({})", c.disk_format.as_str())),
|
||||
}
|
||||
if let Some(a) = &c.vmapple {
|
||||
@@ -1709,6 +1728,13 @@ fn set(a: SetArgs, host: Host) -> Result<()> {
|
||||
None => bail!("{}: --disk-controller is for x86-64 VMs", c.name),
|
||||
}
|
||||
}
|
||||
if let Some(dc) = &a.disk_cache {
|
||||
let dc = vm::DiskCache::parse(dc)?;
|
||||
match &mut c.q35 {
|
||||
Some(q) => q.disk_cache = dc,
|
||||
None => bail!("{}: --disk-cache is for x86-64 VMs", c.name),
|
||||
}
|
||||
}
|
||||
// A count given is checked against the graphics; one kept from reims-vgpu waits unused on
|
||||
// VMware SVGA, as the resolution does.
|
||||
if let Some(n) = a.displays {
|
||||
|
||||
@@ -92,6 +92,7 @@ pub struct Spec {
|
||||
pub ssh_port: Option<u16>,
|
||||
pub mac: Option<String>,
|
||||
// q35
|
||||
pub disk_cache: Option<DiskCache>,
|
||||
/// macOS to download from Apple, for the installer.
|
||||
pub macos: Option<Download>,
|
||||
pub opencore: Option<PathBuf>,
|
||||
@@ -119,6 +120,7 @@ impl Spec {
|
||||
network: true,
|
||||
ssh_port: None,
|
||||
mac: None,
|
||||
disk_cache: None,
|
||||
macos: None,
|
||||
opencore: None,
|
||||
installer: None,
|
||||
@@ -224,13 +226,28 @@ pub fn create_with(
|
||||
check_free(&dir)?;
|
||||
// What was given is checked before the slow steps: a download, a disk's copy.
|
||||
let mut foreign = None;
|
||||
if let Some(DiskSource::Existing { path, .. }) = &spec.disk {
|
||||
if !path.is_file() {
|
||||
bail!("the disk {} does not exist", path.display());
|
||||
let is_raw_dev = matches!(
|
||||
&spec.disk,
|
||||
Some(DiskSource::Existing { path, .. }) if crate::vm::is_windows_raw_device(path)
|
||||
);
|
||||
if let Some(DiskSource::Existing { path, mode }) = &spec.disk {
|
||||
if crate::vm::is_windows_raw_device(path) {
|
||||
if *mode != ImportMode::InPlace {
|
||||
bail!(
|
||||
"raw Windows disk/partition {} can only be used in-place (--disk-mode in-place)",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if !path.is_file() {
|
||||
bail!("the disk {} does not exist", path.display());
|
||||
}
|
||||
foreign = foreign_disk(path, profile)?;
|
||||
}
|
||||
foreign = foreign_disk(path, profile)?;
|
||||
}
|
||||
check_disk_fits(&spec, &dir, foreign.as_ref())?;
|
||||
if !is_raw_dev {
|
||||
check_disk_fits(&spec, &dir, foreign.as_ref())?;
|
||||
}
|
||||
if let (Some(f), Some(DiskSource::Existing { path, .. })) = (&foreign, &spec.disk) {
|
||||
check_room(f, path, &dir)?;
|
||||
}
|
||||
@@ -1409,6 +1426,7 @@ fn make_q35(
|
||||
cpu_model: default_cpu_model(),
|
||||
cpu_flags: default_cpu_flags(),
|
||||
disk_controller: DiskController::Ahci,
|
||||
disk_cache: spec.disk_cache.unwrap_or_default(),
|
||||
disk_port: 3,
|
||||
});
|
||||
Ok(Vm {
|
||||
@@ -1424,6 +1442,15 @@ fn import_disk(
|
||||
stem: &str,
|
||||
progress: &mut dyn FnMut(&str),
|
||||
) -> Result<(PathBuf, ImageFormat)> {
|
||||
if crate::vm::is_windows_raw_device(src) {
|
||||
if mode != ImportMode::InPlace {
|
||||
bail!(
|
||||
"raw Windows disk/partition {} can only be used in-place (--disk-mode in-place)",
|
||||
src.display()
|
||||
);
|
||||
}
|
||||
return Ok((src.to_path_buf(), ImageFormat::Raw));
|
||||
}
|
||||
if !src.is_file() {
|
||||
bail!("the disk {} does not exist", src.display());
|
||||
}
|
||||
|
||||
@@ -18,8 +18,9 @@ use crate::vm::{Graphics, ImageFormat, Vm};
|
||||
use crate::{paths, prebuilt, reims_util, runtime};
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::File;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
@@ -244,65 +245,119 @@ pub enum ProcessorTypeChange {
|
||||
Written { from: u64, to: u16 },
|
||||
}
|
||||
|
||||
/// Gives a stopped x86-64 VM's OpenCore image PlatformInfo > Generic > ProcessorType `value`
|
||||
/// where it has another (processor.rs), so the guest's About This Mac names the processor as
|
||||
/// `value` does from its next boot; refused while the VM, or another VM on the same image, runs.
|
||||
/// The value goes into a copy of the image beside it, `<image>.part`, which is read back and then
|
||||
/// renamed over the image, so a write stopped at any point leaves the image as it was, byte for
|
||||
/// byte, or the whole new one at the VM's path, and either boots. Only config.plist's own
|
||||
/// clusters change, its length kept ([`with_processor_type`]): the image's other files, its
|
||||
/// volume's tables and the qcow2's are the same.
|
||||
/// Sets the display type for an automatic SMBIOS configuration on a stopped x86-64 VM.
|
||||
pub fn match_processor_type(vm: &Vm, value: u16) -> Result<ProcessorTypeChange> {
|
||||
let Some(q) = vm.config.q35.as_ref() else {
|
||||
return Ok(ProcessorTypeChange::Kept);
|
||||
};
|
||||
let name = vm.name();
|
||||
let image = vm.path(&q.opencore);
|
||||
if value == 0 || !fs::symlink_metadata(&image)?.is_file() {
|
||||
return Ok(ProcessorTypeChange::Kept);
|
||||
}
|
||||
let format = q.opencore_format;
|
||||
let Some(from) = Config::read(&image, format)?.processor_type() else {
|
||||
let stamp = Stamp::of(&image).context("read OpenCore image metadata")?;
|
||||
let Some(config) = read_file(&image, format, CONFIG_PLIST)? else {
|
||||
return Ok(ProcessorTypeChange::Kept);
|
||||
};
|
||||
if from == u64::from(value) {
|
||||
if !processor_type_is_automatic(&Config::parse(&config)?) {
|
||||
return Ok(ProcessorTypeChange::Kept);
|
||||
}
|
||||
if runtime::running(vm) {
|
||||
bail!("{name} is running: stop it first");
|
||||
}
|
||||
if let Some(other) = runtime::running_on_image(vm)? {
|
||||
bail!("{other} is running on {name}'s OpenCore image: stop it first");
|
||||
}
|
||||
let config = read_file(&image, format, CONFIG_PLIST)?
|
||||
.context("its EFI system partition has no EFI/OC/config.plist")?;
|
||||
let edited = with_processor_type(&config, value)?;
|
||||
let mut part = image.clone().into_os_string();
|
||||
part.push(".part");
|
||||
let part = PathBuf::from(part);
|
||||
ensure_processor_image_unused(vm)?;
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let part = image.with_extension(format!(
|
||||
"cpu-{}-{}-{}.part",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)?
|
||||
.as_nanos(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
let file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&part)?;
|
||||
let written = (|| -> Result<()> {
|
||||
std::fs::copy(&image, &part).with_context(|| format!("copy {}", image.display()))?;
|
||||
let mut source = File::open(&image)?;
|
||||
file.set_permissions(source.metadata()?.permissions())?;
|
||||
std::io::copy(&mut source, &mut &file)?;
|
||||
drop(file);
|
||||
drop(source);
|
||||
|
||||
let disk = Disk::open_rw(&part, format)?;
|
||||
Fat32::open(&disk, esp_start(&disk)?)?.overwrite(CONFIG_PLIST, &edited)?;
|
||||
disk.sync()?;
|
||||
let fat = Fat32::open(&disk, esp_start(&disk)?)?;
|
||||
ensure!(
|
||||
Config::read(&part, format)?.processor_type() == Some(u64::from(value)),
|
||||
"the copy does not read back with ProcessorType {value}"
|
||||
fat.holds(CONFIG_PLIST, &config)? == Some(true),
|
||||
"OpenCore config changed while copying"
|
||||
);
|
||||
fat.overwrite(CONFIG_PLIST, &edited)?;
|
||||
disk.sync()?;
|
||||
drop(disk);
|
||||
ensure!(
|
||||
read_file(&part, format, CONFIG_PLIST)?.as_deref() == Some(&edited),
|
||||
"the OpenCore config did not read back"
|
||||
);
|
||||
#[cfg(test)]
|
||||
tests::STOP_BEFORE_RENAME.with(|s| {
|
||||
if s.get() {
|
||||
bail!("stopped before the rename");
|
||||
}
|
||||
Ok(())
|
||||
ensure!(!s.get(), "stopped before the rename");
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})?;
|
||||
std::fs::rename(&part, &image).with_context(|| format!("replace {}", image.display()))
|
||||
|
||||
ensure_processor_image_unused(vm)?;
|
||||
ensure!(
|
||||
Stamp::of(&image) == Some(stamp),
|
||||
"OpenCore image changed while copying"
|
||||
);
|
||||
fs::rename(&part, &image).with_context(|| format!("replace {}", image.display()))
|
||||
})();
|
||||
if let Err(e) = written {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(e);
|
||||
if let Err(error) = written {
|
||||
let _ = fs::remove_file(&part);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
KEPT.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&image);
|
||||
Ok(ProcessorTypeChange::Written { from, to: value })
|
||||
Ok(ProcessorTypeChange::Written { from: 0, to: value })
|
||||
}
|
||||
|
||||
fn ensure_processor_image_unused(vm: &Vm) -> Result<()> {
|
||||
let name = vm.name();
|
||||
ensure!(!runtime::running(vm), "{name} is running: stop it first");
|
||||
if let Some(other) = runtime::running_on_image(vm)? {
|
||||
bail!("{other} is running on {name}'s OpenCore image: stop it first");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn processor_type_is_automatic(config: &Config) -> bool {
|
||||
let vault = config
|
||||
.0
|
||||
.get("Misc")
|
||||
.and_then(plist::Value::as_dictionary)
|
||||
.and_then(|misc| misc.get("Security"))
|
||||
.and_then(plist::Value::as_dictionary)
|
||||
.and_then(|security| security.get("Vault"))
|
||||
.and_then(plist::Value::as_string);
|
||||
let Some(platform) = config
|
||||
.0
|
||||
.get("PlatformInfo")
|
||||
.and_then(plist::Value::as_dictionary)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
vault == Some("Optional")
|
||||
&& platform.get("Automatic").and_then(plist::Value::as_boolean) == Some(true)
|
||||
&& platform
|
||||
.get("UpdateSMBIOS")
|
||||
.and_then(plist::Value::as_boolean)
|
||||
== Some(true)
|
||||
&& platform
|
||||
.get("UpdateSMBIOSMode")
|
||||
.and_then(plist::Value::as_string)
|
||||
== Some("Create")
|
||||
&& config.processor_type() == Some(0)
|
||||
}
|
||||
|
||||
/// Whether a VM's OpenCore image shows its boot picker; `None` for an image reims-ctl cannot
|
||||
@@ -598,6 +653,102 @@ pub fn made_for_other_graphics(vm: &Vm) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The existing OpenCore drivers that provide keyboard and pointer input before macOS starts.
|
||||
const PREBOOT_INPUT_DRIVERS: [&str; 2] = ["ReimsTablet.efi", "OpenUsbKbDxe.efi"];
|
||||
|
||||
#[derive(PartialEq)]
|
||||
struct PrebootInput {
|
||||
config: plist::Value,
|
||||
files: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl PrebootInput {
|
||||
/// Reads the selected driver entries, their binaries, and the existing UEFI input settings.
|
||||
fn read(config: &Config, image: &Path, format: ImageFormat) -> Result<Option<Self>> {
|
||||
let Some(uefi) = config.0.get("UEFI").and_then(plist::Value::as_dictionary) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut drivers = Vec::new();
|
||||
let mut files = BTreeMap::<String, Vec<u8>>::new();
|
||||
for driver in uefi
|
||||
.get("Drivers")
|
||||
.and_then(plist::Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let Some(path) = driver
|
||||
.as_dictionary()
|
||||
.and_then(|entry| entry.get("Path"))
|
||||
.and_then(plist::Value::as_string)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !PREBOOT_INPUT_DRIVERS
|
||||
.iter()
|
||||
.any(|name| path.eq_ignore_ascii_case(name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ensure!(
|
||||
!files.keys().any(|seen| seen.eq_ignore_ascii_case(path)),
|
||||
"OpenCore lists the preboot input driver {path} more than once"
|
||||
);
|
||||
let efi_path = format!("EFI/OC/Drivers/{path}");
|
||||
let bytes = read_file(image, format, &efi_path)?
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.with_context(|| {
|
||||
format!("OpenCore's preboot input driver {efi_path} is missing or empty")
|
||||
})?;
|
||||
files.insert(path.to_owned(), bytes);
|
||||
drivers.push(driver.clone());
|
||||
}
|
||||
if drivers.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let input = uefi
|
||||
.get("Input")
|
||||
.filter(|input| input.as_dictionary().is_some())
|
||||
.context("OpenCore's preboot drivers require the existing UEFI > Input dictionary")?;
|
||||
let mut bundle = plist::Dictionary::new();
|
||||
bundle.insert("Input".into(), input.clone());
|
||||
bundle.insert("Drivers".into(), plist::Value::Array(drivers));
|
||||
Ok(Some(Self {
|
||||
config: plist::Value::Dictionary(bundle),
|
||||
files,
|
||||
}))
|
||||
}
|
||||
|
||||
fn stage(&self) -> Result<PrebootInputDir> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"reims-ctl-opencore-input-{}-{}-{}",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)?
|
||||
.as_nanos(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
crate::os::create_private_dir(&dir).context("create temporary preboot input directory")?;
|
||||
let dir = PrebootInputDir(dir);
|
||||
self.config
|
||||
.to_writer_xml(File::create(dir.0.join("input.plist"))?)
|
||||
.context("write preboot input configuration")?;
|
||||
for (name, bytes) in &self.files {
|
||||
fs::write(dir.0.join(name), bytes)
|
||||
.with_context(|| format!("stage OpenCore's preboot input driver {name}"))?;
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
}
|
||||
|
||||
struct PrebootInputDir(PathBuf);
|
||||
|
||||
impl Drop for PrebootInputDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces a stopped VM's OpenCore image with one the installed reims-util makes, presenting
|
||||
/// the same Mac, with its boot picker shown where `show_picker` says, or as the old image shows
|
||||
/// it when `None`; refused while the VM, or another VM on the same image, runs. The new image is
|
||||
@@ -606,7 +757,8 @@ pub fn made_for_other_graphics(vm: &Vm) -> bool {
|
||||
/// one, so a renewal stopped at any point leaves the old image or the whole new one at the VM's
|
||||
/// path, and either boots.
|
||||
/// It holds the kexts for the VM's graphics ([`reims_util::kext_args`]): on reims-vgpu's own
|
||||
/// device, the guest's that this reims-ctl carries. The VM keeps its OVMF: its variables hold
|
||||
/// device, the guest's that this reims-ctl carries. Existing preboot keyboard and tablet drivers
|
||||
/// and their input options are carried over. The VM keeps its OVMF: its variables hold
|
||||
/// its boot entries. The image is set in the VM's settings as they are once it is made, which
|
||||
/// `vm` becomes: others may be saved meanwhile. Returns what happened, and, where the old image
|
||||
/// loaded reims-vgpu's kexts on other graphics, what they left in the guest
|
||||
@@ -633,14 +785,33 @@ pub fn renew(
|
||||
let read = || format!("read the Mac {} presents", paths::tilde(&old));
|
||||
let config = Config::read(&old, q.opencore_format).with_context(read)?;
|
||||
let id = config.identity().with_context(read)?;
|
||||
let preboot = PrebootInput::read(&config, &old, q.opencore_format)
|
||||
.context("read the old OpenCore image's preboot input")?;
|
||||
let staged = preboot.as_ref().map(PrebootInput::stage).transpose()?;
|
||||
let picker = show_picker.unwrap_or_else(|| config.shows_picker());
|
||||
let image = vm.dir.join("opencore.qcow2");
|
||||
let new = vm.dir.join("opencore.new.qcow2");
|
||||
let dropped = holds_unused_guest_kexts(vm);
|
||||
let kexts = reims_util::kext_args(vm.config.graphics())?;
|
||||
let made = reims_util::opencore_as(&new, &id, picker, &kexts, progress).and_then(|()| {
|
||||
let made = reims_util::opencore_as(
|
||||
&new,
|
||||
&id,
|
||||
picker,
|
||||
&kexts,
|
||||
staged.as_ref().map(|dir| dir.0.as_path()),
|
||||
progress,
|
||||
)
|
||||
.and_then(|()| {
|
||||
let config = Config::read(&new, ImageFormat::Qcow2)
|
||||
.context("read the new OpenCore image before replacing the old one")?;
|
||||
if let Some(expected) = &preboot {
|
||||
let actual = PrebootInput::read(&config, &new, ImageFormat::Qcow2)
|
||||
.context("verify the new OpenCore image's preboot input")?;
|
||||
ensure!(
|
||||
actual.as_ref() == Some(expected),
|
||||
"reims-util did not preserve the old OpenCore image's preboot input"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
!config
|
||||
.configured_kexts()
|
||||
@@ -902,7 +1073,7 @@ impl Qcow2 {
|
||||
}
|
||||
|
||||
/// Where guest cluster `index` is in the file; None where it reads as zeros.
|
||||
fn cluster(&self, index: u64) -> Result<Option<u64>> {
|
||||
fn cluster(&self, index: u64, write: bool) -> Result<Option<u64>> {
|
||||
let per_table = 1u64 << (self.cluster_bits - 3);
|
||||
let l1 = self
|
||||
.l1
|
||||
@@ -917,8 +1088,15 @@ impl Qcow2 {
|
||||
.read_exact_at(&mut e, (l1 & QCOW2_OFFSET) + index % per_table * 8)?;
|
||||
let e = u64::from_be_bytes(e);
|
||||
ensure!(e & 1 << 62 == 0, "a qcow2 image with compressed clusters");
|
||||
// Bit 0: a zero cluster.
|
||||
Ok((e & 1 == 0 && e & QCOW2_OFFSET != 0).then_some(e & QCOW2_OFFSET))
|
||||
// Bit 0 denotes a zero cluster. Bit 63 on both entries denotes exclusive ownership.
|
||||
if e & 1 != 0 || e & QCOW2_OFFSET == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
ensure!(
|
||||
!write || l1 & e & (1 << 63) != 0,
|
||||
"OpenCore QCOW2 cluster is shared"
|
||||
);
|
||||
Ok(Some(e & QCOW2_OFFSET))
|
||||
}
|
||||
|
||||
/// Writes `buf` at `offset` of what the guest sees into the clusters the image has there;
|
||||
@@ -930,9 +1108,11 @@ impl Qcow2 {
|
||||
let at = offset + done as u64;
|
||||
let within = at & (cluster - 1);
|
||||
let n = ((cluster - within) as usize).min(buf.len() - done);
|
||||
let c = self.cluster(at >> self.cluster_bits)?.with_context(|| {
|
||||
format!("a write at {at:#x}, where the qcow2 image has no cluster")
|
||||
})?;
|
||||
let c = self
|
||||
.cluster(at >> self.cluster_bits, true)?
|
||||
.with_context(|| {
|
||||
format!("a write at {at:#x}, where the qcow2 image has no cluster")
|
||||
})?;
|
||||
self.file.write_all_at(&buf[done..done + n], c + within)?;
|
||||
done += n;
|
||||
}
|
||||
@@ -947,7 +1127,7 @@ impl Qcow2 {
|
||||
let within = at & (cluster - 1);
|
||||
let n = ((cluster - within) as usize).min(buf.len() - done);
|
||||
let part = &mut buf[done..done + n];
|
||||
match self.cluster(at >> self.cluster_bits)? {
|
||||
match self.cluster(at >> self.cluster_bits, false)? {
|
||||
Some(c) => self.file.read_exact_at(part, c + within)?,
|
||||
None => part.fill(0),
|
||||
}
|
||||
@@ -1056,9 +1236,14 @@ impl<'a> Fat32<'a> {
|
||||
c = u32::from_le_bytes(next) & 0x0fff_ffff;
|
||||
}
|
||||
ensure!(given == bytes.len() as u64, "{path} is cut short");
|
||||
let mut before = vec![0; self.cluster_size as usize];
|
||||
for (at, from, n) in spans {
|
||||
self.disk
|
||||
.write(at, &bytes[from as usize..(from + n) as usize])?;
|
||||
let after = &bytes[from as usize..(from + n) as usize];
|
||||
let before = &mut before[..after.len()];
|
||||
self.disk.read(at, before)?;
|
||||
if before != after {
|
||||
self.disk.write(at, after)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1543,6 +1728,76 @@ pub(crate) mod tests {
|
||||
assert!(!dir.join("opencore.img").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renew_keeps_preboot_input_and_refuses_a_lost_driver() {
|
||||
let env = crate::testenv::Env::new("renew-preboot-input");
|
||||
let dir = env.root.join("vm");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
let plist = plist("").replace(
|
||||
"</dict></plist>",
|
||||
r#"<key>UEFI</key><dict>
|
||||
<key>Drivers</key><array>
|
||||
<dict><key>Path</key><string>reimstablet.efi</string>
|
||||
<key>Enabled</key><true/><key>Arguments</key><string>tablet</string></dict>
|
||||
<dict><key>Path</key><string>OpenUsbKbDxe.efi</string>
|
||||
<key>Enabled</key><true/><key>LoadEarly</key><true/></dict>
|
||||
<dict><key>Path</key><string>Extra.efi</string><key>Enabled</key><true/></dict>
|
||||
</array>
|
||||
<key>Input</key><dict><key>KeySupport</key><false/></dict>
|
||||
</dict></dict></plist>"#,
|
||||
);
|
||||
let tablet = ("EFI/OC/Drivers/ReimsTablet.efi", &b"fake tablet"[..]);
|
||||
let keyboard = ("EFI/OC/Drivers/OpenUsbKbDxe.efi", &b"fake keyboard"[..]);
|
||||
let old = image_of_config(&plist, b"", &[tablet, keyboard]);
|
||||
let mut vm = on_reims_vgpu(&dir, &old, ImageFormat::Raw);
|
||||
let made = env.root.join("made.img");
|
||||
let args = env.root.join("args");
|
||||
let input = env.root.join("staged.plist");
|
||||
let script = format!(
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > '{args}'\n\
|
||||
while [ \"$1\" != -o ]; do shift; done\n\
|
||||
out=$2\nshift 2\n\
|
||||
while [ \"$1\" != --preboot-input ]; do shift; done\n\
|
||||
cp \"$2/input.plist\" '{input}'\n\
|
||||
test \"$(cat \"$2/reimstablet.efi\")\" = 'fake tablet' || exit 1\n\
|
||||
test \"$(cat \"$2/OpenUsbKbDxe.efi\")\" = 'fake keyboard' || exit 1\n\
|
||||
test ! -e \"$2/Extra.efi\" || exit 1\n\
|
||||
cp '{made}' \"$out\"\n\
|
||||
echo '{{\"event\":\"done\",\"result\":{{}}}}'\n",
|
||||
args = args.display(),
|
||||
input = input.display(),
|
||||
made = made.display(),
|
||||
);
|
||||
let util = crate::testenv::program(&env.root.join("reims-util"), &script);
|
||||
env.set("REIMS_CTL_UTIL", &util);
|
||||
|
||||
let old_path = dir.join("opencore.img");
|
||||
fs::write(&old_path, image_of_config(&plist, b"", &[keyboard])).unwrap();
|
||||
let err = renew(&mut vm, None, &mut |_| {}).unwrap_err();
|
||||
assert!(format!("{err:#}").contains("reimstablet.efi is missing"));
|
||||
assert!(!args.exists());
|
||||
fs::write(&old_path, &old).unwrap();
|
||||
fs::write(&made, qcow2(&image_of_config(&plist, b"", &[tablet]))).unwrap();
|
||||
let err = renew(&mut vm, None, &mut |_| {}).unwrap_err();
|
||||
assert!(format!("{err:#}").contains("OpenUsbKbDxe.efi is missing"));
|
||||
assert_eq!(fs::read(&old_path).unwrap(), old);
|
||||
assert!(!dir.join("opencore.new.qcow2").exists());
|
||||
|
||||
fs::write(&made, qcow2(&old)).unwrap();
|
||||
renew(&mut vm, None, &mut |_| {}).unwrap();
|
||||
let captured = fs::read_to_string(args).unwrap();
|
||||
let staging = captured.lines().last().unwrap();
|
||||
assert!(!Path::new(staging).exists());
|
||||
let bundle = plist::Value::from_file(input).unwrap();
|
||||
let bundle = bundle.as_dictionary().unwrap();
|
||||
assert_eq!(
|
||||
bundle["Input"].as_dictionary().unwrap()["KeySupport"].as_boolean(),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(bundle["Drivers"].as_array().unwrap().len(), 2);
|
||||
assert!(!old_path.exists());
|
||||
}
|
||||
|
||||
/// The old image goes only where its path, resolved, names a file in the VM's directory
|
||||
/// other than the new image: an OpenCore path edited to `../other/oc.img` leaves that file
|
||||
/// be, and one spelling the new image's place another way, `sub/../opencore.qcow2`, leaves
|
||||
@@ -2341,11 +2596,30 @@ pub(crate) mod tests {
|
||||
fn with_processor_type_key(plist: &str, value: u64) -> String {
|
||||
let at = " <key>ROM</key>";
|
||||
assert!(plist.contains(at));
|
||||
plist.replacen(
|
||||
at,
|
||||
&format!("\t\t\t<key>ProcessorType</key>\n\t\t\t<integer>{value}</integer>\n{at}"),
|
||||
1,
|
||||
)
|
||||
plist
|
||||
.replacen(
|
||||
" <key>PlatformInfo</key>",
|
||||
concat!(
|
||||
" <key>Misc</key><dict><key>Security</key><dict>",
|
||||
"<key>Vault</key><string>Optional</string></dict></dict>\n",
|
||||
" <key>PlatformInfo</key>",
|
||||
),
|
||||
1,
|
||||
)
|
||||
.replacen(
|
||||
"<key>Automatic</key><true/>",
|
||||
concat!(
|
||||
"<key>Automatic</key><true/>\n",
|
||||
"<key>UpdateSMBIOS</key><true/>\n",
|
||||
"<key>UpdateSMBIOSMode</key><string>Create</string>",
|
||||
),
|
||||
1,
|
||||
)
|
||||
.replacen(
|
||||
at,
|
||||
&format!("\t\t\t<key>ProcessorType</key>\n\t\t\t<integer>{value}</integer>\n{at}"),
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
/// A new ProcessorType keeps config.plist's length, whatever its digits, and changes
|
||||
@@ -2386,7 +2660,7 @@ pub(crate) mod tests {
|
||||
|
||||
/// The value goes into the image, raw or qcow2, through a copy renamed over it: the image
|
||||
/// keeps its length, every other file it holds and its identity, and no copy stays beside
|
||||
/// it. The same value again writes nothing; 0 gives the name back to OpenCore's own pick.
|
||||
/// it. An explicit type remains in the image across later starts.
|
||||
#[test]
|
||||
fn the_image_takes_the_processor_type() {
|
||||
let env = crate::testenv::Env::new("processor-type");
|
||||
@@ -2435,15 +2709,9 @@ pub(crate) mod tests {
|
||||
assert_eq!(std::fs::read(&path).unwrap(), after);
|
||||
assert_eq!(
|
||||
match_processor_type(&v, 0).unwrap(),
|
||||
ProcessorTypeChange::Written {
|
||||
from: 0x0709,
|
||||
to: 0
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
Config::read(&path, format).unwrap().processor_type(),
|
||||
Some(0)
|
||||
ProcessorTypeChange::Kept
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), after);
|
||||
}
|
||||
// An image without the key is left as it is.
|
||||
let dir = env.root.join("nokey");
|
||||
@@ -2490,7 +2758,10 @@ pub(crate) mod tests {
|
||||
);
|
||||
let c = Config::read(&dir.join("opencore.qcow2"), ImageFormat::Qcow2).unwrap();
|
||||
assert_eq!(c.processor_type(), Some(0x0709));
|
||||
assert!(!part.exists());
|
||||
assert_eq!(
|
||||
std::fs::read(&part).unwrap(),
|
||||
b"left by a write killed before"
|
||||
);
|
||||
}
|
||||
|
||||
/// The write is refused before any copy while another VM runs on the same image, which its
|
||||
@@ -2542,8 +2813,7 @@ pub(crate) mod tests {
|
||||
}
|
||||
|
||||
/// A start writes the host's processor type after it makes an image of an older set again,
|
||||
/// whose reims-util writes OpenCore's own pick, 0: the new image boots with the host's. A host
|
||||
/// whose CPU states no family gives the name back to OpenCore.
|
||||
/// whose reims-util writes OpenCore's own pick, 0: the new image boots with the host's.
|
||||
#[test]
|
||||
fn a_start_names_the_hosts_processor_after_a_new_image() {
|
||||
let env = crate::testenv::Env::new("start-processor-type");
|
||||
@@ -2586,7 +2856,86 @@ pub(crate) mod tests {
|
||||
crate::runtime::prepare(&mut v, &mut |s| said.push(s.to_string()))
|
||||
});
|
||||
assert!(warned.is_empty(), "{warned:?}");
|
||||
assert_eq!(read(), Some(0));
|
||||
assert!(said.last().unwrap().contains("to OpenCore"), "{said:?}");
|
||||
assert_eq!(read(), Some(0x0709));
|
||||
assert!(said.is_empty(), "{said:?}");
|
||||
}
|
||||
#[test]
|
||||
fn processor_type_preserves_explicit_or_unsupported_configs() {
|
||||
let env = crate::testenv::Env::new("processor-type-custom");
|
||||
let baseline = with_processor_type_key(&plist(""), 0);
|
||||
for (label, config) in [
|
||||
("explicit", with_processor_type_key(&plist(""), 0x0709)),
|
||||
(
|
||||
"manual",
|
||||
baseline.replace(
|
||||
"<key>Automatic</key><true/>",
|
||||
"<key>Automatic</key><false/>",
|
||||
),
|
||||
),
|
||||
(
|
||||
"no-smbios-update",
|
||||
baseline.replace(
|
||||
"<key>UpdateSMBIOS</key><true/>",
|
||||
"<key>UpdateSMBIOS</key><false/>",
|
||||
),
|
||||
),
|
||||
(
|
||||
"other-mode",
|
||||
baseline.replace("<string>Create</string>", "<string>Custom</string>"),
|
||||
),
|
||||
(
|
||||
"secure",
|
||||
baseline.replace("<string>Optional</string>", "<string>Secure</string>"),
|
||||
),
|
||||
(
|
||||
"basic",
|
||||
baseline.replace("<string>Optional</string>", "<string>Basic</string>"),
|
||||
),
|
||||
] {
|
||||
let dir = env.root.join(label);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = image(config.as_bytes());
|
||||
let vm = on_reims_vgpu(&dir, &source, ImageFormat::Raw);
|
||||
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
|
||||
|
||||
assert_eq!(
|
||||
match_processor_type(&vm, 0x0609).unwrap(),
|
||||
ProcessorTypeChange::Kept,
|
||||
"{label}"
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), source, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_type_preserves_qcow2_with_shared_or_snapshotted_clusters() {
|
||||
let env = crate::testenv::Env::new("processor-type-shared-clusters");
|
||||
let config = with_processor_type_key(&plist(""), 0);
|
||||
let generated = qcow2(&image(config.as_bytes()));
|
||||
let mut shared = generated.clone();
|
||||
let l1 = be64(&shared, 40) as usize;
|
||||
let l1_size = be32(&shared, 36) as usize * 8;
|
||||
for entry in shared[l1..l1 + l1_size].as_chunks_mut::<8>().0 {
|
||||
entry[0] &= 0x7f;
|
||||
}
|
||||
let mut snapshot = generated;
|
||||
snapshot[60..64].copy_from_slice(&1u32.to_be_bytes());
|
||||
|
||||
for (label, source) in [("shared", shared), ("snapshots", snapshot)] {
|
||||
let dir = env.root.join(label);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let vm = on_reims_vgpu(&dir, &source, ImageFormat::Qcow2);
|
||||
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
|
||||
|
||||
let error = match_processor_type(&vm, 0x0609).unwrap_err().to_string();
|
||||
assert!(error.contains(label), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), source, "{label}");
|
||||
assert!(std::fs::read_dir(&dir).unwrap().all(|file| {
|
||||
file.unwrap()
|
||||
.path()
|
||||
.extension()
|
||||
.is_none_or(|ext| ext != "part")
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,10 @@ pub fn home() -> PathBuf {
|
||||
/// after a `\`; elsewhere as it is.
|
||||
pub fn native(p: PathBuf) -> PathBuf {
|
||||
if cfg!(windows) {
|
||||
if crate::vm::is_windows_raw_device(&p) {
|
||||
let s = p.to_string_lossy().replace('/', "\\");
|
||||
return PathBuf::from(s.trim_end_matches('\\'));
|
||||
}
|
||||
p.components().collect()
|
||||
} else {
|
||||
p
|
||||
|
||||
@@ -19,10 +19,9 @@
|
||||
//! picks one itself where that is 0, as reims-util's images have it: from QEMU's CPU, model 0x5E,
|
||||
//! with no family in its brand string, it picks 0x0905, Core i3, which shows as "Quad-Core Intel
|
||||
//! Core i3" with 4 vCPUs and "Unknown" with 8 (measured on macOS 26.7.2). reims-ctl writes the
|
||||
//! value for the host's CPU instead, at each start ([`crate::opencore::match_processor_type`]):
|
||||
//! the family its brand string states ([`Family::of`]), Intel's own words or AMD's rank of the
|
||||
//! same steps, and 0, OpenCore's own pick, for a CPU that states none. The CPU the guest runs
|
||||
//! on, its model and its features, is the same whatever the value: only the name changes.
|
||||
//! value for the host's CPU on cold starts when the image uses automatic detection
|
||||
//! ([`crate::opencore::match_processor_type`]). Where Apple has no name for the family and core
|
||||
//! count, the image keeps its setting. The processor type controls the displayed name.
|
||||
|
||||
/// A family of the host's CPU that Apple has names for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -88,16 +87,17 @@ impl Family {
|
||||
/// Apple's processor type for the family, in a guest of `cpus` vCPUs: a value Intel's Macs
|
||||
/// had, whose family Apple's table names at the core count macOS reads, `cpus` rounded up to
|
||||
/// a power of two, where any of the family's types is named there. A Xeon is "Intel Xeon",
|
||||
/// 0x0501, up to 4 vCPUs, and "Intel Xeon W", 0x0F01, from 5: macOS counts 5 to 8 vCPUs as 8
|
||||
/// cores, which "Intel Xeon" has no name for and "Intel Xeon W" has.
|
||||
/// 0x0501, up to 4 vCPUs, and "Intel Xeon W", 0x0F01, from 5 to 16: macOS counts 5 to 8 vCPUs as 8
|
||||
/// cores, which "Intel Xeon" has no name for and "Intel Xeon W" has. Returns 0 where Apple has no name.
|
||||
pub fn processor_type(self, cpus: u32) -> u16 {
|
||||
match self {
|
||||
Family::CoreI3 => 0x0909,
|
||||
Family::CoreI5 => 0x0609,
|
||||
Family::CoreI7 => 0x0709,
|
||||
Family::CoreI9 => 0x1009,
|
||||
Family::Xeon if cpus <= 4 => 0x0501,
|
||||
Family::Xeon => 0x0F01,
|
||||
match (self, cpus) {
|
||||
(Family::CoreI3, 2..=4) => 0x0909,
|
||||
(Family::CoreI5, 2..=8) => 0x0609,
|
||||
(Family::CoreI7, 2..=8) => 0x0709,
|
||||
(Family::CoreI9, 5..=8) => 0x1009,
|
||||
(Family::Xeon, 1..=4) => 0x0501,
|
||||
(Family::Xeon, 5..=16) => 0x0F01,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,7 +179,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// The value for each family, which Apple's table names: Core i3 to i9 by their family's
|
||||
/// type whatever the count, a Xeon as "Intel Xeon" up to 4 vCPUs and "Intel Xeon W" from 5;
|
||||
/// type at a supported count, a Xeon as "Intel Xeon" up to 4 vCPUs and "Intel Xeon W" from 5;
|
||||
/// 0 where the host states no family, or gives no brand string.
|
||||
#[test]
|
||||
fn each_family_has_its_processor_type() {
|
||||
@@ -205,6 +205,11 @@ mod tests {
|
||||
assert_eq!(processor_type(xeon, 6), 0x0F01);
|
||||
assert_eq!(processor_type(xeon, 8), 0x0F01);
|
||||
assert_eq!(processor_type(Some("Intel(R) Pentium(R) Gold 7505"), 4), 0);
|
||||
assert_eq!(
|
||||
processor_type(Some("Intel(R) Core(TM) i5-12400"), 8),
|
||||
0x0609
|
||||
);
|
||||
assert_eq!(processor_type(Some("Intel(R) Core(TM) i9-13900H"), 4), 0);
|
||||
assert_eq!(processor_type(None, 8), 0);
|
||||
for t in [0x0909, 0x0609, 0x0709, 0x1009, 0x0501, 0x0F01] {
|
||||
assert!(family_name(t).is_some(), "{t:#06x}");
|
||||
|
||||
+182
-12
@@ -169,6 +169,8 @@ pub struct Ctx {
|
||||
/// The host CPU's brand string ([`crate::host::cpu_brand`]), which an x86-64 guest's CPU
|
||||
/// gives as its own (`model-id`); None where the host gives none.
|
||||
pub cpu_brand: Option<String>,
|
||||
/// Whether this Windows QEMU has the repaired native block AIO backend.
|
||||
pub win32_native_aio: bool,
|
||||
/// Whether QEMU's own window can open ([`crate::host::has_screen`]).
|
||||
pub screen: bool,
|
||||
/// Whether the start is headless (`reims-ctl start --headless`): it opens no window, and
|
||||
@@ -451,31 +453,72 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
),
|
||||
]);
|
||||
push(&["-device", "ide-hd,bus=sata.2,drive=opencore,bootindex=1"]);
|
||||
let mut disk = format!(
|
||||
"id=disk,if=none,format={},file={}",
|
||||
c.disk_format.as_str(),
|
||||
optp(&vm.disk())
|
||||
);
|
||||
let disk_path = vm.disk();
|
||||
let is_raw_dev = crate::vm::is_windows_raw_device(&disk_path);
|
||||
let mut disk = if is_raw_dev {
|
||||
format!(
|
||||
"id=disk,if=none,format=raw,file.driver=host_device,file.filename={}",
|
||||
optp(&disk_path)
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"id=disk,if=none,format={},file={}",
|
||||
c.disk_format.as_str(),
|
||||
optp(&disk_path)
|
||||
)
|
||||
};
|
||||
// The qcow2 image's L2 cache, its table of where each cluster is, up to 32 MiB, which maps
|
||||
// 256 GiB of a disk of 64 KiB clusters (qemu-img's default, which a new disk has). QEMU's own
|
||||
// limit is 32 MiB on Linux and 8 MiB elsewhere, which maps 64 GiB, half a new 128 GiB disk:
|
||||
// on Windows a guest access whose table has left the cache reads it from the image again.
|
||||
// QEMU takes the smaller of this and what the image's size needs (block/qcow2.c,
|
||||
// `read_cache_sizes`), so a smaller disk keeps a smaller cache.
|
||||
if c.disk_format == crate::vm::ImageFormat::Qcow2 {
|
||||
if !is_raw_dev && c.disk_format == crate::vm::ImageFormat::Qcow2 {
|
||||
disk.push_str(",l2-cache-size=32M");
|
||||
}
|
||||
// An install's flushes, which the module's doc measures, are dropped while the installer is
|
||||
// attached.
|
||||
if q.installer.is_some() {
|
||||
disk.push_str(",cache.no-flush=on");
|
||||
if ctx.win32_native_aio
|
||||
&& matches!(
|
||||
q.disk_controller,
|
||||
DiskController::Nvme | DiskController::Virtio
|
||||
)
|
||||
{
|
||||
if is_raw_dev {
|
||||
disk.push_str(",file.aio=native");
|
||||
} else {
|
||||
disk.push_str(",aio=native");
|
||||
}
|
||||
}
|
||||
match q.disk_cache {
|
||||
crate::vm::DiskCache::Default => {
|
||||
// An install's flushes, which the module's doc measures, are dropped while the
|
||||
// installer is attached.
|
||||
if q.installer.is_some() {
|
||||
disk.push_str(",cache.no-flush=on");
|
||||
}
|
||||
}
|
||||
crate::vm::DiskCache::Writeback => {
|
||||
disk.push_str(",cache.direct=off");
|
||||
if q.installer.is_some() {
|
||||
disk.push_str(",cache.no-flush=on");
|
||||
}
|
||||
}
|
||||
crate::vm::DiskCache::None => {
|
||||
disk.push_str(",cache.direct=on");
|
||||
if q.installer.is_some() {
|
||||
disk.push_str(",cache.no-flush=on");
|
||||
}
|
||||
}
|
||||
crate::vm::DiskCache::Unsafe => {
|
||||
disk.push_str(",cache.direct=off,cache.no-flush=on");
|
||||
}
|
||||
}
|
||||
let discard_opt = if is_raw_dev { "" } else { ",discard=unmap" };
|
||||
match q.disk_controller {
|
||||
// `discard=unmap` passes the guest's TRIMs to the image, which frees their space. QEMU's
|
||||
// NVMe controller needs a serial, and without an address takes slot 3, virtio-net's.
|
||||
DiskController::Nvme => push(&[
|
||||
"-drive",
|
||||
&format!("{disk},discard=unmap"),
|
||||
&format!("{disk}{discard_opt}"),
|
||||
"-device",
|
||||
"nvme,drive=disk,serial=reims-ctl,addr=0xa",
|
||||
]),
|
||||
@@ -492,7 +535,7 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
"-object",
|
||||
"iothread,id=io0",
|
||||
"-drive",
|
||||
&format!("{disk},discard=unmap"),
|
||||
&format!("{disk}{discard_opt}"),
|
||||
"-device",
|
||||
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
|
||||
]),
|
||||
@@ -953,6 +996,7 @@ pub(crate) mod tests {
|
||||
cpu_model: default_cpu_model(),
|
||||
cpu_flags: default_cpu_flags(),
|
||||
disk_controller: DiskController::Ahci,
|
||||
disk_cache: crate::vm::DiskCache::Default,
|
||||
disk_port: 3,
|
||||
}),
|
||||
vmapple: None,
|
||||
@@ -980,6 +1024,7 @@ pub(crate) mod tests {
|
||||
smbios_error_correction: Some(3),
|
||||
smbios_memory_slots: None,
|
||||
cpu_brand: None,
|
||||
win32_native_aio: false,
|
||||
screen: true,
|
||||
headless: false,
|
||||
graphics_rom: "/d/firmware/ReimsGraphics-0123456789abcdef.rom".into(),
|
||||
@@ -2231,6 +2276,131 @@ pub(crate) mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_patched_windows_qemu_gets_native_aio_on_the_system_disk() {
|
||||
let mut vm = q35_vm();
|
||||
for controller in [
|
||||
DiskController::Nvme,
|
||||
DiskController::Virtio,
|
||||
DiskController::Ahci,
|
||||
] {
|
||||
vm.config.q35.as_mut().unwrap().disk_controller = controller;
|
||||
for supported in [false, true] {
|
||||
let c = Ctx {
|
||||
win32_native_aio: supported,
|
||||
..ctx(Host {
|
||||
os: Os::Windows,
|
||||
..linux()
|
||||
})
|
||||
};
|
||||
let args = invocation(&vm, &c).unwrap().args;
|
||||
let disk = args.iter().find(|arg| arg.starts_with("id=disk,")).unwrap();
|
||||
assert_eq!(
|
||||
disk.split(',').any(|opt| opt == "aio=native"),
|
||||
supported
|
||||
&& matches!(controller, DiskController::Nvme | DiskController::Virtio),
|
||||
);
|
||||
assert!(args.iter().filter(|arg| arg.contains("aio=native")).count() <= 1);
|
||||
assert!(!disk.contains("cache.no-flush"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disk_cache_modes_emit_expected_qemu_drive_options() {
|
||||
use crate::vm::{DiskCache, ImageFormat};
|
||||
for fmt in [ImageFormat::Qcow2, ImageFormat::Raw] {
|
||||
let mut vm = q35_vm();
|
||||
vm.config.disk_format = fmt;
|
||||
vm.config.disk = if fmt == ImageFormat::Raw {
|
||||
"disk.img".into()
|
||||
} else {
|
||||
"disk.qcow2".into()
|
||||
};
|
||||
vm.config.q35.as_mut().unwrap().disk_controller = DiskController::Nvme;
|
||||
let c = Ctx {
|
||||
win32_native_aio: true,
|
||||
..ctx(Host {
|
||||
os: Os::Windows,
|
||||
..linux()
|
||||
})
|
||||
};
|
||||
|
||||
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Default;
|
||||
let d = invocation(&vm, &c)
|
||||
.unwrap()
|
||||
.args
|
||||
.into_iter()
|
||||
.find(|a| a.starts_with("id=disk,"))
|
||||
.unwrap();
|
||||
assert!(!d.contains("cache.direct"), "{d}");
|
||||
assert!(!d.contains("cache.no-flush"), "{d}");
|
||||
|
||||
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Writeback;
|
||||
let d = invocation(&vm, &c)
|
||||
.unwrap()
|
||||
.args
|
||||
.into_iter()
|
||||
.find(|a| a.starts_with("id=disk,"))
|
||||
.unwrap();
|
||||
assert!(d.contains(",cache.direct=off"), "{d}");
|
||||
assert!(!d.contains("cache.no-flush"), "{d}");
|
||||
|
||||
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::None;
|
||||
let d = invocation(&vm, &c)
|
||||
.unwrap()
|
||||
.args
|
||||
.into_iter()
|
||||
.find(|a| a.starts_with("id=disk,"))
|
||||
.unwrap();
|
||||
assert!(d.contains(",cache.direct=on"), "{d}");
|
||||
assert!(!d.contains("cache.no-flush"), "{d}");
|
||||
|
||||
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Unsafe;
|
||||
let d = invocation(&vm, &c)
|
||||
.unwrap()
|
||||
.args
|
||||
.into_iter()
|
||||
.find(|a| a.starts_with("id=disk,"))
|
||||
.unwrap();
|
||||
assert!(d.contains(",cache.direct=off,cache.no-flush=on"), "{d}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_raw_partition_uses_host_device_with_native_aio() {
|
||||
use crate::vm::{DiskCache, ImageFormat};
|
||||
let win_ctx = Ctx {
|
||||
win32_native_aio: true,
|
||||
..ctx(Host {
|
||||
os: Os::Windows,
|
||||
..linux()
|
||||
})
|
||||
};
|
||||
for raw_path in [
|
||||
r"\\?\Volume{11111111-2222-3333-4444-555555555555}",
|
||||
r"\\.\PhysicalDrive2",
|
||||
] {
|
||||
let mut vm = q35_vm();
|
||||
vm.config.disk = raw_path.into();
|
||||
vm.config.disk_format = ImageFormat::Raw;
|
||||
let q = vm.config.q35.as_mut().unwrap();
|
||||
q.disk_controller = DiskController::Nvme;
|
||||
q.disk_cache = DiskCache::Unsafe;
|
||||
let args = invocation(&vm, &win_ctx).unwrap().args;
|
||||
let d = args.iter().find(|a| a.starts_with("id=disk,")).unwrap();
|
||||
assert!(
|
||||
d.contains("format=raw,file.driver=host_device,file.filename="),
|
||||
"{d}"
|
||||
);
|
||||
assert!(d.contains(raw_path), "{d}");
|
||||
assert!(d.contains(",file.aio=native"), "{d}");
|
||||
assert!(d.contains(",cache.direct=off,cache.no-flush=on"), "{d}");
|
||||
assert!(!d.contains("discard=unmap"), "{d}");
|
||||
assert!(!d.contains("l2-cache-size"), "{d}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installer_disk_goes_on_its_own_port_through_an_overlay() {
|
||||
let mut vm = q35_vm();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! reims-util (<https://github.com/steelbrain/reims-util>) makes what a new x86-64 VM boots from:
|
||||
//! reims-util (<https://github.com/reims-go/reims-util>) makes what a new x86-64 VM boots from:
|
||||
//! an OpenCore image, with OVMF's code and variables beside it, and a macOS installer, downloaded
|
||||
//! from Apple and checked against Apple's chunklists. It also makes an existing VM a new OpenCore
|
||||
//! image presenting the same Mac (opencore.rs). For a VM on reims-vgpu's own device, an image
|
||||
@@ -43,9 +43,9 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const REPO: &str = "https://github.com/steelbrain/reims-util";
|
||||
pub const REPO: &str = "https://github.com/reims-go/reims-util";
|
||||
/// The commit [`install`] installs.
|
||||
pub const REV: &str = "7867384c0ab703b4c6aae36cbbb1a35fcffc8321";
|
||||
pub const REV: &str = "c363a029b1a9bce696184b3247e6465aa11321bc";
|
||||
|
||||
/// The reims-util binary: `REIMS_CTL_UTIL`, else the one beside reims-ctl, where both are
|
||||
/// installed, else the first on PATH.
|
||||
@@ -342,7 +342,7 @@ pub fn opencore(
|
||||
args.extend(["--model", m]);
|
||||
}
|
||||
args.extend(kexts.iter().map(String::as_str));
|
||||
make_opencore(image, &args, progress)
|
||||
make_opencore(image, &args, None, progress)
|
||||
}
|
||||
|
||||
/// Makes an OpenCore image at `image` presenting the Mac `id`, for a VM that has its OVMF: no
|
||||
@@ -353,6 +353,7 @@ pub fn opencore_as(
|
||||
id: &Identity,
|
||||
show_picker: bool,
|
||||
kexts: &[String],
|
||||
preboot_input: Option<&Path>,
|
||||
progress: &mut dyn FnMut(&str),
|
||||
) -> Result<()> {
|
||||
let mut args = identity_args(id);
|
||||
@@ -361,7 +362,7 @@ pub fn opencore_as(
|
||||
args.push("--show-picker");
|
||||
}
|
||||
args.extend(kexts.iter().map(String::as_str));
|
||||
make_opencore(image, &args, progress)
|
||||
make_opencore(image, &args, preboot_input, progress)
|
||||
}
|
||||
|
||||
/// Makes an OpenCore image at `image` presenting the Mac `id`, with `OVMF_CODE.fd` and
|
||||
@@ -375,7 +376,7 @@ pub fn opencore_presenting(
|
||||
) -> Result<()> {
|
||||
let mut args = identity_args(id);
|
||||
args.extend(kexts.iter().map(String::as_str));
|
||||
make_opencore(image, &args, progress)
|
||||
make_opencore(image, &args, None, progress)
|
||||
}
|
||||
|
||||
/// The arguments that make reims-util's image present the Mac `id`.
|
||||
@@ -386,9 +387,17 @@ fn identity_args(id: &Identity) -> Vec<&str> {
|
||||
]
|
||||
}
|
||||
|
||||
fn make_opencore(image: &Path, args: &[&str], progress: &mut dyn FnMut(&str)) -> Result<()> {
|
||||
fn make_opencore(
|
||||
image: &Path,
|
||||
args: &[&str],
|
||||
preboot_input: Option<&Path>,
|
||||
progress: &mut dyn FnMut(&str),
|
||||
) -> Result<()> {
|
||||
let mut all: Vec<&OsStr> = vec!["opencore".as_ref(), "-o".as_ref(), image.as_os_str()];
|
||||
all.extend(args.iter().map(OsStr::new));
|
||||
if let Some(dir) = preboot_input {
|
||||
all.extend([OsStr::new("--preboot-input"), dir.as_os_str()]);
|
||||
}
|
||||
let r = run(&all, progress)?;
|
||||
if let Ok(o) = serde_json::from_value::<OpencoreResult>(r) {
|
||||
progress(&format!(
|
||||
|
||||
@@ -378,9 +378,15 @@ fn preflight_on(vm: &Vm, host: Host, kernel: &dyn Fn() -> Option<(u32, u32)>) ->
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
need(&vm.disk(), "the disk")?;
|
||||
crate::create::check_disk_format(&vm.disk(), c.profile, crate::create::MAKE_A_VM_OF_THE_COPY)?;
|
||||
crate::create::check_image_fits(&vm.disk(), c.disk_format)?;
|
||||
if !crate::vm::is_windows_raw_device(&vm.disk()) {
|
||||
need(&vm.disk(), "the disk")?;
|
||||
crate::create::check_disk_format(
|
||||
&vm.disk(),
|
||||
c.profile,
|
||||
crate::create::MAKE_A_VM_OF_THE_COPY,
|
||||
)?;
|
||||
crate::create::check_image_fits(&vm.disk(), c.disk_format)?;
|
||||
}
|
||||
match c.profile {
|
||||
Profile::Q35X86_64 => {
|
||||
let q = c.q35.as_ref().unwrap();
|
||||
@@ -973,6 +979,7 @@ pub fn context(vm: &Vm, host: Host) -> Result<Ctx> {
|
||||
let smbios_memory_type = smbios_memory_type(vm, &qemu);
|
||||
let smbios_error_correction = smbios_error_correction(vm, &qemu);
|
||||
let smbios_memory_slots = smbios_memory_slots(vm, &qemu);
|
||||
let win32_native_aio = win32_native_aio(vm, host, &qemu);
|
||||
Ok(Ctx {
|
||||
host,
|
||||
qemu,
|
||||
@@ -985,6 +992,7 @@ pub fn context(vm: &Vm, host: Host) -> Result<Ctx> {
|
||||
smbios_error_correction,
|
||||
smbios_memory_slots,
|
||||
cpu_brand: crate::host::cpu_brand(),
|
||||
win32_native_aio,
|
||||
screen,
|
||||
headless: false,
|
||||
graphics_rom: graphics_rom(vm)?,
|
||||
@@ -1044,6 +1052,14 @@ fn smbios_memory_slots(vm: &Vm, qemu: &Path) -> Option<crate::reims_util::Memory
|
||||
crate::reims_util::model_memory_slots(&config.identity().ok()?.model)
|
||||
}
|
||||
|
||||
/// A version number alone does not distinguish the fixed Windows block backend.
|
||||
fn win32_native_aio(vm: &Vm, host: Host, qemu: &Path) -> bool {
|
||||
host.os == Os::Windows
|
||||
&& vm.config.profile == Profile::Q35X86_64
|
||||
&& crate::install::qemu_version(qemu)
|
||||
.is_some_and(|version| version.ends_with(" [reims-win32-native-aio]"))
|
||||
}
|
||||
|
||||
/// The option ROM of reims-vgpu's own device, written into the data directory for an x86-64 VM
|
||||
/// on it ([`crate::prebuilt::graphics_rom`]); an empty path, which no command names, for another
|
||||
/// VM. An arm64 VM's device has no option ROM: Ambrosia drives it with its module.
|
||||
@@ -1094,6 +1110,7 @@ pub fn invocation_for_print(vm: &Vm, host: Host) -> Result<Invocation> {
|
||||
let smbios_memory_type = smbios_memory_type(vm, &qemu);
|
||||
let smbios_error_correction = smbios_error_correction(vm, &qemu);
|
||||
let smbios_memory_slots = smbios_memory_slots(vm, &qemu);
|
||||
let win32_native_aio = win32_native_aio(vm, host, &qemu);
|
||||
Ctx {
|
||||
host,
|
||||
qemu,
|
||||
@@ -1106,6 +1123,7 @@ pub fn invocation_for_print(vm: &Vm, host: Host) -> Result<Invocation> {
|
||||
smbios_error_correction,
|
||||
smbios_memory_slots,
|
||||
cpu_brand: crate::host::cpu_brand(),
|
||||
win32_native_aio,
|
||||
screen: crate::host::has_screen(&vm.config.extra_env),
|
||||
headless: false,
|
||||
graphics_rom: graphics_rom(vm).unwrap_or_else(|_| crate::prebuilt::graphics_rom_path()),
|
||||
@@ -1280,22 +1298,23 @@ pub fn prepare(vm: &mut Vm, progress: &mut dyn FnMut(&str)) -> Vec<String> {
|
||||
)),
|
||||
}
|
||||
}
|
||||
// The processor About This Mac names, from this host's CPU (processor.rs): after any new
|
||||
// image, which reims-util makes with OpenCore's own pick.
|
||||
if vm.config.profile == Profile::Q35X86_64 {
|
||||
// Keep the OpenCore image intact while resuming an incoming QEMU VM.
|
||||
if vm.config.profile == Profile::Q35X86_64
|
||||
&& !vm
|
||||
.config
|
||||
.extra_args
|
||||
.iter()
|
||||
.any(|arg| arg == "-incoming" || arg.starts_with("-incoming="))
|
||||
{
|
||||
let brand = crate::host::cpu_brand();
|
||||
let value = crate::processor::processor_type(brand.as_deref(), vm.config.cpus);
|
||||
match crate::opencore::match_processor_type(vm, value) {
|
||||
Ok(crate::opencore::ProcessorTypeChange::Written { .. }) => {
|
||||
progress(&match crate::processor::family_name(value) {
|
||||
Some(family) => format!(
|
||||
"its OpenCore image now names the processor {family}, this host's \
|
||||
family, in About This Mac"
|
||||
),
|
||||
None => "its OpenCore image now leaves the processor's name in About This \
|
||||
Mac to OpenCore, as this host's CPU states no family Apple names"
|
||||
.to_string(),
|
||||
})
|
||||
if let Some(family) = crate::processor::family_name(value) {
|
||||
progress(&format!(
|
||||
"its OpenCore image now names the processor {family}, this host's family, in About This Mac"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(crate::opencore::ProcessorTypeChange::Kept) => {}
|
||||
Err(e) => w.push(format!(
|
||||
|
||||
@@ -244,6 +244,73 @@ impl DiskController {
|
||||
}
|
||||
}
|
||||
|
||||
/// Host cache policy for an x86-64 VM's system disk.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum DiskCache {
|
||||
/// QEMU's default (`writeback` with flushes forwarded to the host, except
|
||||
/// during installation when `cache.no-flush=on` is added automatically).
|
||||
#[default]
|
||||
Default,
|
||||
/// Host page cache enabled (`cache.direct=off`), guest flushes forwarded.
|
||||
Writeback,
|
||||
/// Bypass host page cache (`cache.direct=on`), guest flushes forwarded.
|
||||
None,
|
||||
/// Host page cache enabled and guest flushes ignored (`cache.direct=off,cache.no-flush=on`).
|
||||
Unsafe,
|
||||
}
|
||||
|
||||
impl DiskCache {
|
||||
pub const ALL: [DiskCache; 4] = [
|
||||
DiskCache::Default,
|
||||
DiskCache::Writeback,
|
||||
DiskCache::None,
|
||||
DiskCache::Unsafe,
|
||||
];
|
||||
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
DiskCache::Default => "default",
|
||||
DiskCache::Writeback => "writeback",
|
||||
DiskCache::None => "none",
|
||||
DiskCache::Unsafe => "unsafe",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Result<DiskCache> {
|
||||
let low = s.trim().to_ascii_lowercase();
|
||||
DiskCache::ALL
|
||||
.into_iter()
|
||||
.find(|c| c.id() == low)
|
||||
.with_context(|| format!("disk cache is default, writeback, none or unsafe, not {s:?}"))
|
||||
}
|
||||
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == DiskCache::Default
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports whether `path` is a Windows raw physical disk or volume/partition
|
||||
/// device path (`\\.\PhysicalDriveN`, `\\.\HarddiskVolumeN`,
|
||||
/// `\\.\HarddiskNPartitionM`, `\\.\Volume{...}`, or `\\?\Volume{...}`),
|
||||
/// excluding extended-length regular file paths like `\\?\D:\...`.
|
||||
pub fn is_windows_raw_device(path: &Path) -> bool {
|
||||
let norm = path.to_string_lossy().replace('/', "\\");
|
||||
let rest = if let Some(r) = norm.strip_prefix(r"\\.\") {
|
||||
r
|
||||
} else if let Some(r) = norm.strip_prefix(r"\\?\") {
|
||||
let low = r.to_ascii_lowercase();
|
||||
return low.starts_with("volume{");
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
let low = rest.to_ascii_lowercase();
|
||||
low.starts_with("physicaldrive")
|
||||
|| low.starts_with("harddiskvolume")
|
||||
|| low.starts_with("harddisk")
|
||||
|| low.starts_with("volume{")
|
||||
}
|
||||
|
||||
/// reims-vgpu's displays, one by default and up to [`DISPLAYS_MAX`], each in a window of its own:
|
||||
/// each window opens at its display's size of the resolution ([`Display::window_sizes`]) and keeps
|
||||
/// the size the person gives it, which its display follows, at the refresh rate of the host
|
||||
@@ -558,6 +625,9 @@ pub struct Q35 {
|
||||
/// installer may boot instead.
|
||||
#[serde(default, skip_serializing_if = "DiskController::is_ahci")]
|
||||
pub disk_controller: DiskController,
|
||||
/// Host I/O cache mode for the system disk.
|
||||
#[serde(default, skip_serializing_if = "DiskCache::is_default")]
|
||||
pub disk_cache: DiskCache,
|
||||
/// The system disk's AHCI port, on [`DiskController::Ahci`]: 3, after OpenCore's 2.
|
||||
#[serde(default = "default_disk_port")]
|
||||
pub disk_port: u32,
|
||||
@@ -991,6 +1061,10 @@ impl Vm {
|
||||
}
|
||||
|
||||
pub fn disk(&self) -> PathBuf {
|
||||
if is_windows_raw_device(&self.config.disk) {
|
||||
let s = self.config.disk.to_string_lossy().replace('/', "\\");
|
||||
return PathBuf::from(s.trim_end_matches('\\'));
|
||||
}
|
||||
self.path(&self.config.disk)
|
||||
}
|
||||
|
||||
@@ -1411,6 +1485,7 @@ pub(crate) mod tests {
|
||||
cpu_model: default_cpu_model(),
|
||||
cpu_flags: default_cpu_flags(),
|
||||
disk_controller: DiskController::Nvme,
|
||||
disk_cache: DiskCache::Default,
|
||||
disk_port: 3,
|
||||
}),
|
||||
vmapple: None,
|
||||
|
||||
@@ -1019,6 +1019,45 @@ 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
|
||||
|
||||
@@ -1258,5 +1258,121 @@ 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;
|
||||
@@ -241,6 +241,11 @@ 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);
|
||||
|
||||
@@ -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(), 19, "{declared:?}");
|
||||
assert_eq!(declared.len(), 24, "{declared:?}");
|
||||
let missing: Vec<&str> = declared
|
||||
.iter()
|
||||
.copied()
|
||||
|
||||
@@ -1161,6 +1161,8 @@ pub(crate) struct Shared {
|
||||
version_watch: guest_drivers::VersionWatch,
|
||||
/// 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.
|
||||
@@ -1985,6 +1987,7 @@ impl Device {
|
||||
reset_owed: AtomicBool::new(false),
|
||||
version_watch: guest_drivers::VersionWatch::default(),
|
||||
ending: AtomicBool::new(false),
|
||||
quiesced: AtomicBool::new(false),
|
||||
wake: Wake::new()?,
|
||||
doorbell: OnceLock::new(),
|
||||
submit: Mutex::new(Submit {
|
||||
@@ -2273,6 +2276,29 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// What tells the guest's CPU locks that the host lowered a cached surface's hold word they wait
|
||||
@@ -2834,10 +2860,233 @@ 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, then, last, for the host's settle ([`Host::reset_settles`]); the host is told on the
|
||||
/// control thread ([`Self::tell_reset`]).
|
||||
/// Wait for active graphics operations before taking a snapshot.
|
||||
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,
|
||||
driver_features_ext: self.driver_features_ext.load(Ordering::Acquire),
|
||||
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);
|
||||
self.driver_features_ext
|
||||
.store(snap.driver_features_ext, Ordering::Release);
|
||||
if snap.driver_features != 0 || snap.driver_features_ext != 0 {
|
||||
self.host
|
||||
.driver_ready(snap.driver_features, snap.driver_features_ext);
|
||||
}
|
||||
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),
|
||||
context_closed: Mutex::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(())
|
||||
}
|
||||
|
||||
/// Reset waits for the current control and queue ring operations and settles the host.
|
||||
/// The host is told on the control thread ([`Self::tell_reset`]).
|
||||
fn reset(&self) {
|
||||
self.status.store(RGFX_STATUS_RESET, Ordering::Release);
|
||||
self.driver_features.store(0, Ordering::Release);
|
||||
@@ -3604,6 +3853,10 @@ 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);
|
||||
@@ -4812,6 +5065,23 @@ 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.
|
||||
@@ -4850,6 +5120,10 @@ 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) {
|
||||
@@ -5460,6 +5734,9 @@ 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,6 +1035,19 @@ 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) {
|
||||
|
||||
@@ -33,6 +33,7 @@ pub mod managed;
|
||||
pub mod ops;
|
||||
pub mod region;
|
||||
mod ring;
|
||||
pub mod snapshot;
|
||||
pub mod threads;
|
||||
// The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header.
|
||||
/// cbindgen:ignore
|
||||
|
||||
@@ -60,6 +60,19 @@ 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,
|
||||
@@ -213,6 +226,37 @@ 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();
|
||||
}
|
||||
|
||||
@@ -202,6 +202,11 @@ 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
|
||||
@@ -555,6 +560,16 @@ 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);
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
//! 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,
|
||||
/// Negotiated `DRIVER_FEATURES_EXT` bitmask.
|
||||
pub driver_features_ext: u32,
|
||||
/// 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, 2);
|
||||
put_u32(o, self.status);
|
||||
put_u64(o, self.driver_features);
|
||||
put_u32(o, self.driver_features_ext);
|
||||
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> {
|
||||
let version = get_u32(i)?;
|
||||
if !matches!(version, 1 | 2) {
|
||||
return None;
|
||||
}
|
||||
let status = get_u32(i)?;
|
||||
let driver_features = get_u64(i)?;
|
||||
let driver_features_ext = if version == 2 { get_u32(i)? } else { 0 };
|
||||
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,
|
||||
driver_features_ext,
|
||||
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() {
|
||||
// The fixed fields in version 2 occupy 53 bytes.
|
||||
let mut base = Vec::new();
|
||||
let empty = DeviceSnapshot {
|
||||
status: 1,
|
||||
driver_features: 2,
|
||||
driver_features_ext: 1,
|
||||
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.clone()));
|
||||
assert!(s.is_empty());
|
||||
|
||||
let mut legacy = base.clone();
|
||||
legacy[..4].copy_from_slice(&1u32.to_le_bytes());
|
||||
legacy.drain(16..20);
|
||||
let mut legacy = legacy.as_slice();
|
||||
let mut legacy_device = empty;
|
||||
legacy_device.driver_features_ext = 0;
|
||||
assert_eq!(DeviceSnapshot::decode(&mut legacy), Some(legacy_device));
|
||||
assert!(legacy.is_empty());
|
||||
|
||||
// Overwrite each of the 4 top-level collection counts with u32::MAX.
|
||||
for offset in [53usize, 57, 61, 65] {
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -320,6 +320,10 @@ pub trait GpuDevice<P: Platform>: Handle {
|
||||
/// queue between command queues answers `new_command_queue`'s queue. Never nil-checked; a raise
|
||||
/// inside it dies at the call, as one inside `newCommandQueue` does.
|
||||
fn new_command_queue_unshared(&self) -> Option<P::CommandQueue>;
|
||||
/// The private IOSurface copy FIFO. A cache transaction may record all its copies before
|
||||
/// it can publish any of them. Allocating a command buffer here must not wait for a
|
||||
/// previously recorded copy to retire. GPU execution still follows queue order.
|
||||
fn new_cache_transfer_queue(&self) -> Option<P::CommandQueue>;
|
||||
/// No Metal counterpart: how many times the platform recovered the device's GPU so far, its
|
||||
/// lost device made again behind the same device object (the Vulkan platform's runtime makes
|
||||
/// a new `VkDevice`, `device-recovered`). The textures, pipelines and pooled buffers made
|
||||
@@ -608,4 +612,44 @@ 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
|
||||
}
|
||||
}
|
||||
@@ -490,6 +490,11 @@ impl GpuDevice<FakePlatform> for Fk<kind::Device> {
|
||||
}))
|
||||
}
|
||||
|
||||
fn new_cache_transfer_queue(&self) -> Option<<FakePlatform as Platform>::CommandQueue> {
|
||||
// Fake queues allocate independent handles immediately.
|
||||
self.new_command_queue_unshared()
|
||||
}
|
||||
|
||||
/// Unlogged, as the property the platform answers it from: [`World::copy_guest_ram`].
|
||||
///
|
||||
/// [`World::copy_guest_ram`]: crate::core::testkit::objects::World::copy_guest_ram
|
||||
|
||||
@@ -1566,6 +1566,7 @@ impl CommandBuffer<RtPlatform> for RtObj<RtCommandBuffer> {
|
||||
let default_samples = pass.default_raster_sample_count;
|
||||
Some(RtObj::new(RtRenderEncoder::new(
|
||||
encoder,
|
||||
self.device.rt().clone(),
|
||||
mark,
|
||||
kept,
|
||||
targets,
|
||||
|
||||
@@ -1704,6 +1704,35 @@ fn memory_flags(flags: vk::MemoryPropertyFlags) -> String {
|
||||
parts.join(" | ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static FORCE_MULTI_DRAW_INDIRECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_multi_draw_indirect<T>(enabled: bool, run: impl FnOnce() -> T) -> T {
|
||||
struct Reset(bool);
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
FORCE_MULTI_DRAW_INDIRECT.with(|flag| flag.set(self.0));
|
||||
}
|
||||
}
|
||||
let previous = FORCE_MULTI_DRAW_INDIRECT.with(|flag| flag.replace(enabled));
|
||||
let _reset = Reset(previous);
|
||||
run()
|
||||
}
|
||||
|
||||
fn multi_draw_indirect_enabled() -> bool {
|
||||
#[cfg(test)]
|
||||
if FORCE_MULTI_DRAW_INDIRECT.with(std::cell::Cell::get) {
|
||||
return true;
|
||||
}
|
||||
matches!(
|
||||
std::env::var("REIMS_VGPU_MULTI_DRAW_INDIRECT").as_deref(),
|
||||
Ok("1" | "true" | "on")
|
||||
)
|
||||
}
|
||||
|
||||
/// The options a device on `physical`, one of `instance`'s, is opened with both in the VM's
|
||||
/// process ([`open`]) and in a stage's helper (`super::stage::helper_main`), where rt takes the
|
||||
/// helper's compile only from a device that enabled what the VM's did (its `StageFill::Enables`
|
||||
@@ -1717,6 +1746,7 @@ pub(crate) fn shared_options(
|
||||
physical: &rt::PhysicalDevice,
|
||||
) -> (rt::DeviceOptions, Option<&'static std::ffi::CStr>) {
|
||||
let mut options = rt::DeviceOptions::default();
|
||||
options.multi_draw_indirect = multi_draw_indirect_enabled();
|
||||
options.stage_memory_ceiling = crate::os::compile_helper::Limits::of_host().memory;
|
||||
let (_, raw) = instance.raw();
|
||||
// SAFETY: the instance listed the device and is alive.
|
||||
@@ -2244,6 +2274,18 @@ impl GpuDevice<RtPlatform> for RtObj<RtDevice> {
|
||||
recorded_answer
|
||||
}
|
||||
|
||||
fn new_cache_transfer_queue(&self) -> Option<RtObj<RtQueue>> {
|
||||
let call = crate::recorder::rec_call!("m2v.newCacheTransferQueue", self);
|
||||
let queue = crate::recorder::run(|| {
|
||||
Some(RtObj::new(RtQueue::new(
|
||||
self.rt.new_host_batch_queue(),
|
||||
self.clone_ref(),
|
||||
)))
|
||||
});
|
||||
crate::recorder::rec_done!(call, queue);
|
||||
queue
|
||||
}
|
||||
|
||||
/// No: rt copies no guest RAM by its host addresses.
|
||||
fn copies_guest_ram(&self) -> bool {
|
||||
false
|
||||
@@ -2790,6 +2832,331 @@ 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
|
||||
@@ -2809,6 +3176,56 @@ mod tests {
|
||||
use crate::core::platform::device::relaying_gaps;
|
||||
use crate::core::platform::values::{OptionSet, TextureDesc};
|
||||
|
||||
#[test]
|
||||
fn a_cache_transfer_batch_publishes_its_bytes_to_a_waiting_queue() {
|
||||
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().expect("a Vulkan device");
|
||||
let copies = device.new_cache_transfer_queue().expect("cache transfers");
|
||||
let consumer = device.new_command_queue().expect("a guest queue");
|
||||
let shared = || {
|
||||
device
|
||||
.new_buffer_of_length(OnFault::Return, 16, 0)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
};
|
||||
let (source, destination) = (shared(), shared());
|
||||
let filled = device.rt().new_event().unwrap();
|
||||
let done = device.rt().new_shared_event().unwrap();
|
||||
let mut batch = Vec::new();
|
||||
for value in 1..=3 {
|
||||
let copy = copies.command_buffer(OnFault::Return).unwrap().unwrap();
|
||||
let mut blit = copy.rt().blit_command_encoder().unwrap();
|
||||
blit.fill_buffer(source.rt(), 0..16, value).unwrap();
|
||||
blit.end_encoding();
|
||||
copy.rt()
|
||||
.encode_signal_event(&filled, u64::from(value))
|
||||
.unwrap();
|
||||
batch.push(copy);
|
||||
}
|
||||
let read = consumer.command_buffer(OnFault::Return).unwrap().unwrap();
|
||||
read.rt().encode_wait_for_event(&filled, 3).unwrap();
|
||||
let mut blit = read.rt().blit_command_encoder().unwrap();
|
||||
blit.copy_from_buffer_to_buffer(source.rt(), 0, destination.rt(), 0, 16)
|
||||
.unwrap();
|
||||
blit.end_encoding();
|
||||
read.rt().encode_signal_event(done.as_event(), 1).unwrap();
|
||||
read.commit(OnFault::Return).unwrap();
|
||||
for copy in batch {
|
||||
copy.commit(OnFault::Return).unwrap();
|
||||
}
|
||||
assert!(
|
||||
done.wait_until_signaled_value(1, std::time::Duration::from_secs(10))
|
||||
.unwrap()
|
||||
);
|
||||
let at = destination.rt().contents().expect("shared storage");
|
||||
// SAFETY: the GPU signal covers the final copy, the allocation is 16 bytes and kept
|
||||
// alive by destination, and there are no further writers.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(at.as_ptr(), 16) };
|
||||
assert_eq!(bytes, &[3; 16]);
|
||||
}
|
||||
|
||||
/// The options a device is opened with carry the helper's memory ceiling on this host, the
|
||||
/// one a memory breach is kept under.
|
||||
#[test]
|
||||
|
||||
@@ -137,7 +137,9 @@ use crate::core::platform::{Encoded, Handle, ObjId};
|
||||
use crate::core::raise::{OnFault, RaiseResult};
|
||||
use crate::core::sync::ReentrantMutex;
|
||||
|
||||
use super::blit::{Stop, report};
|
||||
use super::blit::Stop;
|
||||
#[cfg(not(test))]
|
||||
use super::blit::report;
|
||||
use super::command::{Kept, OpenMark};
|
||||
use super::compute::{declared, resource_usage, slots, small};
|
||||
use super::copied::Used;
|
||||
@@ -147,6 +149,8 @@ use super::render_pipeline::{Formats, Raster, RtRenderPipeline};
|
||||
use super::texture::RtTexture;
|
||||
use super::unbuilt::{Named, Unbuilt, naming_functions, refuse};
|
||||
use super::{RtBuffer, RtObj, RtPlatform};
|
||||
#[cfg(test)]
|
||||
use tests::report;
|
||||
|
||||
/// A count, a base or an index past rt's 32 bits.
|
||||
const WIDE: Stop = Stop::Metal("a count, a base or an index past 32 bits");
|
||||
@@ -158,6 +162,7 @@ pub struct RtRenderEncoder {
|
||||
/// it again on the thread that holds it, with no atomic operation. A command another thread
|
||||
/// sends meanwhile waits for the run to end.
|
||||
open: ReentrantMutex<RefCell<Open>>,
|
||||
device: rt::Device,
|
||||
/// Its command buffer's mark of it open, until it ends.
|
||||
mark: OpenMark,
|
||||
/// What its command buffer keeps until it completes.
|
||||
@@ -200,6 +205,7 @@ impl RtRenderEncoder {
|
||||
/// naming its operands where `operands` (`super::fault`'s `Operands`).
|
||||
pub fn new(
|
||||
encoder: rt::RenderCommandEncoder,
|
||||
device: rt::Device,
|
||||
mark: OpenMark,
|
||||
kept: Kept,
|
||||
targets: Vec<Target>,
|
||||
@@ -217,6 +223,7 @@ impl RtRenderEncoder {
|
||||
seen: Seen::default(),
|
||||
naming: Naming::new(kept.encoded(), names),
|
||||
})),
|
||||
device,
|
||||
mark,
|
||||
kept,
|
||||
targets,
|
||||
@@ -801,6 +808,40 @@ fn draw_primitives(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Probes a run without changing the encoder or reporting refusals.
|
||||
fn indirect_run<'a>(
|
||||
draws: &[VertexDraw<'a, RtPlatform>],
|
||||
items: &mut [rt::VertexOffsetDraw; 32],
|
||||
) -> Option<(&'a RtObj<RtBuffer>, u32, PrimitiveType, usize)> {
|
||||
let first = draws.first()?;
|
||||
let buffer = first.buffer?;
|
||||
let slot = small(first.index).ok()?;
|
||||
let topology = primitive(first.primitive_type).ok()?;
|
||||
let mut count = 0;
|
||||
for (draw, item) in draws.iter().zip(items) {
|
||||
if draw.buffer.map(Handle::id) != Some(buffer.id())
|
||||
|| draw.index != first.index
|
||||
|| draw.primitive_type != first.primitive_type
|
||||
{
|
||||
break;
|
||||
}
|
||||
let (Ok(vertex_start), Ok(vertex_count)) =
|
||||
(small(draw.vertex_start), small(draw.vertex_count))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
*item = rt::VertexOffsetDraw {
|
||||
offset: draw.offset,
|
||||
vertex_start,
|
||||
vertex_count,
|
||||
instance_count: 1,
|
||||
base_instance: 0,
|
||||
};
|
||||
count += 1;
|
||||
}
|
||||
Some((buffer, slot, topology, count))
|
||||
}
|
||||
|
||||
/// `Ok` where a setting rt has none of is at Metal's default (`at_default`); unbuilt otherwise.
|
||||
fn unbuilt_unless(at_default: bool) -> Result<(), Stop> {
|
||||
match at_default {
|
||||
@@ -1220,64 +1261,195 @@ impl RtObj<RtRenderEncoder> {
|
||||
if crate::recorder::on() {
|
||||
return None;
|
||||
}
|
||||
let held = self.open.lock();
|
||||
let mut open = held.borrow_mut();
|
||||
let Open {
|
||||
rt,
|
||||
pipeline,
|
||||
seen,
|
||||
naming,
|
||||
} = &mut *open;
|
||||
let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else {
|
||||
return None;
|
||||
};
|
||||
let used = self.kept.copies();
|
||||
let mut last = None;
|
||||
let mut buffer = None;
|
||||
for (i, draw) in draws.iter().enumerate() {
|
||||
if let Some(bound) = draw.buffer {
|
||||
names.bound_buffers.add_named(bound.named());
|
||||
}
|
||||
let key = draw.buffer.map(std::ptr::from_ref);
|
||||
if key != last {
|
||||
last = key;
|
||||
buffer = draw.buffer.map(|b| b.rt());
|
||||
draw.buffer.iter().for_each(|b| used.buffer(b));
|
||||
}
|
||||
let bound = small(draw.index).and_then(|index| {
|
||||
encoder
|
||||
.set_vertex_buffer(buffer, draw.offset, index)
|
||||
.map_err(Stop::from)
|
||||
});
|
||||
// A refusal is reported once. After a refused bind, the draw still sees the
|
||||
// encoder's existing binding, and only commands that have yet to run go to encode.
|
||||
if let Err(stop) = bound {
|
||||
let mut items = [rt::VertexOffsetDraw {
|
||||
offset: 0,
|
||||
vertex_start: 0,
|
||||
vertex_count: 0,
|
||||
instance_count: 1,
|
||||
base_instance: 0,
|
||||
}; 32];
|
||||
let mut i = 0;
|
||||
let mut p0_until = 0;
|
||||
let mut p0_init = false;
|
||||
let mut pending_draw = false;
|
||||
let mut encoded = Encoded::RECORDED;
|
||||
while i < draws.len() {
|
||||
let held = self.open.lock();
|
||||
let mut open = held.borrow_mut();
|
||||
let Open {
|
||||
rt,
|
||||
pipeline,
|
||||
seen,
|
||||
naming,
|
||||
} = &mut *open;
|
||||
let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else {
|
||||
drop(open);
|
||||
drop(held);
|
||||
report(draw.vertex_buffer().selector(), Some(stop));
|
||||
if let Err(raise) = self.encode(on, draw.primitives()) {
|
||||
return Some(Err(raise));
|
||||
if i == 0 && !pending_draw {
|
||||
return None;
|
||||
}
|
||||
// The bind was refused: so is the run, whatever the rest answer.
|
||||
return Some(encode_each(self, on, &draws[i + 1..]).map(|_| Encoded::REFUSED));
|
||||
if pending_draw {
|
||||
match self.encode(on, draws[i].primitives()) {
|
||||
Ok(ans) => {
|
||||
if ans == Encoded::REFUSED {
|
||||
encoded = Encoded::REFUSED;
|
||||
}
|
||||
}
|
||||
Err(raise) => return Some(Err(raise)),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
return Some(encode_each(self, on, &draws[i..]).map(|rest| {
|
||||
if encoded == Encoded::REFUSED {
|
||||
Encoded::REFUSED
|
||||
} else {
|
||||
rest
|
||||
}
|
||||
}));
|
||||
};
|
||||
if !p0_init {
|
||||
let mdi = !super::copied::any()
|
||||
&& self.device.draw_indirect_limit() > 0
|
||||
&& names.operands.is_none();
|
||||
p0_until = if mdi { 0 } else { draws.len() };
|
||||
p0_init = true;
|
||||
}
|
||||
if let Err(stop) = draw_primitives(
|
||||
encoder,
|
||||
draw.primitive_type,
|
||||
draw.vertex_start,
|
||||
draw.vertex_count,
|
||||
) {
|
||||
let sel = draw.primitives().selector();
|
||||
let functions =
|
||||
self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None);
|
||||
let (bind, stop) = if pending_draw {
|
||||
pending_draw = false;
|
||||
let draw = &draws[i];
|
||||
if let Err(stop) = draw_primitives(
|
||||
encoder,
|
||||
draw.primitive_type,
|
||||
draw.vertex_start,
|
||||
draw.vertex_count,
|
||||
) {
|
||||
(false, stop)
|
||||
} else {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
let mut last = None;
|
||||
let mut buffer = None;
|
||||
loop {
|
||||
if i == draws.len() {
|
||||
return Some(Ok(encoded));
|
||||
}
|
||||
if i >= p0_until
|
||||
&& draws.len() - i >= 9
|
||||
&& let Some((bound, slot, topology, count)) =
|
||||
indirect_run(&draws[i..], &mut items)
|
||||
&& count != 0
|
||||
{
|
||||
p0_until = i + count;
|
||||
let result = encoder.draw_primitives_batch(
|
||||
topology,
|
||||
slot,
|
||||
bound.rt(),
|
||||
&items[..count],
|
||||
);
|
||||
let named = match &result {
|
||||
Ok(done) => *done,
|
||||
Err(
|
||||
rt::BatchStop::Bind { index, .. }
|
||||
| rt::BatchStop::Draw { index, .. },
|
||||
) => index + 1,
|
||||
Err(rt::BatchStop::Device { completed, .. }) => *completed,
|
||||
};
|
||||
for _ in 0..named {
|
||||
names.bound_buffers.add_named(bound.named());
|
||||
}
|
||||
match result {
|
||||
Ok(0) => {}
|
||||
Ok(1) => {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
Ok(done) => {
|
||||
i += done;
|
||||
p0_until = i;
|
||||
continue;
|
||||
}
|
||||
Err(rt::BatchStop::Bind { index, error }) => {
|
||||
i += index;
|
||||
break (true, Stop::Rt(error));
|
||||
}
|
||||
Err(rt::BatchStop::Draw { index, error }) => {
|
||||
i += index;
|
||||
break (false, Stop::Rt(error));
|
||||
}
|
||||
Err(rt::BatchStop::Device { error, .. }) => {
|
||||
break (false, Stop::Rt(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
let draw = &draws[i];
|
||||
if let Some(bound) = draw.buffer {
|
||||
names.bound_buffers.add_named(bound.named());
|
||||
}
|
||||
let key = draw.buffer.map(Handle::id);
|
||||
if key != last {
|
||||
last = key;
|
||||
buffer = draw.buffer.map(|b| b.rt());
|
||||
draw.buffer.iter().for_each(|b| used.buffer(b));
|
||||
}
|
||||
let bound = small(draw.index).and_then(|index| {
|
||||
encoder
|
||||
.set_vertex_buffer(buffer, draw.offset, index)
|
||||
.map_err(Stop::from)
|
||||
});
|
||||
if let Err(stop) = bound {
|
||||
break (true, stop);
|
||||
}
|
||||
if let Err(stop) = draw_primitives(
|
||||
encoder,
|
||||
draw.primitive_type,
|
||||
draw.vertex_start,
|
||||
draw.vertex_count,
|
||||
) {
|
||||
break (false, stop);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
};
|
||||
let draw = &draws[i];
|
||||
if let Stop::Rt(rt::Error::Vulkan { call, result }) = &stop
|
||||
&& *result == ash::vk::Result::ERROR_DEVICE_LOST
|
||||
{
|
||||
let loss = rt::DeviceLoss {
|
||||
call,
|
||||
result: *result,
|
||||
fault: None,
|
||||
};
|
||||
drop(open);
|
||||
drop(held);
|
||||
naming_functions(functions, || report(sel, Some(stop)));
|
||||
// The draw was refused: so is the run, whatever the rest answer.
|
||||
return Some(encode_each(self, on, &draws[i + 1..]).map(|_| Encoded::REFUSED));
|
||||
self.device.report_loss(loss);
|
||||
return Some(Ok(Encoded::REFUSED));
|
||||
}
|
||||
encoded = Encoded::REFUSED;
|
||||
// A refused bind leaves the prior binding in place for this item's draw.
|
||||
let sel = if bind {
|
||||
draw.vertex_buffer()
|
||||
} else {
|
||||
draw.primitives()
|
||||
}
|
||||
.selector();
|
||||
let functions = if bind {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None)
|
||||
};
|
||||
drop(open);
|
||||
drop(held);
|
||||
naming_functions(functions, || report(sel, Some(stop)));
|
||||
if bind {
|
||||
pending_draw = true;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Some(Ok(Encoded::RECORDED))
|
||||
Some(Ok(encoded))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1433,6 +1605,25 @@ mod tests {
|
||||
/// `MTLPrimitiveTypeTriangle`.
|
||||
const TRIANGLE: u64 = 3;
|
||||
|
||||
thread_local! {
|
||||
static DRAW_REFUSALS: RefCell<Option<Vec<(&'static str, String)>>> =
|
||||
const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
pub(super) fn report(sel: &'static str, stop: Option<Stop>) {
|
||||
DRAW_REFUSALS.with_borrow_mut(|seen| {
|
||||
if let (Some(seen), Some(stop)) = (seen, &stop) {
|
||||
let why = match stop {
|
||||
Stop::Metal(why) => (*why).to_owned(),
|
||||
Stop::Rt(error) => error.to_string(),
|
||||
Stop::Unbuilt(_) | Stop::Counted => unreachable!("only draw and bind refusals"),
|
||||
};
|
||||
seen.push((sel, why));
|
||||
}
|
||||
});
|
||||
super::super::blit::report(sel, stop);
|
||||
}
|
||||
|
||||
fn counted(code: &str) -> u64 {
|
||||
(crate::answer::degradation_counts().into_iter())
|
||||
.find(|(c, _)| c == code)
|
||||
@@ -1897,6 +2088,7 @@ mod tests {
|
||||
);
|
||||
}
|
||||
let before = codes.map(counted);
|
||||
let before_mdi = device.rt().counters().metrics();
|
||||
let answer = if batch {
|
||||
encoder.encode_draws(on, draws)
|
||||
} else {
|
||||
@@ -1917,6 +2109,8 @@ mod tests {
|
||||
assert_eq!(cb.commit(on), Ok(()));
|
||||
assert_eq!(cb.wait_until_completed(on), Ok(()));
|
||||
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED);
|
||||
let after_mdi = device.rt().counters().metrics();
|
||||
assert_eq!(after_mdi.multi_draw_calls, before_mdi.multi_draw_calls);
|
||||
let mut pixels = [0; 64];
|
||||
target.read_pixels(&mut pixels, 16);
|
||||
// SAFETY: the Shared result buffer is mapped for eight bytes and the GPU has finished.
|
||||
@@ -2061,15 +2255,276 @@ mod tests {
|
||||
/// (`super::super::copied`) is taken as a batch, not one at a time, and its draw reads the
|
||||
/// bytes the CPU wrote into the pages before the commit, which the commit copied in.
|
||||
#[test]
|
||||
fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
|
||||
fn indirect_draw_batches_match_pixels_refusals_and_binding_on_vulkan()
|
||||
-> Result<(), &'static str> {
|
||||
use crate::core::platform::command::WorkNames;
|
||||
use std::sync::Arc;
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = crate::rt_platform::device::with_multi_draw_indirect(true, || {
|
||||
platform.system_default_device()
|
||||
})
|
||||
.ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let counters = device.rt().counters();
|
||||
let vbuf = include_bytes!("../../../../tests/shaders/render_vbuf.metallib");
|
||||
let flat = include_bytes!("../../../../tests/shaders/render_flat.metallib");
|
||||
let vertex = function(&device, vbuf, "render_vbuf");
|
||||
let fragment = function(&device, flat, "render_flat");
|
||||
let mut desc = FullRenderPipelineDesc::new(&vertex, Some(&fragment));
|
||||
desc.colors = vec![(
|
||||
0,
|
||||
ColorAttachmentDesc {
|
||||
pixel_format: 70,
|
||||
blending_enabled: true,
|
||||
destination_rgb_blend_factor: 1,
|
||||
..ColorAttachmentDesc::default()
|
||||
},
|
||||
)];
|
||||
let state = device
|
||||
.new_render_pipeline_state_full(&desc)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let floats = |values: &[f32]| {
|
||||
values
|
||||
.iter()
|
||||
.flat_map(|v| v.to_le_bytes())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let positions = |x, right| [x, -1., 0., 1., right, -1., 0., 1., x, 3., 0., 1.];
|
||||
let vertices = floats(&[positions(-1., 1.), positions(-0.5, 2.5)].concat());
|
||||
let a = shared(&device, &vertices);
|
||||
let b_vertices = floats(&positions(0., 2.));
|
||||
let b = shared(&device, &b_vertices);
|
||||
let increment = shared(&device, &floats(&[0., 1. / 255., 0., 1.]));
|
||||
let marker = shared(&device, &floats(&[0., 0., 1., 1.]));
|
||||
let results = shared(&device, &[0; 8]);
|
||||
let other_platform = RtPlatform::new();
|
||||
let other_device = other_platform
|
||||
.system_default_device()
|
||||
.ok_or("no second Vulkan device")?;
|
||||
let foreign = shared(&other_device, &b_vertices);
|
||||
let draw = VertexDraw {
|
||||
buffer: Some(&a),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
primitive_type: TRIANGLE,
|
||||
vertex_start: 0,
|
||||
vertex_count: 3,
|
||||
};
|
||||
let on = OnFault::Return;
|
||||
let target = device
|
||||
.new_texture(
|
||||
on,
|
||||
&platform.texture_descriptor(&TextureDesc {
|
||||
width: 4,
|
||||
height: 4,
|
||||
usage: 5,
|
||||
..TextureDesc::default()
|
||||
}),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let render = |draws: &[VertexDraw<'_, RtPlatform>], batch, visibility, operands: bool| {
|
||||
let pass = pass(&target, 2);
|
||||
if visibility {
|
||||
pass.set_pass(&PassSet {
|
||||
visibility_result_buffer: Some(Some(&results)),
|
||||
..PassSet::default()
|
||||
});
|
||||
}
|
||||
let cb = queue.command_buffer(on).unwrap().unwrap();
|
||||
if !operands {
|
||||
cb.names_work(&Arc::new(WorkNames::new(1)));
|
||||
}
|
||||
let encoder = cb.render_encoder(on, &pass).unwrap().unwrap();
|
||||
encoder
|
||||
.encode(
|
||||
on,
|
||||
RenderCmd::SetRenderPipelineState {
|
||||
pipeline_state: Some(&state),
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
.go_on();
|
||||
let fragment = |buffer| RenderCmd::SetFragmentBuffer {
|
||||
buffer: Some(buffer),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
};
|
||||
encoder.encode(on, fragment(&increment)).unwrap().go_on();
|
||||
encoder
|
||||
.encode(
|
||||
on,
|
||||
RenderCmd::SetVertexBuffer {
|
||||
buffer: Some(&increment),
|
||||
offset: 0,
|
||||
index: 1,
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
.go_on();
|
||||
encoder.encode(on, draw.vertex_buffer()).unwrap().go_on();
|
||||
let before = counters.metrics();
|
||||
DRAW_REFUSALS.set(Some(Vec::new()));
|
||||
let encoded = if batch {
|
||||
encoder.encode_draws(on, draws).unwrap()
|
||||
} else {
|
||||
encode_each(&encoder, on, draws).unwrap()
|
||||
};
|
||||
let bound = encoder
|
||||
.open
|
||||
.lock()
|
||||
.borrow_mut()
|
||||
.naming
|
||||
.names()
|
||||
.unwrap()
|
||||
.bound_buffers
|
||||
.clone();
|
||||
encoder.encode(on, fragment(&marker)).unwrap().go_on();
|
||||
encoder.encode(on, draw.primitives()).unwrap().go_on();
|
||||
let refusals = DRAW_REFUSALS.take().unwrap();
|
||||
encoder.encode(on, RenderCmd::EndEncoding).unwrap().go_on();
|
||||
cb.commit(on).unwrap();
|
||||
cb.wait_until_completed(on).unwrap();
|
||||
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED);
|
||||
let mut pixels = [0; 64];
|
||||
target.read_pixels(&mut pixels, 16);
|
||||
let after = counters.metrics();
|
||||
(
|
||||
(pixels, refusals, bound, encoded),
|
||||
(
|
||||
after.multi_draw_calls - before.multi_draw_calls,
|
||||
after.multi_draw_items - before.multi_draw_items,
|
||||
),
|
||||
)
|
||||
};
|
||||
let long: [_; 68] = std::array::from_fn(|i| VertexDraw {
|
||||
offset: if i % 2 == 0 { 0 } else { 48 },
|
||||
..draw
|
||||
});
|
||||
let (direct, _) = render(&long, false, false, false);
|
||||
let (batched, mdi) = render(&long, true, false, false);
|
||||
assert_eq!(batched, direct);
|
||||
assert!(
|
||||
direct
|
||||
.0
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.any(|pixel| (2..255).contains(&pixel[1]))
|
||||
);
|
||||
match device.rt().draw_indirect_limit() {
|
||||
0..8 => assert_eq!(mdi, (0, 0)),
|
||||
8..31 => assert!(mdi.0 > 0 && mdi.1 > 0),
|
||||
_ => assert_eq!(mdi, (2, 63)),
|
||||
}
|
||||
println!(
|
||||
"68 draws: 16/16 identical pixels, {} MDI calls, {} indirect draws",
|
||||
mdi.0, mdi.1
|
||||
);
|
||||
for (draws, visibility, operands) in [
|
||||
(&long[..8], false, false),
|
||||
(&long[..], true, false),
|
||||
(&long[..], false, true),
|
||||
] {
|
||||
let (batched, mdi) = render(draws, true, visibility, operands);
|
||||
assert_eq!(batched, render(draws, false, visibility, operands).0);
|
||||
assert_eq!(mdi, (0, 0));
|
||||
}
|
||||
let wide = u64::from(u32::MAX) + 1;
|
||||
let switched = VertexDraw {
|
||||
buffer: Some(&b),
|
||||
..draw
|
||||
};
|
||||
let foreign = VertexDraw {
|
||||
buffer: Some(&foreign),
|
||||
..draw
|
||||
};
|
||||
for at in [0, 15, 31, 32, long.len() - 1] {
|
||||
for exceptional in [
|
||||
VertexDraw {
|
||||
index: wide,
|
||||
vertex_start: wide,
|
||||
..draw
|
||||
},
|
||||
VertexDraw { index: 31, ..draw },
|
||||
VertexDraw {
|
||||
vertex_start: wide,
|
||||
..switched
|
||||
},
|
||||
VertexDraw {
|
||||
vertex_count: wide,
|
||||
..switched
|
||||
},
|
||||
VertexDraw {
|
||||
primitive_type: u64::MAX,
|
||||
..switched
|
||||
},
|
||||
VertexDraw { offset: 1, ..draw },
|
||||
VertexDraw {
|
||||
offset: a.length() + 16,
|
||||
..draw
|
||||
},
|
||||
VertexDraw {
|
||||
vertex_count: 0,
|
||||
..draw
|
||||
},
|
||||
switched,
|
||||
VertexDraw {
|
||||
buffer: None,
|
||||
..draw
|
||||
},
|
||||
] {
|
||||
let mut draws = long;
|
||||
draws[at] = exceptional;
|
||||
assert_eq!(
|
||||
render(&draws, true, false, false).0,
|
||||
render(&draws, false, false, false).0,
|
||||
"position {at}"
|
||||
);
|
||||
}
|
||||
}
|
||||
for draw in [VertexDraw { offset: 1, ..draw }, foreign] {
|
||||
let draws = [draw; 10];
|
||||
let (direct, _) = render(&draws, false, false, false);
|
||||
assert!(!direct.1.is_empty());
|
||||
assert_eq!(render(&draws, true, false, false).0, direct);
|
||||
}
|
||||
let mut draws = long;
|
||||
draws[31] = VertexDraw {
|
||||
index: wide,
|
||||
vertex_start: wide,
|
||||
..switched
|
||||
};
|
||||
draws[32] = VertexDraw {
|
||||
primitive_type: u64::MAX,
|
||||
..switched
|
||||
};
|
||||
assert_eq!(
|
||||
render(&draws[..33], true, false, false).0,
|
||||
render(&draws[..33], false, false, false).0
|
||||
);
|
||||
let copied = copied_vertex_buffer(&device, &vertices)?;
|
||||
let draws = long.map(|draw| VertexDraw {
|
||||
buffer: Some(&copied),
|
||||
..draw
|
||||
});
|
||||
let (batched, mdi) = render(&draws, true, false, false);
|
||||
assert_eq!(batched, render(&draws, false, false, false).0);
|
||||
assert_eq!(mdi, (0, 0));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copied_vertex_buffer(
|
||||
device: &RtObj<RtDevice>,
|
||||
data: &[u8],
|
||||
) -> Result<RtObj<RtBuffer>, &'static str> {
|
||||
use crate::core::host::HostPtr;
|
||||
use crate::core::num::ToUsize as _;
|
||||
use crate::core::platform::HostRange;
|
||||
use std::alloc::{Layout, alloc_zeroed, dealloc};
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let on = OnFault::Return;
|
||||
let page = device.facts().page_size;
|
||||
let layout =
|
||||
@@ -2095,14 +2550,23 @@ mod tests {
|
||||
.ok_or("no copied buffer")?;
|
||||
assert!(buffer.copied().is_some());
|
||||
assert!(super::super::copied::any());
|
||||
let green = [0, 255, 0, 255];
|
||||
let data = vertices(&[green]);
|
||||
// SAFETY: the vertices fit in the mapped page, and the copy was already initialized.
|
||||
unsafe {
|
||||
memory
|
||||
.as_ptr::<u8>()
|
||||
.copy_from_nonoverlapping(data.as_ptr(), data.len())
|
||||
};
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let on = OnFault::Return;
|
||||
let green = [0, 255, 0, 255];
|
||||
let buffer = copied_vertex_buffer(&device, &vertices(&[green]))?;
|
||||
let state = vdesc_state(&device, &function(&device, COLOR, "render_color"));
|
||||
let target = device
|
||||
.new_texture(
|
||||
|
||||
@@ -27,6 +27,8 @@ them; its `manual` checks are on a Linux host's guest boot.
|
||||
| `resolution=2560x1600` | the mode the window opens for, and the guest is offered until the window's pixels are known (QEMU's reims-graphics-pci property; 1920x1080 by default); with several displays, every window's |
|
||||
| `displays=2` | the reims-graphics device's displays, 1 to 4, a window each (QEMU's reims-graphics-pci property; 1 by default) |
|
||||
| `REIMS_VGPU_WINDOW_IMPL=sdl` | macOS, built with the `macos-sdl` feature (on by default): SDL3's window in place of AppKit's ("On macOS through SDL3" below) |
|
||||
| `REIMS_VGPU_WINDOW_RELEASE_KEYS=Ctrl+Shift+F12` | additional release shortcut for SDL windows on Windows and Linux; when unset, `REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS` can supply it |
|
||||
| `REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE=1` | on Windows and Linux, release the keyboard grab while the mouse is out of the SDL window |
|
||||
|
||||
Unset or unparsable values give the defaults below.
|
||||
`test: env::unset_or_unparsable_values_are_the_defaults`,
|
||||
@@ -833,6 +835,19 @@ runtime's own device. The switches above apply, and `resolution=` too.
|
||||
GNOME asks once whether the window may take its shortcuts, the answer
|
||||
kept for the installed app's entry, and Super+Escape gives GNOME its
|
||||
shortcuts until the window is focused again)
|
||||
- An additional release shortcut uses at least one modifier and one to three
|
||||
ordinary keys, and releases as the release chord does. The title names it
|
||||
in place of the chord, which still works. An empty or invalid setting
|
||||
leaves the chord alone.
|
||||
`test: native::sdl_thread::input::a_custom_shortcut_releases_the_grab_and_keeps_its_last_key`,
|
||||
`test: native::sdl_thread::input::a_custom_shortcut_can_hold_two_regular_keys`,
|
||||
`test: native::sdl_thread::input::an_invalid_shortcut_keeps_the_default`
|
||||
- With release on mouse leave on, the mouse leaving the window lifts the held
|
||||
keys and buttons and releases the keyboard grab until the mouse comes back
|
||||
or the window next gains the keyboard. The setting also turns off a game's
|
||||
pointer lock and a drag gone on onto another display.
|
||||
`test: native::sdl_thread::input::the_mouse_leaving_releases_the_grab_until_it_returns_when_enabled`,
|
||||
`manual` (move the pointer out of the window and back)
|
||||
- Scrolling: the wheel's notches, or, where the host takes smooth
|
||||
scrolling, its lines at 10 points each, in no gesture (SDL gives no
|
||||
phases); the guest gets the device's own direction.
|
||||
@@ -881,9 +896,11 @@ runtime's own device. The switches above apply, and `resolution=` too.
|
||||
own X11 dialog. zenity's question is a window of another process, which
|
||||
the window does not own, so the display's end (the guest's own
|
||||
shutdown, the host's stop) ends it, as Cancel, and none stays on the
|
||||
screen after the VM. On Windows the system's message box, which the
|
||||
window owns, its OK named Turn Off, left of Cancel; the display's end
|
||||
ends it as Cancel too. Turn Off asks the host
|
||||
screen after the VM. On Windows, Reims-Go can handle the close in its
|
||||
own dialog with Shut down, Suspend and Cancel. When the handoff is
|
||||
unavailable, the system shows a message box owned by the window,
|
||||
with Turn Off left of Cancel. The display's end cancels it as well.
|
||||
Turn Off asks the host
|
||||
to end the VM; Cancel, or the question dismissed, leaves the window and
|
||||
the VM running, nothing held in the guest and the input released. From
|
||||
the close to the answer nothing of the window's input reaches the guest:
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
//! shutdown request with the power-off action, which the guest is not asked about). So the window
|
||||
//! asks first, in a question of the host OS's own over the window ([`QUESTION`], [`DETAIL`]), with
|
||||
//! two answers: [`CANCEL`], the default, keeps the VM running, and [`TURN_OFF`] tells the host.
|
||||
//! A Windows VM started by Reims-Go can hand the question to its client
|
||||
//! instead. The client then handles the chosen action.
|
||||
//!
|
||||
//! **When it asks** ([`Asks::request`]): only where the host would hear of the close, while the
|
||||
//! window lives (the display's release takes the host's callbacks back) and the host gave a close
|
||||
@@ -58,6 +60,9 @@ pub(crate) enum Answer {
|
||||
Cancel,
|
||||
/// No question could show: nothing happens, as for Cancel, and the OS's side logs why.
|
||||
Unshown,
|
||||
/// Reims-Go's dialog handles the close.
|
||||
#[cfg(target_os = "windows")]
|
||||
Delegated,
|
||||
}
|
||||
|
||||
/// The process's questions: whether one is open, and whether the person has chosen Turn Off.
|
||||
@@ -111,6 +116,8 @@ pub(crate) fn answered(answer: Answer) -> bool {
|
||||
Answer::TurnOff => "the person chose Turn Off: the host turns the VM off",
|
||||
Answer::Cancel => "the close is cancelled, or its window ended: the host is not told",
|
||||
Answer::Unshown => "no question showed: the host is not told, and the VM runs on",
|
||||
#[cfg(target_os = "windows")]
|
||||
Answer::Delegated => "the close question was handed to Reims-Go",
|
||||
};
|
||||
log::info!(target: "reims_vgpu_window", "{said}");
|
||||
tell
|
||||
@@ -147,5 +154,13 @@ mod tests {
|
||||
assert_eq!(unshown.request(true), Step::Ask);
|
||||
assert!(!unshown.answered(Answer::Unshown));
|
||||
assert_eq!(unshown.request(true), Step::Ask);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let mut delegated = Asks::default();
|
||||
assert_eq!(delegated.request(true), Step::Ask);
|
||||
assert!(!delegated.answered(Answer::Delegated));
|
||||
assert_eq!(delegated.request(true), Step::Ask);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
//! Collects a window's SDL file or text drop and forwards it to the local host bridge.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::io::{self, Write as _};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::mpsc::{self, SyncSender, TrySendError};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::geometry::{self, Rect};
|
||||
|
||||
/// Maximum number of files forwarded in a single drop.
|
||||
const MAX_DROP_PATHS: usize = 256;
|
||||
|
||||
/// Maximum joined UTF-8 text size forwarded in a single drop.
|
||||
const MAX_DROP_TEXT_BYTES: usize = 128 << 10;
|
||||
|
||||
/// Drop contents and guest-image coordinates for one completed host drop.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DropPayload {
|
||||
/// Guest display port that received the drop.
|
||||
pub display_index: u64,
|
||||
/// Horizontal position, clamped to the guest image.
|
||||
pub norm_x: f64,
|
||||
/// Vertical position, clamped to the guest image.
|
||||
pub norm_y: f64,
|
||||
/// Whether the original position was inside the guest image.
|
||||
pub in_image: bool,
|
||||
/// Host paths in the order SDL delivered them.
|
||||
pub paths: Vec<String>,
|
||||
/// Joined text for a drop without files.
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
/// Maps a window point to the guest image, using its center when geometry is unavailable.
|
||||
pub(crate) fn normalize_point(point: Option<(f64, f64)>, image: Rect) -> (f64, f64, bool) {
|
||||
let Some((x, y)) = point else {
|
||||
return (0.5, 0.5, false);
|
||||
};
|
||||
if ![x, y, image.x, image.y, image.width, image.height]
|
||||
.into_iter()
|
||||
.all(f64::is_finite)
|
||||
|| image.width <= 0.0
|
||||
|| image.height <= 0.0
|
||||
{
|
||||
return (0.5, 0.5, false);
|
||||
}
|
||||
(
|
||||
((x - image.x) / image.width).clamp(0.0, 1.0),
|
||||
((y - image.y) / image.height).clamp(0.0, 1.0),
|
||||
geometry::contains(image, (x, y)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Drop state for one SDL window, active from begin or the first file, text or position.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct DropBatch {
|
||||
/// Host paths collected for this batch.
|
||||
paths: Option<Vec<String>>,
|
||||
/// Nonempty input chunks in delivery order, bounded before joining.
|
||||
texts: Option<Vec<String>>,
|
||||
/// Joined bytes consumed, saturated at the limit once a chunk is truncated.
|
||||
text_bytes: usize,
|
||||
/// Most recent finite position, in SDL window coordinates.
|
||||
last_pos: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl DropBatch {
|
||||
/// Starts a new batch, discarding an unfinished drop.
|
||||
pub(crate) fn begin(&mut self) {
|
||||
self.paths = Some(Vec::new());
|
||||
self.texts = None;
|
||||
self.text_bytes = 0;
|
||||
self.last_pos = None;
|
||||
}
|
||||
|
||||
/// Records the most recent usable position.
|
||||
pub(crate) fn position(&mut self, x: f64, y: f64) {
|
||||
if x.is_finite() && y.is_finite() {
|
||||
self.last_pos = Some((x, y));
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts a file even if SDL omitted begin, taking its position as a fallback.
|
||||
pub(crate) fn file(&mut self, path: String, pos: Option<(f64, f64)>) {
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
let paths = self.paths.get_or_insert_with(Vec::new);
|
||||
if paths.len() < MAX_DROP_PATHS {
|
||||
paths.push(path);
|
||||
}
|
||||
if self.last_pos.is_none()
|
||||
&& let Some((x, y)) = pos
|
||||
{
|
||||
self.position(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects UTF-8 text up to the byte limit, including separators between chunks.
|
||||
pub(crate) fn text(&mut self, chunk: String, pos: Option<(f64, f64)>) {
|
||||
if chunk.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.last_pos.is_none()
|
||||
&& let Some((x, y)) = pos
|
||||
{
|
||||
self.position(x, y);
|
||||
}
|
||||
if self.text_bytes == MAX_DROP_TEXT_BYTES {
|
||||
return;
|
||||
}
|
||||
let separator = usize::from(self.texts.is_some());
|
||||
let remaining = MAX_DROP_TEXT_BYTES - self.text_bytes - separator;
|
||||
let texts = self.texts.get_or_insert_with(Vec::new);
|
||||
if chunk.len() > remaining {
|
||||
let kept = &chunk[..chunk.floor_char_boundary(remaining)];
|
||||
if !kept.is_empty() {
|
||||
texts.push(kept.to_owned());
|
||||
}
|
||||
self.text_bytes = MAX_DROP_TEXT_BYTES;
|
||||
} else {
|
||||
self.text_bytes += separator + chunk.len();
|
||||
texts.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
/// Finishes this batch and yields its files or text and normalized drop position.
|
||||
pub(crate) fn complete(
|
||||
&mut self,
|
||||
display_index: u64,
|
||||
image: Rect,
|
||||
pos: Option<(f64, f64)>,
|
||||
) -> Option<DropPayload> {
|
||||
let point = self.last_pos.take().or(pos);
|
||||
let paths = self.paths.take().unwrap_or_default();
|
||||
let texts = self.texts.take();
|
||||
self.text_bytes = 0;
|
||||
let text = if paths.is_empty() {
|
||||
Some(texts.filter(|chunks| !chunks.is_empty())?.join("\n"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (norm_x, norm_y, in_image) = normalize_point(point, image);
|
||||
Some(DropPayload {
|
||||
display_index,
|
||||
norm_x,
|
||||
norm_y,
|
||||
in_image,
|
||||
paths,
|
||||
text,
|
||||
})
|
||||
}
|
||||
|
||||
/// Discards drop contents and position when the window closes.
|
||||
pub(crate) fn reset(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends one quoted string with RFC 8259 escapes.
|
||||
fn push_json_string(json: &mut String, value: &str) {
|
||||
json.push('"');
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'"' => json.push_str("\\\""),
|
||||
'\\' => json.push_str("\\\\"),
|
||||
'\u{8}' => json.push_str("\\b"),
|
||||
'\u{c}' => json.push_str("\\f"),
|
||||
'\n' => json.push_str("\\n"),
|
||||
'\r' => json.push_str("\\r"),
|
||||
'\t' => json.push_str("\\t"),
|
||||
'\0'..='\u{1f}' => {
|
||||
// Writing to a String is infallible.
|
||||
let _ = write!(json, "\\u{:04x}", u32::from(ch));
|
||||
}
|
||||
_ => json.push(ch),
|
||||
}
|
||||
}
|
||||
json.push('"');
|
||||
}
|
||||
|
||||
/// Encodes a file or text drop as UTF-8 JSON.
|
||||
pub(crate) fn encode_drop_json(payload: &DropPayload) -> String {
|
||||
let mut json = format!(
|
||||
r#"{{"display_index":{},"norm_x":{},"norm_y":{},"in_image":{}"#,
|
||||
payload.display_index, payload.norm_x, payload.norm_y, payload.in_image,
|
||||
);
|
||||
if !payload.paths.is_empty() {
|
||||
json.push_str(r#","paths":["#);
|
||||
for (i, path) in payload.paths.iter().enumerate() {
|
||||
if i != 0 {
|
||||
json.push(',');
|
||||
}
|
||||
push_json_string(&mut json, path);
|
||||
}
|
||||
json.push(']');
|
||||
} else if let Some(text) = &payload.text {
|
||||
json.push_str(r#","text":"#);
|
||||
push_json_string(&mut json, text);
|
||||
}
|
||||
json.push('}');
|
||||
json
|
||||
}
|
||||
|
||||
/// Parses the explicit IPv4 loopback endpoint used by the host drop bridge.
|
||||
fn parse_loopback_drop_url(raw: &str) -> Option<(SocketAddr, String)> {
|
||||
let rest = raw.strip_prefix("http://127.0.0.1:")?;
|
||||
let (port, path) = match rest.find('/') {
|
||||
Some(i) => (&rest[..i], &rest[i..]),
|
||||
None => (rest, "/v1/host-drop"),
|
||||
};
|
||||
if !port.bytes().all(|b| b.is_ascii_digit())
|
||||
|| path.bytes().any(|b| b.is_ascii_control() || b == b' ')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let port: u16 = port.parse().ok()?;
|
||||
(port != 0).then(|| (SocketAddr::from(([127, 0, 0, 1], port)), path.to_owned()))
|
||||
}
|
||||
|
||||
/// SDL's bounded queue to the HTTP worker.
|
||||
static DROP_TX: OnceLock<SyncSender<DropPayload>> = OnceLock::new();
|
||||
|
||||
/// Starts the HTTP worker when the runtime provides a valid local URL and bearer token.
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "linux", target_os = "windows")),
|
||||
expect(
|
||||
dead_code,
|
||||
reason = "only the SDL thread starts the host drop forwarder"
|
||||
)
|
||||
)]
|
||||
pub(crate) fn install_host_drop_forwarder() {
|
||||
let Ok(url) = std::env::var("REIMS_GO_DROP_URL") else {
|
||||
return;
|
||||
};
|
||||
let Ok(token) = std::env::var("REIMS_GO_DROP_TOKEN") else {
|
||||
return;
|
||||
};
|
||||
if token.is_empty() || token.contains(['\r', '\n']) || DROP_TX.get().is_some() {
|
||||
return;
|
||||
}
|
||||
let Some((addr, path)) = parse_loopback_drop_url(&url) else {
|
||||
log::warn!(target: "reims_vgpu_window", "ignoring invalid REIMS_GO_DROP_URL");
|
||||
return;
|
||||
};
|
||||
let (tx, rx) = mpsc::sync_channel(16);
|
||||
match std::thread::Builder::new()
|
||||
.name("reims-vgpu.drop".into())
|
||||
.spawn(move || {
|
||||
for payload in rx {
|
||||
if let Err(err) = post_loopback_drop(addr, &path, &token, &payload) {
|
||||
log::warn!(target: "reims_vgpu_window", "could not forward file drop: {err}");
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Ok(_) => {
|
||||
let _ = DROP_TX.set(tx);
|
||||
}
|
||||
Err(err) => log::warn!(target: "reims_vgpu_window", "could not start drop worker: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Enqueues a drop without waiting for network I/O or queue space on the UI thread.
|
||||
pub(crate) fn submit(payload: DropPayload) {
|
||||
if let Some(tx) = DROP_TX.get()
|
||||
&& let Err(TrySendError::Full(_)) = tx.try_send(payload)
|
||||
{
|
||||
log::warn!(target: "reims_vgpu_window", "file drop queue is full");
|
||||
}
|
||||
}
|
||||
|
||||
/// Posts one complete JSON payload to the authenticated IPv4 loopback bridge.
|
||||
fn post_loopback_drop(
|
||||
addr: SocketAddr,
|
||||
path: &str,
|
||||
token: &str,
|
||||
payload: &DropPayload,
|
||||
) -> io::Result<()> {
|
||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_millis(500))?;
|
||||
stream.set_write_timeout(Some(Duration::from_millis(2000)))?;
|
||||
let body = encode_drop_json(payload);
|
||||
write!(
|
||||
stream,
|
||||
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\n\
|
||||
Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
)?;
|
||||
stream.write_all(body.as_bytes())
|
||||
}
|
||||
|
||||
/// Offline tests for window drops and the host bridge protocol.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
use std::net::TcpListener;
|
||||
|
||||
/// Guest image offset from the window edges.
|
||||
const IMAGE: Rect = Rect {
|
||||
x: 10.0,
|
||||
y: 20.0,
|
||||
width: 40.0,
|
||||
height: 80.0,
|
||||
};
|
||||
|
||||
/// Coordinates use half-open image bounds and clamp outside those bounds.
|
||||
#[test]
|
||||
fn normalizes_window_points() {
|
||||
for (point, expected) in [
|
||||
((20.0, 80.0), (0.25, 0.75, true)),
|
||||
((10.0, 20.0), (0.0, 0.0, true)),
|
||||
((50.0, 100.0), (1.0, 1.0, false)),
|
||||
((0.0, 120.0), (0.0, 1.0, false)),
|
||||
] {
|
||||
assert_eq!(normalize_point(Some(point), IMAGE), expected);
|
||||
}
|
||||
let center = (0.5, 0.5, false);
|
||||
for point in [None, Some((f64::NAN, 40.0)), Some((20.0, f64::INFINITY))] {
|
||||
assert_eq!(normalize_point(point, IMAGE), center);
|
||||
}
|
||||
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
for image in [
|
||||
Rect {
|
||||
width: bad,
|
||||
..IMAGE
|
||||
},
|
||||
Rect {
|
||||
height: bad,
|
||||
..IMAGE
|
||||
},
|
||||
] {
|
||||
assert_eq!(normalize_point(Some((20.0, 80.0)), image), center);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Position events override file and completion coordinates, retaining file order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn batch_completes_with_latest_position() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.begin();
|
||||
batch.file("first".into(), Some((50.0, 100.0)));
|
||||
batch.position(20.0, 80.0);
|
||||
batch.position(f64::NAN, 90.0);
|
||||
batch.file("second".into(), Some((40.0, 30.0)));
|
||||
let p = batch
|
||||
.complete(42, IMAGE, Some((30.0, 60.0)))
|
||||
.expect("two files");
|
||||
assert_eq!(p.display_index, 42);
|
||||
assert_eq!(p.paths, ["first", "second"]);
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
assert!(batch.complete(42, IMAGE, None).is_none());
|
||||
}
|
||||
|
||||
/// Missing begin, invalid file coordinates, completion fallback and reset are independent.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn handles_partial_batches() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.file("".into(), Some((10.0, 20.0)));
|
||||
batch.file("first".into(), Some((1.0, f64::NAN)));
|
||||
batch.file("second".into(), Some((20.0, 80.0)));
|
||||
batch.file("third".into(), Some((40.0, 30.0)));
|
||||
let p = batch.complete(1, IMAGE, None).expect("file-only drop");
|
||||
assert_eq!(p.paths, ["first", "second", "third"]);
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
batch.file("abandoned".into(), Some((20.0, 80.0)));
|
||||
batch.begin();
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.file("closed".into(), Some((20.0, 80.0)));
|
||||
batch.reset();
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.position(20.0, 80.0);
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.file("next".into(), None);
|
||||
let p = batch
|
||||
.complete(2, IMAGE, Some((60.0, 60.0)))
|
||||
.expect("fresh drop");
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (1.0, 0.5, false));
|
||||
}
|
||||
|
||||
/// Oversized drops retain the first 256 paths in order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn caps_paths() {
|
||||
let mut batch = DropBatch::default();
|
||||
for i in 0..260 {
|
||||
batch.file(i.to_string(), None);
|
||||
}
|
||||
let p = batch.complete(0, IMAGE, None).expect("bounded drop");
|
||||
assert_eq!(p.paths, (0..256).map(|i| i.to_string()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// URL drops keep their position and subsequent batches join chunks in order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn collects_url_and_multiline_text() {
|
||||
let mut batch = DropBatch::default();
|
||||
let url = "https://example.org/路径";
|
||||
batch.text(url.into(), Some((20.0, 80.0)));
|
||||
let p = batch.complete(1, IMAGE, None).expect("URL drop");
|
||||
assert_eq!(p.text.as_deref(), Some(url));
|
||||
assert!(p.paths.is_empty());
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
|
||||
batch.text("abandoned".into(), None);
|
||||
batch.begin();
|
||||
batch.text("one\ntwo".into(), None);
|
||||
batch.text(String::new(), None);
|
||||
batch.text("three".into(), None);
|
||||
let p = batch.complete(1, IMAGE, None).expect("multiline drop");
|
||||
assert_eq!(p.text.as_deref(), Some("one\ntwo\nthree"));
|
||||
}
|
||||
|
||||
/// A split UTF-8 character ends collection even when a smaller chunk would fit.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn truncates_text_at_utf8_boundary() {
|
||||
let mut batch = DropBatch::default();
|
||||
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 6);
|
||||
batch.text(prefix.clone(), None);
|
||||
batch.text("界界".into(), None);
|
||||
batch.text("x".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("bounded text drop");
|
||||
assert_eq!(p.text, Some(format!("{prefix}\n界")));
|
||||
|
||||
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 3);
|
||||
batch.text(prefix.clone(), None);
|
||||
batch.text("界".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("two bytes remaining");
|
||||
assert_eq!(p.text, Some(prefix));
|
||||
}
|
||||
|
||||
/// Files take precedence over text regardless of arrival order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn files_take_precedence() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.text("before".into(), None);
|
||||
batch.file("path".into(), None);
|
||||
batch.text("after".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("mixed drop");
|
||||
assert_eq!(p.paths, ["path"]);
|
||||
assert_eq!(p.text, None);
|
||||
assert!(batch.complete(0, IMAGE, None).is_none());
|
||||
}
|
||||
|
||||
/// Text JSON preserves Unicode and escapes quotes, backslashes and newlines.
|
||||
#[test]
|
||||
fn encodes_json_text() {
|
||||
let p = DropPayload {
|
||||
text: Some("你好 \"\\\n".into()),
|
||||
paths: Vec::new(),
|
||||
..sample()
|
||||
};
|
||||
assert_eq!(
|
||||
encode_drop_json(&p),
|
||||
concat!(
|
||||
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"#,
|
||||
r#""text":"你好 \"\\\n"}"#,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// An example drop containing Unicode, delimiters and control characters.
|
||||
fn sample() -> DropPayload {
|
||||
DropPayload {
|
||||
display_index: 17,
|
||||
norm_x: 0.25,
|
||||
norm_y: 0.75,
|
||||
in_image: true,
|
||||
text: None,
|
||||
paths: vec![
|
||||
r"D:\Downloads\测试.pdf".into(),
|
||||
"\"\u{8}\u{c}\n\r\t\0\u{10}".into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks UTF-8 preservation and each class of RFC 8259 escape.
|
||||
#[test]
|
||||
fn encodes_json_paths() {
|
||||
assert_eq!(
|
||||
encode_drop_json(&sample()),
|
||||
concat!(
|
||||
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"paths":["#,
|
||||
r#""D:\\Downloads\\测试.pdf","\"\b\f\n\r\t\u0000\u0010"]}"#,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// Only the literal loopback host, a numeric nonzero port and a safe path are accepted.
|
||||
#[test]
|
||||
fn validates_loopback_urls() {
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 42));
|
||||
assert_eq!(
|
||||
parse_loopback_drop_url("http://127.0.0.1:42"),
|
||||
Some((addr, "/v1/host-drop".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_loopback_drop_url("http://127.0.0.1:42/drop?q=1"),
|
||||
Some((addr, "/drop?q=1".into()))
|
||||
);
|
||||
for raw in [
|
||||
"https://127.0.0.1:42/drop",
|
||||
"http://localhost:42/drop",
|
||||
"http://127.0.0.2:42/drop",
|
||||
"http://[::1]:42/drop",
|
||||
"http://127.0.0.1:/drop",
|
||||
"http://127.0.0.1:0/drop",
|
||||
"http://127.0.0.1:65536/drop",
|
||||
"http://127.0.0.1:+42/drop",
|
||||
"http://127.0.0.1:42@evil/drop",
|
||||
"http://127.0.0.1:42/a b",
|
||||
"http://127.0.0.1:42/a\rheader",
|
||||
"http://127.0.0.1:42/a\nheader",
|
||||
" http://127.0.0.1:42",
|
||||
"http://127.0.0.1:42/drop\r\n",
|
||||
] {
|
||||
assert!(parse_loopback_drop_url(raw).is_none(), "{raw:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A real loopback peer receives the authenticated request and exact UTF-8 byte count.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn posts_the_complete_drop_to_loopback() -> io::Result<()> {
|
||||
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let payload = sample();
|
||||
post_loopback_drop(
|
||||
listener.local_addr()?,
|
||||
"/custom/drop",
|
||||
"test-token",
|
||||
&payload,
|
||||
)?;
|
||||
let (mut stream, _) = listener.accept()?;
|
||||
stream.set_nonblocking(false)?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
let mut request = String::new();
|
||||
stream.read_to_string(&mut request)?;
|
||||
let (headers, body) = request.split_once("\r\n\r\n").expect("HTTP headers");
|
||||
assert_eq!(headers.lines().next(), Some("POST /custom/drop HTTP/1.1"));
|
||||
for field in [
|
||||
"Host: 127.0.0.1",
|
||||
"Authorization: Bearer test-token",
|
||||
"Content-Type: application/json",
|
||||
"Connection: close",
|
||||
] {
|
||||
assert!(headers.lines().any(|line| line == field), "{field}");
|
||||
}
|
||||
assert!(
|
||||
headers
|
||||
.lines()
|
||||
.any(|line| line == format!("Content-Length: {}", body.len()))
|
||||
);
|
||||
assert_eq!(body, encode_drop_json(&payload));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,17 @@
|
||||
//! place of AppKit's, in a build with the `macos-sdl` feature, on by default (one without it
|
||||
//! logs that, and opens AppKit's). Default: AppKit's. Linux has SDL3's alone, and reads no
|
||||
//! value.
|
||||
//! - `REIMS_VGPU_WINDOW_CAPTURE`: `0`, `false`, `no` or `off`, in any case, turns capture off:
|
||||
//! the window leaves the keyboard and pointer ungrabbed. `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.
|
||||
//! - `REIMS_VGPU_WINDOW_RELEASE_KEYS`: an additional release shortcut for SDL's windows on
|
||||
//! Windows and Linux, such as `Ctrl+Shift+F12`. Reims-Go's capture shortcut plugin can supply
|
||||
//! it through its own namespace. The built-in release chord remains available.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -19,6 +30,20 @@ pub const BORDERLESS_VAR: &str = "REIMS_VGPU_WINDOW_BORDERLESS";
|
||||
pub const SCREENS_VAR: &str = "REIMS_VGPU_WINDOW_SCREENS";
|
||||
/// The window implementation's variable (macOS).
|
||||
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";
|
||||
/// The extra release shortcut for Windows and Linux SDL windows.
|
||||
pub const RELEASE_KEYS_VAR: &str = "REIMS_VGPU_WINDOW_RELEASE_KEYS";
|
||||
/// The same shortcut supplied through the Reims-Go capture shortcut plugin.
|
||||
const PLUGIN_RELEASE_KEYS_VAR: &str = "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS";
|
||||
/// The plugin's switch for releasing input when the mouse leaves the window.
|
||||
const PLUGIN_RELEASE_ON_LEAVE_VAR: &str = "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE";
|
||||
|
||||
/// Whether the window may grab the keyboard and lock the game pointer by default.
|
||||
pub const CAPTURE_DEFAULT: bool = true;
|
||||
|
||||
/// What the variables say.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Settings {
|
||||
@@ -28,6 +53,14 @@ pub struct Settings {
|
||||
pub screens: Vec<usize>,
|
||||
/// Which window a display opens on macOS.
|
||||
pub window_impl: WindowImpl,
|
||||
/// Whether the window may grab the keyboard and lock the game pointer.
|
||||
pub capture: bool,
|
||||
/// Keep offering the configured guest resolution instead of following the window's pixels.
|
||||
pub fixed_mode: bool,
|
||||
/// Additional release shortcut text for the SDL window.
|
||||
pub release_keys: Option<String>,
|
||||
/// Release input when the mouse leaves the SDL window.
|
||||
pub release_on_leave: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -36,6 +69,10 @@ impl Default for Settings {
|
||||
borderless: false,
|
||||
screens: Vec::new(),
|
||||
window_impl: WindowImpl::AppKit,
|
||||
capture: CAPTURE_DEFAULT,
|
||||
fixed_mode: false,
|
||||
release_keys: None,
|
||||
release_on_leave: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,6 +121,20 @@ fn parse_screens(value: &str) -> Option<Vec<usize>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the window may grab the keyboard and lock the game pointer. Default on.
|
||||
pub fn parse_capture(value: Option<&str>) -> bool {
|
||||
value.is_none_or(|value| {
|
||||
!["0", "false", "no", "off"]
|
||||
.iter()
|
||||
.any(|off| value.trim().eq_ignore_ascii_case(off))
|
||||
})
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -93,6 +144,12 @@ pub fn settings() -> &'static Settings {
|
||||
let (borderless, screens) = (var(BORDERLESS_VAR), var(SCREENS_VAR));
|
||||
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()),
|
||||
release_keys: var(RELEASE_KEYS_VAR).or_else(|| var(PLUGIN_RELEASE_KEYS_VAR)),
|
||||
release_on_leave: var(PLUGIN_RELEASE_ON_LEAVE_VAR)
|
||||
.as_deref()
|
||||
.is_some_and(parse_switch),
|
||||
..parse(borderless.as_deref(), screens.as_deref())
|
||||
}
|
||||
})
|
||||
|
||||
@@ -98,6 +98,8 @@ pub fn pointer_outside_image(dragging: bool) -> bool {
|
||||
/// Whether the window holds the keyboard grab (the module doc).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Grab {
|
||||
/// The VM's capture setting rejects the keyboard grab.
|
||||
disabled: bool,
|
||||
/// The release chord gave the shell its keys, until the window next gains the keyboard.
|
||||
released: bool,
|
||||
}
|
||||
@@ -108,10 +110,18 @@ impl Grab {
|
||||
Grab::default()
|
||||
}
|
||||
|
||||
/// The VM keeps the host's keyboard shortcuts.
|
||||
pub fn disabled() -> Grab {
|
||||
Grab {
|
||||
disabled: true,
|
||||
..Grab::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the window on `host` asks for the keyboard grab: where its OS takes one, until the
|
||||
/// release chord (the module doc). The OS holds it only while the window has the keyboard.
|
||||
pub fn holds_keyboard(&self, host: HostOs) -> bool {
|
||||
host.grabs_the_keyboard() && !self.released
|
||||
host.grabs_the_keyboard() && !self.disabled && !self.released
|
||||
}
|
||||
|
||||
/// The window gained the keyboard: the grab is held again after a release. Whether it was
|
||||
@@ -164,6 +174,16 @@ mod tests {
|
||||
assert!(!grab.holds_keyboard(HostOs::MacOs));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disabled_keyboard_grab_stays_disabled_after_refocusing() {
|
||||
let mut grab = Grab::disabled();
|
||||
assert!(!grab.holds_keyboard(HostOs::Windows));
|
||||
grab.release();
|
||||
grab.focus_gained();
|
||||
assert!(!grab.holds_keyboard(HostOs::Windows));
|
||||
assert!(!grab.release_chord(CHORD, HostOs::Windows, false));
|
||||
}
|
||||
|
||||
/// ⌃⌥⌘ together, with or without Shift, gives the shell its keys until the window next
|
||||
/// gains the keyboard; fewer keys do not; once released, the chord releases nothing more
|
||||
/// but a game's lock
|
||||
|
||||
@@ -68,6 +68,8 @@ pub mod winsys;
|
||||
// The SDL3 window: Linux's and Windows's (`native/sdl_thread.rs`), and macOS's with the
|
||||
// `macos-sdl` feature, behind `REIMS_VGPU_WINDOW_IMPL`.
|
||||
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
|
||||
mod drop;
|
||||
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
|
||||
mod sdl;
|
||||
|
||||
pub use config::{
|
||||
|
||||
@@ -793,11 +793,13 @@ impl InputState {
|
||||
/// host gives it.
|
||||
pub(crate) fn new(window: Arc<Window>) -> InputState {
|
||||
let mut logic = InputLogic::new(crate::native::is_iso_keyboard());
|
||||
let callbacks = window.callbacks();
|
||||
logic.motion = callbacks
|
||||
.as_ref()
|
||||
.and_then(|callbacks| callbacks.motion.clone());
|
||||
logic.beyond = callbacks.and_then(|callbacks| callbacks.beyond);
|
||||
if crate::env::settings().capture {
|
||||
let callbacks = window.callbacks();
|
||||
logic.motion = callbacks
|
||||
.as_ref()
|
||||
.and_then(|callbacks| callbacks.motion.clone());
|
||||
logic.beyond = callbacks.and_then(|callbacks| callbacks.beyond);
|
||||
}
|
||||
InputState {
|
||||
window,
|
||||
logic,
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! its own, `reims-vgpu.question`, so the UI thread runs on while it is up: the other windows'
|
||||
//! events and the work posted to the UI thread go on, and the windows' frames keep drawing.
|
||||
//!
|
||||
//! - **On Windows** it is the system's message box, which the window owns
|
||||
//! (`super::super::windows`, `ask_in_a_message_box`), for every close.
|
||||
//! - **On Windows** Reims-Go can handle the close first. If it cannot, the system's message
|
||||
//! box is shown with the window as its owner (`super::super::windows`).
|
||||
//! - **On Linux** it is zenity's question (`zenity`), where the window draws no question of its
|
||||
//! own (`super::sdl`, `overlay_unshown`) and zenity is installed. zenity is a process of its
|
||||
//! own, which the window does not own; it is run as SDL 3.4.18 runs it for a message box
|
||||
@@ -168,7 +168,11 @@ pub(super) fn ask(id: u64, parent: *mut SDL_Window, ids: Vec<u64>) {
|
||||
#[cfg(target_os = "linux")]
|
||||
let answer = zenity(OsStr::new("zenity"), id);
|
||||
#[cfg(target_os = "windows")]
|
||||
let answer = super::super::windows::ask_in_a_message_box(owner, id);
|
||||
let answer = if super::super::windows::request_client_close() {
|
||||
Some(Answer::Delegated)
|
||||
} else {
|
||||
super::super::windows::ask_in_a_message_box(owner, id)
|
||||
};
|
||||
let ended = DIALOGS.lock().done(id);
|
||||
super::ui::post(move || match (ended, answer) {
|
||||
(true, _) => super::sdl::finish(id, &ids, Answer::Cancel),
|
||||
|
||||
@@ -70,6 +70,7 @@
|
||||
//! it where it is, moved nowhere, the guest's cursor left where the drag took it; the release
|
||||
//! chord, losing the keyboard and closing unlock it where it was held.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::super::HOST_OS;
|
||||
@@ -81,7 +82,7 @@ use crate::config::{
|
||||
use crate::game::Game;
|
||||
use crate::geometry::{self, Rect};
|
||||
use crate::grab::{self, Grab};
|
||||
use crate::keys::{KeyEvent, KeyState};
|
||||
use crate::keys::{KeyEvent, KeyState, Modifiers};
|
||||
use crate::scroll::POINTS_PER_LINE;
|
||||
|
||||
/// What the window knows when an event reaches it.
|
||||
@@ -175,6 +176,109 @@ fn fixed(points: f64) -> i32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// An additional release shortcut, using USB key positions like SDL's keyboard path.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ReleaseShortcut {
|
||||
modifiers: Modifiers,
|
||||
keys: Vec<u16>,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl ReleaseShortcut {
|
||||
pub(crate) fn parse(value: &str) -> Option<Self> {
|
||||
let parts = value.split('+').map(str::trim).map(str::to_ascii_uppercase);
|
||||
let mut modifiers = Modifiers::default();
|
||||
let mut keys = Vec::new();
|
||||
let mut key_names = Vec::new();
|
||||
for part in parts {
|
||||
let held = match part.as_str() {
|
||||
"CTRL" => &mut modifiers.control,
|
||||
"ALT" => &mut modifiers.option,
|
||||
"SHIFT" => &mut modifiers.shift,
|
||||
"WIN" | "SUPER" => &mut modifiers.command,
|
||||
_ => {
|
||||
let key = Self::parse_key(&part)?;
|
||||
if keys.len() == 3 || keys.contains(&key) {
|
||||
return None;
|
||||
}
|
||||
keys.push(key);
|
||||
key_names.push(part);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if std::mem::replace(held, true) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if modifiers == Modifiers::default() || keys.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut name = String::new();
|
||||
for (held, label) in [
|
||||
(modifiers.control, "Ctrl+"),
|
||||
(modifiers.option, "Alt+"),
|
||||
(modifiers.shift, "Shift+"),
|
||||
(
|
||||
modifiers.command,
|
||||
if cfg!(windows) { "Win+" } else { "Super+" },
|
||||
),
|
||||
] {
|
||||
if held {
|
||||
name.push_str(label);
|
||||
}
|
||||
}
|
||||
name.push_str(&key_names.join("+"));
|
||||
Some(Self {
|
||||
modifiers,
|
||||
keys,
|
||||
name,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_key(key_name: &str) -> Option<u16> {
|
||||
let key = match key_name.as_bytes() {
|
||||
[letter @ b'A'..=b'Z'] => u16::from(*letter - b'A') + 0x04,
|
||||
[digit @ b'1'..=b'9'] => u16::from(*digit - b'1') + 0x1e,
|
||||
[b'0'] => 0x27,
|
||||
_ => {
|
||||
let number = key_name.strip_prefix('F')?.parse::<u16>().ok()?;
|
||||
if !matches!(
|
||||
key_name,
|
||||
"F1" | "F2"
|
||||
| "F3"
|
||||
| "F4"
|
||||
| "F5"
|
||||
| "F6"
|
||||
| "F7"
|
||||
| "F8"
|
||||
| "F9"
|
||||
| "F10"
|
||||
| "F11"
|
||||
| "F12"
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
0x3a + number - 1
|
||||
}
|
||||
};
|
||||
Some(key)
|
||||
}
|
||||
|
||||
pub(crate) fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
/// Whether `usage` going down completes the shortcut, `keys` the keys already down.
|
||||
fn pressed(&self, usage: u16, keys: &KeyState) -> bool {
|
||||
self.keys.contains(&usage)
|
||||
&& self
|
||||
.keys
|
||||
.iter()
|
||||
.all(|&key| key == usage || keys.is_held(key))
|
||||
&& self.modifiers == keys.held_modifiers()
|
||||
}
|
||||
}
|
||||
|
||||
/// One window's input decisions (the module doc).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Input {
|
||||
@@ -182,6 +286,12 @@ pub(crate) struct Input {
|
||||
keys: KeyState,
|
||||
/// Whether the window holds the keyboard grab.
|
||||
grab: Grab,
|
||||
/// The person's own shortcut, which releases as the release chord does.
|
||||
release_shortcut: Option<ReleaseShortcut>,
|
||||
/// Whether the mouse leaving the window releases the input.
|
||||
release_on_leave: bool,
|
||||
/// The mouse leaving released the keyboard grab, until the mouse comes back.
|
||||
left: bool,
|
||||
/// The `BUTTON_*` bits of the buttons the guest was told are down.
|
||||
buttons: u32,
|
||||
/// The pointer event last sent.
|
||||
@@ -236,6 +346,52 @@ impl Input {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the VM's capture setting to keyboard grabs and pointer locks.
|
||||
pub(crate) fn with_capture(mut self, enabled: bool) -> Self {
|
||||
if !enabled {
|
||||
self.grab = Grab::disabled();
|
||||
self.beyond = None;
|
||||
self.motion = None;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets an additional shortcut for releasing the input.
|
||||
pub(crate) fn with_release_shortcut(self, release_shortcut: Option<ReleaseShortcut>) -> Input {
|
||||
Input {
|
||||
release_shortcut,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases the input when the mouse leaves the window. Nothing then locks the pointer, so it
|
||||
/// can always leave.
|
||||
pub(crate) fn with_release_on_leave(self, release_on_leave: bool) -> Input {
|
||||
Input {
|
||||
release_on_leave,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// The mouse left the window: where the setting asks, every key and button held is lifted and
|
||||
/// the shell has its keys until the mouse comes back or the window next gains the keyboard.
|
||||
pub(crate) fn mouse_left(&mut self) -> Reaction {
|
||||
if !self.release_on_leave || !self.focused || self.question || !self.holds_keyboard() {
|
||||
return Reaction::default();
|
||||
}
|
||||
self.lift_buttons();
|
||||
self.left = true;
|
||||
self.release()
|
||||
}
|
||||
|
||||
/// The mouse came back to the window: the grab its leaving released is held again.
|
||||
pub(crate) fn mouse_entered(&mut self) -> Reaction {
|
||||
let left = std::mem::take(&mut self.left);
|
||||
Reaction {
|
||||
held_changed: left && self.focused && self.grab.focus_gained(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a drag has gone past the image's edge.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn is_away(&self) -> bool {
|
||||
@@ -295,13 +451,20 @@ impl Input {
|
||||
|
||||
/// What the title ends with: the release chord while the window has the keyboard and holds
|
||||
/// its grab, or a game's lock holds the pointer, in the host's OS's names for its keys
|
||||
/// ([`grab::held_suffix`]); nothing otherwise.
|
||||
pub(crate) fn title_suffix(&self) -> &'static str {
|
||||
grab::held_suffix(
|
||||
/// ([`grab::held_suffix`]); nothing otherwise. The person's own shortcut is named in place of
|
||||
/// the chord.
|
||||
pub(crate) fn title_suffix(&self) -> Cow<'static, str> {
|
||||
let suffix = grab::held_suffix(
|
||||
HOST_OS,
|
||||
self.focused && self.holds_keyboard(),
|
||||
self.game.is_on(),
|
||||
)
|
||||
);
|
||||
match &self.release_shortcut {
|
||||
Some(shortcut) => suffix
|
||||
.replace(grab::chord_name(HOST_OS), &shortcut.name)
|
||||
.into(),
|
||||
None => suffix.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What to send, taken.
|
||||
@@ -334,7 +497,8 @@ impl Input {
|
||||
return;
|
||||
}
|
||||
if let (Some(point), Some(mode)) = (at.point, guest_mode(at)) {
|
||||
if self.focused
|
||||
if !self.release_on_leave
|
||||
&& self.focused
|
||||
&& geometry::contains(at.image, point)
|
||||
&& let Some(motion) = self.motion.clone()
|
||||
&& let Some(hold) = self.game.begin(motion.as_ref(), point)
|
||||
@@ -346,7 +510,8 @@ impl Input {
|
||||
Some(ToHost::Pointer { at, .. }) => Some(at),
|
||||
_ => None,
|
||||
};
|
||||
if self.buttons != 0
|
||||
if !self.release_on_leave
|
||||
&& self.buttons != 0
|
||||
&& let Some(beyond) = self.beyond.clone()
|
||||
&& let Some(hold) =
|
||||
self.away
|
||||
@@ -542,6 +707,15 @@ impl Input {
|
||||
}
|
||||
return Reaction::default();
|
||||
}
|
||||
if !repeat
|
||||
&& (self.holds_keyboard() || self.game.is_on())
|
||||
&& self
|
||||
.release_shortcut
|
||||
.as_ref()
|
||||
.is_some_and(|shortcut| shortcut.pressed(usage, &self.keys))
|
||||
{
|
||||
return self.release();
|
||||
}
|
||||
if let Some(event) = self.keys.key_down(usage, repeat) {
|
||||
self.out.push(ToHost::Key(event));
|
||||
}
|
||||
@@ -558,6 +732,7 @@ impl Input {
|
||||
/// ([`Grab::focus_gained`]), and the title names the chord where it does.
|
||||
pub(crate) fn focus_gained(&mut self) -> Reaction {
|
||||
self.focused = true;
|
||||
self.left = false;
|
||||
let regrab = self.grab.focus_gained();
|
||||
Reaction {
|
||||
held_changed: regrab || self.holds_keyboard(),
|
||||
@@ -917,6 +1092,86 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The person's own shortcut releases the grab as the chord does, its last key kept from the
|
||||
/// guest and the rest lifted there; the title names it.
|
||||
#[test]
|
||||
fn a_custom_shortcut_releases_the_grab_and_keeps_its_last_key() {
|
||||
let mut input =
|
||||
focused().with_release_shortcut(ReleaseShortcut::parse(" shift + ctrl + f12 "));
|
||||
assert!(input.title_suffix().contains("press Ctrl+Shift+F12 to"));
|
||||
input.key(0xE0, true, false);
|
||||
input.key(0xE1, true, false);
|
||||
assert!(input.key(0x45, true, false).held_changed);
|
||||
assert!(!input.holds_keyboard());
|
||||
assert_eq!(input.title_suffix(), "");
|
||||
assert_eq!(
|
||||
input.take(),
|
||||
vec![
|
||||
ToHost::Key(KeyEvent::down(0xE0)),
|
||||
ToHost::Key(KeyEvent::down(0xE1)),
|
||||
ToHost::Key(KeyEvent::up(0xE1)),
|
||||
ToHost::Key(KeyEvent::up(0xE0)),
|
||||
]
|
||||
);
|
||||
// Released, the shortcut is the guest's keys.
|
||||
input.key(0xE0, true, false);
|
||||
input.key(0xE1, true, false);
|
||||
assert!(!input.key(0x45, true, false).held_changed);
|
||||
assert_eq!(input.take().len(), 3);
|
||||
input.focus_gained();
|
||||
assert!(input.holds_keyboard());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_shortcut_can_hold_two_regular_keys() {
|
||||
let mut input = focused().with_release_shortcut(ReleaseShortcut::parse("Ctrl+A+Z"));
|
||||
assert!(!input.key(0xE0, true, false).held_changed);
|
||||
assert!(!input.key(0x04, true, false).held_changed);
|
||||
assert!(input.key(0x1D, true, false).held_changed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_shortcut_keeps_the_default() {
|
||||
for value in [
|
||||
"",
|
||||
"F12",
|
||||
"Ctrl+Shift",
|
||||
"Ctrl+Ctrl+F12",
|
||||
"Ctrl+F13",
|
||||
"Ctrl+F01",
|
||||
] {
|
||||
assert!(ReleaseShortcut::parse(value).is_none(), "{value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With the setting on, the mouse leaving the window lifts what is held and releases the grab
|
||||
/// until it comes back; the release chord's own release outlasts a visit elsewhere.
|
||||
#[test]
|
||||
fn the_mouse_leaving_releases_the_grab_until_it_returns_when_enabled() {
|
||||
for enabled in [false, true] {
|
||||
let mut input = focused().with_release_on_leave(enabled);
|
||||
input.button_down(BUTTON_LEFT, &at((10.0, 10.0)));
|
||||
input.key(0x04, true, false);
|
||||
input.take();
|
||||
assert_eq!(input.mouse_left().held_changed, enabled);
|
||||
assert_eq!(input.holds_keyboard(), !enabled);
|
||||
let sent = input.take();
|
||||
assert_eq!(sent.contains(&ToHost::Key(KeyEvent::up(0x04))), enabled);
|
||||
assert_eq!(
|
||||
sent.iter()
|
||||
.any(|event| matches!(event, ToHost::Pointer { buttons: 0, .. })),
|
||||
enabled
|
||||
);
|
||||
assert_eq!(input.mouse_entered().held_changed, enabled);
|
||||
assert!(input.holds_keyboard());
|
||||
}
|
||||
let mut input = focused().with_release_on_leave(true);
|
||||
input.release();
|
||||
assert!(!input.mouse_left().held_changed);
|
||||
assert!(!input.mouse_entered().held_changed);
|
||||
assert!(!input.holds_keyboard());
|
||||
}
|
||||
|
||||
/// Nothing holds the pointer: it is sent over the image alone, and outside it only in a drag,
|
||||
/// held at the image's edge, which ends there
|
||||
#[test]
|
||||
|
||||
@@ -133,6 +133,16 @@ impl Input {
|
||||
self.0.focus_lost().held_changed
|
||||
}
|
||||
|
||||
/// The mouse left the window: whether the keyboard's grab and the title follow.
|
||||
pub(crate) fn mouse_left(&mut self) -> bool {
|
||||
self.0.mouse_left().held_changed
|
||||
}
|
||||
|
||||
/// The mouse came back to the window: whether the keyboard's grab and the title follow.
|
||||
pub(crate) fn mouse_entered(&mut self) -> bool {
|
||||
self.0.mouse_entered().held_changed
|
||||
}
|
||||
|
||||
/// The compositor took the keyboard while the window keeps its focus (the module doc): every
|
||||
/// key and button held is lifted.
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -154,7 +164,7 @@ impl Input {
|
||||
|
||||
/// What the title ends with: the release chord while something holds
|
||||
/// ([`input::Input::title_suffix`]).
|
||||
pub(crate) fn title_suffix(&self) -> &'static str {
|
||||
pub(crate) fn title_suffix(&self) -> std::borrow::Cow<'static, str> {
|
||||
self.0.title_suffix()
|
||||
}
|
||||
|
||||
@@ -256,15 +266,39 @@ pub(crate) fn open(window: &Arc<Window>, borderless: bool, _taken: &[Frame]) ->
|
||||
display.0
|
||||
);
|
||||
let callbacks = window.callbacks();
|
||||
let settings = crate::env::settings();
|
||||
let release_shortcut = settings
|
||||
.release_keys
|
||||
.as_deref()
|
||||
.and_then(input::ReleaseShortcut::parse);
|
||||
if release_shortcut.is_none()
|
||||
&& settings
|
||||
.release_keys
|
||||
.as_deref()
|
||||
.is_some_and(|keys| !keys.trim().is_empty())
|
||||
{
|
||||
log::warn!(target: "reims_vgpu_window", "invalid input release shortcut; using the default");
|
||||
}
|
||||
log::info!(target: "reims_vgpu_window",
|
||||
"input settings: capture={}, release shortcut={}, release on mouse leave={}",
|
||||
settings.capture,
|
||||
release_shortcut.as_ref().map_or("default", input::ReleaseShortcut::name),
|
||||
settings.release_on_leave,
|
||||
);
|
||||
Some(Opened {
|
||||
sdl,
|
||||
asked: size,
|
||||
input: Input(input::Input::with_links(
|
||||
callbacks
|
||||
.as_ref()
|
||||
.and_then(|callbacks| callbacks.beyond.clone()),
|
||||
callbacks.and_then(|callbacks| callbacks.motion),
|
||||
)),
|
||||
input: Input(
|
||||
input::Input::with_links(
|
||||
callbacks
|
||||
.as_ref()
|
||||
.and_then(|callbacks| callbacks.beyond.clone()),
|
||||
callbacks.and_then(|callbacks| callbacks.motion),
|
||||
)
|
||||
.with_capture(settings.capture)
|
||||
.with_release_shortcut(release_shortcut)
|
||||
.with_release_on_leave(settings.release_on_leave),
|
||||
),
|
||||
state: State {
|
||||
display,
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
@@ -274,6 +274,7 @@ fn start_video(sink: Option<&dyn FrameSink>) -> bool {
|
||||
unsafe {
|
||||
SDL_SetX11EventHook(Some(x11_event), std::ptr::null_mut());
|
||||
}
|
||||
crate::drop::install_host_drop_forwarder();
|
||||
// SAFETY: SDL's video runs.
|
||||
let kind = unsafe { SDL_RegisterEvents(1) };
|
||||
WAKE.store(kind, Ordering::Release);
|
||||
|
||||
@@ -68,8 +68,14 @@
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::ffi::c_void;
|
||||
use std::io::Write;
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::process::Command;
|
||||
use std::ptr::{NonNull, null, null_mut};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
|
||||
use std::time::Duration;
|
||||
|
||||
use sdl3_sys::everything::{
|
||||
MSG, SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties,
|
||||
@@ -84,7 +90,7 @@ use windows_sys::Win32::System::Com::{
|
||||
CoUninitialize,
|
||||
};
|
||||
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentThreadId;
|
||||
use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, GetCurrentThreadId};
|
||||
use windows_sys::Win32::UI::Shell::TaskbarList;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
CallNextHookEx, HCBT_ACTIVATE, HCBT_DESTROYWND, IDCANCEL, IDOK, MB_DEFBUTTON2, MB_ICONWARNING,
|
||||
@@ -100,6 +106,195 @@ use crate::grab::HostOs;
|
||||
/// The OS whose names the title gives the release chord's keys: Ctrl+Alt+Win (the module doc).
|
||||
pub(super) const HOST_OS: HostOs = HostOs::Windows;
|
||||
|
||||
/// Asks the Reims-Go desktop instance that started this VM to show its
|
||||
/// close dialog. A failed handoff leaves the system dialog available.
|
||||
pub(super) fn request_client_close() -> bool {
|
||||
let Some(executable) = std::env::var_os("REIMS_GO_VM_CLOSE_EXE") else {
|
||||
return false;
|
||||
};
|
||||
let Ok(name) = std::env::var("REIMS_GO_VM_CLOSE_NAME") else {
|
||||
return false;
|
||||
};
|
||||
Command::new(executable)
|
||||
.arg(format!("--close-vm={name}"))
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.status()
|
||||
.is_ok_and(|status| status.success())
|
||||
}
|
||||
|
||||
/// WM_KEYDOWN.
|
||||
const WM_KEYDOWN: u32 = 0x0100;
|
||||
/// WM_CHAR.
|
||||
const WM_CHAR: u32 = 0x0102;
|
||||
/// WM_SYSKEYDOWN.
|
||||
const WM_SYSKEYDOWN: u32 = 0x0104;
|
||||
/// WM_UNICHAR.
|
||||
const WM_UNICHAR: u32 = 0x0109;
|
||||
/// WM_IME_CHAR.
|
||||
const WM_IME_CHAR: u32 = 0x0286;
|
||||
/// UNICODE_NOCHAR.
|
||||
const UNICODE_NOCHAR: usize = 0xFFFF;
|
||||
/// VK_PROCESSKEY (host IME intercepted key).
|
||||
const VK_PROCESSKEY: u16 = 0x00E5;
|
||||
/// VK_PACKET (SendInput with KEYEVENTF_UNICODE).
|
||||
const VK_PACKET: u16 = 0x00E7;
|
||||
|
||||
/// Non-blocking channel carrying UTF-16 code units from the SDL UI thread to the HTTP forwarder.
|
||||
static UNICODE_TX: OnceLock<SyncSender<u16>> = OnceLock::new();
|
||||
|
||||
thread_local! {
|
||||
/// Whether the most recent WM_KEYDOWN was unmapped (VK_PACKET or VK_PROCESSKEY).
|
||||
static LAST_KEY_UNMAPPED: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Reads the loopback HTTP endpoint set by the Reims-Go input bridge.
|
||||
fn parse_loopback_input_url(raw: &str) -> Option<(SocketAddr, String)> {
|
||||
let rest = raw.trim().strip_prefix("http://127.0.0.1:")?;
|
||||
let (port_str, path) = match rest.find('/') {
|
||||
Some(idx) => (&rest[..idx], &rest[idx..]),
|
||||
None => (rest, "/v1/host-text"),
|
||||
};
|
||||
let port: u16 = port_str.parse().ok()?;
|
||||
if port == 0 || path.contains(['\r', '\n', ' ']) {
|
||||
return None;
|
||||
}
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], port));
|
||||
Some((addr, path.to_owned()))
|
||||
}
|
||||
|
||||
/// Enables text forwarding on SDL's UI thread when REIMS_GO_INPUT_URL and
|
||||
/// REIMS_GO_INPUT_TOKEN are set, forwarding non-keyboard WM_CHAR / WM_UNICHAR /
|
||||
/// WM_IME_CHAR text (remote IMEs, dictation, host IME commits) to the local host bridge.
|
||||
fn start_unicode_forwarder() {
|
||||
let Ok(url) = std::env::var("REIMS_GO_INPUT_URL") else {
|
||||
return;
|
||||
};
|
||||
let Ok(token) = std::env::var("REIMS_GO_INPUT_TOKEN") else {
|
||||
return;
|
||||
};
|
||||
if token.is_empty() || token.contains(['\r', '\n']) {
|
||||
return;
|
||||
}
|
||||
let Some((addr, path)) = parse_loopback_input_url(&url) else {
|
||||
log::warn!(target: "reims_vgpu_window", "ignoring non-loopback REIMS_GO_INPUT_URL");
|
||||
return;
|
||||
};
|
||||
let (tx, rx) = mpsc::sync_channel::<u16>(512);
|
||||
if UNICODE_TX.set(tx).is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("reims-vgpu.ime".into())
|
||||
.spawn(move || forward_unicode_loop(rx, addr, path, token));
|
||||
}
|
||||
|
||||
/// Enqueues a UTF-16 code unit without blocking the Win32 message loop.
|
||||
fn enqueue_utf16(unit: u16) {
|
||||
if unit != 0
|
||||
&& let Some(tx) = UNICODE_TX.get()
|
||||
{
|
||||
let _ = tx.try_send(unit);
|
||||
}
|
||||
}
|
||||
|
||||
/// Forwards non-physical WM_CHAR / WM_UNICHAR / WM_IME_CHAR events to the local
|
||||
/// input bridge while leaving physical keyboard events to SDL.
|
||||
fn forward_unicode_message(msg: &WinMsg) -> bool {
|
||||
match msg.message {
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN => {
|
||||
let vk = (msg.wParam & 0xFFFF) as u16;
|
||||
LAST_KEY_UNMAPPED.set(vk == VK_PACKET || vk == VK_PROCESSKEY);
|
||||
true
|
||||
}
|
||||
WM_CHAR => {
|
||||
let unit = (msg.wParam & 0xFFFF) as u16;
|
||||
let scan_code = (msg.lParam.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.lParam == 0);
|
||||
if non_physical && (unit >= 0x20 || unit == 0x0D || unit == 0x09) {
|
||||
enqueue_utf16(unit);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
WM_IME_CHAR => {
|
||||
let unit = (msg.wParam & 0xFFFF) as u16;
|
||||
if unit >= 0x20 || unit == 0x0D || unit == 0x09 {
|
||||
enqueue_utf16(unit);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
WM_UNICHAR => {
|
||||
if msg.wParam != UNICODE_NOCHAR
|
||||
&& let Ok(code) = u32::try_from(msg.wParam)
|
||||
&& let Some(ch) = char::from_u32(code)
|
||||
&& (ch >= ' ' || ch == '\r' || ch == '\t')
|
||||
{
|
||||
let mut pair = [0u16; 2];
|
||||
for &mut u in ch.encode_utf16(&mut pair) {
|
||||
enqueue_utf16(u);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes UTF-16 code units, coalesces bursts, and POSTs UTF-8 text to the loopback bridge.
|
||||
fn forward_unicode_loop(rx: mpsc::Receiver<u16>, addr: SocketAddr, path: String, token: String) {
|
||||
let mut units: Vec<u16> = Vec::with_capacity(64);
|
||||
loop {
|
||||
let first = match rx.recv() {
|
||||
Ok(u) => u,
|
||||
Err(_) => return,
|
||||
};
|
||||
units.clear();
|
||||
units.push(first);
|
||||
if first != 0x0D {
|
||||
while units.len() < 128 {
|
||||
match rx.recv_timeout(Duration::from_millis(35)) {
|
||||
Ok(u) => {
|
||||
units.push(u);
|
||||
if u == 0x0D {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => break,
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
let text: String = char::decode_utf16(units.iter().copied())
|
||||
.filter_map(Result::ok)
|
||||
.map(|c| if c == '\r' { '\n' } else { c })
|
||||
.collect();
|
||||
if !text.is_empty() {
|
||||
post_loopback_text(addr, &path, &token, &text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends a minimal HTTP/1.1 POST with UTF-8 text to the local host bridge.
|
||||
fn post_loopback_text(addr: SocketAddr, path: &str, token: &str, text: &str) {
|
||||
let Ok(mut stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else {
|
||||
return;
|
||||
};
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_millis(500)));
|
||||
let req = format!(
|
||||
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
text.len()
|
||||
);
|
||||
let _ = stream.write_all(req.as_bytes());
|
||||
let _ = stream.write_all(text.as_bytes());
|
||||
}
|
||||
|
||||
/// The GPU the compositor composites SDL's window on: none known on Windows (the module doc).
|
||||
///
|
||||
/// # Safety
|
||||
@@ -176,14 +371,15 @@ pub(super) unsafe fn handle_of(window: *mut SDL_Window) -> *mut c_void {
|
||||
/// Sets SDL's hook of the UI thread's window messages (the module doc, "Modal loops"), as SDL's
|
||||
/// video starts on it.
|
||||
pub(super) fn hook_messages() {
|
||||
start_unicode_forwarder();
|
||||
// SAFETY: SDL's video runs on this thread; the hook is a function, with no data of its own.
|
||||
unsafe { SDL_SetWindowsMessageHook(Some(message_hook), null_mut()) };
|
||||
}
|
||||
|
||||
/// SDL's message hook (the module doc, "Modal loops"), on the UI thread: each message SDL takes
|
||||
/// from the thread's queue, and each a window gets as a modal loop starts and while it runs. A
|
||||
/// loop's start has the window's input lift what it holds; SDL handles every message as it would
|
||||
/// without the hook.
|
||||
/// loop's start has the window's input lift what it holds. When the local input bridge is
|
||||
/// enabled, text forwarded to it is consumed here.
|
||||
unsafe extern "C" fn message_hook(_userdata: *mut c_void, msg: *mut MSG) -> bool {
|
||||
// SAFETY: SDL hands a Win32 MSG, which sdl3-sys leaves opaque without a windows-sys feature
|
||||
// of its own (it has none for this windows-sys): windows-sys's is the same C struct.
|
||||
@@ -193,7 +389,7 @@ unsafe extern "C" fn message_hook(_userdata: *mut c_void, msg: *mut MSG) -> bool
|
||||
if starts_modal_loop(msg.message) {
|
||||
super::sdl_thread::sdl::modal_loop_started(msg.hwnd);
|
||||
}
|
||||
true
|
||||
UNICODE_TX.get().is_none() || forward_unicode_message(msg)
|
||||
}
|
||||
|
||||
/// Whether window message `message` starts a modal loop of Windows' over the window: moving or
|
||||
|
||||
@@ -82,6 +82,8 @@ pub(crate) struct Shell {
|
||||
density: f64,
|
||||
/// Its input.
|
||||
pub(crate) input: Input,
|
||||
/// Files and coordinates supplied by SDL for the current drop.
|
||||
drop_batch: crate::drop::DropBatch,
|
||||
/// Whether it last asked its OS for the keyboard grab ([`Shell::held_changed`]).
|
||||
grab_asked: bool,
|
||||
/// What its OS keeps of it.
|
||||
@@ -190,6 +192,7 @@ pub(crate) fn open(window: &Arc<Window>) {
|
||||
layout: Layout::default(),
|
||||
density: 1.0,
|
||||
input: opened.input,
|
||||
drop_batch: crate::drop::DropBatch::default(),
|
||||
grab_asked: false,
|
||||
os: opened.state,
|
||||
cursor: CursorCache::default(),
|
||||
@@ -218,6 +221,7 @@ pub(crate) fn open(window: &Arc<Window>) {
|
||||
pub(crate) fn close(id: u64) {
|
||||
let gone = with_shell(id, |shell| {
|
||||
ended(shell);
|
||||
shell.drop_batch.reset();
|
||||
shell.closed = true;
|
||||
os::close(shell) || shell.released
|
||||
});
|
||||
@@ -338,6 +342,14 @@ fn settled(before: Option<bool>, kind: u32) -> Option<bool> {
|
||||
pub(crate) fn event(event: &SDL_Event) {
|
||||
// SAFETY: every event starts with its type, and each arm reads the variant its type names.
|
||||
let kind = unsafe { event.r#type };
|
||||
let is_drop = [
|
||||
SDL_EVENT_DROP_BEGIN.0,
|
||||
SDL_EVENT_DROP_POSITION.0,
|
||||
SDL_EVENT_DROP_FILE.0,
|
||||
SDL_EVENT_DROP_TEXT.0,
|
||||
SDL_EVENT_DROP_COMPLETE.0,
|
||||
]
|
||||
.contains(&kind);
|
||||
let sdl_id = match kind {
|
||||
k if (SDL_EVENT_WINDOW_FIRST.0..=SDL_EVENT_WINDOW_LAST.0).contains(&k) => unsafe {
|
||||
event.window.windowID.0
|
||||
@@ -350,9 +362,20 @@ pub(crate) fn event(event: &SDL_Event) {
|
||||
event.button.windowID.0
|
||||
},
|
||||
k if k == SDL_EVENT_MOUSE_WHEEL.0 => unsafe { event.wheel.windowID.0 },
|
||||
_ if is_drop => unsafe { event.drop.windowID.0 },
|
||||
_ => return,
|
||||
};
|
||||
let Some(id) = window_of(sdl_id) else {
|
||||
let target = if is_drop && sdl_id == 0 {
|
||||
OPEN.with(|open| {
|
||||
let open = open.borrow();
|
||||
let mut live = open.iter().filter(|shell| !shell.closed);
|
||||
let first = live.next()?;
|
||||
live.next().is_none().then(|| first.window.id())
|
||||
})
|
||||
} else {
|
||||
window_of(sdl_id)
|
||||
};
|
||||
let Some(id) = target else {
|
||||
return;
|
||||
};
|
||||
with_shell(id, |shell| {
|
||||
@@ -419,6 +442,62 @@ impl Shell {
|
||||
// SDL's cursor is the process's: another window may have hidden it.
|
||||
self.over_image = false;
|
||||
self.refresh_cursor();
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let held_changed = if k == SDL_EVENT_WINDOW_MOUSE_LEAVE.0 {
|
||||
self.input.mouse_left()
|
||||
} else {
|
||||
self.input.mouse_entered()
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let held_changed = false;
|
||||
held_changed
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_BEGIN.0 => {
|
||||
self.drop_batch.begin();
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_POSITION.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let (x, y) = unsafe { (event.drop.x, event.drop.y) };
|
||||
self.drop_batch.position(f64::from(x), f64::from(y));
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_FILE.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if !drop.data.is_null() {
|
||||
// SAFETY: SDL3 owns this NUL-terminated path for the event's lifetime.
|
||||
let path = unsafe { std::ffi::CStr::from_ptr(drop.data) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self.drop_batch
|
||||
.file(path, Some((f64::from(drop.x), f64::from(drop.y))));
|
||||
}
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_TEXT.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if !drop.data.is_null() {
|
||||
// SAFETY: SDL3 owns this NUL-terminated text for the event's lifetime.
|
||||
let text = unsafe { std::ffi::CStr::from_ptr(drop.data) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self.drop_batch
|
||||
.text(text, Some((f64::from(drop.x), f64::from(drop.y))));
|
||||
}
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_COMPLETE.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if let Some(payload) = self.drop_batch.complete(
|
||||
self.window.port(),
|
||||
self.layout.image,
|
||||
Some((f64::from(drop.x), f64::from(drop.y))),
|
||||
) {
|
||||
crate::drop::submit(payload);
|
||||
}
|
||||
false
|
||||
}
|
||||
_ => os::input_event(self, kind, event),
|
||||
|
||||
@@ -101,19 +101,19 @@ use reims_vgpu_graphics::wire::{
|
||||
RGFX_FEATURE_SURFACE_ORDER, RGFX_FEATURE_SURFACE_PAGES, RGFX_FEATURE_SURFACE_REFILL,
|
||||
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_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,
|
||||
RGFX_VIDEO_HEVC_MAIN_10, RGFX_VIDEO_VP9_PROFILE_0, RGFX_VIDEO_VP9_PROFILE_2,
|
||||
RGFX_VT_STATUS_MALFORMED, RgfxBlockGrant, RgfxBlockRelease, RgfxBufferOverPages,
|
||||
RgfxCbComplete, RgfxCbScheduled, RgfxCbSubmitted, RgfxColorEntry, RgfxComplete,
|
||||
RgfxDisplayColor, RgfxEventSignalled, RgfxFunctionPointerState, RgfxHeapOverPages,
|
||||
RgfxIcbState, RgfxLibraryLookup, RgfxMsgHeader, RgfxPageRun, RgfxPipelineAnswersQuery,
|
||||
RgfxPoolGive, RgfxPoolTake, RgfxPrivateGive, RgfxPrivateTake, RgfxRateMapAnswer,
|
||||
RgfxRateMapState, RgfxSamplerState, RgfxScheduledAsk, RgfxSharedEventName, RgfxSharedTexture,
|
||||
RgfxSurfacePages, RgfxSurfacePagesLayout, RgfxVideoCaps,
|
||||
RGFX_RESOURCE_ID_CHUNK, RGFX_RESOURCE_ID_CHUNKS, RGFX_STATUS_CACHE,
|
||||
RGFX_STATUS_INVALID_ARGUMENT, 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, RGFX_VIDEO_HEVC_MAIN_10, RGFX_VIDEO_VP9_PROFILE_0,
|
||||
RGFX_VIDEO_VP9_PROFILE_2, RGFX_VT_STATUS_MALFORMED, RgfxBlockGrant, RgfxBlockRelease,
|
||||
RgfxBufferOverPages, RgfxCbComplete, RgfxCbScheduled, RgfxCbSubmitted, RgfxColorEntry,
|
||||
RgfxComplete, RgfxDisplayColor, RgfxEventSignalled, RgfxFunctionPointerState,
|
||||
RgfxHeapOverPages, RgfxIcbState, RgfxLibraryLookup, RgfxMsgHeader, RgfxPageRun,
|
||||
RgfxPipelineAnswersQuery, RgfxPoolGive, RgfxPoolTake, RgfxPrivateGive, RgfxPrivateTake,
|
||||
RgfxRateMapAnswer, RgfxRateMapState, RgfxSamplerState, RgfxScheduledAsk, RgfxSharedEventName,
|
||||
RgfxSharedTexture, RgfxSurfacePages, RgfxSurfacePagesLayout, RgfxVideoCaps,
|
||||
};
|
||||
use reims_vgpu_graphics::{
|
||||
CompleteAnswer, CompletionPoster, CursorImage, DoorbellAt, Host, Mode, PoolAnswer,
|
||||
@@ -202,6 +202,7 @@ mod read;
|
||||
mod rt_window;
|
||||
mod sink;
|
||||
mod slow_answers;
|
||||
mod snapshot;
|
||||
mod summary;
|
||||
mod trip;
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
@@ -1272,6 +1273,7 @@ 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| {
|
||||
@@ -1615,6 +1617,250 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
|
||||
(self.cursors.get(display as usize)).map_or((0, 0), |cursor| cursor.position())
|
||||
})
|
||||
}
|
||||
|
||||
fn quiesce_device(&self, control: Option<&GraphicsControl<P>>) {
|
||||
self.device.quiesce();
|
||||
if let Some(pool) = &self.pool {
|
||||
pool.quiesce();
|
||||
}
|
||||
let Some(control) = control else {
|
||||
return;
|
||||
};
|
||||
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();
|
||||
}
|
||||
|
||||
/// 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(|_| {
|
||||
self.quiesce_device(self.ending.upgrade().as_deref());
|
||||
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 control = self.ending.upgrade().ok_or(Error::HostResources)?;
|
||||
let started = control.pool.now();
|
||||
self.quiesce_device(Some(&control));
|
||||
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 export_time = control.pool.now().saturating_duration_since(started);
|
||||
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)",
|
||||
control.pool.now().saturating_duration_since(started).as_secs_f64(),
|
||||
export_time.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> {
|
||||
@@ -1836,6 +2082,7 @@ 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
|
||||
@@ -2508,6 +2755,7 @@ 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()
|
||||
@@ -2756,6 +3004,7 @@ 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 {
|
||||
@@ -2818,6 +3067,7 @@ 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);
|
||||
@@ -3121,6 +3371,10 @@ 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 after it.
|
||||
let answer = match status {
|
||||
@@ -3234,6 +3488,191 @@ 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,
|
||||
@@ -3241,6 +3680,8 @@ 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 texture over a buffer, which may be answered once made (`answers_create`): its wait
|
||||
// counted from here.
|
||||
@@ -4157,6 +4598,10 @@ 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());
|
||||
}
|
||||
@@ -4714,7 +5159,15 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
.prepare_library(message)
|
||||
});
|
||||
let job = match start {
|
||||
LibraryStart::Make(job) => job,
|
||||
LibraryStart::Make(job) => {
|
||||
self.live_log.record_library(
|
||||
sender_context(poster, message),
|
||||
job.obj_id,
|
||||
job.bytes.clone(),
|
||||
job.guest_key,
|
||||
);
|
||||
job
|
||||
}
|
||||
LibraryStart::Chunk => return,
|
||||
LibraryStart::Refused { error, answer } => {
|
||||
let (ty, seqno, obj_id) = message_identity(message);
|
||||
@@ -4787,6 +5240,7 @@ 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);
|
||||
@@ -4818,6 +5272,7 @@ 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);
|
||||
@@ -5556,6 +6011,7 @@ 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()
|
||||
@@ -6111,19 +6567,35 @@ impl Screen for WindowScreen {
|
||||
/// draw): the display's first mode, which its smaller modes follow.
|
||||
fn mode(&self) -> Mode {
|
||||
let drawn = *self.shown.drawable.lock();
|
||||
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 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 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: clamp(width),
|
||||
height: clamp(height),
|
||||
width: clamped_w,
|
||||
height: clamped_h,
|
||||
refresh_mhz: self.refresh_mhz,
|
||||
scale_120ths: drawn.map_or(0, |d| scale_in_120ths(d.scale)),
|
||||
scale_120ths,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -583,6 +583,17 @@ 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;
|
||||
@@ -673,10 +684,8 @@ fn run(shared: &Shared, queued: Queued) {
|
||||
ms(ended.saturating_duration_since(started)),
|
||||
);
|
||||
shared.state.lock().ended(of.context(), of.kind);
|
||||
// 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();
|
||||
}
|
||||
// Wake waiters (pre-pass limit or snapshot quiesce wait_idle).
|
||||
shared.waiting.notify_all();
|
||||
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,
|
||||
bytes: Vec<u8>,
|
||||
pub(crate) bytes: Vec<u8>,
|
||||
/// The key the guest sent with the bytes.
|
||||
guest_key: Option<LibraryKey>,
|
||||
pub(crate) guest_key: Option<LibraryKey>,
|
||||
slot: Arc<LibrarySlot<P>>,
|
||||
/// The device's resets when it was prepared.
|
||||
resets: u64,
|
||||
@@ -710,6 +710,29 @@ 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
|
||||
|
||||
@@ -221,6 +221,7 @@ 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;
|
||||
@@ -260,6 +261,7 @@ pub(crate) use lane::{LANE_MOST, LANE_THREADS};
|
||||
use lane::{Lane, Turn};
|
||||
#[cfg(test)]
|
||||
pub(crate) use library::KEY_BESIDE_MIN as TEST_KEY_BESIDE_MIN;
|
||||
pub(crate) use library::LibraryKey;
|
||||
#[cfg(test)]
|
||||
pub(crate) use library::tests::{metallib as test_metallib, sha as test_sha};
|
||||
#[cfg(test)]
|
||||
@@ -614,6 +616,16 @@ 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),
|
||||
@@ -3794,6 +3806,285 @@ 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>>> =
|
||||
@@ -6965,6 +7256,11 @@ 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 {
|
||||
|
||||
@@ -626,7 +626,7 @@ use reims_vgpu_vulkan::core::platform::os::clock::MonoTime;
|
||||
#[cfg(unix)]
|
||||
use reims_vgpu_vulkan::core::platform::resource::SurfaceHandle;
|
||||
use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, MemoryFor, Texture as _};
|
||||
use reims_vgpu_vulkan::core::platform::types::NsRange;
|
||||
use reims_vgpu_vulkan::core::platform::types::{CommandBufferStatus, NsRange};
|
||||
use reims_vgpu_vulkan::core::platform::values::{PagesPlane, TextureDesc};
|
||||
use reims_vgpu_vulkan::core::platform::{Encoded, Handle, Platform};
|
||||
use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult, refusals};
|
||||
@@ -2634,10 +2634,9 @@ impl CarriedPages {
|
||||
|
||||
/// The host's transfer queue, on which every copy runs, and the event its fills signal.
|
||||
struct Transfer<P: Platform> {
|
||||
/// Unshared ([`new_command_queue_unshared`]): a present of a surface waits for its fill, and
|
||||
/// a frame drawn from a cache for the fill before it ([`FillWait`]).
|
||||
///
|
||||
/// [`new_command_queue_unshared`]: reims_vgpu_vulkan::core::platform::device::GpuDevice::new_command_queue_unshared
|
||||
/// Private copy FIFO. A transaction can prepare all of its fills under the cache lock and
|
||||
/// publish them in order after unlocking. Presents and consumers wait for their fill
|
||||
/// ([`FillWait`]).
|
||||
queue: P::CommandQueue,
|
||||
/// The early copies behind writers that hold no video encoder
|
||||
/// ([`SurfaceCaches::early_copies`]), apart from the fills, so neither waits behind the
|
||||
@@ -2659,7 +2658,7 @@ impl<P: Platform> Transfer<P> {
|
||||
/// A transfer queue and its event, its fills telling `hook`; `None` where the platform makes
|
||||
/// either not.
|
||||
fn new(device: &P::Device, hook: &Arc<OnceLock<FillHook>>) -> RaiseResult<Option<Self>> {
|
||||
let Some(queue) = device.new_command_queue_unshared() else {
|
||||
let Some(queue) = device.new_cache_transfer_queue() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(event) = device.new_event(ON)? else {
|
||||
@@ -4440,6 +4439,18 @@ 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
|
||||
@@ -11563,6 +11574,227 @@ impl<P: Platform> Caches<P> {
|
||||
state.fill_now(device, block, generation)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
self.export_unattached_with(
|
||||
device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| device.wait_idle(),
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|buffer| device.read_standalone_buffer(buffer),
|
||||
)
|
||||
}
|
||||
|
||||
fn export_unattached_with(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
mut command_buffer: impl FnMut(&P::CommandQueue) -> RaiseResult<Option<P::CommandBuffer>>,
|
||||
mut commit: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
|
||||
mut wait_idle: impl FnMut(),
|
||||
mut wait_completed: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
|
||||
mut read_buffer: impl FnMut(&P::Buffer) -> Result<Option<Vec<u8>>, &'static str>,
|
||||
) -> 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 (dirty_blocks, queue) = {
|
||||
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();
|
||||
let queue = if dirty_blocks.is_empty() {
|
||||
None
|
||||
} else {
|
||||
if !state
|
||||
.make_transfer(device)
|
||||
.map_err(|_| "snapshot_save: surface cache transfer init failed")?
|
||||
{
|
||||
return Err("snapshot_save: surface cache transfer queue unavailable");
|
||||
}
|
||||
state
|
||||
.transfer
|
||||
.as_ref()
|
||||
.map(|transfer| transfer.queue.clone_ref())
|
||||
};
|
||||
(dirty_blocks, queue)
|
||||
};
|
||||
if let Some(queue) = queue {
|
||||
let mut submitted = Vec::new();
|
||||
let flushed = (|| {
|
||||
for block in dirty_blocks {
|
||||
let cb = command_buffer(&queue)
|
||||
.map_err(|_| "snapshot_save: surface cache command buffer failed")?
|
||||
.ok_or("snapshot_save: surface cache command buffer unavailable")?;
|
||||
let mut state = self.lock();
|
||||
let Some(cache) = state.by_block.get_mut(&block).filter(|cache| {
|
||||
cache.pages.is_none() && cache.shapes.iter().any(|s| s.dirty)
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
if !cache.copy_through(MemoryFor::WriteBack) {
|
||||
return Err("snapshot_save: deferred surface cache allocation failed");
|
||||
}
|
||||
let (back, recorded) =
|
||||
shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| s.dirty)
|
||||
.map_err(|_| "snapshot_save: surface cache shape write_back failed")?;
|
||||
if !recorded.recorded() || back.is_empty() {
|
||||
return Err("snapshot_save: surface cache blit encoder unavailable");
|
||||
}
|
||||
// Retirement frees the queue slot even while we keep the handle for status.
|
||||
let commit_failed = "snapshot_save: surface cache command buffer commit failed";
|
||||
state.unlocked(|| commit(&cb)).map_err(|_| commit_failed)?;
|
||||
let status = cb.status();
|
||||
if status.raw() < CommandBufferStatus::COMMITTED.raw()
|
||||
|| status == CommandBufferStatus::ERROR
|
||||
{
|
||||
return Err(commit_failed);
|
||||
}
|
||||
drop(state);
|
||||
submitted.push((block, back, cb));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let mut wait_failed = false;
|
||||
if !submitted.is_empty() {
|
||||
wait_idle();
|
||||
for (_, _, cb) in &submitted {
|
||||
if wait_completed(cb).is_err() {
|
||||
wait_failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
flushed?;
|
||||
if wait_failed
|
||||
|| submitted
|
||||
.iter()
|
||||
.any(|(_, _, cb)| cb.status() != CommandBufferStatus::COMPLETED)
|
||||
{
|
||||
return Err(
|
||||
"snapshot_save: surface cache command buffer did not complete successfully",
|
||||
);
|
||||
}
|
||||
let mut state = self.lock();
|
||||
let state = &mut *state;
|
||||
for (block, back, _) in &submitted {
|
||||
if let Some(cache) = state.by_block.get_mut(block) {
|
||||
cache.wrote_shapes(back);
|
||||
cache.shapes.written_back(back, &mut state.counts.shapes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 read_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(())
|
||||
}
|
||||
|
||||
/// `SURFACE_DOWNLOAD` of the block at `block` ([`SurfaceCaches::download`]), after every
|
||||
/// command buffer begun and not finished that may write it, waiting for none
|
||||
/// ([`Self::after_writers`]), `ran` as it is carried out then, and what it waited for then in
|
||||
@@ -19886,6 +20118,325 @@ pub(super) mod tests {
|
||||
r.pages_flagged(block, 0, &[], length, flags)
|
||||
}
|
||||
|
||||
const SNAPSHOT_CACHE_LENGTH: u64 = 0x1000;
|
||||
|
||||
fn snapshot_rig(blocks: u64) -> Rig {
|
||||
let r = rig(8);
|
||||
r.dec.set_deferred_budget(blocks * SNAPSHOT_CACHE_LENGTH);
|
||||
r.dec.caches().shaped = true;
|
||||
r
|
||||
}
|
||||
|
||||
fn dirty_unattached_cache(r: &mut Rig, block: u64) -> reims_vgpu_vulkan::core::platform::ObjId {
|
||||
assert_eq!(defer(r, block, SNAPSHOT_CACHE_LENGTH), RGFX_STATUS_OK);
|
||||
let key = ShapeKey {
|
||||
plane: 0,
|
||||
offset: 128,
|
||||
bytes_per_row: 128,
|
||||
width: 16,
|
||||
height: 2,
|
||||
texel_bytes: 4,
|
||||
storage: false,
|
||||
};
|
||||
let desc = r.p.texture_descriptor(&TextureDesc {
|
||||
pixel_format: 80,
|
||||
width: key.width,
|
||||
height: key.height,
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let image = r.device.new_texture(ON, &desc).unwrap().unwrap();
|
||||
let id = image.id();
|
||||
let mut state = r.dec.caches();
|
||||
let cache = state.by_block.get_mut(&block).unwrap();
|
||||
assert!(cache.pages.is_none());
|
||||
assert!(!cache.device.memory_made());
|
||||
let (reference, _) = cache.shapes.insert(key, image, false, 0);
|
||||
assert!(cache.shapes.mark_dirty(reference.id()));
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_exports_more_dirty_unattached_caches_than_the_transfer_queue_holds() {
|
||||
use reims_vgpu_vulkan::core::platform::types::MtlSize;
|
||||
|
||||
const BLOCKS: u64 = 80;
|
||||
const CAPACITY: usize = 64;
|
||||
let mut r = snapshot_rig(BLOCKS + 1);
|
||||
let mut textures = HashMap::default();
|
||||
let mut expected = Vec::new();
|
||||
for i in 0..BLOCKS {
|
||||
let block = BLOCK + i * 0x2000;
|
||||
let texture = dirty_unattached_cache(&mut r, block);
|
||||
let texels = [[i as u8; 64], [255 - i as u8; 64]];
|
||||
let mut bytes = vec![0; SNAPSHOT_CACHE_LENGTH.to_usize()];
|
||||
for (row, texels) in bytes[128..].chunks_mut(128).zip(&texels) {
|
||||
row[..64].copy_from_slice(texels);
|
||||
}
|
||||
textures.insert(texture, texels);
|
||||
expected.push((block, bytes));
|
||||
}
|
||||
assert_eq!(
|
||||
defer(&mut r, BLOCK + BLOCKS * 0x2000, SNAPSHOT_CACHE_LENGTH),
|
||||
RGFX_STATUS_OK
|
||||
);
|
||||
|
||||
let mark = r.p.call_log().mark();
|
||||
let world = r.p.world();
|
||||
let mut acquired = 0;
|
||||
let retired = Cell::new(0);
|
||||
let caches = &r.dec.surface_caches;
|
||||
let exported = caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| {
|
||||
assert!(
|
||||
caches.try_lock().is_some(),
|
||||
"queue acquisition holds the cache lock"
|
||||
);
|
||||
let in_flight = world.committed().len();
|
||||
assert_eq!(
|
||||
world.live("MTLCommandBuffer").len(),
|
||||
in_flight + retired.get(),
|
||||
"a previous buffer is uncommitted"
|
||||
);
|
||||
if in_flight == CAPACITY {
|
||||
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
|
||||
}
|
||||
assert!(world.committed().len() < CAPACITY);
|
||||
acquired += 1;
|
||||
queue.command_buffer(ON)
|
||||
},
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
assert_eq!(caches.try_lock().unwrap().counts.shapes.written_back, 0);
|
||||
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
|
||||
},
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|buffer| {
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
// The fake logs blits without executing them. Reproduce each logged GPU copy.
|
||||
let calls = r.p.call_log().since(mark);
|
||||
let mut copies = calls.iter().filter(|call| {
|
||||
call.sel.starts_with("copyFromTexture:")
|
||||
&& call.args[5].as_obj() == Some(buffer.id())
|
||||
});
|
||||
let copy = copies.next().expect("a copy into this cache");
|
||||
assert!(copies.next().is_none());
|
||||
assert_eq!(copy.args[4], Arg::val(&MtlSize::new(16, 2, 1)));
|
||||
let source = &textures[©.args[0].as_obj().unwrap()];
|
||||
let offset = copy.args[6].as_u64().unwrap().to_usize();
|
||||
let pitch = copy.args[7].as_u64().unwrap().to_usize();
|
||||
let mut bytes = vec![0; buffer.length().to_usize()];
|
||||
for (row, texels) in source.iter().enumerate() {
|
||||
let at = offset + row * pitch;
|
||||
bytes[at..at + 64].copy_from_slice(texels);
|
||||
}
|
||||
Ok(Some(bytes))
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(acquired, BLOCKS);
|
||||
assert_eq!(retired.get(), BLOCKS.to_usize());
|
||||
assert_eq!(exported.unwrap(), expected);
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, BLOCKS);
|
||||
assert!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.all(|cache| cache.shapes.iter().all(|s| !s.dirty))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_drops_uncommitted_unattached_writebacks_on_error() {
|
||||
use reims_vgpu_vulkan::core::testkit::Step;
|
||||
use reims_vgpu_vulkan::core::testkit::impls::resource::MAKE_MEMORY;
|
||||
|
||||
for (selector, steps, error) in [
|
||||
(
|
||||
"commandBuffer",
|
||||
vec![Step::Nil],
|
||||
"snapshot_save: surface cache command buffer unavailable",
|
||||
),
|
||||
(
|
||||
MAKE_MEMORY,
|
||||
vec![Step::value(false); 2],
|
||||
"snapshot_save: deferred surface cache allocation failed",
|
||||
),
|
||||
(
|
||||
"blitCommandEncoder",
|
||||
vec![Step::Nil],
|
||||
"snapshot_save: surface cache blit encoder unavailable",
|
||||
),
|
||||
(
|
||||
"endEncoding",
|
||||
vec![Step::unrecognized("endEncoding")],
|
||||
"snapshot_save: surface cache shape write_back failed",
|
||||
),
|
||||
(
|
||||
"commit",
|
||||
vec![Step::unrecognized("commit")],
|
||||
"snapshot_save: surface cache command buffer commit failed",
|
||||
),
|
||||
] {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
for step in steps {
|
||||
r.p.script().push(selector, step);
|
||||
}
|
||||
let caches = &r.dec.surface_caches;
|
||||
assert_eq!(caches.export_unattached(&r.device), Err(error));
|
||||
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
|
||||
assert!(
|
||||
r.dec.caches().by_block[&BLOCK]
|
||||
.shapes
|
||||
.iter()
|
||||
.all(|s| s.dirty)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_stops_before_readback_if_a_later_writeback_fails() {
|
||||
let mut r = snapshot_rig(2);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
|
||||
r.p.faults()
|
||||
.at("MTLCommandQueue", "commandBuffer", 1, Fault::Nil);
|
||||
|
||||
let caches = &r.dec.surface_caches;
|
||||
let world = r.p.world();
|
||||
let mut retired = 0;
|
||||
let exported = caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| retired += world.complete_all(CompleteOn::Caller),
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|_| panic!("a failed writeback must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer unavailable")
|
||||
);
|
||||
assert_eq!(retired, 1);
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert_eq!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.filter(|c| c.shapes.iter().any(|s| s.dirty))
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_preserves_dirty_shapes_if_writeback_commit_is_silently_refused() {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|_| Ok(()),
|
||||
|| panic!("a refused commit leaves no submitted work to wait for"),
|
||||
|_| panic!("a refused commit leaves no submitted work to wait for"),
|
||||
|_| panic!("a refused commit must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer commit failed")
|
||||
);
|
||||
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| s.dirty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_preserves_dirty_shapes_if_a_submitted_writeback_fails() {
|
||||
let mut r = snapshot_rig(2);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
|
||||
|
||||
let world = r.p.world();
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
let [first, second] = world.committed().try_into().unwrap();
|
||||
assert!(world.complete(
|
||||
first,
|
||||
CommandBufferStatus::COMPLETED,
|
||||
None,
|
||||
CompleteOn::Caller
|
||||
));
|
||||
assert!(world.complete(
|
||||
second,
|
||||
CommandBufferStatus::ERROR,
|
||||
None,
|
||||
CompleteOn::Caller
|
||||
));
|
||||
},
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|_| panic!("a failed writeback must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer did not complete successfully")
|
||||
);
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.all(|cache| cache.shapes.iter().all(|s| s.dirty))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_waits_for_each_submitted_writeback_status_after_wait_idle() {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
|
||||
let world = r.p.world();
|
||||
let mut waited_completed = 0;
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
// Simulate wait_idle returning before the completion worker has
|
||||
// published the command buffer's final COMPLETED status.
|
||||
assert_eq!(world.committed().len(), 1);
|
||||
},
|
||||
|cb| {
|
||||
waited_completed += 1;
|
||||
assert_eq!(cb.status(), CommandBufferStatus::SCHEDULED);
|
||||
assert_eq!(world.complete_all(CompleteOn::Caller), 1);
|
||||
cb.wait_until_completed(ON)
|
||||
},
|
||||
|buffer| {
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
Ok(Some(vec![0xAB; buffer.length().to_usize()]))
|
||||
},
|
||||
);
|
||||
assert_eq!(waited_completed, 1);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Ok(vec![(BLOCK, vec![0xAB; SNAPSHOT_CACHE_LENGTH.to_usize()])])
|
||||
);
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 1);
|
||||
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| !s.dirty));
|
||||
}
|
||||
|
||||
/// A `SURFACE_PAGES` naming the pages of the deferred block at `block`, `runs` as
|
||||
/// [`Rig::pages`]'s, from context `context`; its answer.
|
||||
fn attach(r: &mut Rig, block: u64, context: u32, runs: &[(u64, u64)], length: u64) -> u32 {
|
||||
|
||||
@@ -1669,6 +1669,23 @@ 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 command buffer wrote the storage shape `id`, the block's one, through a texture its walk
|
||||
/// did not name (the module doc, "Dirty"): dirty until it is copied into the buffer (rule 3),
|
||||
/// and each other shape of its plane owes a fill from the buffer, which takes the write
|
||||
|
||||
@@ -309,6 +309,17 @@ 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.
|
||||
@@ -909,6 +920,19 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue `queue` was made, whether the device's reset ended it read through `stale`: what the
|
||||
/// settle at a reset sets of its timeline ([`Self::release_at_reset`]).
|
||||
pub(crate) fn reset_ends(&mut self, queue: u64, stale: Stale) {
|
||||
|
||||
@@ -272,6 +272,16 @@ 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
|
||||
|
||||
@@ -302,6 +302,8 @@ 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 for scaled scanouts whose host import could not make a texture view.
|
||||
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>>,
|
||||
@@ -715,6 +717,7 @@ 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)]
|
||||
@@ -754,6 +757,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
*self.color_table.lock() = None;
|
||||
self.ramps.lock().clear();
|
||||
self.scanout_ramp.forget();
|
||||
*self.scanout_stage.lock() = None;
|
||||
if let Some(import) = self.import.lock().as_mut() {
|
||||
import.texture = None;
|
||||
}
|
||||
@@ -1302,12 +1306,17 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
// Of another size than its place: a pass samples it over the place (the module doc,
|
||||
// "Sizes"), through a texture over its pixels.
|
||||
self.note_route("the scanout, sampled", frame, region);
|
||||
let read = self.scanout_texture(&scanout)?;
|
||||
match &color {
|
||||
Some((changes, color)) => {
|
||||
self.encode_colored(*changes, color, &read, texture, region, recorded)
|
||||
if let Some(read) = self.scanout_texture(&scanout) {
|
||||
match &color {
|
||||
Some((changes, color)) => {
|
||||
self.encode_colored(*changes, color, &read, texture, region, recorded)
|
||||
}
|
||||
None => self.encode_converted(&read, texture, region, recorded),
|
||||
}
|
||||
None => self.encode_converted(&read, texture, region, recorded),
|
||||
} else if cfg!(windows) && reims_vgpu_window::env::settings().fixed_mode {
|
||||
self.encode_scaled_scanout_copy(&scanout, texture, region, recorded)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}?;
|
||||
Some((command_buffer, None))
|
||||
@@ -2007,6 +2016,64 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Scale a scanout through a private texture when importing a texture view is unavailable.
|
||||
fn encode_scaled_scanout_copy(
|
||||
&self,
|
||||
scanout: &Scanout,
|
||||
texture: &P::Texture,
|
||||
region: PixelRect,
|
||||
recorded: &mut Encoded,
|
||||
) -> Option<P::CommandBuffer> {
|
||||
let (buffer, source_offset) = self.scanout_buffer(scanout)?;
|
||||
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: SCANOUT_FORMAT,
|
||||
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);
|
||||
let copied = 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();
|
||||
fold(recorded, copied);
|
||||
if !copied.recorded() {
|
||||
return None;
|
||||
}
|
||||
self.encode_converted_into(&command_buffer, &stage, texture, region, recorded)?;
|
||||
Some(command_buffer)
|
||||
}
|
||||
|
||||
/// A command buffer of the sink's queue with `surface`, a presented surface or a texture over
|
||||
/// the scanout's pixels, drawn into `texture` over `region` by the display's present shaders,
|
||||
/// which convert its format to the drawable's and scale it to the region (the module doc,
|
||||
@@ -2021,12 +2088,24 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
region: PixelRect,
|
||||
recorded: &mut Encoded,
|
||||
) -> Option<P::CommandBuffer> {
|
||||
let command_buffer = self.surface_command_buffer()?;
|
||||
self.encode_converted_into(&command_buffer, surface, texture, region, recorded)?;
|
||||
Some(command_buffer)
|
||||
}
|
||||
|
||||
fn encode_converted_into(
|
||||
&self,
|
||||
command_buffer: &P::CommandBuffer,
|
||||
surface: &P::Texture,
|
||||
texture: &P::Texture,
|
||||
region: PixelRect,
|
||||
recorded: &mut Encoded,
|
||||
) -> 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);
|
||||
@@ -2099,7 +2178,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
}
|
||||
}
|
||||
encoder.end();
|
||||
Some(command_buffer)
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// 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
@@ -87,6 +87,7 @@ mod host_blocks;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod host_memory_blocks;
|
||||
mod private_blocks;
|
||||
pub(crate) use private_blocks::{PrivateBlockSnapshot, PrivateBlocksSnapshot};
|
||||
mod rt_blocks;
|
||||
mod takes;
|
||||
|
||||
@@ -313,6 +314,47 @@ 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.
|
||||
@@ -321,6 +363,27 @@ 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.
|
||||
@@ -1107,18 +1170,158 @@ impl Pool {
|
||||
|
||||
/// The pieces the guest may use and the host mapped, by address: `(physical_address,
|
||||
/// length)`.
|
||||
#[allow(
|
||||
dead_code,
|
||||
reason = "the guest's side of the pool (its ring messages) calls it once it lands"
|
||||
)]
|
||||
#[cfg(test)]
|
||||
pub fn live(&self) -> Vec<(u64, u64)> {
|
||||
let st = self.shared.state.lock();
|
||||
(st.pieces.iter())
|
||||
st.pieces
|
||||
.iter()
|
||||
.filter(|(_, p)| p.mapped == Mapped::Live)
|
||||
.map(|(&a, p)| (a, p.block.len))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Waits until in-flight pool take workers and zeroer are idle.
|
||||
pub(crate) fn quiesce(&self) {
|
||||
let deadline = (self.shared.now)().saturating_add(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 || (self.shared.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
|
||||
.checked_sub(*gpa)
|
||||
.is_some_and(|offset| offset < 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(())
|
||||
}
|
||||
|
||||
/// The device's release: the host removed every piece it added. Ends the pool's thread (which
|
||||
/// gives back the pieces on their way back that no hold is on), its taker, its take workers
|
||||
/// (a take in flight is answered never) and its zeroer, and waits until their threads let go
|
||||
|
||||
@@ -139,6 +139,24 @@ 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,
|
||||
@@ -437,6 +455,128 @@ 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 = (self.inner.now)().saturating_add(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 (self.inner.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();
|
||||
|
||||
@@ -42,7 +42,7 @@ use parking_lot::Mutex;
|
||||
use reims_vgpu_vulkan::core::trace;
|
||||
use reims_vgpu_vulkan::rt_platform::{RtDevice, RtObj};
|
||||
|
||||
use super::{BlockError, BlockId, BlockInfo, BlockSource, MemoryClass};
|
||||
use super::{BlockCapture, 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,6 +144,153 @@ 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 {
|
||||
|
||||
@@ -191,6 +191,47 @@ 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 {
|
||||
|
||||
@@ -3007,4 +3007,3 @@ calls each Mac lets through with an encoder open are carried as before.
|
||||
- Surfaces whose rows miss the host's alignment.
|
||||
- A no-copy buffer past the M3's `maxBufferLength`, 41.7 GB there: the M3 is used little, and
|
||||
the x86 Macs' answers bound the lane's.
|
||||
|
||||
@@ -39,17 +39,17 @@ processors of Intel Macs: its family, with the number of cores in front, such as
|
||||
Core i7". It counts your VM's CPUs rounded up to a power of two, so a VM with 3 CPUs shows
|
||||
"Quad-Core" and one with 5, 6 or 7 shows "8-Core". System Information's "Total Number of Cores"
|
||||
still shows how many CPUs the VM has. macOS only has names for the core counts Apple's Macs had,
|
||||
so where none of them had that many cores in your processor's family, About This Mac says
|
||||
"Unknown" instead. It shows a name for:
|
||||
so a cold start sets the processor type only for an automatic OpenCore configuration whose
|
||||
family and core count have a label:
|
||||
|
||||
- Core i3 with 2 to 4 CPUs;
|
||||
- Core i5 and Core i7 with 2 to 8 CPUs;
|
||||
- Core i9 with 5 to 8 CPUs;
|
||||
- Xeon with 1 to 16 CPUs: Xeon up to 4, and Xeon W from 5.
|
||||
|
||||
So a VM with 10 CPUs on a Core i7 host, or 4 CPUs on a Core i9 host, shows "Unknown". To see the
|
||||
name, give the VM a count from the list, such as `reims-ctl set mac --cpus 8`. A new VM gets half
|
||||
your host's CPUs, at least 2 and at most 8.
|
||||
An unsupported count can show "Unknown" with automatic OpenCore settings. A core count
|
||||
from the list enables the family label. Explicit OpenCore processor types are kept across
|
||||
starts.
|
||||
|
||||
macOS has names for Intel processors only. On an AMD host, About This Mac shows the Intel family
|
||||
of the same rank: a Ryzen 7 shows as a Core i7, and a Threadripper or an EPYC as a Xeon. A newer
|
||||
|
||||
@@ -1322,6 +1322,8 @@ reims-ctl attaches nothing through it yet: no VM it starts has a
|
||||
`usb-redir` device. The build gets the parser from MSYS2's
|
||||
`mingw-w64-clang-x86_64-usbredir` package, and the install stops where the
|
||||
QEMU it staged lists no `usb-redir` device.
|
||||
The standalone [Windows iPad Air M3 enumeration helper](windows-ipad-air-m3.md)
|
||||
uses this device in a running x86-64 macOS guest.
|
||||
|
||||
With `REIMS_INSTALL_SKIP_HOST_CHECKS=1` in its environment, install.ps1
|
||||
skips the hypervisor platform's step, its check and its turning on, and
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Enumerate an iPad Air M3 over USB on Windows
|
||||
|
||||
This experimental source helper exposes one iPad Air M3 to a running x86-64
|
||||
macOS Reims guest on Windows. It checks for USB ID `05ac:12ab`, device
|
||||
revision `1503`, and the initial four-configuration layout. The session
|
||||
ends when the device changes its USB address. The first enumeration is the
|
||||
test target. Reattaching after Apple's mode change and Xcode are pending.
|
||||
|
||||
## Prepare the guest and host
|
||||
|
||||
- Start the guest with a Windows QEMU build that lists `usb-redir` in
|
||||
`-device help`. The guest must have the standard `xhci` controller.
|
||||
- Use 64-bit PowerShell 7, 64-bit Python 3.10 or later with PyUSB 1.3.1, and
|
||||
Go to build the local QMP relay.
|
||||
- Download and extract the signed [libusb-win32 1.4.0.2 binary
|
||||
release](https://github.com/mcuee/libusb-win32/releases/tag/release_1.4.0.2).
|
||||
The `bin/amd64` directory contains the matching SYS and DLL files.
|
||||
The helper checks their hashes before use.
|
||||
- Connect just one unlocked iPad in normal mode. Windows must already
|
||||
recognize it, and the device must be unshared by usbipd-win.
|
||||
|
||||
From the repository root, in an ordinary PowerShell window:
|
||||
|
||||
```powershell
|
||||
py -3 -m venv .\build\windows-ipad-air-m3\venv
|
||||
.\build\windows-ipad-air-m3\venv\Scripts\python.exe -m pip install PyUSB==1.3.1
|
||||
go build -o .\build\windows-ipad-air-m3\qmp-relay.exe .\scripts\windows-ipad-air-m3\qmp-relay.go
|
||||
.\build\windows-ipad-air-m3\venv\Scripts\python.exe .\scripts\windows-ipad-air-m3\attach.py `
|
||||
--vm-dir 'C:\path\to\vm' `
|
||||
--relay .\build\windows-ipad-air-m3\qmp-relay.exe `
|
||||
--driver-dir 'C:\path\to\libusb-win32\bin\amd64'
|
||||
```
|
||||
|
||||
The VM directory is the one shown by `reims-ctl list`. Use `--qmp` if
|
||||
the running guest's QMP socket lives outside that directory.
|
||||
|
||||
Approve Windows elevation for the temporary filter. When prompted, unplug
|
||||
the iPad, wait two seconds and plug it back into the same port. The
|
||||
terminal reports when the guest reads the USB device descriptor. When it
|
||||
requests a final unplug, leave the iPad disconnected until it confirms
|
||||
Windows restoration. If an interrupted session reports pending recovery,
|
||||
unplug the iPad and run
|
||||
`pwsh -File .\scripts\windows-ipad-air-m3\driver-session.ps1 -Recover`
|
||||
from an elevated PowerShell 7 window before reconnecting.
|
||||
|
||||
The driver transaction, USB access and forwarding protocol are adapted from
|
||||
[MonchiLin's Windows iPad contribution](https://github.com/MonchiLin/reims-vgpu/tree/5e69f1ba9d0f0267a670a1fb836b794184ec36bf/scripts/windows-ipad)
|
||||
under this repository's [dual license](../LICENSE).
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"capabilities": [
|
||||
"client-window-close",
|
||||
"display-fixed-mode",
|
||||
"nested-virt-nonfatal",
|
||||
"vm-suspend",
|
||||
"win10-compat",
|
||||
"win10-startup-ipis",
|
||||
"win32-coroutine-fiber",
|
||||
"win32-native-aio",
|
||||
"win32-unicode-input",
|
||||
"window-file-drop",
|
||||
"window-release-shortcut",
|
||||
"window-text-drop"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Enumerate an iPad Air M3 in a running Windows Reims guest."""
|
||||
import argparse
|
||||
from contextlib import closing, contextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
from queue import Empty, Queue
|
||||
from secrets import token_hex
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
from threading import Event, Thread
|
||||
from time import monotonic, sleep
|
||||
|
||||
from driver_pipe import driver_session, peer_is_qemu
|
||||
from usb_device import IPAD, REVISION, Ipad, backend_from
|
||||
from usb_hub import Hub
|
||||
import usb_redir
|
||||
|
||||
|
||||
class Monitor:
|
||||
def __init__(self, process):
|
||||
self.process = process
|
||||
if "QMP" not in self.read():
|
||||
raise RuntimeError("QEMU did not send a QMP greeting")
|
||||
self.call("qmp_capabilities")
|
||||
|
||||
def read(self):
|
||||
line = self.process.stdout.readline()
|
||||
if not line:
|
||||
raise RuntimeError("QEMU closed the monitor connection")
|
||||
return json.loads(line)
|
||||
|
||||
def call(self, command, **arguments):
|
||||
packet = {"execute": command}
|
||||
if arguments:
|
||||
packet["arguments"] = arguments
|
||||
self.process.stdin.write(json.dumps(packet).encode() + b"\n")
|
||||
self.process.stdin.flush()
|
||||
while True:
|
||||
answer = self.read()
|
||||
if "event" in answer:
|
||||
continue
|
||||
if "error" in answer:
|
||||
raise RuntimeError(f"{command}: {answer['error']['desc']}")
|
||||
return answer["return"]
|
||||
|
||||
|
||||
class Guest:
|
||||
def __init__(self, directory, qmp_path, relay):
|
||||
self.pid_file = directory / "qemu.pid"
|
||||
self.pid = self.current_pid()
|
||||
if self.pid is None:
|
||||
raise ValueError("The VM has no valid QEMU PID")
|
||||
self.qmp_path = qmp_path
|
||||
self.relay = relay
|
||||
|
||||
def current_pid(self):
|
||||
try:
|
||||
pid = int(self.pid_file.read_text().strip())
|
||||
return pid if pid > 0 else None
|
||||
except (FileNotFoundError, ValueError):
|
||||
return None
|
||||
|
||||
@contextmanager
|
||||
def monitor(self):
|
||||
if self.current_pid() != self.pid:
|
||||
raise RuntimeError("The VM stopped or restarted during the session")
|
||||
with subprocess.Popen([str(self.relay), str(self.qmp_path)], stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW) as process:
|
||||
try:
|
||||
monitor = Monitor(process)
|
||||
if self.current_pid() != self.pid:
|
||||
raise RuntimeError("The VM restarted before the monitor opened")
|
||||
yield monitor
|
||||
finally:
|
||||
process.stdin.close()
|
||||
|
||||
|
||||
class MeasuredIpad(Ipad):
|
||||
def __init__(self, backend, info, superspeed):
|
||||
super().__init__(backend, info)
|
||||
self.speed = 3 if superspeed else self.speed
|
||||
self.descriptor_read = False
|
||||
self.mode_request_seen = False
|
||||
|
||||
def control(self, setup, data):
|
||||
kind, request, value, index, _ = setup
|
||||
if (kind, request) == (0xC0, 0x52) and not self.mode_request_seen:
|
||||
self.mode_request_seen = True
|
||||
print(f"The guest requested Apple USB mode {index}.", flush=True)
|
||||
reply = super().control(setup, data)
|
||||
if (kind, request, value) == (0x80, 6, 0x0100) and len(reply) >= 18:
|
||||
if struct.unpack_from("<HHH", reply, 8) == (*IPAD, REVISION) and not self.descriptor_read:
|
||||
self.descriptor_read = True
|
||||
print("The guest read the iPad Air M3 USB device descriptor.", flush=True)
|
||||
return reply
|
||||
|
||||
|
||||
def air_m3(info):
|
||||
return (info is not None and info.ids == IPAD
|
||||
and struct.unpack_from("<H", info.descriptor, 12)[0] == REVISION)
|
||||
|
||||
|
||||
def initial_configuration(hub):
|
||||
info = hub.connection()
|
||||
if not air_m3(info) or (info.config, info.count) != (1, 4):
|
||||
raise ValueError("Expected one iPad Air M3 in its initial USB configuration")
|
||||
values = {hub.configuration(index)[5] for index in range(info.count)}
|
||||
if len(values) != info.count or info.config not in values:
|
||||
raise ValueError("The iPad USB configuration descriptors are inconsistent")
|
||||
return info
|
||||
|
||||
|
||||
def superspeed_for_session(hub):
|
||||
raw = hub.query(279, struct.pack("<IIII", hub.port, 16, 4, 0), 16)
|
||||
if len(raw) != 16:
|
||||
raise ValueError("Windows did not report the USB link speed")
|
||||
_, _, _, flags = struct.unpack("<IIII", raw)
|
||||
return bool(flags & 1)
|
||||
|
||||
|
||||
def still_connected(hub, initial, guest):
|
||||
try:
|
||||
current = hub.connection()
|
||||
return (air_m3(current) and current.address == initial.address
|
||||
and guest.current_pid() == guest.pid)
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def export_device(listener, guest, device, done, present):
|
||||
listener.settimeout(0.25)
|
||||
deadline = monotonic() + 25
|
||||
while not done.is_set() and present():
|
||||
if monotonic() >= deadline:
|
||||
raise TimeoutError("QEMU did not connect to the iPad forwarder")
|
||||
try:
|
||||
peer, _ = listener.accept()
|
||||
except TimeoutError:
|
||||
continue
|
||||
with peer:
|
||||
if not peer_is_qemu(peer, guest.pid):
|
||||
continue
|
||||
peer.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
peer.settimeout(0.5)
|
||||
next_check = 0.0
|
||||
|
||||
def stopped():
|
||||
nonlocal next_check
|
||||
if done.is_set():
|
||||
return True
|
||||
now = monotonic()
|
||||
if now >= next_check:
|
||||
next_check = now + 0.25
|
||||
return not present()
|
||||
return False
|
||||
|
||||
usb_redir.serve(peer, device, stopped)
|
||||
return
|
||||
|
||||
|
||||
def remove_guest_device(guest, device_id, chardev):
|
||||
if guest.current_pid() != guest.pid:
|
||||
return
|
||||
with guest.monitor() as qmp:
|
||||
def device_exists():
|
||||
return any(item["name"] == device_id for item in qmp.call("qom-list", path="/machine/peripheral"))
|
||||
|
||||
if device_exists():
|
||||
qmp.call("device_del", id=device_id)
|
||||
deadline = monotonic() + 5
|
||||
while device_exists():
|
||||
if monotonic() >= deadline:
|
||||
raise RuntimeError("QEMU did not remove the iPad device")
|
||||
sleep(0.1)
|
||||
if any(item["label"] == chardev for item in qmp.call("query-chardev")):
|
||||
qmp.call("chardev-remove", id=chardev)
|
||||
|
||||
|
||||
def bridge(guest, device, present):
|
||||
suffix = token_hex(6)
|
||||
device_id, chardev = f"ipad-{suffix}", f"ipad-char-{suffix}"
|
||||
done, errors = Event(), Queue()
|
||||
with socket.socket() as listener:
|
||||
listener.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
port = listener.getsockname()[1]
|
||||
|
||||
def worker():
|
||||
try:
|
||||
export_device(listener, guest, device, done, present)
|
||||
except (OSError, RuntimeError, ValueError) as exc:
|
||||
errors.put(exc)
|
||||
|
||||
exporter = Thread(target=worker)
|
||||
exporter.start()
|
||||
try:
|
||||
with guest.monitor() as qmp:
|
||||
qmp.call("chardev-add", id=chardev, backend={"type": "socket", "data": {
|
||||
"server": False, "addr": {"type": "inet", "data": {"host": "127.0.0.1", "port": str(port)}},
|
||||
}})
|
||||
qmp.call("device_add", driver="usb-redir", id=device_id, chardev=chardev, bus="xhci.0")
|
||||
deadline = monotonic() + 12
|
||||
while monotonic() < deadline and exporter.is_alive():
|
||||
if qmp.call("qom-get", path=f"/machine/peripheral/{device_id}", property="attached") is True:
|
||||
print("iPad attached to the guest USB bus.", flush=True)
|
||||
break
|
||||
sleep(0.15)
|
||||
else:
|
||||
try:
|
||||
raise errors.get_nowait()
|
||||
except Empty:
|
||||
# A guest descriptor read can already have triggered USB re-enumeration.
|
||||
if not device.descriptor_read:
|
||||
raise TimeoutError("The iPad did not attach to the guest USB bus") from None
|
||||
|
||||
deadline = monotonic() + 65
|
||||
while monotonic() < deadline and exporter.is_alive():
|
||||
sleep(0.25)
|
||||
return device.descriptor_read
|
||||
finally:
|
||||
try:
|
||||
remove_guest_device(guest, device_id, chardev)
|
||||
finally:
|
||||
done.set()
|
||||
exporter.join()
|
||||
|
||||
|
||||
def run(guest, directory):
|
||||
with guest.monitor() as qmp:
|
||||
models = qmp.call("device-list-properties", typename="usb-redir")
|
||||
if not any(item["name"] == "chardev" for item in models):
|
||||
raise RuntimeError("The guest QEMU does not support usb-redir")
|
||||
qmp.call("qom-list", path="/machine/peripheral/xhci")
|
||||
backend = backend_from(directory)
|
||||
with driver_session(directory) as driver:
|
||||
selected = driver.expect("selected")
|
||||
with closing(Hub(selected["hub_instance"], int(selected["hub_port"]))) as hub:
|
||||
initial_configuration(hub)
|
||||
driver.stream.write(b"B")
|
||||
driver.expect("replug")
|
||||
print("Unplug the iPad, wait two seconds, then plug it into the same USB port.", flush=True)
|
||||
driver.expect("probe", timeout=105)
|
||||
capture = initial_configuration(hub)
|
||||
driver.stream.write(b"P")
|
||||
driver.expect("switch")
|
||||
with closing(MeasuredIpad(backend, capture, superspeed_for_session(hub))) as device:
|
||||
proof = bridge(guest, device, lambda: still_connected(hub, capture, guest))
|
||||
print("Windows iPad driver restored.", flush=True)
|
||||
return proof
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--vm-dir", required=True, type=Path, help="Directory containing qemu.pid")
|
||||
parser.add_argument("--qmp", type=Path, help="QMP socket path, if outside the VM directory")
|
||||
parser.add_argument("--relay", type=Path, default=Path(__file__).with_name("qmp-relay.exe"))
|
||||
parser.add_argument("--driver-dir", required=True, type=Path, help="Verified libusb-win32 bin/amd64 directory")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
directory = args.vm_dir.resolve(strict=True)
|
||||
# Windows AF_UNIX sockets are reparse points that pathlib cannot resolve.
|
||||
qmp_path = (args.qmp if args.qmp else directory / "qmp.sock").absolute()
|
||||
guest = Guest(directory, qmp_path, args.relay.resolve(strict=True))
|
||||
proof = run(guest, args.driver_dir.resolve(strict=True))
|
||||
except (OSError, ValueError, RuntimeError) as exc:
|
||||
sys.exit(f"iPad USB session: {exc}")
|
||||
if not proof:
|
||||
sys.exit("The guest did not read the iPad device descriptor before the session ended.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,704 @@
|
||||
#requires -Version 7.0
|
||||
# Based on MonchiLin/reims-vgpu@5e69f1ba9d0f0267a670a1fb836b794184ec36bf.
|
||||
# Only the temporary upper-filter transaction runs elevated. Plug changes are user-controlled.
|
||||
[CmdletBinding(DefaultParameterSetName = 'Session')]
|
||||
param(
|
||||
[Parameter(Mandatory, ParameterSetName = 'Session')][string]$DriverDir,
|
||||
[Parameter(Mandatory, ParameterSetName = 'Session')][ValidateRange(1, 2147483647)][int]$OwnerPid,
|
||||
[Parameter(Mandatory, ParameterSetName = 'Session')][ValidatePattern('\A[a-f0-9]{32}\z', Options = 'CultureInvariant')][string]$Token,
|
||||
[Parameter(Mandatory, ParameterSetName = 'Recover')][switch]$Recover
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$script:settings = @('UpperFilters')
|
||||
$script:idPattern = '\AUSB\\VID_05AC&PID_12AB\\[a-zA-Z0-9_&-]{1,160}\z'
|
||||
$script:hardwareId = 'USB\VID_05AC&PID_12AB&REV_1503'
|
||||
$script:driverPattern = '\A\{88bae032-5a81-49f0-bc3d-a4ff138216d6\}\\[0-9]{4}\z'
|
||||
$script:control = 'SYSTEM\CurrentControlSet'
|
||||
$script:journalName = 'SOFTWARE\Reims.WindowsIpadAirM3AttachLab'
|
||||
$script:replugTimeoutSeconds = 90
|
||||
$script:unplugTimeoutSeconds = 90
|
||||
$script:activeTimeoutSeconds = 180
|
||||
# From libusb-win32-bin-1.4.0.2.zip, bin/amd64/libusb0.sys.
|
||||
$script:driverSha256 = 'CDA0070FE4F7C5DE5D3BB06FA6D7E29E6F6740C0F2FA319FB5C1AF235D78D616'
|
||||
|
||||
function Refuse([string]$Message) { throw [System.ApplicationException]::new($Message) }
|
||||
|
||||
function Initialize-Native {
|
||||
if ('ReimsIpad' -as [type]) { return }
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Pipes;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Principal;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
|
||||
public static class ReimsIpad {
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true, CharSet=CharSet.Unicode)]
|
||||
static extern uint CM_Locate_DevNodeW(out uint node, string id, uint flags);
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true)]
|
||||
static extern uint CM_Set_DevNode_Registry_PropertyW(uint node, uint property, byte[] data, uint length, uint flags);
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true)]
|
||||
static extern uint CM_Get_DevNode_Status(out uint status, out uint problem, uint node, uint flags);
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct PropertyKey { public Guid Format; public uint Id; }
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true)]
|
||||
static extern uint CM_Get_DevNode_PropertyW(uint node, ref PropertyKey key, out uint type,
|
||||
out long value, ref uint size, uint flags);
|
||||
[DllImport("cfgmgr32.dll", ExactSpelling=true, EntryPoint="CM_Get_DevNode_PropertyW")]
|
||||
static extern uint ReadProperty(uint node, ref PropertyKey key, out uint type,
|
||||
[Out] byte[] value, ref uint size, uint flags);
|
||||
[DllImport("advapi32.dll", SetLastError=true)]
|
||||
static extern bool OpenProcessToken(SafeProcessHandle process, uint access, out SafeAccessTokenHandle token);
|
||||
[DllImport("advapi32.dll", SetLastError=true)]
|
||||
static extern bool GetTokenInformation(SafeAccessTokenHandle token, int kind, IntPtr buffer, int size, out int length);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
static extern bool GetNamedPipeClientProcessId(SafePipeHandle pipe, out uint pid);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
static extern bool PeekNamedPipe(SafePipeHandle pipe, IntPtr buffer, uint bufferSize,
|
||||
IntPtr bytesRead, out uint bytesAvailable, IntPtr bytesLeft);
|
||||
|
||||
// CM_LOCATE_DEVNODE_NORMAL only finds present nodes. A phantom keeps its registry values.
|
||||
public static bool Present(string id) {
|
||||
uint rc = CM_Locate_DevNodeW(out uint node, id, 0);
|
||||
if (rc == 0x0d) return false; // CR_NO_SUCH_DEVNODE
|
||||
if (rc != 0) throw new ApplicationException("Windows could not query the iPad device node.");
|
||||
return true;
|
||||
}
|
||||
public static bool Started(string id) {
|
||||
return CM_Locate_DevNodeW(out uint n, id, 0) == 0 &&
|
||||
CM_Get_DevNode_Status(out uint flags, out uint problem, n, 0) == 0 && (flags & 8) != 0 && problem == 0;
|
||||
}
|
||||
public static long Arrival(string id) {
|
||||
var key = new PropertyKey { Format = new Guid("83da6326-97a6-4088-9453-a1923f573b29"), Id = 102 };
|
||||
uint size = 8;
|
||||
if (CM_Locate_DevNodeW(out uint node, id, 0) != 0) return 0;
|
||||
if (CM_Get_DevNode_PropertyW(node, ref key, out uint type, out long value, ref size, 0) != 0 ||
|
||||
type != 0x10 || size != 8) throw new ApplicationException("Windows could not read the iPad arrival time.");
|
||||
return value;
|
||||
}
|
||||
public static uint SetFilters(string id, uint property, byte[] data) {
|
||||
uint rc = CM_Locate_DevNodeW(out uint n, id, 1); // includes disconnected devices
|
||||
return rc == 0 ? CM_Set_DevNode_Registry_PropertyW(n, property, data, (uint)(data?.Length ?? 0), 0) : rc;
|
||||
}
|
||||
static string[] StringListProperty(string id, PropertyKey key, bool allowAbsent) {
|
||||
uint rc = CM_Locate_DevNodeW(out uint node, id, 0);
|
||||
if (rc == 0x0d) return null;
|
||||
if (rc != 0) throw new ApplicationException("Windows could not query the iPad device node.");
|
||||
uint size = 0;
|
||||
rc = ReadProperty(node, ref key, out uint type, null, ref size, 0);
|
||||
if (allowAbsent && rc == 0x25) return Array.Empty<string>(); // CR_NO_SUCH_VALUE
|
||||
if (rc != 0x1a || size == 0 || size > 65536 || (size & 1) != 0)
|
||||
throw new ApplicationException("Could not read the iPad device properties.");
|
||||
var bytes = new byte[size];
|
||||
if (ReadProperty(node, ref key, out type, bytes, ref size, 0) != 0 || type != 0x2012)
|
||||
throw new ApplicationException("Unexpected iPad device property type.");
|
||||
return System.Text.Encoding.Unicode.GetString(bytes, 0, (int)size).Split(new char[]{'\0'}, StringSplitOptions.RemoveEmptyEntries);
|
||||
}
|
||||
public static string[] Filters(string id) {
|
||||
var key = new PropertyKey { Format = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), Id = 19 };
|
||||
return StringListProperty(id, key, true);
|
||||
}
|
||||
public static string[] Stack(string id) {
|
||||
var key = new PropertyKey { Format = new Guid("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), Id = 14 };
|
||||
return StringListProperty(id, key, false);
|
||||
}
|
||||
public static bool HasPipeInput(NamedPipeServerStream pipe) {
|
||||
if (!PeekNamedPipe(pipe.SafePipeHandle, IntPtr.Zero, 0, IntPtr.Zero, out uint available, IntPtr.Zero))
|
||||
throw new Win32Exception();
|
||||
return available != 0;
|
||||
}
|
||||
public static SecurityIdentifier LogonSid(Process owner) {
|
||||
if (!OpenProcessToken(owner.SafeHandle, 8, out var token)) throw new Win32Exception();
|
||||
using (token) {
|
||||
GetTokenInformation(token, 28, IntPtr.Zero, 0, out int size); // TokenLogonSid, TOKEN_GROUPS
|
||||
if (size <= 0) throw new Win32Exception();
|
||||
IntPtr data = Marshal.AllocHGlobal(size);
|
||||
try {
|
||||
if (!GetTokenInformation(token, 28, data, size, out size) || Marshal.ReadInt32(data) != 1)
|
||||
throw new Win32Exception();
|
||||
return new SecurityIdentifier(Marshal.ReadIntPtr(data, IntPtr.Size));
|
||||
} finally { Marshal.FreeHGlobal(data); }
|
||||
}
|
||||
}
|
||||
public static bool IsClient(NamedPipeServerStream pipe, int expected) {
|
||||
return GetNamedPipeClientProcessId(pipe.SafePipeHandle, out uint pid) && pid == expected;
|
||||
}
|
||||
public static NamedPipeServerStream CreateAsOwner(Process owner, Func<NamedPipeServerStream> create) {
|
||||
if (!OpenProcessToken(owner.SafeHandle, 10, out var token)) throw new Win32Exception(); // QUERY | DUPLICATE
|
||||
using (token) return WindowsIdentity.RunImpersonated(token, create);
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Open-SessionPipe($Owner, [string]$Token) {
|
||||
if ($Owner.SessionId -ne [Diagnostics.Process]::GetCurrentProcess().SessionId -or $Owner.HasExited) {
|
||||
Refuse 'The requesting process left this Windows session.'
|
||||
}
|
||||
$logon = [ReimsIpad]::LogonSid($Owner).Value
|
||||
$security = [IO.Pipes.PipeSecurity]::new()
|
||||
# The client requests GENERIC_READ | GENERIC_WRITE. The logon SID identifies its session,
|
||||
# and both endpoints verify the other's process ID. Create at the caller's integrity level.
|
||||
$security.SetSecurityDescriptorSddlForm("D:P(D;;GA;;;NU)(A;;GA;;;BA)(A;;GA;;;SY)(A;;GRGW;;;$logon)")
|
||||
$options = [IO.Pipes.PipeOptions]::Asynchronous
|
||||
if ('FirstPipeInstance' -in [IO.Pipes.PipeOptions].GetEnumNames()) { $options = $options -bor [IO.Pipes.PipeOptions]::FirstPipeInstance }
|
||||
[ReimsIpad]::CreateAsOwner($Owner, {
|
||||
[IO.Pipes.NamedPipeServerStreamAcl]::Create("reims-ipad-$Token", 'InOut', 1, 'Byte', $options, 256, 4096, $security)
|
||||
})
|
||||
}
|
||||
|
||||
function Send-Status($Pipe, [string]$State, $Fields = @{}) {
|
||||
$Fields.state = $State
|
||||
$line = (ConvertTo-Json -InputObject $Fields -Compress) + [char]10
|
||||
$data = [Text.Encoding]::UTF8.GetBytes($line)
|
||||
$Pipe.Write($data, 0, $data.Length)
|
||||
}
|
||||
|
||||
function Wait-Signal($Pipe, $Owner, [char]$Expected, [string]$DeviceId = '', [long]$Arrival = 0, [int]$ActiveTimeoutSeconds = $script:activeTimeoutSeconds) {
|
||||
$buffer = [byte[]]::new(1)
|
||||
$read = $Pipe.ReadAsync($buffer, 0, 1)
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
$lastPresent = $clock.Elapsed
|
||||
$switched = $false
|
||||
while (-not $read.Wait(250)) {
|
||||
if ($Owner.HasExited) { return 'R' }
|
||||
if ($DeviceId) {
|
||||
if ($clock.Elapsed.TotalSeconds -ge $ActiveTimeoutSeconds) { return 'R' }
|
||||
# Apple's requested mode switch re-enumerates once. Monitor subsequent arrivals,
|
||||
# including a rapid unplug/replug between two polls.
|
||||
$now = [ReimsIpad]::Arrival($DeviceId)
|
||||
if ($now -ne 0) {
|
||||
if ($arrival -ne $now) {
|
||||
if ($switched -or $clock.Elapsed.TotalSeconds -gt 20) { return 'R' }
|
||||
$switched = $true
|
||||
$arrival = $now
|
||||
}
|
||||
$lastPresent = $clock.Elapsed
|
||||
} elseif (($clock.Elapsed - $lastPresent).TotalSeconds -ge 5) { return 'R' }
|
||||
} elseif ($clock.Elapsed.TotalSeconds -ge 60) { Refuse 'The USB helper timed out during preparation.' }
|
||||
}
|
||||
if ($read.Result -eq 0 -or $Owner.HasExited -or $buffer[0] -eq [byte][char]'R') { return 'R' }
|
||||
if ($buffer[0] -ne [byte]$Expected) { Refuse 'Unexpected USB helper request.' }
|
||||
return [char]$buffer[0]
|
||||
}
|
||||
|
||||
function Read-KeyValue($Key, [string]$Name) {
|
||||
if ($Key.GetValueNames() -notcontains $Name) { return @{ Kind = 'Absent'; Value = $null } }
|
||||
return @{
|
||||
Kind = $Key.GetValueKind($Name).ToString()
|
||||
Value = $Key.GetValue($Name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
}
|
||||
}
|
||||
|
||||
function Test-SameValue($A, $B) {
|
||||
if ($A.Kind -cne $B.Kind) { return $false }
|
||||
if ($A.Kind -ceq 'Absent') { return $true }
|
||||
$left = @($A.Value)
|
||||
$right = @($B.Value)
|
||||
if ($left.Count -ne $right.Count) { return $false }
|
||||
for ($i = 0; $i -lt $left.Count; $i++) {
|
||||
if (-not [string]::Equals([string]$left[$i], [string]$right[$i], [StringComparison]::Ordinal)) { return $false }
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
function Read-DeviceValue($Journal, $Name) {
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\Enum\$($Journal.Id)")
|
||||
if (-not $key) { Refuse 'The original device registry key is missing. Reconnect the same iPad and retry.' }
|
||||
try { Read-KeyValue $key $Name } finally { $key.Dispose() }
|
||||
}
|
||||
|
||||
function Write-KeyValue($Key, $Name, $Setting) {
|
||||
if ($Setting.Kind -eq 'Absent') { $Key.DeleteValue($Name, $false); return }
|
||||
if ($Setting.Kind -ne 'MultiString') { Refuse 'Invalid iPad upper filter type.' }
|
||||
$Key.SetValue($Name, [string[]]$Setting.Value, [Microsoft.Win32.RegistryValueKind]::MultiString)
|
||||
}
|
||||
|
||||
function Write-DeviceValue($Journal, $Name, $Setting) {
|
||||
if ($Name -cne 'UpperFilters') { Refuse 'The probe may change only the selected iPad upper filters.' }
|
||||
[byte[]]$data = $null
|
||||
if ($Setting.Kind -ne 'Absent') {
|
||||
$data = [Text.Encoding]::Unicode.GetBytes(($Setting.Value -join [char]0) + [char]0 + [char]0)
|
||||
}
|
||||
$rc = [ReimsIpad]::SetFilters($Journal.Id, 0x12, $data)
|
||||
$alreadyAbsent = $rc -eq 0x25 -and $Setting.Kind -eq 'Absent'
|
||||
if ($rc -ne 0 -and -not $alreadyAbsent -and [ReimsIpad]::Present($Journal.Id)) { Refuse "Windows rejected the iPad upper filter change ($rc)." }
|
||||
# Some stacks retain the raw value after Configuration Manager removes a PnP property.
|
||||
# Read it back. Open for writing only if an explicit raw restore is still necessary.
|
||||
if (-not (Test-SameValue (Read-DeviceValue $Journal $Name) $Setting)) {
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\Enum\$($Journal.Id)", $true)
|
||||
try { Write-KeyValue $key $Name $Setting; $key.Flush() } finally { if ($key) { $key.Dispose() } }
|
||||
}
|
||||
if (-not (Test-SameValue (Read-DeviceValue $Journal $Name) $Setting)) { Refuse "Windows did not retain the iPad $Name value." }
|
||||
}
|
||||
|
||||
function Get-SettingsPlan($Journal) {
|
||||
$upper = @($Journal.Original.UpperFilters.Value | Where-Object { $null -ne $_ }) + 'libusb0'
|
||||
return [ordered]@{ UpperFilters = @{ Kind = 'MultiString'; Value = $upper } }
|
||||
}
|
||||
|
||||
function Set-ProbeFilter($Journal) {
|
||||
$actual = Read-DeviceValue $Journal 'UpperFilters'
|
||||
if (-not (Test-SameValue $actual $Journal.Original.UpperFilters)) { Refuse 'The iPad upper filters changed outside this session.' }
|
||||
$target = Get-SettingsPlan $Journal
|
||||
Write-DeviceValue $Journal 'UpperFilters' $target.UpperFilters
|
||||
}
|
||||
|
||||
function Assert-DeviceIdentity($Journal) {
|
||||
if ($Journal.Id -notmatch $script:idPattern -or $Journal.Driver -notmatch $script:driverPattern) {
|
||||
Refuse 'Unexpected iPad instance or driver key.'
|
||||
}
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\Enum\$($Journal.Id)")
|
||||
if (-not $key) { Refuse 'Reconnect the original iPad so its saved driver settings can be restored.' }
|
||||
try {
|
||||
if ($key.GetValue('HardwareID') -notcontains $script:hardwareId -or
|
||||
$key.GetValue('Service') -ne 'usbccgp' -or $key.GetValue('Driver') -ne $Journal.Driver) {
|
||||
Refuse 'The iPad or its Windows driver no longer matches the saved device.'
|
||||
}
|
||||
} finally { $key.Dispose() }
|
||||
}
|
||||
|
||||
function Get-SelectedDevice {
|
||||
$parents = @(Get-PnpDevice -PresentOnly | Where-Object InstanceId -Match '^USB\\VID_05AC&PID_12AB\\')
|
||||
if ($parents.Count -ne 1 -or $parents[0].Status -ne 'OK') { Refuse 'Connect one supported iPad Air M3 to Windows.' }
|
||||
$id = $parents[0].InstanceId
|
||||
if ($id -notmatch $script:idPattern) { Refuse 'Unsupported iPad device identity.' }
|
||||
$props = Get-PnpDeviceProperty -InstanceId $id -KeyName DEVPKEY_Device_Parent, DEVPKEY_Device_Address, DEVPKEY_Device_Driver
|
||||
$hub = ($props | Where-Object KeyName -eq 'DEVPKEY_Device_Parent').Data
|
||||
$port = ($props | Where-Object KeyName -eq 'DEVPKEY_Device_Address').Data
|
||||
$driver = ($props | Where-Object KeyName -eq 'DEVPKEY_Device_Driver').Data
|
||||
if (-not $hub -or $port -lt 1 -or $port -gt 255) { Refuse 'Windows did not identify the iPad USB hub and port.' }
|
||||
$selected = @{ Id = $id; Hub = $hub; Port = [int]$port; Driver = $driver }
|
||||
Assert-DeviceIdentity $selected
|
||||
$shared = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SOFTWARE\usbipd-win\Devices')
|
||||
if ($shared) {
|
||||
try {
|
||||
foreach ($name in $shared.GetSubKeyNames()) {
|
||||
$device = $shared.OpenSubKey($name)
|
||||
if (-not $device) { continue }
|
||||
try {
|
||||
if ($device.GetValue('InstanceId') -eq $id) { Refuse 'Unshare this iPad in usbipd-win before using it here.' }
|
||||
} finally { $device.Dispose() }
|
||||
}
|
||||
} finally { $shared.Dispose() }
|
||||
}
|
||||
return $selected
|
||||
}
|
||||
|
||||
# Check class filters and *all* registered device instances, including unplugged devices.
|
||||
# Do not start if any other device or class could own the temporary libusb0 service.
|
||||
function Assert-NoOtherReference($Key, [int]$Depth, $Journal, [string]$Path = '') {
|
||||
if ($Depth -eq 0) {
|
||||
if ($Path -eq $Journal.Id) { return }
|
||||
foreach ($name in 'Service', 'UpperFilters', 'LowerFilters') {
|
||||
if ($Key.GetValue($name) -contains 'libusb0') { Refuse 'Another Windows device or class uses libusb0.' }
|
||||
}
|
||||
if ($Key.GetValue('Driver') -eq $Journal.Driver) { Refuse 'Another device uses the iPad driver software key.' }
|
||||
return
|
||||
}
|
||||
foreach ($name in $Key.GetSubKeyNames()) {
|
||||
$child = $Key.OpenSubKey($name)
|
||||
if (-not $child) { continue }
|
||||
$next = if ($Path) { "$Path\$name" } else { $name }
|
||||
try { Assert-NoOtherReference $child ($Depth - 1) $Journal $next } finally { $child.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-ExclusiveUse($Journal) {
|
||||
foreach ($entry in @(@('Enum', 3), @('Control\Class', 1))) {
|
||||
$root = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\$($entry[0])")
|
||||
try { Assert-NoOtherReference $root $entry[1] $Journal } finally { $root.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-SystemTool([string]$Name, [string[]]$Arguments, [int[]]$Allowed = @(0)) {
|
||||
$info = [Diagnostics.ProcessStartInfo]::new()
|
||||
$info.FileName = [IO.Path]::Combine([Environment]::SystemDirectory, $Name)
|
||||
$info.UseShellExecute = $false
|
||||
$info.CreateNoWindow = $true
|
||||
$info.RedirectStandardOutput = $true
|
||||
$info.RedirectStandardError = $true
|
||||
foreach ($argument in $Arguments) { $info.ArgumentList.Add($argument) }
|
||||
$process = [Diagnostics.Process]::Start($info)
|
||||
try {
|
||||
# Native diagnostics can contain serial numbers. Only the tool and exit code reach the client.
|
||||
$stdout = $process.StandardOutput.ReadToEndAsync()
|
||||
$stderr = $process.StandardError.ReadToEndAsync()
|
||||
if (-not $process.WaitForExit(20000)) { $process.Kill(); Refuse "$Name timed out." }
|
||||
if ($process.ExitCode -notin $Allowed) { Refuse "$Name failed with Windows error $($process.ExitCode)." }
|
||||
} finally { $process.Dispose() }
|
||||
}
|
||||
|
||||
function Get-DeviceArrival($Journal) { [ReimsIpad]::Arrival($Journal.Id) }
|
||||
function Test-DevicePresent($Journal) { [ReimsIpad]::Present($Journal.Id) }
|
||||
function Test-DeviceStarted($Journal) { [ReimsIpad]::Started($Journal.Id) }
|
||||
function Get-EffectiveStack($Journal) { [ReimsIpad]::Stack($Journal.Id) }
|
||||
|
||||
function Assert-SameDevice($Expected, $Current) {
|
||||
if ($Current.Id -ne $Expected.Id -or $Current.Driver -ne $Expected.Driver -or
|
||||
$Current.Hub -ne $Expected.Hub -or $Current.Port -ne $Expected.Port) {
|
||||
Refuse 'Reconnect the same iPad to its original USB port.'
|
||||
}
|
||||
}
|
||||
|
||||
function Wait-ForReplug($Pipe, $Owner, $Journal, [long]$Before, [int]$TimeoutSeconds = $script:replugTimeoutSeconds) {
|
||||
if ($Before -eq 0) { Refuse 'The selected iPad disconnected before filter preparation.' }
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
$left = $false
|
||||
while ($clock.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
|
||||
if ($Owner.HasExited) { return $false }
|
||||
if ([ReimsIpad]::HasPipeInput($Pipe)) {
|
||||
if ($Pipe.ReadByte() -eq [byte][char]'R') { return $false }
|
||||
Refuse 'Unexpected USB helper request while waiting for the iPad to be replugged.'
|
||||
}
|
||||
$arrival = Get-DeviceArrival $Journal
|
||||
if ($arrival -eq 0) {
|
||||
$left = $true
|
||||
} elseif ($left -and $arrival -ne $Before -and (Test-DeviceStarted $Journal)) {
|
||||
Assert-SameDevice $Journal (Get-SelectedDevice)
|
||||
Assert-FilterStack $Journal (Get-SettingsPlan $Journal)
|
||||
$stack = @(Get-EffectiveStack $Journal)
|
||||
if ($stack -notcontains '\Driver\libusb0' -or $stack -notcontains '\Driver\usbccgp') {
|
||||
Refuse 'Windows did not attach the temporary filter to the replugged iPad.'
|
||||
}
|
||||
return $true
|
||||
}
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
Refuse 'Timed out waiting for the iPad to be unplugged and reconnected to its original USB port.'
|
||||
}
|
||||
|
||||
function Wait-ForFilterRelease($Journal, [scriptblock]$NotifyUnplug, [int]$TimeoutSeconds = $script:unplugTimeoutSeconds) {
|
||||
if (-not (Test-DevicePresent $Journal)) { return }
|
||||
try { $stack = @(Get-EffectiveStack $Journal) } catch { $stack = @() }
|
||||
if ($stack -contains '\Driver\usbccgp' -and $stack -notcontains '\Driver\libusb0') { return }
|
||||
|
||||
if ($NotifyUnplug) { & $NotifyUnplug }
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
while (Test-DevicePresent $Journal) {
|
||||
if ($clock.Elapsed.TotalSeconds -ge $TimeoutSeconds) { Refuse 'Timed out waiting for the iPad to be unplugged. The driver recovery record was kept.' }
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-FilterStack($Journal, $Expected, [switch]$AllowAbsent) {
|
||||
$actual = [ReimsIpad]::Filters($Journal.Id)
|
||||
if ($null -eq $actual) {
|
||||
if ($AllowAbsent -and -not [ReimsIpad]::Present($Journal.Id)) { return }
|
||||
Refuse 'The selected iPad disconnected during its Windows driver change.'
|
||||
}
|
||||
$wanted = [string[]]@($Expected.UpperFilters.Value | Where-Object { $null -ne $_ })
|
||||
if (-not (Test-SameValue @{ Kind = 'MultiString'; Value = $actual } @{ Kind = 'MultiString'; Value = $wanted })) {
|
||||
Refuse 'The active Windows upper filters differ from the requested iPad filters.'
|
||||
}
|
||||
}
|
||||
|
||||
function Read-FilterService {
|
||||
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("$script:control\Services\libusb0")
|
||||
if (-not $key) { return }
|
||||
try { return @{ ImagePath = $key.GetValue('ImagePath'); Type = $key.GetValue('Type'); Start = $key.GetValue('Start') } }
|
||||
finally { $key.Dispose() }
|
||||
}
|
||||
|
||||
function Get-ImagePath($Journal) {
|
||||
if ($Journal.Cookie -cnotmatch '\A[a-f0-9]{32}\z') { Refuse 'Invalid saved session identifier.' }
|
||||
return "System32\drivers\reims-ipad-m3-attach-$($Journal.Cookie).sys"
|
||||
}
|
||||
|
||||
function Get-ImageFile($Journal) {
|
||||
return [IO.Path]::Combine([Environment]::GetFolderPath('Windows'), (Get-ImagePath $Journal))
|
||||
}
|
||||
|
||||
function Read-DriverBytes([string]$Directory) {
|
||||
if ($Directory -notmatch '\A[A-Za-z]:[\\/]' -or $Directory.Substring(2).Contains(':')) { Refuse 'Use a local driver directory.' }
|
||||
$path = [IO.Path]::GetFullPath([IO.Path]::Combine($Directory, 'libusb0.sys'))
|
||||
$drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot($path))
|
||||
if ($drive.DriveType -notin 'Fixed', 'Removable') { Refuse 'Use an extracted driver on a local disk.' }
|
||||
for ($part = $path; $part; $part = [IO.Path]::GetDirectoryName($part)) {
|
||||
if (([IO.File]::GetAttributes($part) -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
|
||||
Refuse 'Extract the driver into a directory without symbolic links or junctions.'
|
||||
}
|
||||
}
|
||||
$file = [IO.File]::OpenRead($path)
|
||||
try {
|
||||
if ($file.Length -ne 99224) { Refuse 'Expected the amd64 libusb-win32 1.4.0.2 driver.' }
|
||||
$reader = [IO.BinaryReader]::new($file)
|
||||
try { $bytes = $reader.ReadBytes([int]$file.Length) } finally { $reader.Dispose() }
|
||||
} finally { $file.Dispose() }
|
||||
$sha = [Security.Cryptography.SHA256]::Create()
|
||||
try { $hash = [BitConverter]::ToString($sha.ComputeHash($bytes)).Replace('-', '') } finally { $sha.Dispose() }
|
||||
if ($hash -cne $script:driverSha256) { Refuse 'The supplied driver differs from the released amd64 libusb-win32 1.4.0.2 file.' }
|
||||
return ,$bytes
|
||||
}
|
||||
|
||||
function Install-Filter($Journal, [byte[]]$Bytes) {
|
||||
$image = Get-ImageFile $Journal
|
||||
# CreateNew inside the protected drivers directory. The pinned bytes we verified are the bytes we write.
|
||||
$file = [IO.File]::Open($image, 'CreateNew', 'Write', 'None')
|
||||
try { $file.Write($Bytes, 0, $Bytes.Length); $file.Flush($true) } finally { $file.Dispose() }
|
||||
if ((Get-AuthenticodeSignature -LiteralPath $image).Status -ne 'Valid') { Refuse 'Windows could not validate the libusb-win32 driver signature.' }
|
||||
Invoke-SystemTool 'sc.exe' @('create', 'libusb0', 'type=', 'kernel', 'start=', 'demand', 'binPath=', (Get-ImagePath $Journal))
|
||||
}
|
||||
|
||||
function Remove-FilterService {
|
||||
# 1062 is already stopped, 1072 is marked for deletion, and 1060 is already gone.
|
||||
Invoke-SystemTool 'sc.exe' @('stop', 'libusb0') @(0, 1062, 1072, 1060)
|
||||
Invoke-SystemTool 'sc.exe' @('delete', 'libusb0') @(0, 1072, 1060)
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
while (Read-FilterService) {
|
||||
if ($clock.Elapsed.TotalSeconds -ge 10) { Refuse 'Windows is still unloading libusb0. Retry recovery after it unloads.' }
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-SessionImage($Journal) {
|
||||
# Only the random, journal-owned image can be removed, including a partial copy after a crash.
|
||||
[IO.File]::Delete((Get-ImageFile $Journal))
|
||||
}
|
||||
|
||||
function Remove-OwnedDriver($Journal) {
|
||||
$service = Read-FilterService
|
||||
if ($service) {
|
||||
if ($service.ImagePath -ne (Get-ImagePath $Journal) -or $service.Type -ne 1 -or $service.Start -ne 3) {
|
||||
Refuse 'The libusb0 service belongs to another installation. Its configuration was preserved.'
|
||||
}
|
||||
Assert-ExclusiveUse $Journal
|
||||
Remove-FilterService
|
||||
}
|
||||
Remove-SessionImage $Journal
|
||||
}
|
||||
|
||||
function Open-JournalKey([switch]$Create) {
|
||||
$root = [Microsoft.Win32.Registry]::LocalMachine
|
||||
if ($Create) {
|
||||
$acl = [Security.AccessControl.RegistrySecurity]::new()
|
||||
$acl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;KA;;;BA)(A;;KA;;;SY)')
|
||||
$key = $root.CreateSubKey($script:journalName, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, $acl)
|
||||
} else { $key = $root.OpenSubKey($script:journalName, $true) }
|
||||
if (-not $key) { return }
|
||||
$acl = $key.GetAccessControl()
|
||||
$trusted = @('S-1-5-32-544', 'S-1-5-18')
|
||||
$rules = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]))
|
||||
if (-not $acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin $trusted -or
|
||||
@($rules | Where-Object { $_.IdentityReference.Value -notin $trusted }).Count) {
|
||||
$key.Dispose()
|
||||
Refuse 'Windows driver recovery storage has unexpected permissions.'
|
||||
}
|
||||
return $key
|
||||
}
|
||||
|
||||
function Read-Journal {
|
||||
$key = Open-JournalKey
|
||||
if (-not $key) { return }
|
||||
try { $saved = $key.GetValue('Session') } finally { $key.Dispose() }
|
||||
if ($null -ne $saved) {
|
||||
$journal = [Management.Automation.PSSerializer]::Deserialize($saved)
|
||||
if ($journal.Version -ne 1 -or $journal.Stage -notin 'prepared', 'device', 'restored' -or
|
||||
$journal.Id -notmatch $script:idPattern -or $journal.Driver -notmatch $script:driverPattern -or
|
||||
-not $journal.Hub -or $journal.Port -lt 1 -or $journal.Port -gt 255 -or
|
||||
$journal.Cookie -cnotmatch '\A[a-f0-9]{32}\z' -or $journal.Original.Count -ne $script:settings.Count) {
|
||||
Refuse 'The Windows driver recovery record has an unexpected format.'
|
||||
}
|
||||
foreach ($name in $script:settings) {
|
||||
if ($journal.Original[$name].Kind -notin 'Absent', 'MultiString') {
|
||||
Refuse 'The Windows driver recovery record contains an invalid upper filter value.'
|
||||
}
|
||||
}
|
||||
return $journal
|
||||
}
|
||||
}
|
||||
|
||||
function Save-Journal($Journal) {
|
||||
$key = Open-JournalKey -Create
|
||||
try {
|
||||
# Preserve array types, unexpanded strings, and strings that resemble timestamps.
|
||||
$key.SetValue('Session', [Management.Automation.PSSerializer]::Serialize($Journal, 8), 'String')
|
||||
$key.Flush() # A single durable value before any associated operation.
|
||||
} finally { $key.Dispose() }
|
||||
}
|
||||
|
||||
function Clear-Journal {
|
||||
$key = Open-JournalKey
|
||||
if ($key) {
|
||||
try { $key.DeleteValue('Session', $false); $key.Flush() } finally { $key.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-NoOriginalRecovery($Registry = [Microsoft.Win32.Registry]::LocalMachine) {
|
||||
foreach ($name in 'SOFTWARE\Reims.WindowsIpad', 'SOFTWARE\Reims.WindowsIpadAirM3Lab') {
|
||||
$key = $Registry.OpenSubKey($name)
|
||||
if (-not $key) { continue }
|
||||
try {
|
||||
if ($key.GetValueNames() -contains 'Session') {
|
||||
Refuse 'Another Reims iPad driver session is pending recovery. Restore it with its original helper first.'
|
||||
}
|
||||
} finally { $key.Dispose() }
|
||||
}
|
||||
}
|
||||
|
||||
function New-Journal($Selected) {
|
||||
if ((Read-FilterService) -or [IO.File]::Exists([IO.Path]::Combine([Environment]::SystemDirectory, 'drivers\libusb0.sys'))) {
|
||||
Refuse 'This host already has libusb0 installed. Its existing driver was preserved.'
|
||||
}
|
||||
Assert-ExclusiveUse $Selected
|
||||
$journal = @{
|
||||
Version = 1; Cookie = [guid]::NewGuid().ToString('N'); Stage = 'prepared'
|
||||
Id = $Selected.Id; Driver = $Selected.Driver; Hub = $Selected.Hub; Port = $Selected.Port; Original = [ordered]@{}
|
||||
}
|
||||
if ([IO.File]::Exists((Get-ImageFile $journal))) { Refuse 'The temporary driver image already exists.' }
|
||||
foreach ($name in $script:settings) { $journal.Original[$name] = Read-DeviceValue $journal $name }
|
||||
$lower = Read-DeviceValue $journal 'LowerFilters'
|
||||
if ($journal.Original.UpperFilters.Kind -notin 'Absent', 'MultiString' -or
|
||||
$journal.Original.UpperFilters.Value -contains 'libusb0' -or $lower.Value -contains 'libusb0') {
|
||||
Refuse 'The iPad has an unsupported Windows filter configuration.'
|
||||
}
|
||||
return $journal
|
||||
}
|
||||
|
||||
function Restore-Transaction($Journal, [scriptblock]$NotifyUnplug) {
|
||||
if ($Journal.Stage -eq 'device') {
|
||||
Assert-DeviceIdentity $Journal
|
||||
Assert-ExclusiveUse $Journal
|
||||
$probe = Get-SettingsPlan $Journal
|
||||
foreach ($name in $script:settings) {
|
||||
$actual = Read-DeviceValue $Journal $name
|
||||
if (Test-SameValue $actual $Journal.Original[$name]) { continue }
|
||||
if (-not (Test-SameValue $actual $probe[$name])) {
|
||||
Refuse "The iPad $name value changed outside this session. The recovery record was kept."
|
||||
}
|
||||
Write-DeviceValue $Journal $name $Journal.Original[$name]
|
||||
}
|
||||
foreach ($name in $script:settings) {
|
||||
if (-not (Test-SameValue (Read-DeviceValue $Journal $name) $Journal.Original[$name])) { Refuse "The iPad $name value was not restored." }
|
||||
}
|
||||
Assert-FilterStack $Journal $Journal.Original -AllowAbsent
|
||||
Wait-ForFilterRelease $Journal $NotifyUnplug
|
||||
$Journal.Stage = 'restored'
|
||||
Save-Journal $Journal
|
||||
}
|
||||
Remove-OwnedDriver $Journal
|
||||
Clear-Journal
|
||||
}
|
||||
|
||||
function Get-PublicMessage($ErrorRecord) {
|
||||
$cause = $ErrorRecord.Exception
|
||||
while ($cause) {
|
||||
if ($cause.GetType() -eq [System.ApplicationException]) { return $cause.Message }
|
||||
$cause = $cause.InnerException
|
||||
}
|
||||
# Built-in error messages can carry a serial number, local path or account name.
|
||||
return "Windows could not complete the driver operation ($($ErrorRecord.Exception.GetType().Name))."
|
||||
}
|
||||
|
||||
function Invoke-DriverSession {
|
||||
$identity = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
if (-not $identity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Refuse 'Windows administrator approval is required.' }
|
||||
if ($PSVersionTable.PSEdition -ne 'Core' -or $PSVersionTable.PSVersion.Major -ne 7 -or
|
||||
[Runtime.InteropServices.RuntimeInformation]::OSArchitecture -ne 'X64' -or
|
||||
[Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -ne 'X64') { Refuse 'Use 64-bit PowerShell 7 on x64 Windows.' }
|
||||
$env:PSModulePath = [IO.Path]::Combine($PSHOME, 'Modules') + ';' + [IO.Path]::Combine([Environment]::SystemDirectory, 'WindowsPowerShell\v1.0\Modules')
|
||||
Set-Location -LiteralPath ([Environment]::SystemDirectory)
|
||||
Initialize-Native
|
||||
$owner = $null
|
||||
$pipe = $null
|
||||
$mutex = $null
|
||||
$locked = $false
|
||||
$trustedPeer = $false
|
||||
$recoveryPending = $false
|
||||
$journal = $null
|
||||
$result = 0
|
||||
$notifyUnplug = {
|
||||
if ($trustedPeer) {
|
||||
try { Send-Status $pipe 'unplug' @{ timeout_seconds = $script:unplugTimeoutSeconds }; return } catch {}
|
||||
}
|
||||
[Console]::Error.WriteLine('Unplug the iPad now to release the temporary driver.')
|
||||
}
|
||||
try {
|
||||
if (-not $Recover) {
|
||||
$owner = [Diagnostics.Process]::GetProcessById($OwnerPid)
|
||||
$pipe = Open-SessionPipe $owner $Token
|
||||
$connected = $pipe.WaitForConnectionAsync()
|
||||
$clock = [Diagnostics.Stopwatch]::StartNew()
|
||||
while (-not $connected.Wait(250)) {
|
||||
if ($owner.HasExited -or $clock.Elapsed.TotalSeconds -ge 45) { Refuse 'The requesting USB helper did not connect.' }
|
||||
}
|
||||
$trustedPeer = [ReimsIpad]::IsClient($pipe, $OwnerPid) -and -not $owner.HasExited
|
||||
if (-not $trustedPeer) { Refuse 'The connected process is not the requesting USB helper.' }
|
||||
}
|
||||
$security = [Security.AccessControl.MutexSecurity]::new()
|
||||
$security.SetSecurityDescriptorSddlForm('D:P(A;;GA;;;BA)(A;;GA;;;SY)')
|
||||
$created = $false
|
||||
$mutex = [Threading.MutexAcl]::Create($false, 'Global\Reims.WindowsIpad.DriverSession', [ref]$created, $security)
|
||||
try { $locked = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $locked = $true }
|
||||
if (-not $locked) { Refuse 'Another Windows iPad driver session is active.' }
|
||||
Assert-NoOriginalRecovery
|
||||
$recoveryPending = $true
|
||||
$stale = Read-Journal
|
||||
if ($stale) {
|
||||
if (-not $Recover) { Refuse 'An iPad Air M3 driver recovery is pending. Unplug the iPad and run this helper with -Recover.' }
|
||||
Restore-Transaction $stale $notifyUnplug
|
||||
}
|
||||
$recoveryPending = $false
|
||||
if (-not $Recover) {
|
||||
$bytes = Read-DriverBytes $DriverDir
|
||||
$device = Get-SelectedDevice
|
||||
Send-Status $pipe 'selected' @{ instance_id = $device.Id; hub_instance = $device.Hub; hub_port = $device.Port }
|
||||
if ((Wait-Signal $pipe $owner 'B') -eq 'B') {
|
||||
Assert-SameDevice $device (Get-SelectedDevice)
|
||||
$before = Get-DeviceArrival $device
|
||||
if ($before -eq 0) { Refuse 'The selected iPad disconnected before filter preparation.' }
|
||||
$baselineStack = @(Get-EffectiveStack $device)
|
||||
if ($baselineStack -notcontains '\Driver\usbccgp' -or $baselineStack -contains '\Driver\libusb0') {
|
||||
Refuse 'The iPad does not have its expected Windows device stack.'
|
||||
}
|
||||
$prepared = New-Journal $device
|
||||
Save-Journal $prepared
|
||||
$journal = $prepared
|
||||
Install-Filter $journal $bytes
|
||||
$journal.Stage = 'device'
|
||||
Save-Journal $journal
|
||||
Set-ProbeFilter $journal
|
||||
Send-Status $pipe 'replug' @{ timeout_seconds = $script:replugTimeoutSeconds }
|
||||
if (Wait-ForReplug $pipe $owner $journal $before) {
|
||||
Send-Status $pipe 'probe'
|
||||
if ((Wait-Signal $pipe $owner 'P') -eq 'P') {
|
||||
Assert-SameDevice $journal (Get-SelectedDevice)
|
||||
$arrival = Get-DeviceArrival $journal
|
||||
Send-Status $pipe 'switch' @{ timeout_seconds = $script:activeTimeoutSeconds }
|
||||
$null = Wait-Signal $pipe $owner 'R' $journal.Id $arrival
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
$result = 1
|
||||
$message = Get-PublicMessage $_
|
||||
if ($trustedPeer) { try { Send-Status $pipe 'error' @{ message = $message } } catch {} }
|
||||
else { [Console]::Error.WriteLine($message) }
|
||||
} finally {
|
||||
try {
|
||||
if ($journal) { Restore-Transaction $journal $notifyUnplug }
|
||||
if ($trustedPeer -and -not $recoveryPending) { try { Send-Status $pipe 'restored' } catch {} }
|
||||
} catch {
|
||||
$result = 1
|
||||
$message = 'iPad recovery is pending. Reconnect the same iPad and run -Recover. ' + (Get-PublicMessage $_)
|
||||
if ($trustedPeer) { try { Send-Status $pipe 'error' @{ message = $message } } catch {} }
|
||||
else { [Console]::Error.WriteLine($message) }
|
||||
} finally {
|
||||
if ($locked) { $mutex.ReleaseMutex() }
|
||||
if ($mutex) { $mutex.Dispose() }
|
||||
if ($pipe) { $pipe.Dispose() }
|
||||
if ($owner) { $owner.Dispose() }
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
if ($MyInvocation.InvocationName -ne '.') {
|
||||
try { exit (Invoke-DriverSession) }
|
||||
catch { [Console]::Error.WriteLine((Get-PublicMessage $_)); exit 1 }
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Request normal Windows elevation for the driver worker and supervise its pipe."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
import ctypes as ct
|
||||
from ctypes import wintypes as wt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
def peer_is_qemu(peer, expected_pid):
|
||||
"""Match the reverse (client) half of the accepted loopback connection."""
|
||||
table = ct.WinDLL("iphlpapi").GetExtendedTcpTable
|
||||
table.argtypes = (ct.c_void_p, ct.POINTER(wt.DWORD), wt.BOOL, wt.ULONG, wt.DWORD, wt.ULONG)
|
||||
size = wt.DWORD()
|
||||
data = None
|
||||
for _ in range(4):
|
||||
status = table(data, ct.byref(size), False, socket.AF_INET, 4, 0)
|
||||
if status == 0 and data is not None:
|
||||
break
|
||||
if status != 122:
|
||||
raise OSError(f"could not inspect the QEMU TCP connection ({status})")
|
||||
data = ct.create_string_buffer(size.value)
|
||||
else:
|
||||
raise OSError("Windows TCP table kept changing")
|
||||
client_ip, client_port = peer.getpeername()
|
||||
server_ip, server_port = peer.getsockname()
|
||||
rows = struct.unpack_from("<I", data)[0]
|
||||
for state, local, sport, remote, dport, owner in struct.iter_unpack("<I4sI4sII", data.raw[4:4 + rows * 24]):
|
||||
if (owner == expected_pid and state == 5 and local == socket.inet_aton(client_ip)
|
||||
and remote == socket.inet_aton(server_ip) and socket.ntohs(sport & 0xffff) == client_port
|
||||
and socket.ntohs(dport & 0xffff) == server_port):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class ShellExecuteInfo(ct.Structure):
|
||||
_fields_ = [
|
||||
("cbSize", wt.DWORD), ("fMask", wt.ULONG), ("hwnd", wt.HWND), ("lpVerb", wt.LPCWSTR),
|
||||
("lpFile", wt.LPCWSTR), ("lpParameters", wt.LPCWSTR), ("lpDirectory", wt.LPCWSTR),
|
||||
("nShow", ct.c_int), ("hInstApp", wt.HINSTANCE), ("lpIDList", ct.c_void_p),
|
||||
("lpClass", wt.LPCWSTR), ("hkeyClass", wt.HKEY), ("dwHotKey", wt.DWORD),
|
||||
("hIcon", wt.HANDLE), ("hProcess", wt.HANDLE),
|
||||
]
|
||||
|
||||
|
||||
class Driver:
|
||||
def __init__(self, directory):
|
||||
self.api = ct.WinDLL("kernel32", use_last_error=True)
|
||||
self.api.GetProcessId.argtypes = (wt.HANDLE,)
|
||||
self.api.GetProcessId.restype = wt.DWORD
|
||||
self.api.GetNamedPipeServerProcessId.argtypes = (wt.HANDLE, ct.POINTER(wt.ULONG))
|
||||
self.api.PeekNamedPipe.argtypes = (wt.HANDLE, ct.c_void_p, wt.DWORD, ct.c_void_p,
|
||||
ct.POINTER(wt.DWORD), ct.c_void_p)
|
||||
self.api.GetExitCodeProcess.argtypes = (wt.HANDLE, ct.POINTER(wt.DWORD))
|
||||
self.api.WaitForSingleObject.argtypes = (wt.HANDLE, wt.DWORD)
|
||||
self.api.WaitForSingleObject.restype = wt.DWORD
|
||||
self.api.CloseHandle.argtypes = (wt.HANDLE,)
|
||||
self.api.CreateFileW.argtypes = (wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.c_void_p, wt.DWORD,
|
||||
wt.DWORD, wt.HANDLE)
|
||||
self.api.CreateFileW.restype = wt.HANDLE
|
||||
shell = ct.WinDLL("shell32", use_last_error=True)
|
||||
shell.ShellExecuteExW.argtypes = (ct.POINTER(ShellExecuteInfo),)
|
||||
if shell.IsUserAnAdmin():
|
||||
raise PermissionError("start reims-ctl from an unelevated terminal")
|
||||
token = secrets.token_hex(16)
|
||||
self.name = r"\\.\pipe\reims-ipad-" + token
|
||||
self.stream = None
|
||||
self.buffer = bytearray()
|
||||
pwsh = shutil.which("pwsh.exe")
|
||||
if not pwsh:
|
||||
raise FileNotFoundError("PowerShell 7 (pwsh.exe) is required")
|
||||
args = ["-NoProfile", "-NonInteractive", "-File", str(Path(__file__).with_name("driver-session.ps1")),
|
||||
"-DriverDir", str(directory), "-OwnerPid", str(os.getpid()), "-Token", token]
|
||||
# The OS displays the UAC consent dialog. Only the driver supervisor is elevated.
|
||||
sei = ShellExecuteInfo(cbSize=ct.sizeof(ShellExecuteInfo), fMask=0x40 | 0x100,
|
||||
lpVerb="runas", lpFile=pwsh, lpParameters=subprocess.list2cmdline(args), nShow=0)
|
||||
if not shell.ShellExecuteExW(ct.byref(sei)):
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
self.process = sei.hProcess
|
||||
|
||||
def exited(self):
|
||||
return self.api.WaitForSingleObject(self.process, 0) == 0
|
||||
|
||||
def connect(self):
|
||||
import msvcrt
|
||||
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
# SECURITY_IDENTIFICATION prevents another pipe server from impersonating this client.
|
||||
handle = self.api.CreateFileW(self.name, 0xc0000000, 0, None, 3, 0x110000, None)
|
||||
if handle != ct.c_void_p(-1).value:
|
||||
pid = wt.ULONG()
|
||||
if (not self.api.GetNamedPipeServerProcessId(handle, ct.byref(pid))
|
||||
or pid.value != self.api.GetProcessId(self.process)):
|
||||
self.api.CloseHandle(handle)
|
||||
raise OSError("the driver pipe belongs to another process")
|
||||
self.stream = os.fdopen(msvcrt.open_osfhandle(handle, os.O_RDWR | os.O_BINARY), "r+b", buffering=0)
|
||||
self.handle = handle
|
||||
return
|
||||
if ct.get_last_error() not in (2, 231) or self.exited():
|
||||
raise OSError("the driver worker exited before connecting")
|
||||
time.sleep(0.1)
|
||||
raise TimeoutError("timed out waiting for the driver worker")
|
||||
|
||||
def message(self, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
end = self.buffer.find(b"\n")
|
||||
if end >= 0:
|
||||
line = self.buffer[:end]
|
||||
del self.buffer[:end + 1]
|
||||
msg = json.loads(line.decode("utf-8-sig"))
|
||||
if not isinstance(msg, dict) or not isinstance(msg.get("state"), str):
|
||||
raise ValueError("unexpected driver response")
|
||||
return msg
|
||||
if len(self.buffer) > 8192:
|
||||
raise ValueError("driver response is too long")
|
||||
available = wt.DWORD()
|
||||
if not self.api.PeekNamedPipe(self.handle, None, 0, None, ct.byref(available), None):
|
||||
raise OSError("the driver worker closed its connection")
|
||||
if available.value:
|
||||
self.buffer.extend(self.stream.read(min(available.value, 8192)))
|
||||
elif self.exited():
|
||||
raise OSError("the driver worker exited before reporting its state")
|
||||
else:
|
||||
time.sleep(0.05)
|
||||
raise TimeoutError("the driver worker did not respond")
|
||||
|
||||
def expect(self, state, timeout=90):
|
||||
message = self.message(timeout)
|
||||
if message["state"] != state:
|
||||
raise OSError(message.get("message") or "unexpected driver state: " + message["state"])
|
||||
return message
|
||||
|
||||
def release(self):
|
||||
# If a busy stage has just finished, drain that status as well.
|
||||
error = None
|
||||
if self.stream:
|
||||
try:
|
||||
try:
|
||||
self.stream.write(b"R")
|
||||
except BrokenPipeError:
|
||||
pass # An unplug can complete restoration before we request it.
|
||||
while True:
|
||||
msg = self.message(105)
|
||||
if msg["state"] == "unplug":
|
||||
print("Unplug the iPad and leave it disconnected until Windows restoration finishes.", flush=True)
|
||||
if msg["state"] == "restored":
|
||||
break
|
||||
if msg["state"] == "error":
|
||||
error = msg.get("message", "driver worker failed")
|
||||
except OSError as exc:
|
||||
error = error or str(exc)
|
||||
finally:
|
||||
self.stream.close()
|
||||
if self.api.WaitForSingleObject(self.process, 110000) != 0:
|
||||
raise TimeoutError("the elevated driver worker is still restoring the iPad")
|
||||
status = wt.DWORD()
|
||||
if not self.api.GetExitCodeProcess(self.process, ct.byref(status)):
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
if error or status.value:
|
||||
raise OSError(error or f"driver worker failed with exit code {status.value}")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def driver_session(directory):
|
||||
driver = Driver(directory)
|
||||
try:
|
||||
driver.connect()
|
||||
yield driver
|
||||
finally:
|
||||
try:
|
||||
driver.release()
|
||||
finally:
|
||||
driver.api.CloseHandle(driver.process)
|
||||
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 2 {
|
||||
os.Exit(2)
|
||||
}
|
||||
conn, err := net.DialTimeout("unix", os.Args[1], 6*time.Second)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(25 * time.Second))
|
||||
go func() {
|
||||
_, _ = io.Copy(conn, os.Stdin)
|
||||
_ = conn.Close()
|
||||
}()
|
||||
_, _ = io.Copy(os.Stdout, conn)
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
#requires -Version 7.0
|
||||
# Run in an unelevated PowerShell 7. All device and service operations use in-memory fixtures.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$principal = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run these fixtures unelevated.' }
|
||||
$source = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '../driver-session.ps1')).Path
|
||||
$tokens = $null
|
||||
$errors = $null
|
||||
$null = [Management.Automation.Language.Parser]::ParseFile($source, [ref]$tokens, [ref]$errors)
|
||||
if ($errors.Count) { throw $errors[0].Message }
|
||||
. $source -Recover
|
||||
|
||||
function Assert($Condition, [string]$Message) { if (-not $Condition) { throw $Message } }
|
||||
function Expect-Failure([scriptblock]$Action, [string]$Pattern) {
|
||||
$message = $null
|
||||
try { & $Action } catch { $message = $_.Exception.Message }
|
||||
Assert ($message -like $Pattern) "Expected failure '$Pattern', got '$message'"
|
||||
}
|
||||
|
||||
$originals = [ordered]@{
|
||||
UpperFilters = @{ Kind = 'MultiString'; Value = @('existing-upper') }
|
||||
LowerFilters = @{ Kind = 'MultiString'; Value = @('first', 'AppleLowerFilter', 'last') }
|
||||
OriginalConfigurationValue = @{ Kind = 'ExpandString'; Value = '%example%' }
|
||||
AltConfigurationValue = @{ Kind = 'Absent'; Value = $null }
|
||||
EnumeratorClass = @{ Kind = 'Binary'; Value = @(12, 0, 255) }
|
||||
}
|
||||
$journal = @{
|
||||
Version = 1; Cookie = ('a' * 32); Stage = 'device'
|
||||
Id = 'USB\VID_05AC&PID_12AB\FIXTURE'; Driver = '{88bae032-5a81-49f0-bc3d-a4ff138216d6}\0001'
|
||||
Hub = 'USB\ROOT_HUB30\FIXTURE'; Port = 4
|
||||
Original = [ordered]@{ UpperFilters = $originals.UpperFilters }
|
||||
}
|
||||
function Copy-Object($Value) { [Management.Automation.PSSerializer]::Deserialize([Management.Automation.PSSerializer]::Serialize($Value, 8)) }
|
||||
|
||||
class FixtureRegistryKey {
|
||||
[hashtable]$Values = @{}
|
||||
[hashtable]$Kinds = @{}
|
||||
[int]$Flushes = 0
|
||||
|
||||
[string[]] GetValueNames() { return @($this.Values.Keys) }
|
||||
[object] GetValueKind([string]$Name) { return $this.Kinds[$Name] }
|
||||
[object] GetValue([string]$Name) { return $this.Values[$Name] }
|
||||
[object] GetValue([string]$Name, [object]$Default, [object]$Options) {
|
||||
if (-not $this.Values.ContainsKey($Name)) { return $Default }
|
||||
return $this.Values[$Name]
|
||||
}
|
||||
[void] SetValue([string]$Name, [object]$Value, [object]$Kind) {
|
||||
$this.Values[$Name] = $Value
|
||||
$this.Kinds[$Name] = $Kind
|
||||
}
|
||||
[void] DeleteValue([string]$Name, [bool]$ThrowIfMissing) {
|
||||
$this.Values.Remove($Name)
|
||||
$this.Kinds.Remove($Name)
|
||||
}
|
||||
[void] Flush() { $this.Flushes++ }
|
||||
[void] Dispose() {}
|
||||
}
|
||||
|
||||
# Round-trip the journal with an in-memory registry double.
|
||||
function Test-RegistryRoundTrip {
|
||||
$journalKey = [FixtureRegistryKey]::new()
|
||||
function Open-JournalKey([switch]$Create) { return $journalKey }
|
||||
foreach ($sample in @($originals.UpperFilters, @{ Kind = 'Absent'; Value = $null })) {
|
||||
Write-KeyValue $journalKey 'Sample' $sample
|
||||
Assert (Test-SameValue $sample (Read-KeyValue $journalKey 'Sample')) "registry round-trip $($sample.Kind)"
|
||||
$snapshot = Copy-Object $journal
|
||||
$snapshot.Original.UpperFilters = $sample
|
||||
Save-Journal $snapshot
|
||||
Assert (Test-SameValue (Read-Journal).Original.UpperFilters $sample) "journal round-trip $($sample.Kind)"
|
||||
}
|
||||
Clear-Journal
|
||||
Assert ($null -eq (Read-Journal) -and $journalKey.Flushes -eq 3) 'journal clearance or missing flush'
|
||||
}
|
||||
Test-RegistryRoundTrip
|
||||
|
||||
$legacyKey = [FixtureRegistryKey]::new()
|
||||
$probeKey = [FixtureRegistryKey]::new()
|
||||
$registry = [pscustomobject]@{ LegacyKey = $legacyKey; ProbeKey = $probeKey }
|
||||
$registry | Add-Member -MemberType ScriptMethod -Name OpenSubKey -Value {
|
||||
param($Path)
|
||||
switch -CaseSensitive ($Path) {
|
||||
'SOFTWARE\Reims.WindowsIpad' { return $this.LegacyKey }
|
||||
'SOFTWARE\Reims.WindowsIpadAirM3Lab' { return $this.ProbeKey }
|
||||
default { throw 'Unexpected registry path.' }
|
||||
}
|
||||
}
|
||||
Assert-NoOriginalRecovery $registry
|
||||
foreach ($key in @($legacyKey, $probeKey)) {
|
||||
$key.SetValue('Session', 'pending', 'String')
|
||||
Expect-Failure { Assert-NoOriginalRecovery $registry } '*Another Reims iPad driver session is pending recovery*'
|
||||
Assert ($key.Values.Session -ceq 'pending') 'foreign journal was touched'
|
||||
$key.DeleteValue('Session', $false)
|
||||
}
|
||||
Assert ($script:hardwareId -ceq 'USB\VID_05AC&PID_12AB&REV_1503') 'model guard changed'
|
||||
Assert ($script:journalName -ceq 'SOFTWARE\Reims.WindowsIpadAirM3AttachLab') 'M3 attach journal must stay separate'
|
||||
Expect-Failure { Write-DeviceValue $journal 'LowerFilters' $originals.LowerFilters } '*only the selected iPad upper filters*'
|
||||
|
||||
# Exercise the real logon ACL, PID check and protocol without launching an elevated process.
|
||||
function Test-PrivatePipe {
|
||||
Initialize-Native
|
||||
$owner = [Diagnostics.Process]::GetCurrentProcess()
|
||||
$token = [guid]::NewGuid().ToString('N')
|
||||
$server = Open-SessionPipe $owner $token
|
||||
$client = [IO.Pipes.NamedPipeClientStream]::new('.', "reims-ipad-$token", 'InOut', 'Asynchronous')
|
||||
try {
|
||||
$pending = $server.WaitForConnectionAsync()
|
||||
$client.Connect(2000)
|
||||
Assert ($pending.Wait(2000) -and [ReimsIpad]::IsClient($server, $PID) -and -not [ReimsIpad]::IsClient($server, 0)) 'pipe client PID'
|
||||
$reader = [IO.StreamReader]::new($client)
|
||||
Send-Status $server 'selected' @{ hub_port = 4 }
|
||||
$message = ConvertFrom-Json $reader.ReadLine()
|
||||
Assert ($message.state -ceq 'selected' -and $message.hub_port -eq 4) 'pipe status'
|
||||
$client.WriteByte([byte][char]'B')
|
||||
Assert ((Wait-Signal $server $owner 'B') -ceq 'B') 'begin signal'
|
||||
$client.WriteByte([byte][char]'X')
|
||||
Expect-Failure { Wait-Signal $server $owner 'P' } '*Unexpected USB helper request*'
|
||||
$client.WriteByte([byte][char]'R')
|
||||
Assert ((Wait-Signal $server $owner 'P') -ceq 'R') 'early release'
|
||||
Assert ((Wait-Signal $server @{ HasExited = $true } 'P') -ceq 'R') 'parent exit while waiting'
|
||||
} finally { $client.Dispose(); $server.Dispose(); $owner.Dispose() }
|
||||
}
|
||||
Test-PrivatePipe
|
||||
|
||||
function Test-ManualReplug {
|
||||
$owner = [Diagnostics.Process]::GetCurrentProcess()
|
||||
$token = [guid]::NewGuid().ToString('N')
|
||||
$server = Open-SessionPipe $owner $token
|
||||
$client = [IO.Pipes.NamedPipeClientStream]::new('.', "reims-ipad-$token", 'InOut', 'Asynchronous')
|
||||
$arrivals = [Collections.Generic.Queue[long]]::new()
|
||||
$current = Copy-Object $journal
|
||||
$stack = [Collections.Generic.List[string]]::new()
|
||||
$stack.Add('\Driver\usbccgp')
|
||||
$stack.Add('\Driver\libusb0')
|
||||
function Get-DeviceArrival($Journal) { $arrivals.Dequeue() }
|
||||
function Test-DeviceStarted($Journal) { return $true }
|
||||
function Get-SelectedDevice { return $current }
|
||||
function Get-EffectiveStack($Journal) { return $stack }
|
||||
function Assert-FilterStack($Journal, $Expected) {}
|
||||
try {
|
||||
$pending = $server.WaitForConnectionAsync()
|
||||
$client.Connect(2000)
|
||||
Assert ($pending.Wait(2000)) 'replug fixture pipe connection'
|
||||
$client.WriteByte([byte][char]'R')
|
||||
Assert (-not (Wait-ForReplug $server $owner $journal 100)) 'replug ignored cancellation'
|
||||
Expect-Failure { Wait-ForReplug $server $owner $journal 100 -TimeoutSeconds 0 } '*Timed out waiting for the iPad*'
|
||||
foreach ($arrival in @(100, 0, 101)) { $arrivals.Enqueue($arrival) }
|
||||
Assert (Wait-ForReplug $server $owner $journal 100) 'valid replug did not activate'
|
||||
$client.WriteByte([byte][char]'P')
|
||||
Assert ((Wait-Signal $server $owner 'P') -ceq 'P') 'replug reader consumed next-phase signal'
|
||||
$current.Port = 9
|
||||
foreach ($arrival in @(0, 102)) { $arrivals.Enqueue($arrival) }
|
||||
Expect-Failure { Wait-ForReplug $server $owner $journal 101 } '*original USB port*'
|
||||
$current.Port = $journal.Port
|
||||
$stack.RemoveAt(1)
|
||||
foreach ($arrival in @(0, 103)) { $arrivals.Enqueue($arrival) }
|
||||
Expect-Failure { Wait-ForReplug $server $owner $journal 102 } '*did not attach the temporary filter*'
|
||||
} finally { $client.Dispose(); $server.Dispose(); $owner.Dispose() }
|
||||
}
|
||||
Test-ManualReplug
|
||||
|
||||
# An unanswered active wait returns even while a device might remain present.
|
||||
$owner = [Diagnostics.Process]::GetCurrentProcess()
|
||||
$token = [guid]::NewGuid().ToString('N')
|
||||
$server = Open-SessionPipe $owner $token
|
||||
$client = [IO.Pipes.NamedPipeClientStream]::new('.', "reims-ipad-$token", 'InOut', 'Asynchronous')
|
||||
try {
|
||||
$pending = $server.WaitForConnectionAsync()
|
||||
$client.Connect(2000)
|
||||
Assert ($pending.Wait(2000)) 'timeout fixture pipe connection'
|
||||
Assert ((Wait-Signal $server $owner 'R' -DeviceId 'fixture-only' -ActiveTimeoutSeconds 0) -ceq 'R') 'active timeout'
|
||||
} finally { $client.Dispose(); $server.Dispose(); $owner.Dispose() }
|
||||
|
||||
$directory = [IO.Directory]::CreateDirectory([IO.Path]::Combine([IO.Path]::GetTempPath(), 'reims-ipad-test-' + [guid]::NewGuid().ToString('N')))
|
||||
$file = [IO.Path]::Combine($directory.FullName, 'libusb0.sys')
|
||||
try {
|
||||
[IO.File]::WriteAllBytes($file, [byte[]]::new(99224))
|
||||
Expect-Failure { Read-DriverBytes $directory.FullName } '*differs from the released*'
|
||||
} finally { [IO.File]::Delete($file); $directory.Delete() }
|
||||
function Reset-Fixture {
|
||||
$script:values = Copy-Object $originals
|
||||
$script:journal = Copy-Object $journal
|
||||
$script:journal.Stage = 'device'
|
||||
$script:present = $true
|
||||
$script:stack = @('\Driver\usbccgp', '\Driver\AppleLowerFilter')
|
||||
$script:unplugs = 0
|
||||
$script:hardwareWrites = 0
|
||||
$script:removed = $false
|
||||
$script:saved = $null
|
||||
}
|
||||
function Assert-DeviceIdentity($Journal) {}
|
||||
function Assert-ExclusiveUse($Journal) {}
|
||||
function Read-DeviceValue($Journal, $Name) { $script:values[$Name] }
|
||||
function Write-DeviceValue($Journal, $Name, $Value) {
|
||||
$script:hardwareWrites++
|
||||
$script:values[$Name] = Copy-Object $Value
|
||||
}
|
||||
function Test-DevicePresent($Journal) { return $script:present }
|
||||
function Get-EffectiveStack($Journal) { return $script:stack }
|
||||
function Assert-FilterStack($Journal, $Expected, [switch]$AllowAbsent) {}
|
||||
function Save-Journal($Journal) { $script:saved = Copy-Object $Journal }
|
||||
function Clear-Journal { $script:saved = $null }
|
||||
|
||||
# Exercise real ownership checks with fake SCM/registry and filesystem endpoints.
|
||||
$realRemove = ${function:Remove-OwnedDriver}
|
||||
function Remove-OwnedDriver($Journal) { $script:removed = $true }
|
||||
|
||||
Reset-Fixture
|
||||
Set-ProbeFilter $journal
|
||||
Assert (($values.UpperFilters.Value -join ',') -ceq 'existing-upper,libusb0') 'upper filter was not appended'
|
||||
foreach ($name in $originals.Keys | Where-Object { $_ -ne 'UpperFilters' }) {
|
||||
Assert (Test-SameValue $values[$name] $originals[$name]) "changed untouched value $name"
|
||||
}
|
||||
Assert ($hardwareWrites -eq 1) 'probe wrote more than the upper filter'
|
||||
$script:present = $false
|
||||
Restore-Transaction $journal
|
||||
foreach ($name in $originals.Keys) { Assert (Test-SameValue $values[$name] $originals[$name]) "restore $name" }
|
||||
Assert ($unplugs -eq 0 -and $removed -and $null -eq $saved) 'unplugged rollback did not finish'
|
||||
|
||||
# The journal precedes file/service creation and every device mutation. Replay from each cut point.
|
||||
foreach ($count in 0..1) {
|
||||
Reset-Fixture
|
||||
$plan = Get-SettingsPlan $journal
|
||||
foreach ($name in @($plan.Keys | Select-Object -First $count)) { $values[$name] = $plan[$name] }
|
||||
Restore-Transaction (Copy-Object $journal)
|
||||
foreach ($name in $originals.Keys) { Assert (Test-SameValue $values[$name] $originals[$name]) "crash after $count/$name" }
|
||||
Assert ($removed -and $null -eq $saved) "crash after $count kept resources"
|
||||
}
|
||||
Reset-Fixture
|
||||
$journal.Stage = 'prepared'
|
||||
Restore-Transaction $journal
|
||||
Assert ($unplugs -eq 0 -and $hardwareWrites -eq 0 -and $removed) 'preparation touched the device'
|
||||
Reset-Fixture
|
||||
Set-ProbeFilter $journal
|
||||
$values.UpperFilters = @{ Kind = 'MultiString'; Value = @('external-filter') }
|
||||
Expect-Failure { Restore-Transaction $journal } '*changed outside*'
|
||||
Assert ($values.UpperFilters.Value[0] -eq 'external-filter' -and -not $removed) 'changed a foreign filter'
|
||||
|
||||
Reset-Fixture
|
||||
Set-ProbeFilter $journal
|
||||
$values.LowerFilters = @{ Kind = 'MultiString'; Value = @('external-lower-filter') }
|
||||
$script:stack += '\Driver\libusb0'
|
||||
Save-Journal $journal
|
||||
$defaultTimeout = $script:unplugTimeoutSeconds
|
||||
try {
|
||||
$script:unplugTimeoutSeconds = 0
|
||||
Expect-Failure { Restore-Transaction $journal { $script:unplugs++ } } '*Timed out waiting for the iPad to be unplugged*'
|
||||
} finally { $script:unplugTimeoutSeconds = $defaultTimeout }
|
||||
Assert ((Test-SameValue $values.UpperFilters $originals.UpperFilters) -and $unplugs -eq 1) 'unplug must be requested after restoring the registry'
|
||||
Assert (-not $removed -and $saved.Stage -ceq 'device') 'timed out cleanup discarded its recovery state'
|
||||
Restore-Transaction $journal {
|
||||
Assert (Test-SameValue $values.UpperFilters $originals.UpperFilters) 'registry not restored before unplug'
|
||||
Assert (-not $removed) 'removed a still-attached driver'
|
||||
$script:unplugs++
|
||||
$script:present = $false
|
||||
}
|
||||
Assert ($removed -and $unplugs -eq 2 -and $null -eq $saved) 'timed-out cleanup could not be retried'
|
||||
Assert ($values.LowerFilters.Value[0] -ceq 'external-lower-filter') 'rollback changed an untouched filter'
|
||||
|
||||
Reset-Fixture
|
||||
$script:stack = @()
|
||||
Wait-ForFilterRelease $journal { $script:unplugs++; $script:present = $false }
|
||||
Assert ($unplugs -eq 1) 'unknown live stack treated as proof of detachment'
|
||||
|
||||
Set-Item Function:Remove-OwnedDriver $realRemove
|
||||
$script:service = @{ Type = 1; Start = 3; ImagePath = 'System32\drivers\foreign.sys' }
|
||||
$script:foreignUse = $false
|
||||
$script:stopped = $false
|
||||
$script:deleted = $false
|
||||
function Read-FilterService { $script:service }
|
||||
function Assert-ExclusiveUse($Journal) { if ($script:foreignUse) { throw 'fixture shared filter' } }
|
||||
function Remove-FilterService { $script:stopped = $true; $script:service = $null }
|
||||
function Remove-SessionImage($Journal) { $script:deleted = $true }
|
||||
Expect-Failure { Remove-OwnedDriver $journal } '*another installation*'
|
||||
Assert (-not $stopped -and -not $deleted) 'touched a foreign service'
|
||||
$service.ImagePath = Get-ImagePath $journal
|
||||
$script:foreignUse = $true
|
||||
Expect-Failure { Remove-OwnedDriver $journal } '*shared filter*'
|
||||
Assert (-not $stopped -and -not $deleted) 'removed a shared service'
|
||||
$script:foreignUse = $false
|
||||
Remove-OwnedDriver $journal
|
||||
Remove-OwnedDriver $journal
|
||||
Assert ($stopped -and $deleted) 'could not replay owned removal'
|
||||
|
||||
Write-Output 'Windows iPad Air M3 manual-replug transaction fixtures passed.'
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Exercise the Air M3 frontend against QEMU with a synthetic USB device."""
|
||||
import argparse
|
||||
from contextlib import suppress
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from tempfile import TemporaryDirectory
|
||||
from threading import Event, Thread
|
||||
from time import monotonic, sleep
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from attach import bridge, main
|
||||
|
||||
|
||||
class Fixture:
|
||||
descriptor = bytes.fromhex("12 01 00 02 00 00 00 40 34 12 78 56 00 01 00 00 00 01")
|
||||
configuration = bytes.fromhex("09 02 12 00 01 01 00 80 32 09 04 00 00 00 ff 00 00 00")
|
||||
speed = 2
|
||||
|
||||
def __init__(self):
|
||||
self.config = 0
|
||||
self.alternates = {}
|
||||
self.announced = Event()
|
||||
self.descriptor_read = False
|
||||
|
||||
def layout(self):
|
||||
self.announced.set()
|
||||
return [(0, 0xff, 0, 0)], []
|
||||
|
||||
def control(self, setup, outgoing):
|
||||
request_type, request, value, _, length = setup
|
||||
if (request_type, request, value) == (0x80, 6, 0x0100):
|
||||
self.descriptor_read = True
|
||||
return self.descriptor[:length]
|
||||
if (request_type, request, value) == (0x80, 6, 0x0200):
|
||||
return self.configuration[:length]
|
||||
if (request_type, request) == (0, 9) and value in (0, 1):
|
||||
self.config = value
|
||||
return len(outgoing)
|
||||
raise OSError("synthetic device stalls this USB request")
|
||||
|
||||
|
||||
def check(qemu, firmware, relay, env, accelerator):
|
||||
listing = subprocess.run([str(qemu), "-device", "help"], env=env, text=True,
|
||||
capture_output=True, timeout=10, check=True)
|
||||
for model in ("usb-redir", "reims-graphics-pci"):
|
||||
if not re.search(r'^name "' + re.escape(model) + '"', listing.stdout, re.MULTILINE):
|
||||
raise RuntimeError(f"QEMU does not list {model}")
|
||||
print("QEMU lists usb-redir and reims-graphics-pci.", flush=True)
|
||||
|
||||
with TemporaryDirectory(prefix="reims-usb-") as directory:
|
||||
root = Path(directory)
|
||||
socket_path = root / "qmp.sock"
|
||||
command = [
|
||||
str(qemu), "-L", str(firmware), "-machine", f"q35,accel={accelerator}",
|
||||
"-m", "128", "-nodefaults", "-no-user-config", "-display", "none", "-serial", "none",
|
||||
"-monitor", "none", "-qmp", f"unix:{socket_path},server=on,wait=off",
|
||||
"-S", "-device", "qemu-xhci,id=xhci",
|
||||
]
|
||||
with subprocess.Popen(command, env=env, stdout=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW) as process:
|
||||
try:
|
||||
(root / "qemu.pid").write_text(str(process.pid))
|
||||
deadline = monotonic() + 10
|
||||
while not socket_path.exists():
|
||||
if process.poll() is not None or monotonic() >= deadline:
|
||||
raise RuntimeError("The synthetic guest did not open its QMP socket")
|
||||
sleep(0.1)
|
||||
selected = []
|
||||
|
||||
def accept_guest(guest, _directory):
|
||||
selected.append(guest)
|
||||
return True
|
||||
|
||||
with patch("attach.run", side_effect=accept_guest):
|
||||
if main(["--vm-dir", str(root), "--driver-dir", str(root), "--relay", str(relay)]) != 0:
|
||||
raise RuntimeError("The helper could not open the running guest's QMP path")
|
||||
guest = selected[0]
|
||||
with guest.monitor() as qmp:
|
||||
qmp.call("cont")
|
||||
|
||||
fixture = Fixture()
|
||||
busy_probe = Event()
|
||||
proven = Event()
|
||||
|
||||
def verify_qmp_is_available():
|
||||
if fixture.announced.wait(8):
|
||||
sleep(0.7)
|
||||
with suppress(OSError, RuntimeError), guest.monitor() as qmp:
|
||||
if qmp.call("query-status")["running"]:
|
||||
proven.set()
|
||||
busy_probe.set()
|
||||
|
||||
reader = Thread(target=verify_qmp_is_available, daemon=True)
|
||||
reader.start()
|
||||
deadline = monotonic() + 14
|
||||
bridge(guest, fixture, lambda: not busy_probe.is_set() and monotonic() < deadline)
|
||||
if not (fixture.announced.is_set() and proven.is_set()):
|
||||
raise RuntimeError("The forwarder did not negotiate or the guest monitor stayed busy")
|
||||
with guest.monitor() as qmp:
|
||||
if any(item["name"].startswith("ipad-") for item in qmp.call("qom-list", path="/machine/peripheral")):
|
||||
raise RuntimeError("The USB device was not removed")
|
||||
if any(item["label"].startswith("ipad-char-") for item in qmp.call("query-chardev")):
|
||||
raise RuntimeError("The USB chardev was not removed")
|
||||
qmp.call("quit")
|
||||
if process.wait(timeout=6) != 0:
|
||||
raise RuntimeError("The test guest did not exit normally")
|
||||
print("Synthetic USB handshake, concurrent monitor access, and session cleanup passed.")
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=6)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--qemu", type=Path, required=True)
|
||||
parser.add_argument("--firmware-dir", type=Path, required=True)
|
||||
parser.add_argument("--relay", type=Path, required=True)
|
||||
parser.add_argument("--accel", choices=("whpx", "tcg"), default="whpx")
|
||||
args = parser.parse_args()
|
||||
environment = dict(os.environ, PATH="")
|
||||
check(args.qemu.resolve(strict=True), args.firmware_dir.resolve(strict=True),
|
||||
args.relay.resolve(strict=True), environment, args.accel)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Check how short physical USB sessions report the enumeration result."""
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from attach import bridge
|
||||
|
||||
|
||||
class ImmediateExporter:
|
||||
def __init__(self, target):
|
||||
self.target = target
|
||||
|
||||
def start(self):
|
||||
self.target()
|
||||
|
||||
def is_alive(self):
|
||||
return False
|
||||
|
||||
def join(self):
|
||||
pass
|
||||
|
||||
|
||||
class ShortSessionTest(unittest.TestCase):
|
||||
def bridge_with_short_session(self, read_descriptor):
|
||||
device = SimpleNamespace(descriptor_read=False)
|
||||
guest = SimpleNamespace(monitor=lambda: nullcontext(Mock()))
|
||||
|
||||
def export_then_disconnect(_listener, _guest, device, _done, _present):
|
||||
device.descriptor_read = read_descriptor
|
||||
|
||||
with patch("attach.Thread", ImmediateExporter), \
|
||||
patch("attach.export_device", side_effect=export_then_disconnect), \
|
||||
patch("attach.remove_guest_device") as cleanup:
|
||||
try:
|
||||
return bridge(guest, device, lambda: True)
|
||||
finally:
|
||||
cleanup.assert_called_once()
|
||||
|
||||
def test_read_before_mode_change_remains_successful(self):
|
||||
self.assertTrue(self.bridge_with_short_session(read_descriptor=True))
|
||||
|
||||
def test_no_read_or_attachment_reports_timeout(self):
|
||||
with self.assertRaises(TimeoutError):
|
||||
self.bridge_with_short_session(read_descriptor=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Exercise the same wire protocol as QEMU's usb-redir device."""
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
HEADER = struct.Struct("<IIQ")
|
||||
HELLO = struct.pack("<III64sI", 0, 68, 0, b"QEMU test", 0x72)
|
||||
CTRL = struct.Struct("<BBBBHHH")
|
||||
BULK = struct.Struct("<BBHIH")
|
||||
|
||||
|
||||
def exact(peer, length):
|
||||
buf = bytearray()
|
||||
while len(buf) < length:
|
||||
chunk = peer.recv(length - len(buf))
|
||||
if not chunk:
|
||||
raise EOFError
|
||||
buf.extend(chunk)
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
def packet(peer):
|
||||
op, length, seq = HEADER.unpack(exact(peer, 16))
|
||||
return op, seq, exact(peer, length)
|
||||
|
||||
|
||||
class Tablet:
|
||||
descriptor = bytes.fromhex("12 01 00 02 00 00 00 40 ac 05 ab 12 11 07 01 02 03 05")
|
||||
speed = 2
|
||||
config = 5
|
||||
alternates = {}
|
||||
|
||||
def __init__(self):
|
||||
self.reading = threading.Event()
|
||||
self.cancelled = threading.Event()
|
||||
|
||||
def layout(self):
|
||||
return [(2, 2, 13, 0)], [(0x81, 2, 0, 2, 512), (0x02, 2, 0, 2, 512)]
|
||||
|
||||
def control(self, setup, outgoing):
|
||||
if setup == (0xa1, 0x80, 0, 2, 28):
|
||||
return bytes(range(28))
|
||||
if setup == (0, 9, 5, 0, 0):
|
||||
return 0
|
||||
raise OSError("stalled")
|
||||
|
||||
def transfer(self, address, length, data, flags, cancel):
|
||||
if address == 0x81:
|
||||
self.reading.set()
|
||||
if not cancel.wait(2):
|
||||
raise OSError("read did not get cancelled")
|
||||
self.cancelled.set()
|
||||
return b""
|
||||
return len(data)
|
||||
|
||||
|
||||
class ControlEndpointSizeTest(unittest.TestCase):
|
||||
def test_usbredir_advertises_control_endpoint_size_in_bytes(self):
|
||||
from usb_redir import Session
|
||||
|
||||
for speed, descriptor_size, expected_size in ((2, 64, 64), (3, 9, 512)):
|
||||
with self.subTest(speed=speed):
|
||||
tablet = Tablet()
|
||||
tablet.speed = speed
|
||||
descriptor = bytearray(tablet.descriptor)
|
||||
descriptor[7] = descriptor_size
|
||||
tablet.descriptor = bytes(descriptor)
|
||||
peer = Mock()
|
||||
Session(peer, tablet).topology()
|
||||
message = peer.sendall.call_args_list[0].args[0]
|
||||
sizes = struct.unpack_from("<32H", message, HEADER.size + 96)
|
||||
self.assertEqual((sizes[0], sizes[16]), (expected_size, expected_size))
|
||||
|
||||
|
||||
class InterruptCleanupTest(unittest.TestCase):
|
||||
def test_disconnect_during_interrupt_ack_still_closes_workers(self):
|
||||
from usb_redir import Op, Session
|
||||
|
||||
tablet = Tablet()
|
||||
tablet.layout = lambda: ([(2, 2, 13, 0)], [(0x81, 3, 1, 2, 64)])
|
||||
peer = Mock()
|
||||
peer.sendall.side_effect = ConnectionError("guest disconnected")
|
||||
session = Session(peer, tablet)
|
||||
worker = Mock()
|
||||
session.workers[1] = worker
|
||||
|
||||
with self.assertRaises(ConnectionError):
|
||||
session.interrupt(Op.START_INTERRUPT, 1, 0x81)
|
||||
session.close()
|
||||
|
||||
self.assertFalse(session.interrupts)
|
||||
worker.shutdown.assert_called_once_with(wait=True, cancel_futures=True)
|
||||
|
||||
|
||||
class RedirectionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.assertIsNotNone(importlib.util.find_spec("usb_redir"), "usbredir exporter is missing")
|
||||
from usb_redir import serve
|
||||
self.tablet = Tablet()
|
||||
self.client, server = socket.socketpair()
|
||||
self.client.settimeout(3)
|
||||
def run():
|
||||
with server:
|
||||
serve(server, self.tablet, lambda: False)
|
||||
self.thread = threading.Thread(target=run)
|
||||
self.thread.start()
|
||||
self.client.sendall(HELLO)
|
||||
hello = exact(self.client, 80)
|
||||
self.assertEqual(struct.unpack_from("<III", hello), (0, 68, 0))
|
||||
ep, intf, connected = (packet(self.client) for _ in range(3))
|
||||
self.assertEqual([ep[0], intf[0], connected[0]], [5, 4, 1])
|
||||
self.assertEqual(ep[2][17], 2)
|
||||
self.assertEqual(intf[2][:5], bytes((1, 0, 0, 0, 2)))
|
||||
self.assertEqual(connected[2], bytes.fromhex("02 00 00 00 ac 05 ab 12 11 07"))
|
||||
|
||||
def tearDown(self):
|
||||
if hasattr(self, "client"):
|
||||
self.client.close()
|
||||
self.thread.join(3)
|
||||
self.assertFalse(self.thread.is_alive())
|
||||
|
||||
def send(self, op, seq, data):
|
||||
self.client.sendall(HEADER.pack(op, len(data), seq) + data)
|
||||
|
||||
def test_ncm_control_data_and_configuration(self):
|
||||
self.send(6, 1, b"\x05")
|
||||
self.assertEqual([packet(self.client)[0] for _ in range(2)], [5, 4])
|
||||
self.assertEqual(packet(self.client), (8, 1, b"\x00\x05"))
|
||||
ctrl = CTRL.pack(0x80, 0x80, 0xa1, 0, 0, 2, 28)
|
||||
self.send(100, 2, ctrl)
|
||||
self.assertEqual(packet(self.client), (100, 2, ctrl + bytes(range(28))))
|
||||
|
||||
def test_pending_read_does_not_block_write_or_cancel(self):
|
||||
self.send(101, 7, BULK.pack(0x81, 0, 512, 0, 0))
|
||||
self.assertTrue(self.tablet.reading.wait(2))
|
||||
out = BULK.pack(2, 0, 3, 0, 0)
|
||||
self.send(101, 8, out + b"abc")
|
||||
self.assertEqual(packet(self.client), (101, 8, out))
|
||||
self.send(21, 7, b"")
|
||||
self.assertEqual(packet(self.client), (101, 7, BULK.pack(0x81, 1, 0, 0, 0)))
|
||||
self.assertTrue(self.tablet.cancelled.is_set())
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Switch the tested iPad into NCM mode and pass transfers to its signed filter."""
|
||||
|
||||
from array import array
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
|
||||
import usb.backend.libusb0
|
||||
import usb.core
|
||||
import usb.util
|
||||
|
||||
|
||||
IPAD = (0x05AC, 0x12AB)
|
||||
REVISION = 0x1503
|
||||
# User-mode library in libusb-win32-bin-1.4.0.2/bin/amd64.
|
||||
DLL_SHA256 = "0cd18719d5701e9cc642fc93a83f13830931d6f29f664fedbdf212bcb7c349bd"
|
||||
|
||||
|
||||
def backend_from(directory):
|
||||
path = directory / "libusb0.dll"
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != DLL_SHA256:
|
||||
raise ValueError("select the amd64 directory from libusb-win32 1.4.0.2")
|
||||
backend = usb.backend.libusb0.get_backend(find_library=lambda _: str(path))
|
||||
if backend is None:
|
||||
raise OSError("could not load libusb0.dll with this Python interpreter")
|
||||
return backend
|
||||
|
||||
|
||||
def filtered_ipad(backend, expected_count):
|
||||
matches = []
|
||||
for raw in backend.enumerate_devices():
|
||||
descriptor = backend.get_device_descriptor(raw)
|
||||
if (descriptor.idVendor, descriptor.idProduct) == IPAD:
|
||||
matches.append((raw, descriptor))
|
||||
if len(matches) != 1:
|
||||
raise OSError("The temporary filter did not expose exactly one iPad")
|
||||
raw, descriptor = matches[0]
|
||||
if descriptor.bcdDevice != REVISION or descriptor.bNumConfigurations != expected_count:
|
||||
raise OSError("The filtered iPad does not match the USB hub descriptor")
|
||||
return raw, usb.core.Device(raw, backend)
|
||||
|
||||
|
||||
class Ipad:
|
||||
def __init__(self, backend, info):
|
||||
self.backend = backend
|
||||
self.raw, self.dev = filtered_ipad(backend, info.count)
|
||||
self.descriptor = info.descriptor
|
||||
self.speed = info.speed - 1 # usbredir uses Windows' zero-based speed values
|
||||
self.config = info.config
|
||||
self.lock = Lock()
|
||||
self.handles = {}
|
||||
self.alternates = {}
|
||||
self.in_flight = 0
|
||||
self.control_handle = backend.open_device(self.raw)
|
||||
try:
|
||||
backend.set_configuration(self.control_handle, self.config)
|
||||
except BaseException:
|
||||
backend.close_device(self.control_handle)
|
||||
raise
|
||||
|
||||
def layout(self):
|
||||
interfaces, endpoints = [], []
|
||||
config = usb.util.find_descriptor(self.dev, bConfigurationValue=self.config)
|
||||
if config is not None:
|
||||
for intf in config:
|
||||
index = intf.bInterfaceNumber
|
||||
if intf.bAlternateSetting != self.alternates.get(index, 0):
|
||||
continue
|
||||
interfaces.append((index, intf.bInterfaceClass, intf.bInterfaceSubClass, intf.bInterfaceProtocol))
|
||||
for ep in intf:
|
||||
endpoints.append((ep.bEndpointAddress, ep.bmAttributes & 3, ep.bInterval,
|
||||
index, ep.wMaxPacketSize & 0x7ff))
|
||||
return interfaces, endpoints
|
||||
|
||||
def handle(self, interface):
|
||||
if interface not in self.handles:
|
||||
handle = self.backend.open_device(self.raw)
|
||||
try:
|
||||
self.backend.set_configuration(handle, self.config)
|
||||
self.backend.claim_interface(handle, interface)
|
||||
except BaseException:
|
||||
self.backend.close_device(handle)
|
||||
raise
|
||||
self.handles[interface] = handle
|
||||
return self.handles[interface]
|
||||
|
||||
def release_interfaces(self):
|
||||
handles, self.handles = self.handles, {}
|
||||
self.alternates.clear()
|
||||
error = None
|
||||
for handle in handles.values():
|
||||
try:
|
||||
self.backend.close_device(handle)
|
||||
except OSError as exc:
|
||||
error = exc
|
||||
if error:
|
||||
raise error
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.release_interfaces()
|
||||
finally:
|
||||
self.backend.close_device(self.control_handle)
|
||||
|
||||
def control(self, setup, data):
|
||||
kind, request, value, index, length = setup
|
||||
if (kind, request) == (0, 9):
|
||||
with self.lock:
|
||||
if value != self.config:
|
||||
if self.in_flight:
|
||||
raise OSError("configuration changed with transfers in flight")
|
||||
self.release_interfaces()
|
||||
self.backend.set_configuration(self.control_handle, value)
|
||||
self.config = value
|
||||
return 0
|
||||
if (kind, request) == (1, 11):
|
||||
with self.lock:
|
||||
self.backend.set_interface_altsetting(self.handle(index), index, value)
|
||||
self.alternates[index] = value
|
||||
return 0
|
||||
buf = usb.util.create_buffer(length) if kind & 0x80 else array("B", data)
|
||||
size = self.backend.ctrl_transfer(self.control_handle, kind, request, value, index, buf, 1500)
|
||||
return buf[:size].tobytes() if kind & 0x80 else size
|
||||
|
||||
@contextmanager
|
||||
def endpoint(self, address):
|
||||
with self.lock:
|
||||
cfg = usb.util.find_descriptor(self.dev, bConfigurationValue=self.config)
|
||||
if cfg is None:
|
||||
raise OSError("the iPad has no active USB configuration")
|
||||
for interface in cfg:
|
||||
index = interface.bInterfaceNumber
|
||||
if interface.bAlternateSetting != self.alternates.get(index, 0):
|
||||
continue
|
||||
ep = usb.util.find_descriptor(interface, bEndpointAddress=address)
|
||||
if ep is not None:
|
||||
handle = self.handle(index)
|
||||
break
|
||||
else:
|
||||
raise OSError("endpoint is not active")
|
||||
self.in_flight += 1
|
||||
try:
|
||||
yield handle, index, ep
|
||||
finally:
|
||||
with self.lock:
|
||||
self.in_flight -= 1
|
||||
|
||||
def transfer(self, address, length, outgoing, flags, cancelled):
|
||||
with self.endpoint(address) as (handle, interface, ep):
|
||||
kind = ep.bmAttributes & 3
|
||||
if kind not in (2, 3):
|
||||
raise NotImplementedError("only bulk and interrupt endpoints are supported")
|
||||
if address & 0x80:
|
||||
read = self.backend.bulk_read if kind == 2 else self.backend.intr_read
|
||||
data = usb.util.create_buffer(length)
|
||||
while not cancelled.is_set():
|
||||
try:
|
||||
got = read(handle, address, interface, data, 350)
|
||||
return data[:got].tobytes()
|
||||
except usb.core.USBError as exc:
|
||||
if (getattr(exc, "backend_error_code", None) not in (-110, -116)
|
||||
and not isinstance(exc, usb.core.USBTimeoutError)):
|
||||
raise
|
||||
return b""
|
||||
write = self.backend.bulk_write if kind == 2 else self.backend.intr_write
|
||||
got = write(handle, address, interface, array("B", outgoing), 1000)
|
||||
packet = ep.wMaxPacketSize & 0x7ff
|
||||
if flags & 0x40 and packet and got == length and got and got % packet == 0:
|
||||
write(handle, address, interface, array("B"), 1000)
|
||||
return got
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Read the connection and descriptors of a selected port through its Windows hub."""
|
||||
|
||||
import ctypes as ct
|
||||
from ctypes import wintypes as wt
|
||||
from dataclasses import dataclass
|
||||
import struct
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Connection:
|
||||
descriptor: bytes
|
||||
config: int
|
||||
speed: int
|
||||
address: int
|
||||
|
||||
@property
|
||||
def ids(self):
|
||||
return struct.unpack_from("<HH", self.descriptor, 8)
|
||||
|
||||
@property
|
||||
def count(self):
|
||||
return self.descriptor[17]
|
||||
|
||||
@classmethod
|
||||
def decode(cls, data):
|
||||
# USB_NODE_CONNECTION_INFORMATION_EX (usbioctl.h). Windows speed starts
|
||||
# at zero for low speed. USB/IP starts at one.
|
||||
if len(data) < 35:
|
||||
raise ValueError("short USB hub connection record")
|
||||
if struct.unpack_from("<I", data, 31)[0] != 1:
|
||||
return None
|
||||
if data[4:6] != b"\x12\x01":
|
||||
raise ValueError("invalid device descriptor")
|
||||
return cls(bytes(data[4:22]), data[22], data[23] + 1, struct.unpack_from("<H", data, 25)[0])
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self, instance, port):
|
||||
self.port = port
|
||||
cm = ct.WinDLL("CfgMgr32", use_last_error=True)
|
||||
self.kernel = ct.WinDLL("Kernel32", use_last_error=True)
|
||||
guid = (ct.c_byte * 16).from_buffer_copy(UUID("f18a0e88-c30c-11d0-8815-00a0c906bed8").bytes_le)
|
||||
cm.CM_Get_Device_Interface_List_SizeW.argtypes = (ct.POINTER(wt.ULONG), ct.c_void_p, wt.LPCWSTR, wt.ULONG)
|
||||
cm.CM_Get_Device_Interface_ListW.argtypes = (ct.c_void_p, wt.LPCWSTR, wt.LPWSTR, wt.ULONG, wt.ULONG)
|
||||
length = wt.ULONG()
|
||||
if cm.CM_Get_Device_Interface_List_SizeW(ct.byref(length), ct.byref(guid), instance, 0) or length.value < 2:
|
||||
raise OSError("cannot locate the selected iPad's USB hub")
|
||||
paths = ct.create_unicode_buffer(length.value)
|
||||
if cm.CM_Get_Device_Interface_ListW(ct.byref(guid), instance, paths, length.value, 0) or not paths.value:
|
||||
raise OSError("cannot open the selected iPad's USB hub interface")
|
||||
self.kernel.CreateFileW.argtypes = (wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE)
|
||||
self.kernel.CreateFileW.restype = wt.HANDLE
|
||||
self.kernel.DeviceIoControl.argtypes = (wt.HANDLE, wt.DWORD, ct.c_void_p, wt.DWORD, ct.c_void_p,
|
||||
wt.DWORD, ct.POINTER(wt.DWORD), ct.c_void_p)
|
||||
self.kernel.CloseHandle.argtypes = (wt.HANDLE,)
|
||||
self.handle = self.kernel.CreateFileW(paths.value, 0, 3, None, 3, 0, None)
|
||||
if self.handle == ct.c_void_p(-1).value:
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
|
||||
def close(self):
|
||||
self.kernel.CloseHandle(self.handle)
|
||||
|
||||
def query(self, function, prefix, size):
|
||||
buffer = ct.create_string_buffer(size)
|
||||
ct.memmove(buffer, prefix, len(prefix))
|
||||
received = wt.DWORD()
|
||||
code = (0x22 << 16) | (function << 2)
|
||||
if not self.kernel.DeviceIoControl(self.handle, code, buffer, size, buffer, size, ct.byref(received), None):
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
return buffer.raw[:received.value]
|
||||
|
||||
def connection(self):
|
||||
data = self.query(274, struct.pack("<I", self.port), 4096)
|
||||
return Connection.decode(data)
|
||||
|
||||
def configuration(self, index):
|
||||
def read(length):
|
||||
request = struct.pack("<IBBHHH", self.port, 0x80, 6, 0x0200 | index, 0, length)
|
||||
return self.query(260, request, len(request) + length)[len(request):]
|
||||
header = read(9)
|
||||
if len(header) != 9 or header[:2] != b"\x09\x02":
|
||||
raise ValueError("invalid USB configuration header")
|
||||
size = struct.unpack_from("<H", header, 2)[0]
|
||||
if size < 9:
|
||||
raise ValueError("incomplete USB configuration")
|
||||
return read(size)
|
||||
@@ -0,0 +1,288 @@
|
||||
"""Host end of the usbredir 0.7 protocol for the iPad's development interfaces."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from enum import IntEnum
|
||||
import struct
|
||||
from threading import Event, Lock, Thread
|
||||
import time
|
||||
|
||||
|
||||
class Op(IntEnum):
|
||||
HELLO = 0
|
||||
CONNECT = 1
|
||||
DISCONNECT = 2
|
||||
RESET = 3
|
||||
INTERFACES = 4
|
||||
ENDPOINTS = 5
|
||||
SET_CONFIG = 6
|
||||
GET_CONFIG = 7
|
||||
CONFIG = 8
|
||||
SET_ALT = 9
|
||||
GET_ALT = 10
|
||||
ALT = 11
|
||||
START_INTERRUPT = 15
|
||||
STOP_INTERRUPT = 16
|
||||
INTERRUPT_STATUS = 17
|
||||
CANCEL = 21
|
||||
CONTROL = 100
|
||||
BULK = 101
|
||||
INTERRUPT = 103
|
||||
|
||||
|
||||
SHORT = struct.Struct("<III") # Initial hello uses 32-bit IDs.
|
||||
HEADER = struct.Struct("<IIQ")
|
||||
CONTROL = struct.Struct("<BBBBHHH")
|
||||
BULK = struct.Struct("<BBHIH")
|
||||
INTERRUPT = struct.Struct("<BBH")
|
||||
# Device version, endpoint packet sizes, 64-bit IDs and 32-bit bulk lengths.
|
||||
CAPABILITIES = 0x72
|
||||
MAX_TRANSFER = 16 << 20
|
||||
MAX_PENDING_BYTES = 32 << 20
|
||||
|
||||
|
||||
def receive(peer, size, stopped):
|
||||
buf = bytearray()
|
||||
while len(buf) < size:
|
||||
if stopped():
|
||||
raise EOFError
|
||||
try:
|
||||
part = peer.recv(size - len(buf))
|
||||
except TimeoutError:
|
||||
continue
|
||||
if not part:
|
||||
raise EOFError
|
||||
buf.extend(part)
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, peer, device):
|
||||
self.peer = peer
|
||||
self.device = device
|
||||
self.pending = {}
|
||||
self.queued_bytes = 0
|
||||
self.workers = {}
|
||||
self.interrupts = {}
|
||||
self.lock = Lock()
|
||||
self.writes = Lock()
|
||||
self.closed = Event()
|
||||
|
||||
def send(self, op, seq, payload=b""):
|
||||
with self.writes:
|
||||
self.peer.sendall(HEADER.pack(op, len(payload), seq) + payload)
|
||||
|
||||
def topology(self):
|
||||
interfaces, endpoints = self.device.layout()
|
||||
kinds = bytearray([255] * 32)
|
||||
owners = bytearray([255] * 32)
|
||||
intervals = bytearray(32)
|
||||
sizes = [0] * 32
|
||||
control_size = self.device.descriptor[7]
|
||||
if self.device.speed == 3: # usbredir SuperSpeed
|
||||
# USB 3 encodes bMaxPacketSize0 as an exponent. usbredir sends bytes.
|
||||
if control_size != 9:
|
||||
raise ValueError("invalid SuperSpeed control endpoint size")
|
||||
control_size = 1 << control_size
|
||||
for slot in (0, 16):
|
||||
kinds[slot] = 0
|
||||
sizes[slot] = control_size
|
||||
for address, kind, interval, interface, size in endpoints:
|
||||
slot = (address & 15) + (16 if address & 0x80 else 0)
|
||||
kinds[slot], intervals[slot], owners[slot], sizes[slot] = kind, interval, interface, size
|
||||
self.send(Op.ENDPOINTS, 0, kinds + intervals + owners + struct.pack("<32H", *sizes))
|
||||
columns = [bytearray(32) for _ in range(4)]
|
||||
for i, values in enumerate(interfaces):
|
||||
for column, value in zip(columns, values):
|
||||
column[i] = value
|
||||
self.send(Op.INTERFACES, 0, struct.pack("<I", len(interfaces)) + b"".join(columns))
|
||||
|
||||
def announce(self):
|
||||
self.topology()
|
||||
desc = self.device.descriptor
|
||||
identity = bytes([self.device.speed]) + desc[4:7] + desc[8:14]
|
||||
self.send(Op.CONNECT, 0, identity)
|
||||
|
||||
def dispatch(self, op, seq, body):
|
||||
if op in (Op.CONTROL, Op.BULK, Op.INTERRUPT):
|
||||
self.submit(op, seq, body)
|
||||
elif op == Op.CANCEL:
|
||||
with self.lock:
|
||||
if seq in self.pending:
|
||||
self.pending[seq].set()
|
||||
elif op in (Op.GET_CONFIG, Op.SET_CONFIG, Op.GET_ALT, Op.SET_ALT):
|
||||
self.configure(op, seq, body)
|
||||
elif op in (Op.START_INTERRUPT, Op.STOP_INTERRUPT):
|
||||
endpoint, = struct.unpack("B", body)
|
||||
self.interrupt(op, seq, endpoint)
|
||||
elif op == Op.RESET:
|
||||
# Cycling this iPad's physical port loses configuration 5. Drop
|
||||
# queued endpoint I/O; the guest will select the USB settings again.
|
||||
self.cancel_all()
|
||||
else:
|
||||
raise ValueError(f"unsupported usbredir packet {op}")
|
||||
|
||||
def configure(self, op, seq, body):
|
||||
dev = self.device
|
||||
if op in (Op.SET_CONFIG, Op.GET_CONFIG):
|
||||
status = 0
|
||||
if op == Op.SET_CONFIG:
|
||||
config, = struct.unpack("B", body)
|
||||
try:
|
||||
dev.control((0, 9, config, 0, 0), b"")
|
||||
self.topology()
|
||||
except (ValueError, OSError):
|
||||
status = 4
|
||||
self.send(Op.CONFIG, seq, bytes((status, dev.config)))
|
||||
else:
|
||||
status = 0
|
||||
if op == Op.SET_ALT:
|
||||
index, alt = struct.unpack("BB", body)
|
||||
try:
|
||||
dev.control((1, 11, alt, index, 0), b"")
|
||||
self.topology()
|
||||
except (ValueError, OSError):
|
||||
status = 4
|
||||
else:
|
||||
index, = struct.unpack("B", body)
|
||||
self.send(Op.ALT, seq, bytes((status, index, dev.alternates.get(index, 0))))
|
||||
|
||||
def submit(self, op, seq, body):
|
||||
fmt = {Op.CONTROL: CONTROL, Op.BULK: BULK, Op.INTERRUPT: INTERRUPT}[op]
|
||||
fields = list(fmt.unpack_from(body))
|
||||
endpoint = fields[0]
|
||||
if endpoint & 0x70 or (op != Op.CONTROL and endpoint & 15 == 0):
|
||||
raise ValueError("invalid USB endpoint")
|
||||
if op == Op.CONTROL:
|
||||
_, request, kind, _, value, index, length = fields
|
||||
if endpoint != (kind & 0x80):
|
||||
raise ValueError("inconsistent control direction")
|
||||
setup = (kind, request, value, index, length)
|
||||
elif op == Op.BULK:
|
||||
length = fields[2] | fields[4] << 16
|
||||
if fields[3]:
|
||||
raise ValueError("bulk streams are unavailable on this iPad")
|
||||
setup = None
|
||||
else:
|
||||
length = fields[2]
|
||||
setup = None
|
||||
incoming = bool(endpoint & 0x80)
|
||||
data = body[fmt.size:]
|
||||
if length > MAX_TRANSFER or len(data) != (0 if incoming else length):
|
||||
raise ValueError("invalid USB transfer length")
|
||||
with self.lock:
|
||||
if seq in self.pending or len(self.pending) >= 256 or self.queued_bytes + length > MAX_PENDING_BYTES:
|
||||
raise ValueError("usbredir transfer queue limit or duplicate ID")
|
||||
cancelled = self.pending[seq] = Event()
|
||||
self.queued_bytes += length
|
||||
slot = 0 if op == Op.CONTROL else endpoint
|
||||
if slot not in self.workers:
|
||||
self.workers[slot] = ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
def complete():
|
||||
actual = status = 0
|
||||
payload = b""
|
||||
try:
|
||||
if not cancelled.is_set():
|
||||
result = (self.device.control(setup, data) if setup is not None
|
||||
else self.device.transfer(endpoint, length, data, 0, cancelled))
|
||||
actual = len(result) if incoming else result
|
||||
if actual < 0 or actual > length:
|
||||
raise ValueError("invalid completion size")
|
||||
if incoming:
|
||||
payload = result
|
||||
except (OSError, ValueError, NotImplementedError):
|
||||
status, actual, payload = 4, 0, b"" # STALL
|
||||
with self.lock:
|
||||
try:
|
||||
if cancelled.is_set():
|
||||
status, actual, payload = 1, 0, b""
|
||||
if op == Op.CONTROL:
|
||||
fields[3], fields[6] = status, actual
|
||||
elif op == Op.BULK:
|
||||
fields[1], fields[2], fields[4] = status, actual & 0xffff, actual >> 16
|
||||
else:
|
||||
fields[1], fields[2] = status, actual
|
||||
if not self.closed.is_set():
|
||||
self.send(op, seq, fmt.pack(*fields) + payload)
|
||||
except OSError:
|
||||
self.closed.set()
|
||||
finally:
|
||||
del self.pending[seq]
|
||||
self.queued_bytes -= length
|
||||
self.workers[slot].submit(complete)
|
||||
|
||||
def interrupt(self, op, seq, address):
|
||||
previous = self.interrupts.pop(address, None)
|
||||
if previous:
|
||||
previous[0].set()
|
||||
previous[1].join()
|
||||
if op == Op.STOP_INTERRUPT:
|
||||
self.send(Op.INTERRUPT_STATUS, seq, bytes((0, address)))
|
||||
return
|
||||
_, endpoints = self.device.layout()
|
||||
length = next((size for ep, kind, _, _, size in endpoints
|
||||
if ep == address and kind == 3 and ep & 0x80), 0)
|
||||
if not length:
|
||||
self.send(Op.INTERRUPT_STATUS, seq, bytes((2, address)))
|
||||
return
|
||||
stop = Event()
|
||||
def read():
|
||||
try:
|
||||
while not stop.is_set():
|
||||
data = self.device.transfer(address, length, b"", 0, stop)
|
||||
if not stop.is_set():
|
||||
self.send(Op.INTERRUPT, 0, INTERRUPT.pack(address, 0, len(data)) + data)
|
||||
except (OSError, ValueError):
|
||||
if not stop.is_set() and not self.closed.is_set():
|
||||
try:
|
||||
self.send(Op.INTERRUPT_STATUS, 0, bytes((3, address)))
|
||||
except OSError:
|
||||
self.closed.set()
|
||||
thread = Thread(target=read, name=f"iPad interrupt {address:02x}")
|
||||
self.send(Op.INTERRUPT_STATUS, seq, bytes((0, address)))
|
||||
thread.start()
|
||||
self.interrupts[address] = stop, thread
|
||||
|
||||
def cancel_all(self):
|
||||
with self.lock:
|
||||
for cancel in self.pending.values():
|
||||
cancel.set()
|
||||
for stop, thread in self.interrupts.values():
|
||||
stop.set()
|
||||
thread.join()
|
||||
self.interrupts.clear()
|
||||
|
||||
def close(self):
|
||||
self.closed.set()
|
||||
self.cancel_all()
|
||||
for worker in self.workers.values():
|
||||
worker.shutdown(wait=True, cancel_futures=True)
|
||||
|
||||
|
||||
def serve(peer, device, stopped):
|
||||
session = Session(peer, device)
|
||||
try:
|
||||
# QEMU and the host both send hello using the old 12-byte header first.
|
||||
peer.sendall(SHORT.pack(Op.HELLO, 68, 0) + struct.pack("<64sI", b"reims-ctl", CAPABILITIES))
|
||||
deadline = time.monotonic() + 15
|
||||
def expired():
|
||||
return stopped() or time.monotonic() >= deadline
|
||||
op, size, seq = SHORT.unpack(receive(peer, SHORT.size, expired))
|
||||
if op != Op.HELLO or seq or not 68 <= size <= 256 or size % 4:
|
||||
raise ValueError("invalid usbredir hello")
|
||||
hello = receive(peer, size, expired)
|
||||
caps = struct.unpack_from("<I", hello, 64)[0]
|
||||
if caps & CAPABILITIES != CAPABILITIES:
|
||||
raise ValueError("QEMU lacks required usbredir capabilities")
|
||||
session.announce()
|
||||
def finished():
|
||||
return session.closed.is_set() or stopped()
|
||||
while True:
|
||||
op, length, seq = HEADER.unpack(receive(peer, HEADER.size, finished))
|
||||
if length > MAX_TRANSFER + 16:
|
||||
raise ValueError("usbredir packet exceeds maximum size")
|
||||
session.dispatch(op, seq, receive(peer, length, finished))
|
||||
except (EOFError, ConnectionError):
|
||||
pass
|
||||
finally:
|
||||
session.close()
|
||||
Vendored
+1
-1
Submodule vendor/qemu updated: f073adfb3e...c6f4d7b5c6.
Reference in new issue
Block a user