From d7e10910741d8c9c4209634e3294f1a1fdaa723a Mon Sep 17 00:00:00 2001 From: Admilkk <78579687+Admilkk@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:17:19 +0800 Subject: [PATCH 01/23] feat: parallelize macOS offline installer downloads --- .github/workflows/build-runtime.yml | 21 +- patches/LICENSE | 2 +- patches/README.md | 5 +- ...reims-util-parallel-offline-download.patch | 524 ++++++++++++++++++ patches/series.txt | 3 +- scripts/apply-patch-series.ps1 | 25 +- scripts/pack-runtime.ps1 | 47 +- 7 files changed, 609 insertions(+), 18 deletions(-) create mode 100644 patches/reims-util-parallel-offline-download.patch diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 40234aa..6f6650d 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -132,6 +132,16 @@ jobs: git -C $work submodule update --init --depth 1 vendor/qemu if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu } if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' } + $utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util' + $utilPin = Get-Content -Raw -LiteralPath (Join-Path $work 'crates/reims-ctl/src/reims_util.rs') + if ($utilPin -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found' } + $utilRev = $Matches[1] + git init -q $utilRepo + if ($LASTEXITCODE) { throw 'reims-util init failed' } + git -C $utilRepo fetch -q --depth 1 https://github.com/steelbrain/reims-util.git $utilRev + if ($LASTEXITCODE) { throw 'reims-util fetch failed' } + git -C $utilRepo checkout -q --detach FETCH_HEAD + if ($LASTEXITCODE) { throw 'reims-util checkout failed' } $short = (git -C $work rev-parse --short=7 HEAD).Trim() $releaseId = "$short${{ needs.resolve.outputs.suffix }}" "short=$short" >> $env:GITHUB_OUTPUT @@ -141,7 +151,7 @@ jobs: # conflict without touching the patch (AGENTS.md rule 4). $resultFile = Join-Path $env:RUNNER_TEMP 'patches.json' try { - pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -ResultFile $resultFile + pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -ResultFile $resultFile $ok = $LASTEXITCODE -eq 0 } finally { if (Test-Path $resultFile) { @@ -154,6 +164,7 @@ jobs: } if (-not $ok) { throw 'patch queue does not apply' } "UPSTREAM_DIR=$work" >> $env:GITHUB_ENV + "REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV "SHORT_COMMIT=$short" >> $env:GITHUB_ENV "RELEASE_ID=$releaseId" >> $env:GITHUB_ENV "CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV @@ -169,6 +180,13 @@ jobs: cd "$(cygpath -u "$UPSTREAM_DIR")" # Upstream's own non-interactive CLANG64 build script. bash scripts/install-ctl.sh --yes + util_repo="$(cygpath -u "$REIMS_UTIL_DIR")" + if [[ -n "$(git -C "$util_repo" status --porcelain)" ]]; then + toolchain="$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)" + export PATH="$(cygpath -u "$CARGO_HOME")/bin:$PATH" + CC=clang CXX=clang++ AR=llvm-ar cargo +"$toolchain-x86_64-pc-windows-gnullvm" install \ + --locked --force --root "$CARGO_HOME" --path "$REIMS_UTIL_DIR" + fi - name: Package alpha runtime and source archives shell: pwsh @@ -181,6 +199,7 @@ jobs: $applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ }) & ./scripts/pack-runtime.ps1 ` -ReimsRepo $env:UPSTREAM_DIR ` + -UtilRepo $env:REIMS_UTIL_DIR ` -CargoHome $env:CARGO_HOME ` -QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') ` -Msys2 '${{ steps.msys2.outputs.msys2-location }}' ` diff --git a/patches/LICENSE b/patches/LICENSE index 42d8969..8803aeb 100644 --- a/patches/LICENSE +++ b/patches/LICENSE @@ -7,5 +7,5 @@ strict license compatibility with each target codebase: - `qemu-*.patch` (targeting `vendor/qemu` / QEMU) are licensed under **GPL-2.0-or-later**. -- `reims-*.patch` (targeting `steelbrain/reims-vgpu` / `reims-ctl`) are +- `reims-*.patch` (targeting `steelbrain/reims-vgpu` or `steelbrain/reims-util`) are dual-licensed under **GPL-2.0-or-later OR LGPL-3.0-or-later**. diff --git a/patches/README.md b/patches/README.md index 67677b0..695e20d 100644 --- a/patches/README.md +++ b/patches/README.md @@ -4,11 +4,13 @@ ## 维护原则 -1. **不长期维护 fork**:所有底层修复优先向上游仓库([`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) / [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu))提交 PR,目标是补丁队列清零。 +1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu) 和 [`reims-util`](https://github.com/steelbrain/reims-util)。 2. **人工提 PR,冲突即停**:更新上游基线时由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按顺序执行 `git apply --check`。已合入上游(反向检查通过)的补丁会自动跳过并开 Issue 提醒退役;遇到冲突时立刻中止构建,不自动改写补丁。 3. **文件格式约束**:所有 `.patch` 文件必须为 **无 BOM、LF 行尾**(由 `.gitattributes` 中的 `*.patch -text` 约束),避免 `git apply` 在 Windows 上失败。 4. **来源透明与协议兼容**:每个运行时包的 `manifest.json` 与 `patches/` 目录必须如实记录实际应用的全部补丁及哈希;本目录补丁不适用根目录的 Apache-2.0,而是遵循目标上游兼容协议(详见 [`patches/LICENSE`](LICENSE))。 +本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树。用相同的 MSYS2 CLANG64 工具链安装其中的 `reims-util` 后,把同一工作树传给打包脚本。 + --- ## 当前补丁清单 @@ -23,6 +25,7 @@ | [`reims-ctl-win32-random-bytes.patch`](reims-ctl-win32-random-bytes.patch) | `reims-vgpu` (`crates/reims-ctl/src/vm.rs`) | 修复 Windows 下打不开 `/dev/urandom` 时回退到低熵时间戳种子的缺陷,改用标准库 `RandomState`(底层调用 `ProcessPrng`)生成 MAC/ROM 随机字节 | `git apply --check` 通过;待编入 `alpha` 验证后提 PR | | [`reims-ctl-virtio-discard-iothread.patch`](reims-ctl-virtio-discard-iothread.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 为 VirtIO 系统盘补齐 `discard=unmap`(与 NVMe 一致透传客体 TRIM)并启用独立 `-object iothread,id=io0`,避免块完成回调与 QEMU 主循环争抢 | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;真机实测与休眠唤醒通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | | [`reims-ctl-qcow2-l2-cache.patch`](reims-ctl-qcow2-l2-cache.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 按 `qcow2` 文件头虚拟容量与簇大小计算全覆盖所需 `l2-cache-size`(上限 32 MiB,仅大于 8 MiB 默认值时追加),避免非 Linux 宿主默认 8 MiB 上限仅覆盖 64 GiB | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;128 GiB 镜像真机实测通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | +| [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `reims-util` (`src/http.rs`, `src/installer.rs`) | 对有 Apple 分块校验数据的完整离线包并发请求四段,按顺序校验并写入镜像。分段读取失败时用原有单路下载继续 | 待编入 `alpha` 冒烟验证 | | [`qemu-whpx-win10-compat.patch`](qemu-whpx-win10-compat.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 修复 Windows 10 19045 上两处 WHPX 必现崩溃(探测 TSC deadline 污染主分区、`WHvResetPartition` 未判空) | 已在 Win10 19045 真机验证并随稳定运行时发布;待提 PR | | [`qemu-whpx-win10-startup-ipis.patch`](qemu-whpx-win10-startup-ipis.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 在 Win10 开启 `kernel-irqchip` 且多核启动时经 `WHvRequestInterrupt` 转发 INIT/SIPI,避免 XNU 从核卡死(依赖上一项) | 8/12 核冷启动通过;客体软重启待验证,待提 PR | | [`qemu-whpx-nested-virt-nonfatal.patch`](qemu-whpx-nested-virt-nonfatal.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 部分 Win11 宿主设置嵌套虚拟化属性返回 `0x80370302` 时改为警告并清零特性位,保留 `kernel-irqchip=on` 加速(依赖前两项) | 待编入 `alpha` 并在 Win11 真机验证后提 PR | diff --git a/patches/reims-util-parallel-offline-download.patch b/patches/reims-util-parallel-offline-download.patch new file mode 100644 index 0000000..4af222b --- /dev/null +++ b/patches/reims-util-parallel-offline-download.patch @@ -0,0 +1,524 @@ +diff --git a/src/http.rs b/src/http.rs +index 69aeb817b8dc1ff2cebb91bbcad5d4ad749b1540..777a7d8adf65faaff0f08e228a4165ed48984e42 100644 +--- a/src/http.rs ++++ b/src/http.rs +@@ -13,13 +13,15 @@ + use crate::progress::{self, Reporter}; + use anyhow::{Context, Result, bail}; + use std::fs::{File, OpenOptions}; +-use std::io::{Read, Seek, SeekFrom, Write}; ++use std::io::{Cursor, Read, Seek, SeekFrom, Write}; + use std::path::{Path, PathBuf}; ++use std::thread; + use std::time::Duration; + use ureq::Agent; + + /// The most each request asks for. + pub const SEGMENT: u64 = 64 << 20; ++const PARALLEL_REQUESTS: usize = 4; + /// How long a request may take to send its range: a stall is noticed within this. (On a + /// connection too slow to send a whole range in it, each request sends what it can.) + pub const SEGMENT_BUDGET: Duration = Duration::from_secs(180); +@@ -124,6 +126,8 @@ pub struct Download<'a> { + /// For requests the server refuses (401, 403): new headers, such as a fresh asset token. + pub refresh: Option<&'a mut dyn FnMut() -> Result>, + pub user_agent: Option<&'static str>, ++ /// Fetch the public installer package in parallel within each checked segment. ++ pub parallel: bool, + /// Failed requests in a row, with no byte received between them, before it gives up: + /// [`MAX_FAILURES`], or fewer when there is another place to download the file from. + pub tries: u32, +@@ -138,6 +142,7 @@ impl Download<'_> { + size: None, + refresh: None, + user_agent: None, ++ parallel: false, + tries: MAX_FAILURES, + } + } +@@ -229,6 +234,8 @@ pub fn download( + let mut failures = 0u32; + let mut bad_chunks = 0u32; + let mut buf = vec![0u8; 1 << 18]; ++ let mut parallel = ++ d.parallel && check.verifies() && d.headers.is_empty() && d.user_agent.is_none(); + r.progress(have, total); + + 'requests: loop { +@@ -240,94 +247,116 @@ pub fn download( + Some(t) => (have + SEGMENT).min(t) - 1, + None => have + SEGMENT - 1, + }; +- let mut req = agent +- .get(&d.url) +- .header("Range", format!("bytes={have}-{end}")); +- for (k, v) in &d.headers { +- req = req.header(k, v); +- } +- let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET)); +- if let Some(ua) = d.user_agent { +- cfg = cfg.user_agent(ua); +- } +- let resp = match cfg.build().call() { +- Ok(resp) => resp, +- Err(e) => { +- failures += 1; +- retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?; +- continue; ++ // Keep one segment in memory and commit it through the same ordered ++ // writer and chunk checker used by serial downloads. ++ let batch = if parallel ++ && let Some(size) = total ++ && end - have >= (PARALLEL_REQUESTS - 1) as u64 ++ { ++ match read_parallel_segment(agent, &d.url, have, end, size, r) { ++ Ok(bytes) => Some(bytes), ++ Err(_) => { ++ progress::check(r)?; ++ parallel = false; ++ r.note("Parallel ranges could not be read. Continuing with one connection."); ++ None ++ } + } ++ } else { ++ None + }; +- let status = resp.status().as_u16(); +- match status { +- 206 => { +- let range = resp +- .headers() +- .get("content-range") +- .and_then(|v| v.to_str().ok()) +- .and_then(content_range) +- .with_context(|| format!("{} sent a range without Content-Range", d.url))?; +- if range.0 != have { +- bail!( +- "{} sent bytes from {} when asked for {have}", +- d.url, +- range.0 +- ); ++ let mut body: Box = if let Some(bytes) = batch { ++ Box::new(Cursor::new(bytes)) ++ } else { ++ let mut req = agent ++ .get(&d.url) ++ .header("Range", format!("bytes={have}-{end}")); ++ for (k, v) in &d.headers { ++ req = req.header(k, v); ++ } ++ let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET)); ++ if let Some(ua) = d.user_agent { ++ cfg = cfg.user_agent(ua); ++ } ++ let resp = match cfg.build().call() { ++ Ok(resp) => resp, ++ Err(e) => { ++ failures += 1; ++ retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?; ++ continue; ++ } ++ }; ++ let status = resp.status().as_u16(); ++ match status { ++ 206 => { ++ let range = resp ++ .headers() ++ .get("content-range") ++ .and_then(|v| v.to_str().ok()) ++ .and_then(content_range) ++ .with_context(|| format!("{} sent a range without Content-Range", d.url))?; ++ if range.0 != have { ++ bail!( ++ "{} sent bytes from {} when asked for {have}", ++ d.url, ++ range.0 ++ ); ++ } ++ match (total, range.1) { ++ (Some(t), Some(rt)) if t != rt => bail!( ++ "{} is {} long, not the expected {}: it changed on the server", ++ d.url, ++ rt, ++ t ++ ), ++ (None, Some(rt)) => { ++ total = Some(rt); ++ r.progress(have, total); ++ } ++ _ => {} ++ } + } +- match (total, range.1) { +- (Some(t), Some(rt)) if t != rt => bail!( +- "{} is {} long, not the expected {}: it changed on the server", +- d.url, +- rt, +- t +- ), +- (None, Some(rt)) => { +- total = Some(rt); +- r.progress(have, total); ++ 200 => { ++ // The whole file: the server ignored the range. ++ if have > 0 { ++ cut(file, 0)?; ++ have = 0; ++ check.restart_at(0); ++ } ++ if total.is_none() { ++ total = resp.body().content_length(); + } +- _ => {} + } +- } +- 200 => { +- // The whole file: the server ignored the range. +- if have > 0 { ++ 416 if total.is_some_and(|t| have >= t) => break, ++ 416 => { ++ // Past the end: the file on the server is shorter than what we have. ++ if have == 0 { ++ bail!("{} refused every range", d.url); ++ } ++ r.note("The file changed on the server: starting over"); + cut(file, 0)?; + have = 0; + check.restart_at(0); ++ continue; + } +- if total.is_none() { +- total = resp.body().content_length(); +- } +- } +- 416 if total.is_some_and(|t| have >= t) => break, +- 416 => { +- // Past the end: the file on the server is shorter than what we have. +- if have == 0 { +- bail!("{} refused every range", d.url); ++ 401 | 403 if d.refresh.is_some() && failures < 3 => { ++ failures += 1; ++ if let Some(f) = d.refresh.as_mut() { ++ d.headers = f()?; ++ } ++ continue; + } +- r.note("The file changed on the server: starting over"); +- cut(file, 0)?; +- have = 0; +- check.restart_at(0); +- continue; +- } +- 401 | 403 if d.refresh.is_some() && failures < 3 => { +- failures += 1; +- if let Some(f) = d.refresh.as_mut() { +- d.headers = f()?; ++ 408 | 429 | 500..=599 => { ++ failures += 1; ++ retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?; ++ continue; + } +- continue; +- } +- 408 | 429 | 500..=599 => { +- failures += 1; +- retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?; +- continue; ++ _ => bail!("{} answered HTTP {status}", d.url), + } +- _ => bail!("{} answered HTTP {status}", d.url), +- } ++ Box::new(resp.into_body().into_reader()) ++ }; + + file.seek(SeekFrom::Start(base + have))?; +- let mut body = resp.into_body().into_reader(); + let start = have; + loop { + if r.cancelled() { +@@ -389,6 +418,79 @@ pub fn download( + Ok(()) + } + ++fn read_parallel_segment( ++ agent: &Agent, ++ url: &str, ++ start: u64, ++ end: u64, ++ total: u64, ++ r: &dyn Reporter, ++) -> Result> { ++ let mut segment = vec![0; (end - start + 1) as usize]; ++ let request_size = segment.len().div_ceil(PARALLEL_REQUESTS); ++ thread::scope(|scope| -> Result<()> { ++ let mut requests = Vec::with_capacity(PARALLEL_REQUESTS); ++ for (index, chunk) in segment.chunks_mut(request_size).enumerate() { ++ let first = start + (index * request_size) as u64; ++ let request = thread::Builder::new().spawn_scoped(scope, move || { ++ read_exact_range(agent, url, first, total, chunk, r) ++ })?; ++ requests.push(request); ++ } ++ for request in requests { ++ request ++ .join() ++ .map_err(|_| anyhow::anyhow!("range worker failed"))??; ++ } ++ Ok(()) ++ })?; ++ Ok(segment) ++} ++ ++fn read_exact_range( ++ agent: &Agent, ++ url: &str, ++ start: u64, ++ total: u64, ++ mut remaining: &mut [u8], ++ r: &dyn Reporter, ++) -> Result<()> { ++ let end = start + remaining.len() as u64 - 1; ++ progress::check(r)?; ++ let response = agent ++ .get(url) ++ .header("Range", format!("bytes={start}-{end}")) ++ .header("Accept-Encoding", "identity") ++ .config() ++ .timeout_recv_body(Some(SEGMENT_BUDGET)) ++ .build() ++ .call()?; ++ let expected = format!("bytes {start}-{end}/{total}"); ++ if response.status().as_u16() != 206 ++ || response ++ .headers() ++ .get("Content-Range") ++ .and_then(|value| value.to_str().ok()) ++ != Some(expected.as_str()) ++ { ++ bail!("server did not return the requested byte range"); ++ } ++ let mut body = response.into_body().into_reader(); ++ while !remaining.is_empty() { ++ progress::check(r)?; ++ let n = body.read(remaining)?; ++ if n == 0 { ++ bail!("range body ended before its declared length"); ++ } ++ remaining = &mut remaining[n..]; ++ } ++ progress::check(r)?; ++ if body.read(&mut [0u8; 1])? != 0 { ++ bail!("range body exceeded its declared length"); ++ } ++ Ok(()) ++} ++ + fn retry_or_fail( + failures: &mut u32, + tries: u32, +@@ -455,6 +557,173 @@ pub fn hex(b: &[u8]) -> String { + #[cfg(test)] + mod tests { + use super::*; ++ use std::io::{BufRead, BufReader}; ++ use std::net::{TcpListener, TcpStream}; ++ ++ struct Silent; ++ ++ impl Reporter for Silent { ++ fn event(&self, _: progress::Event) {} ++ } ++ ++ fn read_request(stream: &TcpStream) -> Result { ++ stream.set_read_timeout(Some(Duration::from_secs(5)))?; ++ let mut reader = BufReader::new(stream); ++ let mut range = String::new(); ++ loop { ++ let mut line = String::new(); ++ if reader.read_line(&mut line)? == 0 || line == "\r\n" { ++ break; ++ } ++ if let Some((name, value)) = line.split_once(':') ++ && name.eq_ignore_ascii_case("range") ++ { ++ range = value.trim().to_string(); ++ } ++ } ++ Ok(range) ++ } ++ ++ #[test] ++ fn sends_four_ranges_before_waiting_for_their_bodies() -> Result<()> { ++ let listener = TcpListener::bind("127.0.0.1:0")?; ++ listener.set_nonblocking(true)?; ++ let url = format!("http://{}", listener.local_addr()?); ++ let server = thread::spawn(move || -> Result<()> { ++ let deadline = std::time::Instant::now() + Duration::from_secs(5); ++ let mut requests = std::collections::BTreeMap::new(); ++ while requests.len() < 4 { ++ match listener.accept() { ++ Ok((stream, _)) => { ++ let range = read_request(&stream)?; ++ requests.insert(range, stream); ++ } ++ Err(e) ++ if e.kind() == std::io::ErrorKind::WouldBlock ++ && std::time::Instant::now() < deadline => ++ { ++ thread::sleep(Duration::from_millis(5)); ++ } ++ Err(e) => { ++ return Err(e).context("waiting for four simultaneous range requests"); ++ } ++ } ++ } ++ // No worker gets a response until all four requests have arrived. ++ let data = b"abcdefghijklmnop"; ++ for offset in (0..data.len()).step_by(4).rev() { ++ let mut stream = requests ++ .remove(&format!("bytes={offset}-{}", offset + 3)) ++ .context("missing requested range")?; ++ write!( ++ stream, ++ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes {offset}-{}/16\r\nConnection: close\r\n\r\n", ++ offset + 3 ++ )?; ++ stream.write_all(&data[offset..offset + 4])?; ++ } ++ Ok(()) ++ }); ++ let data = read_parallel_segment(&test_agent(), &url, 0, 15, 16, &Silent); ++ server ++ .join() ++ .map_err(|_| anyhow::anyhow!("test server failed"))??; ++ assert_eq!(data?, b"abcdefghijklmnop"); ++ Ok(()) ++ } ++ ++ #[test] ++ fn rejects_ignored_misaligned_and_truncated_ranges() -> Result<()> { ++ let listener = TcpListener::bind("127.0.0.1:0")?; ++ let url = format!("http://{}", listener.local_addr()?); ++ let server = thread::spawn(move || -> Result<()> { ++ for reply in [ ++ "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\nabcd", ++ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes 5-8/16\r\nConnection: close\r\n\r\nabcd", ++ "HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 4-7/16\r\nConnection: close\r\n\r\nabc", ++ ] { ++ let (mut stream, _) = listener.accept()?; ++ read_request(&stream)?; ++ stream.write_all(reply.as_bytes())?; ++ } ++ Ok(()) ++ }); ++ let agent = test_agent(); ++ for _ in 0..3 { ++ assert!(read_exact_range(&agent, &url, 4, 16, &mut [0; 4], &Silent).is_err()); ++ } ++ server ++ .join() ++ .map_err(|_| anyhow::anyhow!("test server failed"))??; ++ Ok(()) ++ } ++ ++ #[test] ++ fn falls_back_to_a_single_request_from_the_verified_prefix() -> Result<()> { ++ use crate::chunklist::{ChunkCheck, Chunklist, Signature}; ++ use sha2::{Digest, Sha256}; ++ ++ let data = b"abcdefghijklmnop"; ++ let listener = TcpListener::bind("127.0.0.1:0")?; ++ let url = format!("http://{}", listener.local_addr()?); ++ let server = thread::spawn(move || -> Result<()> { ++ for _ in 0..PARALLEL_REQUESTS { ++ let (mut stream, _) = listener.accept()?; ++ read_request(&stream)?; ++ stream.write_all( ++ b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", ++ )?; ++ } ++ let (mut stream, _) = listener.accept()?; ++ assert_eq!(read_request(&stream)?, "bytes=4-15"); ++ stream.write_all( ++ b"HTTP/1.1 206 Partial Content\r\nContent-Length: 12\r\nContent-Range: bytes 4-15/16\r\nConnection: close\r\n\r\n", ++ )?; ++ stream.write_all(&data[4..])?; ++ Ok(()) ++ }); ++ let dir = std::env::temp_dir().join(format!("reims-util-fallback-{}", std::process::id())); ++ std::fs::create_dir_all(&dir)?; ++ let path = dir.join("download"); ++ std::fs::write(part_path(&path), &data[..4])?; ++ let chunks = data ++ .chunks_exact(4) ++ .map(|chunk| (4, Sha256::digest(chunk).into())) ++ .collect(); ++ let mut check = ChunkCheck::new(Chunklist { ++ chunks, ++ signature: Signature::Digest, ++ }); ++ let mut request = Download::new(&url, "Test download".into()); ++ request.size = Some(data.len() as u64); ++ request.parallel = true; ++ let result = download( ++ &test_agent(), ++ request, ++ Dest::File(&path), ++ &mut check, ++ &Silent, ++ ); ++ let actual = std::fs::read(&path); ++ let _ = std::fs::remove_file(&path); ++ let _ = std::fs::remove_file(part_path(&path)); ++ let _ = std::fs::remove_dir(&dir); ++ result?; ++ server ++ .join() ++ .map_err(|_| anyhow::anyhow!("test server failed"))??; ++ assert_eq!(actual?, data); ++ Ok(()) ++ } ++ ++ fn test_agent() -> Agent { ++ Agent::config_builder() ++ .proxy(None) ++ .http_status_as_error(false) ++ .timeout_global(Some(Duration::from_secs(5))) ++ .build() ++ .into() ++ } + + #[test] + fn parses_content_range() { +diff --git a/src/installer.rs b/src/installer.rs +index 7c17423300c153fd24fe9e031de3a835dcda57e1..265031a5d2ff54e0b8c9b752bad579c5927c5ef1 100644 +--- a/src/installer.rs ++++ b/src/installer.rs +@@ -475,6 +475,7 @@ pub fn offline_installer(inst: &Installer, dir: &Path, r: &dyn Reporter) -> Resu + progress::check(r)?; + let mut d = Download::new(&inst.url, format!("Downloading {}", inst.label())); + d.size = Some(inst.size); ++ d.parallel = true; + let pkg = Dest::Region { + file: &mut f, + offset: pkg_at, +@@ -746,6 +747,7 @@ mod tests { + /// macOS 12's and 26's do, through `Applications`), and where it fails after placing + /// the app (as Big Sur's does, needing zsh), the app gets the package as SharedSupport.dmg + /// and the script starts its startosinstall on the volume. ++ #[cfg(unix)] + #[test] + fn install_script_runs_without_dirname_or_zsh() { + use std::os::unix::fs::{PermissionsExt, symlink}; +diff --git a/src/recovery.rs b/src/recovery.rs +index fe4eadc745ac4867802254a53197821acac3d411..11406e790884549b7e4e6b297f29c3a0285c606f 100644 +--- a/src/recovery.rs ++++ b/src/recovery.rs +@@ -311,6 +311,7 @@ impl Image { + size: Some(self.size()), + refresh: Some(&mut refresh), + user_agent: Some(USER_AGENT), ++ parallel: false, + tries: http::MAX_FAILURES, + }; + http::download(&self.agent, d, dest, check, r) diff --git a/patches/series.txt b/patches/series.txt index fcc4326..1de7565 100644 --- a/patches/series.txt +++ b/patches/series.txt @@ -1,6 +1,6 @@ # Patch queue, in the order the patches are applied (see patches/README.md). # One patch per line: . -# target is "reims-vgpu" (the upstream repository root) or "vendor/qemu". +# Targets are "reims-vgpu", "vendor/qemu", and "reims-util". # CI (build-runtime.yml via scripts/apply-patch-series.ps1) and # scripts/pack-runtime.ps1 both read this file; add or retire patches here. reims-vgpu reims-vgpu-cargo-lock.patch @@ -9,6 +9,7 @@ reims-vgpu reims-vgpu-display-fixed-mode.patch reims-vgpu reims-ctl-win32-random-bytes.patch reims-vgpu reims-ctl-virtio-discard-iothread.patch reims-vgpu reims-ctl-qcow2-l2-cache.patch +reims-util reims-util-parallel-offline-download.patch vendor/qemu qemu-whpx-win10-compat.patch vendor/qemu qemu-whpx-win10-startup-ipis.patch vendor/qemu qemu-whpx-nested-virt-nonfatal.patch diff --git a/scripts/apply-patch-series.ps1 b/scripts/apply-patch-series.ps1 index dd76ddd..e04aeaa 100644 --- a/scripts/apply-patch-series.ps1 +++ b/scripts/apply-patch-series.ps1 @@ -1,6 +1,6 @@ <# .SYNOPSIS - Apply the patch queue in patches/series.txt to an upstream reims-vgpu checkout. + Apply the patch queue in patches/series.txt to the checked-out upstream sources. .DESCRIPTION For each patch, in series order: @@ -16,18 +16,24 @@ was really applied, AGENTS.md rule 5) and report merged or conflicting patches. .EXAMPLE - pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -ResultFile patches.json + pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -ResultFile patches.json #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ReimsRepo, - [string]$ResultFile = '' + [string]$ResultFile = '', + [string]$UtilRepo = '' ) $ErrorActionPreference = 'Stop' $repoRoot = Split-Path -Parent $PSScriptRoot $patchesDir = Join-Path $repoRoot 'patches' +$repositories = @{ + 'reims-vgpu' = $ReimsRepo + 'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu' + 'reims-util' = $UtilRepo +} function Read-PatchSeries { $series = Join-Path $patchesDir 'series.txt' @@ -35,7 +41,7 @@ function Read-PatchSeries { $t = $line.Trim() if (-not $t -or $t.StartsWith('#')) { continue } $parts = $t -split '\s+' - if ($parts.Count -ne 2 -or $parts[0] -notin @('reims-vgpu', 'vendor/qemu')) { + if ($parts.Count -ne 2 -or -not $repositories.ContainsKey($parts[0])) { throw "Bad line in patches/series.txt: '$line'" } [pscustomobject]@{ Target = $parts[0]; Name = $parts[1] } @@ -49,17 +55,22 @@ function Save-Result { } } -foreach ($p in Read-PatchSeries) { +$series = @(Read-PatchSeries) +if (-not $UtilRepo -and $series.Target -contains 'reims-util') { + throw 'Pass -UtilRepo with a checkout at the reims-util revision pinned by reims-ctl.' +} + +foreach ($p in $series) { $file = Join-Path $patchesDir $p.Name if (-not (Test-Path -LiteralPath $file)) { throw "Patch listed in series.txt is missing: $file" } - $dir = if ($p.Target -eq 'vendor/qemu') { Join-Path $ReimsRepo 'vendor\qemu' } else { $ReimsRepo } + $dir = $repositories[$p.Target] # git -C into a missing or uninitialised submodule falls back to the outer # repository, where "git apply" silently skips paths outside the current # directory and reports success. Require $dir to be its own work tree. $top = (& git -C $dir rev-parse --show-toplevel 2>$null) if ($LASTEXITCODE -ne 0 -or -not $top -or [IO.Path]::GetFullPath($top.Trim()).TrimEnd([char[]]'\/') -ne [IO.Path]::GetFullPath($dir).TrimEnd([char[]]'\/')) { - throw "$dir is not a checked-out git work tree (is the vendor/qemu submodule initialised?)" + throw "$dir is not a checked-out git work tree for $($p.Target)" } & git -C $dir apply --check $file 2>$null diff --git a/scripts/pack-runtime.ps1 b/scripts/pack-runtime.ps1 index 29d7fa4..40928b9 100644 --- a/scripts/pack-runtime.ps1 +++ b/scripts/pack-runtime.ps1 @@ -34,6 +34,7 @@ [CmdletBinding(PositionalBinding = $false)] param( [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', + [string]$UtilRepo = '', [string]$CargoHome = 'D:\DevTools\cargo', [string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current', [string]$Msys2 = 'D:\DevTools\msys64', @@ -126,6 +127,17 @@ $qemuCommit = (git -C $qemuRepo rev-parse HEAD).Trim() $utilSrc = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'crates\reims-ctl\src\reims_util.rs') if ($utilSrc -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found in reims_util.rs' } $utilCommit = $Matches[1] +$checkouts = Join-Path $CargoHome 'git\checkouts' +$utilTree = if ($UtilRepo) { + (Resolve-Path -LiteralPath $UtilRepo).Path +} else { + Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' | + ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } | + Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $utilTree) { throw "reims-util source at $utilCommit not found" } +$actualUtil = git -C $utilTree rev-parse HEAD +if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" } # metal2vulkan's git rev as built (Cargo.lock in the build tree). $lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock') @@ -136,11 +148,16 @@ $qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim() $utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim() # ── 2. Patches must equal the build tree's diffs ───────────── +$repositories = @{ + 'reims-vgpu' = $ReimsRepo + 'vendor/qemu' = $qemuRepo + 'reims-util' = $utilTree +} $series = @(foreach ($line in Get-Content -LiteralPath (Join-Path $patchesDir 'series.txt')) { $t = $line.Trim() if (-not $t -or $t.StartsWith('#')) { continue } $parts = $t -split '\s+' - if ($parts.Count -ne 2 -or $parts[0] -notin @('reims-vgpu', 'vendor/qemu')) { throw "Bad line in patches/series.txt: '$line'" } + if ($parts.Count -ne 2 -or -not $repositories.ContainsKey($parts[0])) { throw "Bad line in patches/series.txt: '$line'" } [pscustomobject]@{ Target = $parts[0]; Name = $parts[1] } }) # PowerShell -File passes "a,b" as one string: accept both forms. @@ -161,7 +178,7 @@ foreach ($e in $series) { $patchSpecs += @{ Name = $e.Name Target = $e.Target - Repo = $(if ($e.Target -eq 'vendor/qemu') { $qemuRepo } else { $ReimsRepo }) + Repo = $repositories[$e.Target] Paths = $paths } } @@ -254,8 +271,10 @@ function Get-Undeclared([string]$repo, [string]$target, [string[]]$statusArgs) { } $otherCtl = Get-Undeclared $ReimsRepo 'reims-vgpu' @('--ignore-submodules=all') $otherQemu = Get-Undeclared $qemuRepo 'vendor/qemu' @('--untracked-files=no') -if ($otherCtl.Count -or $otherQemu.Count) { - throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu -join "`n")" +$utilStatusArgs = if ($UtilRepo) { '--untracked-files=all' } else { '--untracked-files=no' } +$otherUtil = Get-Undeclared $utilTree 'reims-util' @($utilStatusArgs) +if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count) { + throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil -join "`n")" } $bundleName = "reims-runtime-win-x64-$id" @@ -369,10 +388,7 @@ Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory | Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } | ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force } -$checkouts = Join-Path $CargoHome 'git\checkouts' -$utilTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' | ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 $m2vTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' | ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 -if (-not $utilTree) { throw "reims-util source at $utilCommit not found under $checkouts" } if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found under $checkouts" } Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))") Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))") @@ -395,6 +411,22 @@ New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\" Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt" Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md" +$utilBuildSteps = if ($byTarget.Contains('reims-util')) { + $utilDir = "reims-util-$($utilCommit.Substring(0, 7))" + $utilApply = ($byTarget['reims-util'] | ForEach-Object { " git -C $utilDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n" +@" + +After the upstream build, run these commands from the extracted source +archive's root in the same MSYS2 CLANG64 shell. They apply the reims-util +patches and replace the stock reims-util executable with this build: + +$utilApply + cd reims-vgpu-$commit + toolchain=`$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml) + CC=clang CXX=clang++ AR=llvm-ar cargo +"`$toolchain-x86_64-pc-windows-gnullvm" install --locked --force --path ../$utilDir + +"@ +} Write-Utf8 "$srcDir\README.md" @" # Source for $bundleName @@ -418,6 +450,7 @@ $((($patchSpecs | Where-Object { $_.Target -eq 'vendor/qemu' } | ForEach-Object (``patch -p1`` works too.) Then build as upstream documents (``scripts/install-ctl.sh`` in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2 packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources. +$utilBuildSteps "@ # ── 5. Manifest (schema 2) ─────────────────────────────────── From 93c981ff0168b4d5180a3943d112ad3e1b54aecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A3=A0=E6=B8=9A=E5=90=AC=E6=BD=AE?= <108173440+reiasu2@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:14:38 +0800 Subject: [PATCH 02/23] fix(guesttools): harden Windows clipboard locking, DIB/PNG handling, and echo prevention --- internal/guesttools/clipboard_agent_test.go | 290 ++++++++++ internal/guesttools/clipboard_other.go | 32 +- internal/guesttools/clipboard_test.go | 348 ++++++++++++ internal/guesttools/clipboard_windows.go | 514 ++++++++++++------ internal/guesttools/clipboard_windows_test.go | 97 ++++ internal/guesttools/dib.go | 89 ++- internal/guesttools/image.go | 205 ++++--- internal/guesttools/server.go | 344 ++++++------ 8 files changed, 1491 insertions(+), 428 deletions(-) create mode 100644 internal/guesttools/clipboard_agent_test.go create mode 100644 internal/guesttools/clipboard_test.go create mode 100644 internal/guesttools/clipboard_windows_test.go diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go new file mode 100644 index 0000000..666e80c --- /dev/null +++ b/internal/guesttools/clipboard_agent_test.go @@ -0,0 +1,290 @@ +package guesttools + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestGuestAgentClipboardScript(t *testing.T) { + sh, err := exec.LookPath("sh") + if err != nil { + sh = "C:/Program Files/Git/bin/sh.exe" + if _, err := os.Stat(sh); err != nil { + t.Skip("POSIX sh is unavailable") + } + } + agent := string(GuestAgentScript()) + start := strings.Index(agent, "read_local_clipboard() {") + end := strings.Index(agent, "sync_files() {") + if start < 0 || end <= start || !strings.Contains(agent, "agent_version\\\":6") { + t.Fatal("missing generated clipboard code or agent version 6") + } + if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) { + t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u") + } + + for _, name := range []string{ + "failed_png", "failed_text", "reencoded_png", "guest_changes_during_get", + "conflict", "conflict_skipped_host", "oversized", "disabled_upload", "post_error", + "guest_only_after_switch", "cold_guest_only", "cold_304", "empty_text_and_png_fallback", + } { + t.Run(name, func(t *testing.T) { + tmp := t.TempDir() + script := filepath.Join(tmp, "clipboard-test.sh") + code := "set -eu\n" + agent[start:end] + clipboardShellFixture + if err := os.WriteFile(script, []byte(code), 0o600); err != nil { + t.Fatal(err) + } + cmd := exec.Command(sh, script, name) + cmd.Dir = tmp + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("clipboard script: %v\n%s", err, out) + } + }) + } +} + +const clipboardShellFixture = ` +PATH="/usr/bin:/bin:$PATH" +TMP_DIR=. +INJECT_LOCK=./injecting +REIMS_HOST_URL=http://stub +REIMS_TOKEN=token +printf A > local_value +: > calls +local_info="Unicode text" +flags="" +get_code=200 +get_hash=B +get_seq=8 +get_kind=text +get_value=B +post_code=200 +post_hash=C +post_seq=9 +check_post_base=0 + +hash_file() { cat "$1"; } +hash_png_file() { printf 'png:'; cat "$1"; } +pbpaste() { cat local_value; } +pbcopy() { + [ "$flags" != fail ] || return 1 + cat > local_value +} +osascript() { + case "$2" in + 'clipboard info') + if [ -f reencoded ]; then + printf 'PNGf\n' + else + printf '%s\n' "$local_info" + fi + ;; + 'set fp to open for access'*) + case "$6" in + *PNGf*) + [ -f reencoded ] || return 1 + cat local_value > ./clip_in + ;; + *TIFF*) printf 'tiff' > ./clip_in.tiff ;; + esac + ;; + 'set the clipboard'*) + [ "$flags" != fail ] || return 1 + printf 'B-reencoded' > local_value + : > reencoded + ;; + esac +} +sips() { printf 'tiff-converted' > "$6"; } +curl() { + method=GET + headers="" + output="" + base="" + body="" + url="" + while [ "$#" -gt 0 ]; do + case "$1" in + -X) method="$2"; shift ;; + -D) headers="$2"; shift ;; + -o) output="$2"; shift ;; + --data-binary) body="${2#@}"; shift ;; + -H) + case "$2" in + 'X-Clip-Base-Seq: '*) base="$2" ;; + esac + shift + ;; + http://*) url="$1" ;; + esac + shift + done + if [ "$method" = POST ]; then + printf '%s %s\n' "$method" "$base" >> calls + if [ "$check_post_base" = 1 ] && [ "$get_code" != 204 ] && [ "$base" != "X-Clip-Base-Seq: $get_seq" ]; then + printf 'X-Clip-Seq: %s\r\n' "$get_seq" > "$headers" + printf '409' + return + fi + if [ "$post_code" = 200 ]; then + cat "$body" > host_value + fi + printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\n' "$post_hash" "$post_seq" > "$headers" + printf '%s' "$post_code" + else + printf '%s %s\n' "$method" "$url" >> calls + printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers" + printf '%s' "$get_value" > "$output" + if [ "$flags" = guest_change ]; then + printf C > local_value + fi + printf '%s' "$get_code" + fi +} +expect() { + if [ "$1" != "$2" ]; then + printf 'expected <%s>, got <%s>\n' "$2" "$1" >&2 + cat calls >&2 + exit 1 + fi +} +methods() { awk '{print $1}' calls | paste -sd ',' -; } + +case "$1" in + failed_png|failed_text) + [ "$1" != failed_png ] || get_kind=png + last_local_hash=A + last_server_hash=A + last_server_seq=7 + flags=fail + sync_clipboard + sync_clipboard + expect "$(methods)" GET,GET + expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/A/7/A + ;; + reencoded_png) + get_kind=png + get_hash=png:B + sync_clipboard + expect "$last_local_hash/$last_server_hash/$last_server_seq" png:B-reencoded/png:B/8 + get_code=304 + sync_clipboard + expect "$(methods)" GET,GET + grep -F 'since=png:B&' calls + ;; + guest_changes_during_get) + last_local_hash=A + last_server_hash=A + last_server_seq=7 + flags=guest_change + check_post_base=1 + sync_clipboard + expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/A/8/C + flags="" + sync_clipboard + expect "$(methods)" GET,POST + grep -Fx 'POST X-Clip-Base-Seq: 8' calls + expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)/$(cat host_value)" C/C/9/C/C + ;; + conflict|conflict_skipped_host|oversized|disabled_upload|post_error) + last_local_hash=old + last_server_hash=old-remote + last_server_seq=7 + case "$1" in + conflict) post_code=409 ;; + conflict_skipped_host) + get_code=304 + get_hash="" + check_post_base=1 + printf host-image > host_value + ;; + oversized) post_code=413 ;; + disabled_upload) post_code=204; get_code=304; get_hash=old-remote; get_seq=7 ;; + post_error) post_code=500 ;; + esac + sync_clipboard + expect "$(methods)" POST,GET + grep -Fx 'POST X-Clip-Base-Seq: 7' calls + grep -F 'since=old-remote&' calls + case "$1" in + conflict_skipped_host) + expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/old-remote/8/A + sync_clipboard + expect "$(methods)" POST,GET,GET + expect "$(cat host_value)" host-image + printf C > local_value + sync_clipboard + expect "$(methods)" POST,GET,GET,POST + grep -Fx 'POST X-Clip-Base-Seq: 8' calls + expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat host_value)" C/C/9/C + ;; + disabled_upload) + expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/old-remote/7/A + ;; + *) + expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" B/B/8/B + ;; + esac + if [ "$1" = oversized ]; then + get_code=304 + sync_clipboard + expect "$(methods)" POST,GET,GET + fi + ;; + guest_only_after_switch) + sync_clipboard + expect "$last_local_hash/$last_server_hash/$last_server_seq" B/B/8 + check_post_base=1 + get_code=204 + get_seq=9 + post_seq=10 + printf 'new host' > host_value + printf C > local_value + sync_clipboard + expect "$(methods)" GET,POST + grep -Fx 'POST X-Clip-Base-Seq: 8' calls + expect "$(cat host_value)" C + sync_clipboard + expect "$(methods)" GET,POST,GET + expect "$last_local_hash/$last_server_hash/$last_server_seq" C/C/ + ;; + cold_guest_only|cold_304) + get_code=204 + expected_base="POST " + if [ "$1" = cold_304 ]; then + get_code=304 + get_hash="" + expected_base="POST X-Clip-Base-Seq: 8" + fi + sync_clipboard + expect "$last_local_hash/$last_server_hash" A/ + printf C > local_value + sync_clipboard + expect "$(methods)" GET,POST + grep -Fx "$expected_base" calls + expect "$last_local_hash/$last_server_hash/$last_server_seq" C/C/9 + if [ "$1" = cold_guest_only ]; then + check_post_base=1 + get_seq=10 + post_seq=11 + post_hash=D + printf 'new host' > host_value + printf D > local_value + sync_clipboard + expect "$(methods)" GET,POST,POST + grep -Fx 'POST X-Clip-Base-Seq: 9' calls + expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat host_value)" D/D/11/D + fi + ;; + empty_text_and_png_fallback) + local_info="Unicode text, PNGf, TIFF" + : > local_value + expect "$(read_local_clipboard ./clip_in)" png + expect "$(cat ./clip_in)" tiff-converted + ;; +esac +` diff --git a/internal/guesttools/clipboard_other.go b/internal/guesttools/clipboard_other.go index 4462055..2c177f4 100644 --- a/internal/guesttools/clipboard_other.go +++ b/internal/guesttools/clipboard_other.go @@ -27,27 +27,39 @@ func (c *OSClipboard) ReadText() (string, error) { } func (c *OSClipboard) WriteText(text string) error { - c.mu.Lock() - defer c.mu.Unlock() - c.kind = ClipText - c.data = []byte(text) - c.seq++ - return nil + _, err := c.writeClipboard(ClipPayload{Kind: ClipText, Data: []byte(text)}, nil) + return err } func (c *OSClipboard) Read() (ClipPayload, error) { + payload, _, err := c.readClipboard(true) + return payload, err +} + +func (c *OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) { c.mu.Lock() defer c.mu.Unlock() + if !wantImage && c.kind == ClipPNG { + return ClipPayload{Kind: ClipEmpty}, c.seq, nil + } cp := make([]byte, len(c.data)) copy(cp, c.data) - return ClipPayload{Kind: c.kind, Data: cp}, nil + return ClipPayload{Kind: c.kind, Data: cp}, c.seq, nil } func (c *OSClipboard) WritePNG(pngBytes []byte) error { + _, err := c.writeClipboard(ClipPayload{Kind: ClipPNG, Data: pngBytes}, nil) + return err +} + +func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (uint32, error) { c.mu.Lock() defer c.mu.Unlock() - c.kind = ClipPNG - c.data = append([]byte(nil), pngBytes...) + if baseSeq != nil && c.seq != *baseSeq { + return c.seq, errClipboardConflict + } + c.kind = payload.Kind + c.data = append([]byte(nil), payload.Data...) c.seq++ - return nil + return c.seq, nil } diff --git a/internal/guesttools/clipboard_test.go b/internal/guesttools/clipboard_test.go new file mode 100644 index 0000000..17af8e9 --- /dev/null +++ b/internal/guesttools/clipboard_test.go @@ -0,0 +1,348 @@ +package guesttools + +import ( + "bytes" + "encoding/binary" + "errors" + "image/color" + "image/png" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +func TestTrimPNG(t *testing.T) { + valid := makeSamplePNG(t, 1, 2, 3) + badLength := bytes.Clone(valid) + binary.BigEndian.PutUint32(badLength[8:12], 0xffffffff) + for _, tc := range []struct { + name string + raw []byte + ok bool + }{ + {"PNG", valid, true}, + {"padding", append(bytes.Clone(valid), make([]byte, 16)...), true}, + {"truncated", valid[:len(valid)-1], false}, + {"missing IEND", valid[:len(valid)-12], false}, + {"illegal chunk length", badLength, false}, + {"non-PNG", []byte("not an image"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + got, ok := TrimPNG(tc.raw) + if ok != tc.ok || (ok && !bytes.Equal(got, valid)) || (!ok && got != nil) { + t.Fatalf("TrimPNG returned %d bytes, ok=%t", len(got), ok) + } + }) + } +} + +func TestDecodeDIBFormats(t *testing.T) { + le := binary.LittleEndian + for _, tc := range []struct { + name string + header int + depth uint16 + masks []uint32 + palette []byte + topDown bool + pixels []byte + want []color.NRGBA + }{ + {"24-bit RGB bottom-up", 40, 24, nil, nil, false, + []byte{0, 0, 255, 0, 0, 255, 0, 0}, + []color.NRGBA{{G: 255, A: 255}, {R: 255, A: 255}}}, + {"32-bit RGB zero alpha and optional palette", 40, 32, nil, []byte{4, 9, 14, 0}, false, + []byte{100, 20, 30, 0}, []color.NRGBA{{R: 30, G: 20, B: 100, A: 255}}}, + {"32-bit RGB with alpha", 40, 32, nil, nil, false, + []byte{100, 20, 30, 70}, []color.NRGBA{{R: 30, G: 20, B: 100, A: 70}}}, + {"swapped red and blue with external masks", 40, 32, []uint32{0xff, 0xff00, 0xff0000}, nil, false, + []byte{34, 56, 78, 12}, []color.NRGBA{{R: 34, G: 56, B: 78, A: 255}}}, + {"V4 explicit zero alpha", 108, 32, []uint32{0xff, 0xff00, 0xff0000, 0xff000000}, nil, false, + []byte{34, 56, 78, 0}, []color.NRGBA{{R: 34, G: 56, B: 78}}}, + {"V5 explicit zero alpha", 124, 32, []uint32{0xff0000, 0xff00, 0xff, 0xff000000}, nil, false, + []byte{34, 56, 78, 0}, []color.NRGBA{{R: 78, G: 56, B: 34}}}, + {"16-bit RGB565 top-down", 40, 16, []uint32{0xf800, 0x07e0, 0x1f}, nil, true, + []byte{0x00, 0xfc, 0, 0, 0x1f, 0, 0, 0}, + []color.NRGBA{{R: 255, G: 130, A: 255}, {B: 255, A: 255}}}, + } { + t.Run(tc.name, func(t *testing.T) { + header := make([]byte, tc.header) + height := int32(len(tc.want)) + if tc.topDown { + height = -height + } + le.PutUint32(header, uint32(tc.header)) + le.PutUint32(header[4:], 1) + le.PutUint32(header[8:], uint32(height)) + le.PutUint16(header[12:], 1) + le.PutUint16(header[14:], tc.depth) + le.PutUint32(header[32:], uint32(len(tc.palette)/4)) + if len(tc.masks) > 0 { + le.PutUint32(header[16:], 3) + if tc.header == 40 { + header = append(header, make([]byte, len(tc.masks)*4)...) + } + for i, mask := range tc.masks { + le.PutUint32(header[40+4*i:], mask) + } + } + data, err := DecodeDIBToPNG(append(append(header, tc.palette...), tc.pixels...)) + if err != nil { + t.Fatal(err) + } + img, err := png.Decode(bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + for y, want := range tc.want { + if got := color.NRGBAModel.Convert(img.At(0, y)); got != want { + t.Errorf("pixel y=%d: got %+v, want %+v", y, got, want) + } + } + }) + } +} + +func clipboardRequest(t *testing.T, srv *Server, method, query, contentType, baseSeq string, body []byte) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, "/v1/clipboard"+query, bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer clipboard-test-token") + req.Header.Set("Content-Type", contentType) + req.Header.Set("X-Clip-Base-Seq", baseSeq) + resp := httptest.NewRecorder() + srv.handleClipboard(resp, req) + return resp +} + +func newClipboardTestServer(clip Clipboard) *Server { + srv := NewServer(clip) + srv.RegisterVM(VMConfig{VMName: "clipboard-test", Token: "clipboard-test-token"}) + return srv +} + +func TestClipboardPOSTSequenceConflict(t *testing.T) { + oldPNG := makeSamplePNG(t, 255, 0, 0) + newPNG := makeSamplePNG(t, 0, 255, 0) + clip := &memClipboard{kind: ClipPNG, data: oldPNG, seq: 7} + srv := newClipboardTestServer(clip) + get := clipboardRequest(t, srv, http.MethodGet, "?accept=image", "", "", nil) + if get.Code != http.StatusOK || get.Header().Get("X-Clip-Seq") != "7" { + t.Fatalf("initial GET: %d %v", get.Code, get.Header()) + } + if err := clip.WritePNG(newPNG); err != nil { + t.Fatal(err) + } + stale := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "7", oldPNG) + if stale.Code != http.StatusConflict || stale.Header().Get("X-Clip-Seq") != "8" { + t.Fatalf("stale POST: %d %v", stale.Code, stale.Header()) + } + got, _ := clip.Read() + if got.Kind != ClipPNG || !bytes.Equal(got.Data, newPNG) { + t.Fatal("stale POST changed the new host image") + } + for _, tc := range []struct{ base, seq string }{{"8", "9"}, {"", "10"}} { + post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", tc.base, []byte(tc.seq)) + if post.Code != http.StatusOK || post.Header().Get("X-Clip-Seq") != tc.seq { + t.Fatalf("POST with base %q: %d %v", tc.base, post.Code, post.Header()) + } + poll := clipboardRequest(t, srv, http.MethodGet, "?since="+post.Header().Get("X-Clip-Hash"), "", "", nil) + if poll.Code != http.StatusNotModified || poll.Header().Get("X-Clip-Seq") != tc.seq { + t.Fatalf("unchanged GET: %d %v", poll.Code, poll.Header()) + } + } +} + +func TestClipboardGuestToHostIgnoresStaleBase(t *testing.T) { + for _, name := range []string{"after switching from bidirectional", "guest to host from startup"} { + t.Run(name, func(t *testing.T) { + clip := &memClipboard{kind: ClipText, data: []byte("initial host"), seq: 7} + srv := newClipboardTestServer(clip) + policy := DefaultClipboardPolicy() + policy.Direction = ClipboardGuestToHost + if name == "guest to host from startup" { + srv.SetGlobalClipboardPolicy(policy) + } + + initial := clipboardRequest(t, srv, http.MethodGet, "", "", "", nil) + wantBase := "7" + if name == "guest to host from startup" { + if initial.Code != http.StatusNoContent { + t.Fatalf("initial GET: %d", initial.Code) + } + initial = clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "", []byte("first guest")) + wantBase = "8" + } else { + srv.SetGlobalClipboardPolicy(policy) + } + base := initial.Header().Get("X-Clip-Seq") + if initial.Code != http.StatusOK || base != wantBase { + t.Fatalf("initial sync: %d %v", initial.Code, initial.Header()) + } + if err := clip.WriteText("new host"); err != nil { + t.Fatal(err) + } + post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", base, []byte("new guest")) + if post.Code != http.StatusOK || post.Header().Get("X-Clip-Seq") != strconv.FormatUint(uint64(clip.SequenceNumber()), 10) { + t.Fatalf("POST after host copied: %d %v", post.Code, post.Header()) + } + if got, _ := clip.ReadText(); got != "new guest" { + t.Fatalf("host clipboard: %q", got) + } + }) + } +} + +type clipboardReadFailure struct { + *memClipboard + writeBase *uint32 + writeErr error +} + +func (c *clipboardReadFailure) readClipboard(bool) (ClipPayload, uint32, error) { + return ClipPayload{}, 0, errors.New("OpenClipboard failed") +} + +func (c *clipboardReadFailure) writeClipboard(payload ClipPayload, baseSeq *uint32) (uint32, error) { + c.writeBase = baseSeq + if c.writeErr != nil { + return c.SequenceNumber(), c.writeErr + } + err := c.WriteText(string(payload.Data)) + return c.SequenceNumber(), err +} + +func TestClipboardPOSTUsesAtomicWriteAfterReadFailure(t *testing.T) { + for _, tc := range []struct { + name string + writeErr error + wantStatus int + wantSeq string + wantErrors uint64 + }{ + {"write succeeds", nil, http.StatusOK, "8", 0}, + {"write also fails", errors.New("OpenClipboard failed on write"), http.StatusInternalServerError, "", 1}, + {"wrapped conflict", errors.Join(errClipboardConflict, errors.New("CloseClipboard failed")), http.StatusConflict, "7", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + clip := &clipboardReadFailure{memClipboard: &memClipboard{seq: 7}, writeErr: tc.writeErr} + srv := newClipboardTestServer(clip) + post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "7", []byte("guest")) + if post.Code != tc.wantStatus || post.Header().Get("X-Clip-Seq") != tc.wantSeq { + t.Fatalf("POST: got %d %v %q, want status %d and seq %q", post.Code, post.Header(), post.Body, tc.wantStatus, tc.wantSeq) + } + if clip.writeBase == nil || *clip.writeBase != 7 { + t.Fatalf("atomic write did not receive base 7") + } + if got := srv.ClipboardDiagnostics().ErrorCount; got != tc.wantErrors { + t.Fatalf("clipboard errors: got %d, want %d", got, tc.wantErrors) + } + }) + } +} + +type clipboardReadHook struct { + *memClipboard + once sync.Once + afterRead func() +} + +func (c *clipboardReadHook) Read() (ClipPayload, error) { + payload, err := c.memClipboard.Read() + c.once.Do(c.afterRead) + return payload, err +} + +func TestClipboardGETDoesNotLoseWakeup(t *testing.T) { + clip := &clipboardReadHook{memClipboard: &memClipboard{kind: ClipText, data: []byte("old"), seq: 1}} + srv := newClipboardTestServer(clip) + clip.afterRead = func() { + _ = clip.WriteText("new") + srv.NotifyClipboardChanged() + } + start := time.Now() + resp := clipboardRequest(t, srv, http.MethodGet, "?wait=5&since="+textHash("old"), "", "", nil) + if resp.Code != http.StatusOK || resp.Body.String() != "new" || resp.Header().Get("X-Clip-Seq") != "2" { + t.Fatalf("GET got %d %v %q", resp.Code, resp.Header(), resp.Body) + } + if elapsed := time.Since(start); elapsed >= 4*time.Second { + t.Fatalf("GET returned only after waiting %s", elapsed) + } +} + +func TestClipboardGETRechecksPolicyAfterWake(t *testing.T) { + png := makeSamplePNG(t, 1, 2, 3) + payload := ClipPayload{Kind: ClipPNG, Data: png} + clip := &clipboardReadHook{memClipboard: &memClipboard{kind: payload.Kind, data: payload.Data}} + srv := newClipboardTestServer(clip) + clip.afterRead = func() { + policy := DefaultClipboardPolicy() + policy.Direction = ClipboardGuestToHost + srv.SetGlobalClipboardPolicy(policy) + _ = clip.WritePNG(makeSamplePNG(t, 4, 5, 6)) + } + resp := clipboardRequest(t, srv, http.MethodGet, "?accept=image&wait=1&since="+payloadHash(payload), "", "", nil) + if resp.Code != http.StatusNoContent { + t.Fatalf("GET after switching direction: %d, body %q", resp.Code, resp.Body) + } +} + +func TestClipboardGETSkipsUnavailablePayloads(t *testing.T) { + png := makeSamplePNG(t, 1, 2, 3) + for i, tc := range []struct { + name string + kind ClipKind + query string + syncImages bool + maxBytes int + }{ + {"too large", ClipPNG, "?accept=image", true, len(png) - 1}, + {"images disabled", ClipPNG, "?accept=image", false, len(png)}, + {"legacy text request", ClipPNG, "", true, len(png)}, + {"unsupported", ClipEmpty, "?accept=image", true, len(png)}, + } { + t.Run(tc.name, func(t *testing.T) { + clip := &memClipboard{kind: tc.kind, seq: uint32(i)} + if tc.kind == ClipPNG { + clip.data = png + } + srv := newClipboardTestServer(clip) + policy := DefaultClipboardPolicy() + policy.SyncImages = tc.syncImages + policy.MaxImageBytes = tc.maxBytes + srv.SetGlobalClipboardPolicy(policy) + resp := clipboardRequest(t, srv, http.MethodGet, tc.query, "", "", nil) + if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Seq") != strconv.Itoa(i) { + t.Fatalf("skipped GET: %d %v, %d bytes", resp.Code, resp.Header(), resp.Body.Len()) + } + _ = clip.WriteText("next item") + resp = clipboardRequest(t, srv, http.MethodGet, tc.query, "", "", nil) + if resp.Code != http.StatusOK || resp.Body.String() != "next item" { + t.Fatalf("subsequent GET: %d %q", resp.Code, resp.Body) + } + }) + } +} + +func TestClipboardPOSTTextLimitAndEmptyOverwrite(t *testing.T) { + png := makeSamplePNG(t, 1, 2, 3) + clip := &memClipboard{kind: ClipPNG, data: png} + srv := newClipboardTestServer(clip) + policy := DefaultClipboardPolicy() + policy.MaxImageBytes = 16 + srv.SetGlobalClipboardPolicy(policy) + img := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", png) + if img.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("oversized PNG POST: got %d", img.Code) + } + for _, value := range []string{"", strings.Repeat("文本", 100)} { + resp := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "", []byte(value)) + got, _ := clip.Read() + if resp.Code != http.StatusOK || got.Kind != ClipText || string(got.Data) != value { + t.Fatalf("text POST (%d bytes): got status %d and payload %+v", len(value), resp.Code, got) + } + } +} diff --git a/internal/guesttools/clipboard_windows.go b/internal/guesttools/clipboard_windows.go index dc9aa66..6dbf86d 100644 --- a/internal/guesttools/clipboard_windows.go +++ b/internal/guesttools/clipboard_windows.go @@ -3,7 +3,9 @@ package guesttools import ( + "errors" "fmt" + "runtime" "strings" "sync" "syscall" @@ -14,6 +16,11 @@ import ( var ( user32 = syscall.NewLazyDLL("user32.dll") + procCreateWindowExW = user32.NewProc("CreateWindowExW") + procDestroyWindow = user32.NewProc("DestroyWindow") + procGetMessageW = user32.NewProc("GetMessageW") + procDispatchMessageW = user32.NewProc("DispatchMessageW") + procPostMessageW = user32.NewProc("PostMessageW") procOpenClipboard = user32.NewProc("OpenClipboard") procCloseClipboard = user32.NewProc("CloseClipboard") procEmptyClipboard = user32.NewProc("EmptyClipboard") @@ -33,26 +40,122 @@ var ( pngFormatOnce sync.Once pngFormatID uintptr + pngFormatErr error + + clipboardWorkerOnce sync.Once + clipOwnerHWND uintptr + clipboardJobs = make(chan func(uintptr)) + clipboardWorkerDone = make(chan struct{}) + clipboardWorkerErr error ) const ( cfDIB = 8 cfUnicodeText = 13 gmemMoveable = 0x0002 + hwndMessage = ^uintptr(2) + wmClipJob = 0x8000 // WM_APP + maxDIBBytes = 128 << 20 ) type OSClipboard struct{} -func registerPNGFormat() uintptr { - pngFormatOnce.Do(func() { - p, err := syscall.UTF16PtrFromString("PNG") - if err != nil { +type clipboardWindowMessage struct { + hwnd uintptr + message uint32 + wParam uintptr + lParam uintptr + time uint32 + x, y int32 + lPrivate uint32 +} + +func runClipboardWorker(ready chan<- struct{}) { + runtime.LockOSThread() + defer close(clipboardWorkerDone) + class := [...]uint16{'S', 'T', 'A', 'T', 'I', 'C', 0} + hwnd, _, err := procCreateWindowExW.Call(0, uintptr(unsafe.Pointer(&class[0])), 0, 0, + 0, 0, 0, 0, hwndMessage, 0, 0, 0) + clipOwnerHWND = hwnd + close(ready) + if hwnd == 0 { + clipboardWorkerErr = fmt.Errorf("CreateWindowExW: %w", err) + return + } + defer procDestroyWindow.Call(hwnd) + + // Keep dispatching messages such as WM_DESTROYCLIPBOARD while idle. + for { + var msg clipboardWindowMessage + result, _, err := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + switch int32(result) { + case -1: + clipboardWorkerErr = fmt.Errorf("GetMessageW: %w", err) + return + case 0: + clipboardWorkerErr = errors.New("clipboard worker window quit") return } - id, _, _ := procRegisterClipboardFormatW.Call(uintptr(unsafe.Pointer(p))) - pngFormatID = id + if msg.hwnd == hwnd && msg.message == wmClipJob { + job := <-clipboardJobs + job(hwnd) + } else { + procDispatchMessageW.Call(uintptr(unsafe.Pointer(&msg))) + } + } +} + +func onClipboardThread(job func(uintptr) error) error { + clipboardWorkerOnce.Do(func() { + ready := make(chan struct{}) + go runClipboardWorker(ready) + <-ready }) - return pngFormatID + if clipOwnerHWND == 0 { + <-clipboardWorkerDone + return clipboardWorkerErr + } + if ok, _, err := procPostMessageW.Call(clipOwnerHWND, wmClipJob, 0, 0); ok == 0 { + return fmt.Errorf("PostMessageW: %w", err) + } + result := make(chan error, 1) + select { + case clipboardJobs <- func(hwnd uintptr) { result <- job(hwnd) }: + return <-result + case <-clipboardWorkerDone: + return clipboardWorkerErr + } +} + +func withOpenClipboard(hwnd uintptr, job func() error) (err error) { + for attempt := 0; ; attempt++ { + ok, _, openErr := procOpenClipboard.Call(hwnd) + if ok != 0 { + break + } + if attempt == 4 { + return fmt.Errorf("OpenClipboard: %w", openErr) + } + time.Sleep(15 * time.Millisecond) + } + defer func() { + if ok, _, closeErr := procCloseClipboard.Call(); ok == 0 { + err = errors.Join(err, fmt.Errorf("CloseClipboard: %w", closeErr)) + } + }() + return job() +} + +func registerPNGFormat() (uintptr, error) { + pngFormatOnce.Do(func() { + name := [...]uint16{'P', 'N', 'G', 0} + id, _, err := procRegisterClipboardFormatW.Call(uintptr(unsafe.Pointer(&name[0]))) + pngFormatID = id + if id == 0 { + pngFormatErr = fmt.Errorf("RegisterClipboardFormatW: %w", err) + } + }) + return pngFormatID, pngFormatErr } func (OSClipboard) SequenceNumber() uint32 { @@ -60,213 +163,264 @@ func (OSClipboard) SequenceNumber() uint32 { return uint32(r) } -func openClipboardWithRetry() error { - var lastErr error - for i := 0; i < 5; i++ { - r, _, err := procOpenClipboard.Call(0) - if r != 0 { - return nil - } - lastErr = err - time.Sleep(15 * time.Millisecond) +func unlockClipboardMem(h uintptr) error { + // A zero return with no error means the last lock was released. + if ok, _, err := procGlobalUnlock.Call(h); ok == 0 && err != syscall.Errno(0) { + return fmt.Errorf("GlobalUnlock: %w", err) } - return fmt.Errorf("OpenClipboard: %w", lastErr) + return nil } -func readClipboardRawLocked(format uintptr, maxBytes int) ([]byte, error) { - h, _, err := procGetClipboardData.Call(format) +func readClipboardImageLocked(format uintptr, maxBytes int) ([]byte, error) { + h, _, _ := procGetClipboardData.Call(format) if h == 0 { - return nil, fmt.Errorf("GetClipboardData(%d): %w", format, err) - } - sz, _, _ := procGlobalSize.Call(h) - if sz == 0 { return nil, nil } - if int(sz) > maxBytes { - return nil, fmt.Errorf("clipboard data (%d bytes) exceeds limit", sz) + size, _, _ := procGlobalSize.Call(h) + if size == 0 || size > uintptr(maxBytes) { + return nil, nil + } + ptr, _, _ := procGlobalLock.Call(h) + if ptr == 0 { + return nil, nil + } + buf := make([]byte, int(size)) + procRtlMoveMem.Call(uintptr(unsafe.Pointer(&buf[0])), ptr, size) + return buf, unlockClipboardMem(h) +} + +func readUnicodeTextLocked() ([]uint16, error) { + h, _, err := procGetClipboardData.Call(cfUnicodeText) + if h == 0 { + return nil, fmt.Errorf("GetClipboardData: %w", err) + } + size, _, _ := procGlobalSize.Call(h) + if size < 2 { + return nil, nil } ptr, _, err := procGlobalLock.Call(h) if ptr == 0 { return nil, fmt.Errorf("GlobalLock: %w", err) } - defer procGlobalUnlock.Call(h) - - buf := make([]byte, int(sz)) - procRtlMoveMem.Call(uintptr(unsafe.Pointer(&buf[0])), ptr, sz) - return buf, nil + // UTF-16 CRLF takes up to four bytes per normalized UTF-8 byte. + words := make([]uint16, min(size/2, MaxClipboardBytes*2+1)) + procRtlMoveMem.Call(uintptr(unsafe.Pointer(&words[0])), ptr, uintptr(len(words)*2)) + return words, unlockClipboardMem(h) } -func setClipboardRawLocked(format uintptr, data []byte) error { - if len(data) == 0 { - return nil - } - hMem, _, err := procGlobalAlloc.Call(gmemMoveable, uintptr(len(data))) - if hMem == 0 { - return fmt.Errorf("GlobalAlloc: %w", err) - } - ptr, _, err := procGlobalLock.Call(hMem) - if ptr == 0 { - procGlobalFree.Call(hMem) - return fmt.Errorf("GlobalLock: %w", err) - } - procRtlMoveMem.Call(ptr, uintptr(unsafe.Pointer(&data[0])), uintptr(len(data))) - procGlobalUnlock.Call(hMem) - - if r, _, err := procSetClipboardData.Call(format, hMem); r == 0 { - procGlobalFree.Call(hMem) - return fmt.Errorf("SetClipboardData(%d): %w", format, err) - } - return nil -} - -// ReadText reads UTF-8 text from the Windows clipboard, normalizing CRLF to LF -// for macOS guests. Returns ("", nil) when the clipboard has no text. -func (OSClipboard) ReadText() (string, error) { - avail, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText) - if avail == 0 { - return "", nil - } - if err := openClipboardWithRetry(); err != nil { - return "", err - } - defer procCloseClipboard.Call() - return readUnicodeTextLocked() -} - -func readUnicodeTextLocked() (string, error) { - h, _, err := procGetClipboardData.Call(cfUnicodeText) - if h == 0 { - return "", fmt.Errorf("GetClipboardData: %w", err) - } - sz, _, _ := procGlobalSize.Call(h) - if sz < 2 { - return "", nil - } - ptr, _, err := procGlobalLock.Call(h) - if ptr == 0 { - return "", fmt.Errorf("GlobalLock: %w", err) - } - defer procGlobalUnlock.Call(h) - - maxWords := int(sz / 2) - if maxWords > MaxClipboardBytes/2 { - maxWords = MaxClipboardBytes / 2 - } - words := make([]uint16, maxWords) - procRtlMoveMem.Call(uintptr(unsafe.Pointer(&words[0])), ptr, uintptr(maxWords*2)) +func decodeClipboardText(words []uint16) string { n := 0 for n < len(words) && words[n] != 0 { n++ } - s := string(utf16.Decode(words[:n])) - return strings.ReplaceAll(s, "\r\n", "\n"), nil + return strings.ReplaceAll(string(utf16.Decode(words[:n])), "\r\n", "\n") } -// Read inspects the Windows clipboard and returns either UTF-8 text or a PNG image. -func (OSClipboard) Read() (ClipPayload, error) { - hasText, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText) - pngFmt := registerPNGFormat() - var hasPNG uintptr - if pngFmt != 0 { - hasPNG, _, _ = procIsClipboardFormatAvail.Call(pngFmt) +// ReadText reads UTF-8 text from the Windows clipboard, normalizing CRLF to LF. +func (OSClipboard) ReadText() (string, error) { + var words []uint16 + err := onClipboardThread(func(hwnd uintptr) error { + return withOpenClipboard(hwnd, func() error { + if avail, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText); avail == 0 { + return nil + } + var err error + words, err = readUnicodeTextLocked() + return err + }) + }) + if err != nil { + return "", err } - hasDIB, _, _ := procIsClipboardFormatAvail.Call(cfDIB) - - if hasText == 0 && hasPNG == 0 && hasDIB == 0 { - return ClipPayload{Kind: ClipEmpty}, nil - } - if err := openClipboardWithRetry(); err != nil { - return ClipPayload{}, err - } - defer procCloseClipboard.Call() - - if hasText != 0 { - text, err := readUnicodeTextLocked() - if err != nil { - return ClipPayload{}, err - } - return ClipPayload{Kind: ClipText, Data: []byte(text)}, nil - } - if hasPNG != 0 { - if raw, err := readClipboardRawLocked(pngFmt, MaxClipboardBytes); err == nil && IsPNG(raw) { - return ClipPayload{Kind: ClipPNG, Data: raw}, nil - } - } - if hasDIB != 0 { - raw, err := readClipboardRawLocked(cfDIB, MaxClipboardBytes*4) - if err != nil { - return ClipPayload{}, err - } - pngBytes, err := DecodeDIBToPNG(raw) - if err != nil { - return ClipPayload{}, err - } - if len(pngBytes) > MaxClipboardBytes { - return ClipPayload{}, fmt.Errorf("encoded PNG (%d bytes) exceeds clipboard limit", len(pngBytes)) - } - return ClipPayload{Kind: ClipPNG, Data: pngBytes}, nil - } - return ClipPayload{Kind: ClipEmpty}, nil + return decodeClipboardText(words), nil } -// WriteText writes UTF-8 text to the Windows clipboard as CF_UNICODETEXT -// (normalizing bare LF to CRLF for Windows apps). -func (OSClipboard) WriteText(text string) error { - if len(text) > MaxClipboardBytes { - return fmt.Errorf("clipboard payload exceeds %d bytes", MaxClipboardBytes) - } - norm := strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\n", "\r\n") - u16 := utf16.Encode([]rune(norm)) - u16 = append(u16, 0) - byteLen := uintptr(len(u16) * 2) +type clipboardSnapshot struct { + text []uint16 + png []byte + dib []byte + kind ClipKind +} - if err := openClipboardWithRetry(); err != nil { - return err +func (snap clipboardSnapshot) payload() ClipPayload { + if snap.kind == ClipText && len(snap.text) > 0 && snap.text[0] != 0 { + return ClipPayload{Kind: ClipText, Data: []byte(decodeClipboardText(snap.text))} } - defer procCloseClipboard.Call() + if data, ok := TrimPNG(snap.png); ok { + return ClipPayload{Kind: ClipPNG, Data: data} + } + if len(snap.dib) > 0 { + if data, err := DecodeDIBToPNG(snap.dib); err == nil && len(data) <= MaxClipboardBytes { + return ClipPayload{Kind: ClipPNG, Data: data} + } + } + return ClipPayload{Kind: snap.kind} +} - if r, _, err := procEmptyClipboard.Call(); r == 0 { - return fmt.Errorf("EmptyClipboard: %w", err) +func (snap *clipboardSnapshot) readImagesLocked(wantImage bool, pngFormat uintptr, available func(uintptr) bool, readImage func(uintptr, int) ([]byte, error)) error { + if pngFormat != 0 && available(pngFormat) { + snap.kind = ClipEmpty + if !wantImage { + return nil + } + var err error + snap.png, err = readImage(pngFormat, MaxClipboardBytes) + if err != nil { + return err + } } - hMem, _, err := procGlobalAlloc.Call(gmemMoveable, byteLen) - if hMem == 0 { - return fmt.Errorf("GlobalAlloc: %w", err) - } - ptr, _, err := procGlobalLock.Call(hMem) - if ptr == 0 { - procGlobalFree.Call(hMem) - return fmt.Errorf("GlobalLock: %w", err) - } - procRtlMoveMem.Call(ptr, uintptr(unsafe.Pointer(&u16[0])), byteLen) - procGlobalUnlock.Call(hMem) - - if r, _, err := procSetClipboardData.Call(cfUnicodeText, hMem); r == 0 { - procGlobalFree.Call(hMem) - return fmt.Errorf("SetClipboardData: %w", err) + // Keep the DIB from this snapshot in case the PNG fails validation after close. + if available(cfDIB) { + snap.kind = ClipEmpty + if wantImage { + var err error + snap.dib, err = readImage(cfDIB, maxDIBBytes) + return err + } } return nil } -// WritePNG writes a PNG image to the Windows clipboard in both native "PNG" -// and universal 32-bit CF_DIB formats. -func (OSClipboard) WritePNG(pngBytes []byte) error { - if len(pngBytes) == 0 || len(pngBytes) > MaxClipboardBytes { - return fmt.Errorf("clipboard PNG size %d out of bounds", len(pngBytes)) +// Read inspects the Windows clipboard and returns either UTF-8 text or a PNG image. +func (c OSClipboard) Read() (ClipPayload, error) { + payload, _, err := c.readClipboard(true) + return payload, err +} + +func (c OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) { + pngFormat, _ := registerPNGFormat() + var snap clipboardSnapshot + var seq uint32 + err := onClipboardThread(func(hwnd uintptr) error { + return withOpenClipboard(hwnd, func() error { + defer func() { seq = c.SequenceNumber() }() + if avail, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText); avail != 0 { + var err error + snap.text, err = readUnicodeTextLocked() + if err != nil { + return err + } + snap.kind = ClipText + if len(snap.text) > 0 && snap.text[0] != 0 { + return nil + } + } + return snap.readImagesLocked(wantImage, pngFormat, func(format uintptr) bool { + avail, _, _ := procIsClipboardFormatAvail.Call(format) + return avail != 0 + }, readClipboardImageLocked) + }) + }) + if err != nil { + return ClipPayload{}, seq, err + } + return snap.payload(), seq, nil +} + +type clipboardMem struct { + format uintptr + handle uintptr +} + +func freeClipboardMem(h uintptr) error { + if result, _, err := procGlobalFree.Call(h); result != 0 { + return fmt.Errorf("GlobalFree: %w", err) } - dib, err := EncodePNGToDIB(pngBytes) - if err != nil { - return err + return nil +} + +func prepareClipboardMem(format, size uintptr, src unsafe.Pointer) (clipboardMem, error) { + h, _, err := procGlobalAlloc.Call(gmemMoveable, size) + if h == 0 { + return clipboardMem{}, fmt.Errorf("GlobalAlloc: %w", err) + } + ptr, _, err := procGlobalLock.Call(h) + if ptr == 0 { + return clipboardMem{}, errors.Join(fmt.Errorf("GlobalLock: %w", err), freeClipboardMem(h)) } - if err := openClipboardWithRetry(); err != nil { - return err + procRtlMoveMem.Call(ptr, uintptr(src), size) + if err := unlockClipboardMem(h); err != nil { + return clipboardMem{}, errors.Join(err, freeClipboardMem(h)) } - defer procCloseClipboard.Call() + return clipboardMem{format: format, handle: h}, nil +} + +// WriteText writes UTF-8 text as CF_UNICODETEXT, with CRLF for Windows apps. +func (c OSClipboard) WriteText(text string) error { + _, err := c.writeClipboard(ClipPayload{Kind: ClipText, Data: []byte(text)}, nil) + return err +} - if r, _, err := procEmptyClipboard.Call(); r == 0 { - return fmt.Errorf("EmptyClipboard: %w", err) +// WritePNG writes an image in both native "PNG" and 32-bit CF_DIB formats. +func (c OSClipboard) WritePNG(pngBytes []byte) error { + _, err := c.writeClipboard(ClipPayload{Kind: ClipPNG, Data: pngBytes}, nil) + return err +} + +func (c OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq uint32, err error) { + var mem []clipboardMem + defer func() { + for _, item := range mem { + if item.handle != 0 { + if freeErr := freeClipboardMem(item.handle); freeErr != nil { + err = errors.Join(err, freeErr) + } + } + } + }() + if len(payload.Data) > MaxClipboardBytes { + return 0, fmt.Errorf("clipboard payload exceeds %d bytes", MaxClipboardBytes) } - if pngFmt := registerPNGFormat(); pngFmt != 0 { - _ = setClipboardRawLocked(pngFmt, pngBytes) + if payload.Kind == ClipPNG { + dib, err := EncodePNGToDIB(payload.Data) + if err != nil { + return 0, err + } + format, err := registerPNGFormat() + if err != nil { + return 0, err + } + pngMem, err := prepareClipboardMem(format, uintptr(len(payload.Data)), unsafe.Pointer(&payload.Data[0])) + if err != nil { + return 0, err + } + mem = append(mem, pngMem) + dibMem, err := prepareClipboardMem(cfDIB, uintptr(len(dib)), unsafe.Pointer(&dib[0])) + if err != nil { + return 0, err + } + mem = append(mem, dibMem) + } else { + norm := strings.ReplaceAll(strings.ReplaceAll(string(payload.Data), "\r\n", "\n"), "\n", "\r\n") + words := append(utf16.Encode([]rune(norm)), 0) + textMem, err := prepareClipboardMem(cfUnicodeText, uintptr(len(words)*2), unsafe.Pointer(&words[0])) + if err != nil { + return 0, err + } + mem = append(mem, textMem) } - return setClipboardRawLocked(cfDIB, dib) + + err = onClipboardThread(func(hwnd uintptr) error { + return withOpenClipboard(hwnd, func() error { + seq = c.SequenceNumber() + if baseSeq != nil && seq != *baseSeq { + return errClipboardConflict + } + if ok, _, err := procEmptyClipboard.Call(); ok == 0 { + return fmt.Errorf("EmptyClipboard: %w", err) + } + var writeErr error + for i := range mem { + item := &mem[i] + if ok, _, err := procSetClipboardData.Call(item.format, item.handle); ok == 0 { + writeErr = errors.Join(writeErr, fmt.Errorf("SetClipboardData(%d): %w", item.format, err)) + } else { + item.handle = 0 // The system now owns the handle. + } + } + seq = c.SequenceNumber() + return writeErr + }) + }) + return seq, err } diff --git a/internal/guesttools/clipboard_windows_test.go b/internal/guesttools/clipboard_windows_test.go new file mode 100644 index 0000000..3779cb8 --- /dev/null +++ b/internal/guesttools/clipboard_windows_test.go @@ -0,0 +1,97 @@ +//go:build windows + +package guesttools + +import ( + "bytes" + "sync" + "testing" + + "golang.org/x/sys/windows" +) + +func TestClipboardWorkerUsesOneThreadAndWindow(t *testing.T) { + type owner struct { + thread uint32 + hwnd uintptr + } + const jobs = 32 + results := make(chan owner, jobs) + var wg sync.WaitGroup + for range jobs { + wg.Go(func() { + if err := onClipboardThread(func(hwnd uintptr) error { + results <- owner{windows.GetCurrentThreadId(), hwnd} + return nil + }); err != nil { + t.Errorf("clipboard worker: %v", err) + } + }) + } + wg.Wait() + close(results) + want := <-results + if want.thread == 0 || want.hwnd == 0 { + t.Fatalf("expected a thread and owner window, got %+v", want) + } + for got := range results { + if got != want { + t.Errorf("clipboard job ran on %+v, want %+v", got, want) + } + } +} + +func TestWindowsClipboardSnapshotFormats(t *testing.T) { + origPNG := makeSamplePNG(t, 1, 2, 3) + dib, err := EncodePNGToDIB(origPNG) + if err != nil { + t.Fatal(err) + } + dibPNG, err := DecodeDIBToPNG(dib) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + snap clipboardSnapshot + want ClipPayload + }{ + {"text first", clipboardSnapshot{text: []uint16{'x', 0}, png: origPNG, kind: ClipText}, + ClipPayload{Kind: ClipText, Data: []byte("x")}}, + {"empty text does not hide PNG", clipboardSnapshot{text: []uint16{0}, png: append(bytes.Clone(origPNG), 0, 0)}, + ClipPayload{Kind: ClipPNG, Data: origPNG}}, + {"bad PNG falls back to DIB", clipboardSnapshot{png: origPNG[:len(origPNG)-2], dib: dib}, + ClipPayload{Kind: ClipPNG, Data: dibPNG}}, + {"empty text is representable", clipboardSnapshot{text: []uint16{0}, kind: ClipText}, + ClipPayload{Kind: ClipText}}, + {"unusable image is skipped", clipboardSnapshot{dib: []byte{1, 2}}, + ClipPayload{Kind: ClipEmpty}}, + } { + t.Run(tc.name, func(t *testing.T) { + got := tc.snap.payload() + if got.Kind != tc.want.Kind || !bytes.Equal(got.Data, tc.want.Data) { + t.Fatalf("got %s (%d bytes), want %s (%d bytes)", got.Kind, len(got.Data), tc.want.Kind, len(tc.want.Data)) + } + }) + } +} + +func TestWindowsClipboardSnapshotSkipsDisabledImages(t *testing.T) { + const pngFormat = 0xc000 + for _, format := range []uintptr{pngFormat, cfDIB} { + for _, snap := range []clipboardSnapshot{{}, {text: []uint16{0}, kind: ClipText}} { + err := snap.readImagesLocked(false, pngFormat, func(candidate uintptr) bool { + return candidate == format + }, func(uintptr, int) ([]byte, error) { + t.Fatalf("disabled image format %#x must not be copied for decoding", format) + return nil, nil + }) + if err != nil { + t.Fatal(err) + } + if got := snap.payload(); got.Kind != ClipEmpty || len(got.Data) != 0 { + t.Fatalf("disabled image format %#x: got %+v, want ClipEmpty", format, got) + } + } + } +} diff --git a/internal/guesttools/dib.go b/internal/guesttools/dib.go index cfc1c85..50de871 100644 --- a/internal/guesttools/dib.go +++ b/internal/guesttools/dib.go @@ -9,6 +9,7 @@ import ( "image/color" "image/draw" "image/png" + "math/bits" ) // pngMagic is the standard 8-byte PNG file signature. @@ -21,6 +22,28 @@ func IsPNG(data []byte) bool { return len(data) >= len(pngMagic) && bytes.Equal(data[:len(pngMagic)], pngMagic) } +// TrimPNG returns the portion of raw through the end of its IEND chunk. +func TrimPNG(raw []byte) ([]byte, bool) { + if !IsPNG(raw) { + return nil, false + } + for off := len(pngMagic); len(raw)-off >= 12; { + chunk := raw[off:] + size := binary.BigEndian.Uint32(chunk[:4]) + if size > 0x7fffffff || uint64(size) > uint64(len(chunk)-12) { + return nil, false + } + off += int(size) + 12 + if string(chunk[4:8]) == "IEND" { + if size != 0 { + return nil, false + } + return raw[:off], true + } + } + return nil, false +} + // EncodeImageToDIB encodes an image into a standard 32-bit bottom-up Windows // CF_DIB (BITMAPINFOHEADER + BGRA pixels) accepted by all Windows applications. func EncodeImageToDIB(img image.Image) ([]byte, error) { @@ -38,9 +61,9 @@ func EncodeImageToDIB(img image.Image) ([]byte, error) { binary.LittleEndian.PutUint32(out[0:4], hdrSize) binary.LittleEndian.PutUint32(out[4:8], uint32(w)) binary.LittleEndian.PutUint32(out[8:12], uint32(h)) // positive => bottom-up - binary.LittleEndian.PutUint16(out[12:14], 1) // planes - binary.LittleEndian.PutUint16(out[14:16], 32) // bpp - binary.LittleEndian.PutUint32(out[16:20], 0) // BI_RGB + binary.LittleEndian.PutUint16(out[12:14], 1) // planes + binary.LittleEndian.PutUint16(out[14:16], 32) // bpp + binary.LittleEndian.PutUint32(out[16:20], 0) // BI_RGB binary.LittleEndian.PutUint32(out[20:24], uint32(pixelBytes)) for y := 0; y < h; y++ { @@ -78,8 +101,7 @@ func EncodePNGToDIB(pngBytes []byte) ([]byte, error) { return EncodeImageToDIB(img) } -// DecodeDIBToPNG converts Windows CF_DIB bytes (24-bit or 32-bit BI_RGB / BI_BITFIELDS) -// into PNG bytes. +// DecodeDIBToPNG converts 24/32-bit BI_RGB or 16/32-bit BI_BITFIELDS to PNG. func DecodeDIBToPNG(dib []byte) ([]byte, error) { if len(dib) < 40 { return nil, errors.New("CF_DIB too short") @@ -107,28 +129,51 @@ func DecodeDIBToPNG(dib []byte) ([]byte, error) { if comp != biRGB && comp != biBitfields { return nil, fmt.Errorf("unsupported DIB compression %d", comp) } - if bpp != 24 && bpp != 32 { + if bpp != 32 && !(comp == biRGB && bpp == 24) && !(comp == biBitfields && bpp == 16) { return nil, fmt.Errorf("unsupported DIB bit depth %d", bpp) } pixelOffset := hdrSize - if comp == biBitfields && hdrSize == 40 { - // Standard BITMAPINFOHEADER + BI_BITFIELDS appends 3 DWORD color masks (12 bytes). - pixelOffset += 12 - } - if clrUsed := int(binary.LittleEndian.Uint32(dib[32:36])); clrUsed > 0 && bpp <= 8 { - pixelOffset += clrUsed * 4 + var masks [4]uint32 + var shifts [4]int + var maxima [4]uint64 + if comp == biBitfields { + switch { + case hdrSize == 40 && len(dib) >= 52: + pixelOffset += 12 + case hdrSize >= 56: + masks[3] = binary.LittleEndian.Uint32(dib[52:56]) + default: + return nil, errors.New("CF_DIB color masks truncated") + } + used := uint32(0) + for i := range masks { + if i < 3 { + masks[i] = binary.LittleEndian.Uint32(dib[40+i*4:]) + } else if masks[i] == 0 { + continue + } + shifts[i] = bits.TrailingZeros32(masks[i]) + field := masks[i] >> shifts[i] + if field == 0 || field&(field+1) != 0 || masks[i]&used != 0 || bits.Len32(masks[i]) > bpp { + return nil, errors.New("invalid CF_DIB color masks") + } + used |= masks[i] + maxima[i] = uint64(field) + } } + tableBytes := uint64(binary.LittleEndian.Uint32(dib[32:36])) * 4 rowStride := ((w*bpp + 31) / 32) * 4 - if pixelOffset+rowStride*h > len(dib) { + if uint64(pixelOffset)+tableBytes+uint64(rowStride)*uint64(h) > uint64(len(dib)) { return nil, errors.New("CF_DIB pixel data truncated") } + pixelOffset += int(tableBytes) img := image.NewNRGBA(image.Rect(0, 0, w, h)) // Track whether any 32-bit pixel carries non-zero alpha; many Windows apps // leave the 4th byte of BI_RGB 32-bit DIBs as 0 (opaque XRGB). hasAlpha := false - if bpp == 32 { + if comp == biRGB && bpp == 32 { for y := 0; y < h && !hasAlpha; y++ { row := dib[pixelOffset+y*rowStride:] for x := 0; x < w; x++ { @@ -147,7 +192,21 @@ func DecodeDIBToPNG(dib []byte) ([]byte, error) { } row := dib[pixelOffset+srcY*rowStride:] for x := 0; x < w; x++ { - if bpp == 32 { + if comp == biBitfields { + pixel := row[x*(bpp/8):] + value := uint32(binary.LittleEndian.Uint16(pixel)) + if bpp == 32 { + value = binary.LittleEndian.Uint32(pixel) + } + channels := [4]uint8{0, 0, 0, 255} + for i, mask := range masks { + if mask != 0 { + level := uint64((value & mask) >> shifts[i]) + channels[i] = uint8((level*255 + maxima[i]/2) / maxima[i]) + } + } + img.SetNRGBA(x, y, color.NRGBA{R: channels[0], G: channels[1], B: channels[2], A: channels[3]}) + } else if bpp == 32 { off := x * 4 a := row[off+3] if !hasAlpha { diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index bb9fc8e..2cc945d 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -309,57 +309,79 @@ report_status() { curl -fsS -m 3 -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":5}" \ + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":6}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true } read_local_clipboard() { out_file="$1" - # Fast path: inspect macOS clipboard types via osascript to detect screenshots/images. cinfo=$(osascript -e 'clipboard info' 2>/dev/null || true) - has_text=0 case "$cinfo" in - *utf8*|*"Unicode text"*|*string*) has_text=1 ;; + *utf8*|*"Unicode text"*|*string*) + if pbpaste >"$out_file" 2>/dev/null && [ -s "$out_file" ]; then + echo "text" + return 0 + fi + ;; esac - if [ "$has_text" -eq 0 ]; then - case "$cinfo" in - *PNGf*) - rm -f "$out_file" - if osascript -e "set fp to open for access POSIX file \"$out_file\" with write permission" \ - -e "set eof fp to 0" \ - -e "write (the clipboard as «class PNGf») to fp" \ - -e "close access fp" >/dev/null 2>&1 && [ -s "$out_file" ]; then - echo "png" - return 0 - fi - ;; - *TIFF*) - tiff_tmp="$TMP_DIR/clip_in.tiff" - rm -f "$tiff_tmp" "$out_file" - if osascript -e "set fp to open for access POSIX file \"$tiff_tmp\" with write permission" \ - -e "set eof fp to 0" \ - -e "write (the clipboard as TIFF picture) to fp" \ - -e "close access fp" >/dev/null 2>&1 && [ -s "$tiff_tmp" ]; then - if sips -s format png "$tiff_tmp" --out "$out_file" >/dev/null 2>&1 && [ -s "$out_file" ]; then - rm -f "$tiff_tmp" - echo "png" - return 0 - fi - fi + case "$cinfo" in + *PNGf*) + rm -f "$out_file" + if osascript -e "set fp to open for access POSIX file \"$out_file\" with write permission" \ + -e "set eof fp to 0" \ + -e "write (the clipboard as «class PNGf») to fp" \ + -e "close access fp" >/dev/null 2>&1 && [ -s "$out_file" ]; then + echo "png" + return 0 + fi + ;; + esac + case "$cinfo" in + *TIFF*) + tiff_tmp="$TMP_DIR/clip_in.tiff" + rm -f "$tiff_tmp" "$out_file" + if osascript -e "set fp to open for access POSIX file \"$tiff_tmp\" with write permission" \ + -e "set eof fp to 0" \ + -e "write (the clipboard as TIFF picture) to fp" \ + -e "close access fp" >/dev/null 2>&1 && [ -s "$tiff_tmp" ] && + sips -s format png "$tiff_tmp" --out "$out_file" >/dev/null 2>&1 && [ -s "$out_file" ]; then rm -f "$tiff_tmp" - ;; - esac - fi - pbpaste >"$out_file" 2>/dev/null || : >"$out_file" - echo "text" + echo "png" + return 0 + fi + rm -f "$tiff_tmp" + ;; + esac + case "$cinfo" in + *PNGf*|*TIFF*) + echo "empty" + ;; + *) + pbpaste >"$out_file" 2>/dev/null || : >"$out_file" + echo "text" + ;; + esac } write_local_png() { - in_file="$1" - osascript -e "set the clipboard to (read (POSIX file \"$in_file\") as «class PNGf»)" >/dev/null 2>&1 || true + osascript -e "set the clipboard to (read (POSIX file \"$1\") as «class PNGf»)" >/dev/null 2>&1 } -last_clip_hash="" +local_clip_hash() { + case "$1" in + png) hash_png_file "$2" ;; + text) hash_file "$2" ;; + empty) echo "empty" ;; + esac +} + +clip_header() { + awk -v name="$1:" 'tolower($1)==name {gsub(/\r/,"",$2); print $2; exit}' "$hdr_out" +} + +last_local_hash="" +last_server_hash="" +last_server_seq="" clip_enabled="1" tick=0 TAB=$(printf '\t') @@ -375,50 +397,91 @@ sync_clipboard() { hdr_out="$TMP_DIR/clip_hdr" local_kind=$(read_local_clipboard "$clip_in") - if [ "$local_kind" = "png" ]; then - cur_hash=$(hash_png_file "$clip_in") - else - cur_hash=$(hash_file "$clip_in") - fi + cur_hash=$(local_clip_hash "$local_kind" "$clip_in") + post_conflict=0 - if [ -n "$last_clip_hash" ] && [ "$cur_hash" != "$last_clip_hash" ]; then + if [ "$local_kind" != "empty" ] && [ -n "$last_local_hash" ] && [ "$cur_hash" != "$last_local_hash" ]; then ct="text/plain; charset=utf-8" [ "$local_kind" = "png" ] && ct="image/png" - if curl -fsS -m 5 -X POST \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - -H "Content-Type: $ct" \ - --data-binary "@$clip_in" \ - "$REIMS_HOST_URL/v1/clipboard" >/dev/null 2>&1; then - last_clip_hash="$cur_hash" + set -- + if [ -n "$last_server_seq" ]; then + set -- -H "X-Clip-Base-Seq: $last_server_seq" fi - return 0 + code=$(curl -sS -m 5 -X POST -D "$hdr_out" -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $REIMS_TOKEN" \ + -H "Content-Type: $ct" ${1+"$@"} \ + --data-binary "@$clip_in" \ + "$REIMS_HOST_URL/v1/clipboard" 2>/dev/null) || code=000 + case "$code" in + 200) + last_local_hash="$cur_hash" + last_server_hash=$(clip_header x-clip-hash) + last_server_seq=$(clip_header x-clip-seq) + return 0 + ;; + 204|413) + last_local_hash="$cur_hash" + ;; + 409) + post_conflict=1 + ;; + esac fi # Long-poll up to 2s: host changes return immediately (~150ms), idle stays quiet. code=$(curl -sS -m 5 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \ -H "Authorization: Bearer $REIMS_TOKEN" \ - "$REIMS_HOST_URL/v1/clipboard?since=$last_clip_hash&wait=2&accept=image" 2>/dev/null || echo "000") - if [ "$code" = "200" ]; then - new_hash=$(awk 'tolower($1)=="x-clip-hash:" {gsub(/\r/,"",$2); print $2; exit}' "$hdr_out") - new_kind=$(awk 'tolower($1)=="x-clip-kind:" {gsub(/\r/,"",$2); print tolower($2); exit}' "$hdr_out") - if [ -n "$new_hash" ] && [ "$new_hash" != "$cur_hash" ]; then - if [ "$new_kind" = "png" ]; then - write_local_png "$clip_out" - else - pbcopy <"$clip_out" 2>/dev/null || true + "$REIMS_HOST_URL/v1/clipboard?since=$last_server_hash&wait=2&accept=image" 2>/dev/null) || code=000 + case "$code" in + 200) + new_hash=$(clip_header x-clip-hash) + [ -n "$new_hash" ] || return 0 + new_kind=$(clip_header x-clip-kind) + new_seq=$(clip_header x-clip-seq) + post_get_kind=$(read_local_clipboard "$clip_in") + post_get_hash=$(local_clip_hash "$post_get_kind" "$clip_in") + if [ "$post_get_hash" != "$cur_hash" ]; then + last_server_seq="$new_seq" + return 0 fi - last_clip_hash="$new_hash" - elif [ -n "$new_hash" ]; then - last_clip_hash="$new_hash" - fi - elif [ "$code" = "503" ]; then - # Feature disabled on host: back off instead of busy-looping osascript + curl (M11). - sleep 5 - elif [ "$code" = "304" ] && [ -z "$last_clip_hash" ]; then - last_clip_hash="$cur_hash" - elif [ "$code" = "000" ]; then - sleep 2 - fi + if [ "$new_hash" != "$cur_hash" ]; then + if [ "$new_kind" = "png" ]; then + write_local_png "$clip_out" || return 0 + else + pbcopy <"$clip_out" 2>/dev/null || return 0 + fi + post_get_kind=$(read_local_clipboard "$clip_in") + post_get_hash=$(local_clip_hash "$post_get_kind" "$clip_in") + fi + last_local_hash="$post_get_hash" + last_server_hash="$new_hash" + last_server_seq="$new_seq" + ;; + 204|304) + if [ -z "$last_local_hash" ]; then + last_local_hash="$cur_hash" + fi + if [ "$code" = 204 ]; then + last_server_seq="" + else + new_seq=$(clip_header x-clip-seq) + if [ -n "$new_seq" ]; then + last_server_seq="$new_seq" + fi + new_hash=$(clip_header x-clip-hash) + if [ "$post_conflict" = 1 ] && [ -z "$new_hash" ]; then + last_local_hash="$cur_hash" + fi + fi + ;; + 503) + # Feature disabled on host: back off instead of busy-looping osascript + curl (M11). + sleep 5 + ;; + 000) + sleep 2 + ;; + esac } sync_files() { diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 26d844f..0d62b2f 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -1,6 +1,7 @@ package guesttools import ( + "bytes" "context" "crypto/rand" "crypto/sha256" @@ -198,6 +199,7 @@ type registeredVM struct { // (reachable from QEMU SLIRP guests as http://10.0.2.2:). type Server struct { mu sync.RWMutex + clipWriteMu sync.Mutex clip Clipboard vms map[string]*registeredVM // keyed by VM name davHandlers map[string]*webdav.Handler @@ -759,15 +761,21 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -func (s *Server) readClipboardPayload(acceptImage bool) (ClipPayload, error) { - if acceptImage { - return s.clip.Read() +func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error) { + if clip, ok := s.clip.(interface { + readClipboard(bool) (ClipPayload, uint32, error) + }); ok { + return clip.readClipboard(wantImage) } - text, err := s.clip.ReadText() - if err != nil { - return ClipPayload{}, err - } - return ClipPayload{Kind: ClipText, Data: []byte(text)}, nil + // A clipboard without atomic snapshots can return a newer payload with + // this sequence, which is safe for a subsequent conditional write. + seq := s.clip.SequenceNumber() + payload, err := s.clip.Read() + return payload, seq, err +} + +func setClipboardSeq(w http.ResponseWriter, seq uint32) { + w.Header().Set("X-Clip-Seq", strconv.FormatUint(uint64(seq), 10)) } func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { @@ -776,53 +784,42 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { http.Error(w, "unauthorized", http.StatusUnauthorized) return } - policy := s.EffectiveClipboardPolicy(vm.name) - if !policy.Enabled { - writeFeatureDisabled(w, "clipboard") - return - } switch r.Method { case http.MethodGet: - waitSec := 0 - if rawWait := r.URL.Query().Get("wait"); rawWait != "" { - if n, err := strconv.Atoi(rawWait); err == nil && n > 0 { - if n > MaxLongPollSec { - n = MaxLongPollSec - } - waitSec = n - } - } - if policy.Direction == ClipboardGuestToHost { - // Hold the long-poll instead of returning 204 immediately so the - // guest agent loop does not busy-spin CPU in guest-to-host mode (M11). - if waitSec > 0 { - ch := s.clipNotifyChan() - timer := time.NewTimer(time.Duration(waitSec) * time.Second) - select { - case <-ch: - timer.Stop() - case <-timer.C: - case <-r.Context().Done(): - timer.Stop() - return - } - } - w.WriteHeader(http.StatusNoContent) + s.getClipboard(w, r, vm.name) + case http.MethodPost, http.MethodPut: + s.postClipboard(w, r, vm.name) + default: + if !s.EffectiveClipboardPolicy(vm.name).Enabled { + writeFeatureDisabled(w, "clipboard") return } - acceptImage := policy.SyncImages && (strings.EqualFold(r.URL.Query().Get("accept"), "image") || - strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")) - since := r.URL.Query().Get("since") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} - deadline := time.Now().Add(time.Duration(waitSec) * time.Second) - for { - if !s.EffectiveClipboardPolicy(vm.name).Enabled { - writeFeatureDisabled(w, "clipboard") - return - } - if ov := s.takeClipOverride(vm.name); ov != nil { - s.touchLastSeen(vm.name) +func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmName string) { + waitSec, err := strconv.Atoi(r.URL.Query().Get("wait")) + if err != nil { + waitSec = 0 + } + deadline := time.Now().Add(time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second) + wantsImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") || + strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png") + since := r.URL.Query().Get("since") + + for { + ch := s.clipNotifyChan() + policy := s.EffectiveClipboardPolicy(vmName) + if !policy.Enabled { + writeFeatureDisabled(w, "clipboard") + return + } + if policy.Direction != ClipboardGuestToHost { + if ov := s.takeClipOverride(vmName); ov != nil { + s.touchLastSeen(vmName) atomic.AddUint64(&s.clipStatsH2G, 1) + setClipboardSeq(w, s.clip.SequenceNumber()) w.Header().Set("X-Clip-Hash", ov.hash) w.Header().Set("X-Clip-Kind", string(ClipText)) w.Header().Set("Content-Type", "text/plain; charset=utf-8") @@ -830,128 +827,171 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { close(ov.servedCh) return } - payload, err := s.readClipboardPayload(acceptImage) + + wantImage := wantsImage && policy.SyncImages + payload, seq, err := s.readClipboardState(wantImage) if err != nil { atomic.AddUint64(&s.clipStatsErr, 1) http.Error(w, err.Error(), http.StatusInternalServerError) return } - if payload.Kind == ClipPNG && len(payload.Data) > policy.MaxImageBytes { - payload = ClipPayload{Kind: ClipText, Data: nil} - } - h := payloadHash(payload) - if since == "" || since != h { - s.touchLastSeen(vm.name) - atomic.AddUint64(&s.clipStatsH2G, 1) - w.Header().Set("X-Clip-Hash", h) - if payload.Kind == ClipPNG { - w.Header().Set("X-Clip-Kind", string(ClipPNG)) - w.Header().Set("Content-Type", "image/png") - _, _ = w.Write(payload.Data) - } else { - w.Header().Set("X-Clip-Kind", string(ClipText)) - w.Header().Set("Content-Type", "text/plain; charset=utf-8") + syncable := payload.Kind == ClipText || (payload.Kind == ClipPNG && + wantImage && len(payload.Data) <= policy.MaxImageBytes) + if syncable { + h := payloadHash(payload) + if since != h || time.Until(deadline) <= 0 { + setClipboardSeq(w, seq) + w.Header().Set("X-Clip-Hash", h) + w.Header().Set("X-Clip-Kind", string(payload.Kind)) + s.touchLastSeen(vmName) + if since == h { + w.WriteHeader(http.StatusNotModified) + return + } + atomic.AddUint64(&s.clipStatsH2G, 1) + if payload.Kind == ClipPNG { + w.Header().Set("Content-Type", "image/png") + } else { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + } _, _ = w.Write(payload.Data) + return } - return - } - if waitSec <= 0 { - w.Header().Set("X-Clip-Hash", h) - w.Header().Set("X-Clip-Kind", string(payload.Kind)) + } else if time.Until(deadline) <= 0 { + s.touchLastSeen(vmName) + setClipboardSeq(w, seq) w.WriteHeader(http.StatusNotModified) return } - rem := time.Until(deadline) - if rem <= 0 { - s.touchLastSeen(vm.name) - w.Header().Set("X-Clip-Hash", h) - w.Header().Set("X-Clip-Kind", string(payload.Kind)) - w.WriteHeader(http.StatusNotModified) - return - } - ch := s.clipNotifyChan() - timer := time.NewTimer(rem) - select { - case <-ch: - timer.Stop() - case <-timer.C: - s.touchLastSeen(vm.name) - w.Header().Set("X-Clip-Hash", h) - w.Header().Set("X-Clip-Kind", string(payload.Kind)) - w.WriteHeader(http.StatusNotModified) - return - case <-r.Context().Done(): - timer.Stop() - return - } - } - - case http.MethodPost, http.MethodPut: - if policy.Direction == ClipboardHostToGuest { + } else if time.Until(deadline) <= 0 { + // Keep guest-to-host-only agents from busy-looping. w.WriteHeader(http.StatusNoContent) return } - limit := policy.MaxImageBytes - if limit <= 0 || limit > MaxClipboardBytes { - limit = MaxClipboardBytes - } - body, err := io.ReadAll(io.LimitReader(r.Body, int64(limit)+1)) - if err != nil { - atomic.AddUint64(&s.clipStatsErr, 1) - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if len(body) > limit { - http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge) - return - } - ct := strings.ToLower(r.Header.Get("Content-Type")) - if strings.Contains(ct, "image/png") { - if !policy.SyncImages { - w.WriteHeader(http.StatusNoContent) - return - } - if !IsPNG(body) { - http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest) - return - } - h := payloadHash(ClipPayload{Kind: ClipPNG, Data: body}) - if cur, err := s.clip.Read(); err != nil || payloadHash(cur) != h { - if err := s.clip.WritePNG(body); err != nil { - atomic.AddUint64(&s.clipStatsErr, 1) - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - atomic.AddUint64(&s.clipStatsG2H, 1) - s.broadcastClipChange() - } - w.Header().Set("X-Clip-Kind", string(ClipPNG)) - w.Header().Set("X-Clip-Hash", h) - w.WriteHeader(http.StatusOK) - return - } + timer := time.NewTimer(time.Until(deadline)) + select { + case <-ch: + timer.Stop() + case <-timer.C: + // Re-read after the timeout in case the watcher has yet to notify us. + case <-r.Context().Done(): + timer.Stop() + return + } + } +} + +var errClipboardConflict = errors.New("host clipboard changed") + +func (s *Server) postClipboard(w http.ResponseWriter, r *http.Request, vmName string) { + policy := s.EffectiveClipboardPolicy(vmName) + if !policy.Enabled { + writeFeatureDisabled(w, "clipboard") + return + } + isImage := strings.Contains(strings.ToLower(r.Header.Get("Content-Type")), "image/png") + if policy.Direction == ClipboardHostToGuest || (isImage && !policy.SyncImages) { + w.WriteHeader(http.StatusNoContent) + return + } + + var baseSeq *uint32 + if raw := r.Header.Get("X-Clip-Base-Seq"); policy.Direction != ClipboardGuestToHost && raw != "" { + n, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + http.Error(w, "invalid X-Clip-Base-Seq", http.StatusBadRequest) + return + } + base := uint32(n) + baseSeq = &base + } + + limit := MaxClipboardBytes + if isImage { + limit = policy.MaxImageBytes + } + body, err := io.ReadAll(io.LimitReader(r.Body, int64(limit)+1)) + if err != nil { + atomic.AddUint64(&s.clipStatsErr, 1) + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if len(body) > limit { + http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge) + return + } + payload := ClipPayload{Kind: ClipText, Data: body} + if isImage { + if !IsPNG(body) { + http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest) + return + } + payload.Kind = ClipPNG + } else { if !utf8.Valid(body) { http.Error(w, "clipboard payload must be valid UTF-8", http.StatusBadRequest) return } - text := strings.ReplaceAll(string(body), "\r\n", "\n") - h := textHash(text) - if cur, err := s.clip.ReadText(); err != nil || textHash(cur) != h { - if err := s.clip.WriteText(text); err != nil { - atomic.AddUint64(&s.clipStatsErr, 1) - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - atomic.AddUint64(&s.clipStatsG2H, 1) - s.broadcastClipChange() - } - w.Header().Set("X-Clip-Kind", string(ClipText)) - w.Header().Set("X-Clip-Hash", h) - w.WriteHeader(http.StatusOK) - default: - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + payload.Data = []byte(strings.ReplaceAll(string(body), "\r\n", "\n")) } + h := payloadHash(payload) + seq, err := s.applyClipboardPost(payload, baseSeq) + if errors.Is(err, errClipboardConflict) { + setClipboardSeq(w, seq) + http.Error(w, errClipboardConflict.Error(), http.StatusConflict) + return + } + if err != nil { + atomic.AddUint64(&s.clipStatsErr, 1) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + setClipboardSeq(w, seq) + w.Header().Set("X-Clip-Kind", string(payload.Kind)) + w.Header().Set("X-Clip-Hash", h) + w.WriteHeader(http.StatusOK) +} + +func (s *Server) applyClipboardPost(payload ClipPayload, baseSeq *uint32) (uint32, error) { + s.clipWriteMu.Lock() + defer s.clipWriteMu.Unlock() + + seq := s.clip.SequenceNumber() + if baseSeq != nil && seq != *baseSeq { + return seq, errClipboardConflict + } + current, seq, err := s.readClipboardState(true) + if err == nil { + if baseSeq != nil && seq != *baseSeq { + return seq, errClipboardConflict + } + if current.Kind == payload.Kind && bytes.Equal(current.Data, payload.Data) { + return seq, nil + } + } + + if clip, ok := s.clip.(interface { + writeClipboard(ClipPayload, *uint32) (uint32, error) + }); ok { + seq, err = clip.writeClipboard(payload, baseSeq) + } else { + seq = s.clip.SequenceNumber() + if baseSeq != nil && seq != *baseSeq { + return seq, errClipboardConflict + } + if payload.Kind == ClipPNG { + err = s.clip.WritePNG(payload.Data) + } else { + err = s.clip.WriteText(string(payload.Data)) + } + seq = s.clip.SequenceNumber() + } + if err == nil { + atomic.AddUint64(&s.clipStatsG2H, 1) + s.broadcastClipChange() + } + return seq, err } func (s *Server) takeClipOverride(vmName string) *pendingClipOverride { From f96d78be14c542cfee866fc35805985108135ddf Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 07:37:44 +0800 Subject: [PATCH 03/23] fix(guesttools): propagate fallback sync deletions --- .gitattributes | 1 + frontend/src/components/VMPage.tsx | 4 +- frontend/wailsjs/go/models.ts | 2 + internal/app/stats_flow.go | 11 +- internal/guesttools/clipboard_agent_test.go | 8 +- internal/guesttools/file_sync.go | 378 ++++++++++++++++++++ internal/guesttools/file_sync.sh | 213 +++++++++++ internal/guesttools/file_sync_test.go | 101 ++++++ internal/guesttools/image.go | 73 +--- internal/guesttools/server.go | 209 +---------- 10 files changed, 723 insertions(+), 277 deletions(-) create mode 100644 internal/guesttools/file_sync.go create mode 100644 internal/guesttools/file_sync.sh create mode 100644 internal/guesttools/file_sync_test.go diff --git a/.gitattributes b/.gitattributes index 8083b67..3ab406d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,3 @@ *.patch -text *.diff -text +internal/guesttools/file_sync.sh text eol=lf diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e8b60ea..c14b3c5 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -853,7 +853,9 @@ export const VMPage: React.FC = ({ const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || '' const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false - const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3 + const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0 + const minimumAgentVersion = gtMountMode === 'sync' ? 7 : 3 + const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < minimumAgentVersion // Plugin switched off: show the state and hide controls that would only fail. const gtOff = !!detail.guest_tools_disabled diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 9883e88..c0d44a9 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -411,6 +411,7 @@ export namespace app { uptime_seconds: number; guest_tools_connected: boolean; guest_tools_mount_mode?: string; + guest_tools_agent_version?: number; guest_tools_sleep_guard: boolean; static createFrom(source: any = {}) { @@ -435,6 +436,7 @@ export namespace app { this.uptime_seconds = source["uptime_seconds"]; this.guest_tools_connected = source["guest_tools_connected"]; this.guest_tools_mount_mode = source["guest_tools_mount_mode"]; + this.guest_tools_agent_version = source["guest_tools_agent_version"]; this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"]; } } diff --git a/internal/app/stats_flow.go b/internal/app/stats_flow.go index 66be5f5..4192d6a 100644 --- a/internal/app/stats_flow.go +++ b/internal/app/stats_flow.go @@ -27,9 +27,11 @@ type VMStats struct { DiskBackingBroken bool `json:"disk_backing_broken,omitempty"` DiskBackingDepthWarn bool `json:"disk_backing_depth_warn,omitempty"` UptimeSeconds int64 `json:"uptime_seconds"` - GuestToolsConnected bool `json:"guest_tools_connected"` - GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"` - GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"` + + GuestToolsConnected bool `json:"guest_tools_connected"` + GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"` + GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` + GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"` } func resolveVMDiskPath(d reims.VMDetail) string { @@ -53,7 +55,7 @@ func resolveVMDiskPath(d reims.VMDetail) string { } // GetVMStats samples QEMU CPU/memory usage (when running), disk actual vs -// virtual capacity, and live Guest Tools 2.0 connection state. +// virtual capacity, and live Guest Tools status. func (a *App) GetVMStats(name string) (VMStats, error) { stats := VMStats{Name: name} c, err := a.client() @@ -114,6 +116,7 @@ func (a *App) GetVMStats(name string) (VMStats, error) { st := srv.Status(name, 15*time.Second) stats.GuestToolsConnected = st.Connected stats.GuestToolsMountMode = st.MountMode + stats.GuestToolsAgentVersion = st.AgentVersion stats.GuestToolsSleepGuard = st.SleepActive } return stats, nil diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 666e80c..cf5fd8f 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -4,6 +4,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "strings" "testing" ) @@ -19,8 +20,11 @@ func TestGuestAgentClipboardScript(t *testing.T) { agent := string(GuestAgentScript()) start := strings.Index(agent, "read_local_clipboard() {") end := strings.Index(agent, "sync_files() {") - if start < 0 || end <= start || !strings.Contains(agent, "agent_version\\\":6") { - t.Fatal("missing generated clipboard code or agent version 6") + if start < 0 || end <= start { + t.Fatal("missing generated clipboard code") + } + if !regexp.MustCompile(`agent_version\\":([6-9]|[1-9][0-9]+)\}`).MatchString(agent) { + t.Fatal("clipboard sync requires agent version 6 or newer") } if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) { t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u") diff --git a/internal/guesttools/file_sync.go b/internal/guesttools/file_sync.go new file mode 100644 index 0000000..76ba4d8 --- /dev/null +++ b/internal/guesttools/file_sync.go @@ -0,0 +1,378 @@ +package guesttools + +import ( + "crypto/sha256" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" +) + +const ( + syncScopeHeader = "X-Reims-Sync-Scope" + syncDigestHeader = "X-Reims-File-SHA256" +) + +func syncFileScope(token, root string) string { + return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root))) +} + +func syncFileTag(info fs.FileInfo) string { + return fmt.Sprintf("\"%d-%d\"", info.ModTime().UnixNano(), info.Size()) +} + +func isIgnoredSharedName(name string) bool { + return name == "" || strings.HasPrefix(name, ".") +} + +func validSyncFileName(name string) bool { + return strings.TrimSpace(name) == name && !strings.ContainsAny(name, "\t\r\n") +} + +// sharedFilePath returns the one relative path used by both the legacy copy +// endpoints and the versioned sync operations. +func sharedFilePath(name string) (string, error) { + name = strings.TrimSpace(name) + parts := strings.FieldsFunc(name, func(r rune) bool { return r == '/' }) + if len(parts) == 0 || len(parts) > MaxSharedDepth || strings.HasPrefix(name, "/") { + return "", errors.New("invalid relative path") + } + for _, part := range parts { + if isIgnoredSharedName(part) || strings.ContainsAny(part, "\x00:\\<>|\"?*") { + return "", errors.New("invalid path segment") + } + } + rel := strings.Join(parts, "/") + if !filepath.IsLocal(filepath.FromSlash(rel)) { + return "", errors.New("invalid relative path") + } + return rel, nil +} + +func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + versioned := r.URL.Query().Get("sync") == "1" + if vm.sharedDir == "" { + if versioned { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + } + return + } + root, err := filepath.Abs(vm.sharedDir) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + return + } + if !versioned { + if err := os.MkdirAll(root, 0o755); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + } + type entry struct { + name string + info fs.FileInfo + } + var files []entry + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if p == root { + if versioned && err == nil && !d.IsDir() { + return fs.ErrInvalid + } + return err + } + if err != nil { + return nil + } + if isIgnoredSharedName(d.Name()) || d.Type()&os.ModeSymlink != 0 { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + rel, err := filepath.Rel(root, p) + if err != nil { + return nil + } + name := filepath.ToSlash(rel) + if strings.Count(name, "/")+1 > MaxSharedDepth { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() || (versioned && !validSyncFileName(name)) { + return nil + } + info, err := d.Info() + if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes { + return nil + } + if len(files) == MaxSharedFiles { + return fs.SkipAll + } + files = append(files, entry{name, info}) + return nil + }) + if versioned { + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + w.Header().Set(syncScopeHeader, syncFileScope(vm.token, root)) + } + sort.Slice(files, func(i, j int) bool { return files[i].name < files[j].name }) + w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8") + for _, file := range files { + _, _ = fmt.Fprintf(w, "%d\t%d\t", file.info.ModTime().Unix(), file.info.Size()) + if versioned { + _, _ = fmt.Fprintf(w, "%s\t", syncFileTag(file.info)) + } + _, _ = fmt.Fprintln(w, file.name) + } +} + +func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + rawName := r.URL.Query().Get("path") + name, err := sharedFilePath(rawName) + if err != nil || vm.sharedDir == "" { + http.Error(w, "invalid shared file path", http.StatusBadRequest) + return + } + dir, err := filepath.Abs(vm.sharedDir) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + return + } + scope := r.Header.Get(syncScopeHeader) + if scope != "" && (!validSyncFileName(rawName) || scope != syncFileScope(vm.token, dir)) { + http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed) + return + } + switch r.Method { + case http.MethodHead, http.MethodDelete: + if scope == "" { + http.Error(w, "sync scope required", http.StatusPreconditionRequired) + return + } + fallthrough + case http.MethodGet: + s.readSharedFile(w, r, dir, name, scope != "") + case http.MethodPut, http.MethodPost: + s.writeSharedFile(w, r, filepath.Join(dir, filepath.FromSlash(name)), scope != "") + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func matchSyncFile(r *http.Request, info fs.FileInfo) bool { + if tag := r.Header.Get("If-Match"); tag != "" { + return info != nil && info.Mode().IsRegular() && syncFileTag(info) == tag + } + return r.Header.Get("If-None-Match") != "*" || info == nil +} + +// A path replaced by a symlink or directory is a conflict rather than a +// missing file. Missing files are the only ones that propagate a deletion. +func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) { + for i, ch := range name { + if ch != '/' { + continue + } + info, err := root.Lstat(name[:i]) + if err != nil { + return nil, err + } + if !info.IsDir() { + return nil, fs.ErrInvalid + } + } + info, err := root.Lstat(name) + if err == nil && !info.Mode().IsRegular() { + return nil, fs.ErrInvalid + } + return info, err +} + +func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, name string, versioned bool) { + deleting := r.Method == http.MethodDelete + expectedDigest := r.Header.Get(syncDigestHeader) + if deleting && (r.Header.Get("If-Match") == "" || expectedDigest == "") { + http.Error(w, "file revision required", http.StatusPreconditionRequired) + return + } + + root, err := os.OpenRoot(dir) + if err != nil { + switch { + case versioned: + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + case errors.Is(err, fs.ErrNotExist): + http.NotFound(w, r) + default: + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + } + return + } + defer root.Close() + info, err := statSharedFile(root, name) + switch { + case errors.Is(err, fs.ErrNotExist): + http.NotFound(w, r) + return + case errors.Is(err, fs.ErrInvalid): + status := http.StatusBadRequest + if versioned { + status = http.StatusConflict + } + http.Error(w, "path is not a regular file", status) + return + case err != nil: + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + case versioned && !matchSyncFile(r, info): + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + + tag := syncFileTag(info) + if !deleting { + w.Header().Set("ETag", tag) + } + head := r.Method == http.MethodHead + if head && r.URL.Query().Get("sha256") != "1" { + return + } + if (head || deleting) && info.Size() > MaxUploadBytes { + http.Error(w, "file exceeds sync size limit", http.StatusRequestEntityTooLarge) + return + } + file, err := root.Open(name) + if err != nil { + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + } + opened, err := file.Stat() + if err != nil || !opened.Mode().IsRegular() || syncFileTag(opened) != tag { + _ = file.Close() + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + if r.Method == http.MethodGet { + defer file.Close() + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10)) + w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10)) + _, _ = io.Copy(w, file) + return + } + + h := sha256.New() + n, err := io.Copy(h, io.LimitReader(file, info.Size()+1)) + _ = file.Close() + if err != nil || n != info.Size() { + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + digest := fmt.Sprintf("%x", h.Sum(nil)) + if head { + w.Header().Set(syncDigestHeader, digest) + return + } + s.fileMu.Lock() + defer s.fileMu.Unlock() + current, err := statSharedFile(root, name) + if digest != expectedDigest || err != nil || !os.SameFile(opened, current) || !matchSyncFile(r, current) { + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + if r.Context().Err() == nil { + if err := root.Remove(name); err != nil { + http.Error(w, "file deletion failed", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + } +} + +func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, full string, versioned bool) { + dir := filepath.Dir(full) + if err := os.MkdirAll(dir, 0o755); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + tmp, err := os.CreateTemp(dir, ".reims-upload-*") + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer os.Remove(tmp.Name()) + h := sha256.New() + var dst io.Writer = tmp + if versioned { + dst = io.MultiWriter(tmp, h) + } + n, copyErr := io.Copy(dst, io.LimitReader(r.Body, MaxUploadBytes+1)) + closeErr := tmp.Close() + switch { + case n > MaxUploadBytes: + http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge) + return + case copyErr != nil || closeErr != nil: + http.Error(w, "write failed", http.StatusInternalServerError) + return + } + if ts, err := strconv.ParseInt(r.URL.Query().Get("mtime"), 10, 64); err == nil && ts > 0 { + t := time.Unix(ts, 0) + _ = os.Chtimes(tmp.Name(), t, t) + } + s.fileMu.Lock() + defer s.fileMu.Unlock() + var uploadedTag string + if versioned { + info, err := os.Lstat(full) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + } + if !matchSyncFile(r, info) { + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + uploaded, err := os.Stat(tmp.Name()) + if err != nil { + http.Error(w, "uploaded file unavailable", http.StatusInternalServerError) + return + } + uploadedTag = syncFileTag(uploaded) + } + if err := os.Rename(tmp.Name(), full); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if versioned { + w.Header().Set("ETag", uploadedTag) + w.Header().Set(syncDigestHeader, fmt.Sprintf("%x", h.Sum(nil))) + } + w.WriteHeader(http.StatusOK) +} diff --git a/internal/guesttools/file_sync.sh b/internal/guesttools/file_sync.sh new file mode 100644 index 0000000..f6ecf65 --- /dev/null +++ b/internal/guesttools/file_sync.sh @@ -0,0 +1,213 @@ +# Keep confirmed pairs outside the share, scoped to the VM and host directory. +sync_files() { + [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 + [ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] || return 0 + + sync_remote="$TMP_DIR/sync-remote.tsv" + sync_local="$TMP_DIR/sync-local.tsv" + sync_headers="$TMP_DIR/sync-headers" + sync_plan="$TMP_DIR/sync-plan.tsv" + sync_delta="$TMP_DIR/sync-delta.tsv" + sync_state=/dev/null + if ! sync_request -fsS -m 5 -D "$sync_headers" -o "$sync_remote" "$REIMS_HOST_URL/v1/files?sync=1" 2>/dev/null; then + return 0 + fi + sync_scope=$(sync_header X-Reims-Sync-Scope) + case "$sync_scope" in + "") ;; + *[!0-9a-f]*) return 0 ;; + *) sync_state="$APP_DIR/file-sync-$sync_scope.tsv" ;; + esac + sync_previous="$sync_state" + [ -f "$sync_state" ] || sync_previous=/dev/null + + if ! find "$SHARE_SYNC"/. -name '.*' ! -name . -prune -o -type f -exec /bin/sh -c ' + root=$1 + tab=$2 + shift 2 + newline=$(printf "\nx") + newline=${newline%x} + cr=$(printf "\r") + for file do + rel=${file#"$root"/./} + case "$rel" in *"$tab"*|*"$newline"*|*"$cr"*) continue ;; esac + row=$(stat -f "%m${tab}%z${tab}%Fm:%Fc:%i:%z" "$file") || exit 1 + printf "%s\t%s\n" "$row" "$rel" + done + ' sh "$SHARE_SYNC" "$TAB" {} + > "$sync_local" 2>/dev/null; then + return 0 + fi + + # A missing path is a deletion only after a confirmed pair has existed. + # If the remaining copy changed, preserve it using the usual copy rules. + awk -F '\t' -v extended="$sync_scope" ' + BEGIN { OFS = FS } + FILENAME == ARGV[1] { + previousLocal[$4] = $1; previousRemote[$4] = $2; state[$4] = $3; paths[$4] = 1 + } + FILENAME == ARGV[2] { + p = extended == "" ? $3 : $4 + if (p != "") { + remoteTime[p] = $1; remoteSize[p] = $2; remote[p] = extended == "" ? "-" : $3; paths[p] = 1 + } + } + FILENAME == ARGV[3] && $4 != "" { + localTime[$4] = $1; localSize[$4] = $2; local[$4] = $3; paths[$4] = 1 + } + END { + for (p in paths) { + l = p in local; r = p in remote + paired = state[p] != "" && state[p] != "different" + op = "" + if (l && r) { + if (remoteTime[p] + 0 > localTime[p] + 2) op = "download" + else if (localTime[p] + 0 > remoteTime[p] + 2 && localSize[p] <= 268435456) op = "upload" + else if (extended != "" && localTime[p] == remoteTime[p] && localSize[p] == remoteSize[p] && + (local[p] != previousLocal[p] || remote[p] != previousRemote[p])) op = "verify" + } else if (r) { + op = paired && remote[p] == previousRemote[p] ? "delete-host" : "download" + } else if (l) { + if (paired && local[p] == previousLocal[p]) op = "delete-guest" + else if (localSize[p] <= 268435456) op = "upload" + } else { + op = "forget" + } + if (op != "") { + localRevision = l ? local[p] : "-" + remoteRevision = r ? remote[p] : "-" + localMtime = l ? localTime[p] : "-" + digest = state[p] != "" ? state[p] : "-" + print op, localRevision, remoteRevision, localMtime, digest, p + } + } + } + ' "$sync_previous" "$sync_remote" "$sync_local" > "$sync_plan" || return 0 + + : > "$sync_delta" || return 0 + sync_verify_left=8 + while IFS="$TAB" read -r sync_op sync_guest_rev sync_host_rev sync_guest_time sync_digest sync_rel; do + sync_apply_file + done < "$sync_plan" + if [ "$sync_state" != /dev/null ]; then + awk -F '\t' ' + $1 == "-" { delete rows[$4]; next } + { rows[$4] = $0 } + END { for (p in rows) print rows[p] } + ' "$sync_previous" "$sync_delta" > "$TMP_DIR/sync-state.next" && + mv -f "$TMP_DIR/sync-state.next" "$sync_state" + fi +} + +sync_request() { + curl -H "Authorization: Bearer $REIMS_TOKEN" "$@" +} + +sync_header() { + awk -v name="$1:" 'tolower($1) == tolower(name) { sub(/\r$/, "", $2); print $2; exit }' "$sync_headers" +} + +sync_guest_revision() { + sync_check=$1 + while [ "$sync_check" != "$SHARE_SYNC" ]; do + [ ! -L "$sync_check" ] || return 1 + sync_check=${sync_check%/*} + done + if [ -f "$1" ]; then + stat -f '%Fm:%Fc:%i:%z' "$1" 2>/dev/null + elif [ ! -e "$1" ]; then + printf '%s\n' '-' + fi +} + +sync_record() { + [ -n "$1" ] && [ -n "$2" ] && [ -n "$3" ] || return 0 + printf '%s\t%s\t%s\t%s\n' "$1" "$2" "$3" "$sync_rel" >> "$sync_delta" +} + +sync_apply_file() { + case "/$sync_rel/" in //*|*/../*|*/./*|*//*) return ;; esac + sync_target="$SHARE_SYNC/$sync_rel" + [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0 + + sync_url="$REIMS_HOST_URL/v1/file?path=$(urlencode "$sync_rel")" + if [ -n "$sync_scope" ]; then + set -- -H "X-Reims-Sync-Scope: $sync_scope" + if [ "$sync_host_rev" != - ]; then + set -- "$@" -H "If-Match: $sync_host_rev" + fi + else + set -- + fi + + case "$sync_op" in + delete-host) + sync_status=$(sync_request -sS -m 60 "$@" -H "X-Reims-File-SHA256: $sync_digest" -X DELETE \ + -o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0 + case "$sync_status" in + 204) sync_record - - -; return ;; + 412) sync_op=download ;; + *) return 0 ;; + esac + ;; + delete-guest|forget) + # A partial host listing cannot confirm that a file was deleted. + sync_status=$(sync_request -sS -m 10 "$@" -I -o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0 + [ "$sync_status" = 404 ] || return 0 + if [ "$sync_op" = "forget" ]; then + sync_record - - - + return + fi + sync_actual=$(hash_file "$sync_target") + [ -n "$sync_actual" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0 + if [ "$sync_actual" = "$sync_digest" ]; then + rm "$sync_target" && sync_record - - - + return + fi + sync_op=upload + ;; + esac + + case "$sync_op" in + download) + sync_part="$TMP_DIR/sync-download.part" + if sync_request -fsS -m 60 "$@" -D "$sync_headers" -o "$sync_part" "$sync_url" 2>/dev/null; then + sync_download_digest="" + if [ -n "$sync_scope" ]; then + sync_download_digest=$(hash_file "$sync_part") + fi + if sync_stamp=$(TZ=UTC date -r "$(sync_header X-File-Mtime)" '+%Y%m%d%H%M.%S' 2>/dev/null); then + TZ=UTC touch -t "$sync_stamp" "$sync_part" 2>/dev/null || true + fi + if [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] && + mkdir -p "$(dirname "$sync_target")" && mv -f "$sync_part" "$sync_target"; then + sync_record "$(sync_guest_revision "$sync_target")" "$(sync_header ETag)" "$sync_download_digest" + fi + fi + rm -f "$sync_part" + ;; + upload) + if [ -n "$sync_scope" ] && [ "$sync_host_rev" = - ]; then + set -- "$@" -H 'If-None-Match: *' + fi + if sync_request -fsS -m 60 "$@" -X PUT --data-binary "@$sync_target" -D "$sync_headers" -o /dev/null \ + "$sync_url&mtime=$sync_guest_time" 2>/dev/null && + [ -n "$sync_scope" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then + sync_record "$sync_guest_rev" "$(sync_header ETag)" "$(sync_header X-Reims-File-SHA256)" + fi + ;; + verify) + # Bound initial migration work when adopting pre-existing copies. + [ "$sync_verify_left" -gt 0 ] || return 0 + sync_verify_left=$((sync_verify_left - 1)) + if sync_request -fsS -m 15 "$@" -I -D "$sync_headers" -o /dev/null "$sync_url&sha256=1" 2>/dev/null; then + sync_host_hash=$(sync_header X-Reims-File-SHA256) + sync_guest_hash=$(hash_file "$sync_target") + if [ -n "$sync_host_hash" ] && [ -n "$sync_guest_hash" ] && + [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then + [ "$sync_host_hash" = "$sync_guest_hash" ] || sync_host_hash=different + sync_record "$sync_guest_rev" "$sync_host_rev" "$sync_host_hash" + fi + fi + ;; + esac +} diff --git a/internal/guesttools/file_sync_test.go b/internal/guesttools/file_sync_test.go new file mode 100644 index 0000000..99b79e1 --- /dev/null +++ b/internal/guesttools/file_sync_test.go @@ -0,0 +1,101 @@ +package guesttools + +import ( + "context" + "crypto/sha256" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFileSyncRequiresConfirmedRevisionAndContent(t *testing.T) { + root := t.TempDir() + shared := filepath.Join(root, "share") + srv := NewTransportServer(&memClipboard{}) + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = srv.Close(context.Background()) }) + cfg, err := LoadOrCreateVMConfig(root, "sync-test", shared, port) + if err != nil { + t.Fatal(err) + } + srv.RegisterVM(cfg) + + request := func(method, path, body string, headers http.Header, want int) (http.Header, string) { + t.Helper() + req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, path), strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if headers != nil { + req.Header = headers.Clone() + } + req.Header.Set("Authorization", "Bearer "+cfg.Token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, err := io.ReadAll(resp.Body) + if err != nil || resp.StatusCode != want { + t.Fatalf("%s %s: status=%d, want=%d, body=%q, read error=%v", method, path, resp.StatusCode, want, b, err) + } + return resp.Header, string(b) + } + + const fileURL = "/v1/file?path=entry.txt" + const contents = "original" + digest := fmt.Sprintf("%x", sha256.Sum256([]byte(contents))) + list, _ := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK) + scope := list.Get(syncScopeHeader) + if scope == "" { + t.Fatal("missing sync scope") + } + conditions := make(http.Header) + conditions.Set(syncScopeHeader, scope) + conditions.Set("If-None-Match", "*") + created, _ := request(http.MethodPut, fileURL+"&mtime=1700000000", contents, conditions, http.StatusOK) + tag := created.Get("ETag") + if tag == "" || created.Get(syncDigestHeader) != digest { + t.Fatalf("upload revision or digest missing: %v", created) + } + _, legacyList := request(http.MethodGet, "/v1/files", "", nil, http.StatusOK) + _, versionedList := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK) + if legacyList != "1700000000\t8\tentry.txt\n" || + versionedList != "1700000000\t8\t"+tag+"\tentry.txt\n" { + t.Fatalf("unexpected file listings: legacy=%q, versioned=%q", legacyList, versionedList) + } + + request(http.MethodPut, fileURL, "overwritten", conditions, http.StatusPreconditionFailed) + conditions.Del("If-None-Match") + conditions.Set("If-Match", tag) + probed, _ := request(http.MethodHead, fileURL+"&sha256=1", "", conditions, http.StatusOK) + if probed.Get(syncDigestHeader) != digest { + t.Fatalf("unexpected digest: %v", probed) + } + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionRequired) + conditions.Set(syncDigestHeader, digest) + conditions.Set("If-Match", "\"stale-revision\"") + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed) + conditions.Set("If-Match", tag) + request(http.MethodPut, fileURL+"&mtime=1700000000", "modified", nil, http.StatusOK) + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed) + _, got := request(http.MethodGet, fileURL, "", nil, http.StatusOK) + if got != "modified" { + t.Fatalf("modified copy was lost: %q", got) + } + conditions.Set(syncDigestHeader, fmt.Sprintf("%x", sha256.Sum256([]byte(got)))) + request(http.MethodDelete, fileURL, "", conditions, http.StatusNoContent) + request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound) + if err := os.Remove(shared); err != nil { + t.Fatal(err) + } + request(http.MethodGet, "/v1/files?sync=1", "", conditions, http.StatusServiceUnavailable) + request(http.MethodHead, fileURL, "", conditions, http.StatusServiceUnavailable) +} diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 2cc945d..0a16051 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -2,6 +2,7 @@ package guesttools import ( "bytes" + _ "embed" "fmt" "io" "os" @@ -15,8 +16,11 @@ const ( InstallCommand = "sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command" ) +//go:embed file_sync.sh +var guestFileSync string + // BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS") -// containing the per-VM Bearer token config, Guest Tools 4 POSIX agent script +// containing the per-VM Bearer token config, Guest Tools POSIX agent script // (text + PNG image clipboard with long-poll, WebDAV live mount with fallback // sync, and caffeinate prevent-sleep daemon), plus install/uninstall/pmset scripts. func BuildToolsDiskImage(outPath string, cfg VMConfig) error { @@ -65,7 +69,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files) } -// GuestAgentScript returns the Guest Tools 4 stock-macOS POSIX shell daemon +// GuestAgentScript returns the Guest Tools stock-macOS POSIX shell daemon // (no Xcode or Python required): // - Two-way UTF-8 text + PNG screenshot clipboard with server long-polling // - Zero-duplication WebDAV shared folder mount (~/Desktop/ReimsShare) with automatic sync fallback @@ -73,7 +77,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { // - Live host-controlled prevent-sleep guard via `caffeinate -dims` (no sudo required) func GuestAgentScript() []byte { return []byte(`#!/bin/sh -# Reims Guest Tools 4: clipboard, WebDAV share, read-only Windows drives, prevent-sleep. +# Reims Guest Tools: clipboard, WebDAV share, read-only Windows drives, prevent-sleep. set -u # Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified @@ -309,7 +313,7 @@ report_status() { curl -fsS -m 3 -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":6}" \ + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":7}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true } @@ -484,62 +488,7 @@ sync_clipboard() { esac } -sync_files() { - [ "$mount_mode" = "webdav" ] && return 0 - [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 - remote_list="$TMP_DIR/remote_files.tsv" - if ! curl -fsS -m 5 \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - "$REIMS_HOST_URL/v1/files" -o "$remote_list" 2>/dev/null; then - return 0 - fi - - # 1. Host -> Guest (download new or strictly newer files) - while IFS="$TAB" read -r rmtime rsize rrel; do - [ -n "$rrel" ] || continue - local_path="$SHARE_SYNC/$rrel" - need_dl=0 - if [ ! -f "$local_path" ]; then - need_dl=1 - else - lmtime=$(stat -f '%m' "$local_path" 2>/dev/null || echo 0) - if [ "$rmtime" -gt $((lmtime + 2)) ]; then - need_dl=1 - fi - fi - if [ "$need_dl" -eq 1 ]; then - mkdir -p "$(dirname "$local_path")" - enc=$(urlencode "$rrel") - dl_tmp="$TMP_DIR/dl.part" - if curl -fsS -m 60 \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - "$REIMS_HOST_URL/v1/file?path=$enc" -o "$dl_tmp" 2>/dev/null; then - mv -f "$dl_tmp" "$local_path" - touch -d "@$rmtime" "$local_path" 2>/dev/null || true - else - rm -f "$dl_tmp" - fi - fi - done <"$remote_list" - - # 2. Guest -> Host (upload new or strictly newer files) - find "$SHARE_SYNC" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do - rel=${fpath#"$SHARE_SYNC/"} - [ -n "$rel" ] || continue - lmtime=$(stat -f '%m' "$fpath" 2>/dev/null || echo 0) - lsize=$(stat -f '%z' "$fpath" 2>/dev/null || echo 0) - [ "$lsize" -le 268435456 ] || continue - rmtime=$(awk -F '\t' -v p="$rel" '$3==p {print $1; exit}' "$remote_list") - [ -n "$rmtime" ] || rmtime=0 - if [ "$lmtime" -gt $((rmtime + 2)) ]; then - enc=$(urlencode "$rel") - curl -fsS -m 60 -X PUT \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - --data-binary "@$fpath" \ - "$REIMS_HOST_URL/v1/file?path=$enc&mtime=$lmtime" >/dev/null 2>&1 || true - fi - done -} +` + guestFileSync + ` text_input_loop() { hdr="$TMP_DIR/txt_hdr" @@ -668,12 +617,12 @@ launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST # Verify host bridge connectivity immediately. . "$APP_DIR/config" if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then - echo "Reims Guest Tools 4 installed and connected!" + echo "Reims Guest Tools installed and connected!" echo "Clipboard: UTF-8 text + PNG screenshots (two-way)" echo "Shared folder: ~/Desktop/ReimsShare (WebDAV live mount, auto-fallback to sync)" echo "Prevent-sleep: controlled live from Reims-Go host UI" else - echo "Reims Guest Tools 4 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..." + echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..." fi `) } diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 0d62b2f..bb5aacb 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -11,13 +11,10 @@ import ( "errors" "fmt" "io" - "io/fs" "net" "net/http" "os" - "path" "path/filepath" - "sort" "strconv" "strings" "sync" @@ -199,6 +196,7 @@ type registeredVM struct { // (reachable from QEMU SLIRP guests as http://10.0.2.2:). type Server struct { mu sync.RWMutex + fileMu sync.Mutex clipWriteMu sync.Mutex clip Clipboard vms map[string]*registeredVM // keyed by VM name @@ -1163,208 +1161,3 @@ func (s *Server) handleHostText(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusAccepted) } - -func isIgnoredSharedName(name string) bool { - return name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "._") -} - -// resolveSharedPath validates a relative slash path and ensures the resulting -// path stays strictly inside rootDir (no .., absolute paths, drive letters, or -// symlink escapes). -func resolveSharedPath(rootDir, rel string) (string, error) { - if rootDir == "" { - return "", errors.New("shared directory not configured") - } - if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) { - return "", errors.New("invalid path") - } - trimmed := strings.TrimSpace(rel) - if trimmed == "" || strings.HasPrefix(trimmed, "/") { - return "", errors.New("invalid relative path") - } - for _, rawSeg := range strings.Split(trimmed, "/") { - if rawSeg == ".." || rawSeg == "." { - return "", errors.New("path traversal not allowed") - } - } - clean := path.Clean("/" + trimmed) - clean = strings.TrimPrefix(clean, "/") - if clean == "" || clean == "." || strings.HasPrefix(clean, "..") { - return "", errors.New("invalid relative path") - } - parts := strings.Split(clean, "/") - if len(parts) > MaxSharedDepth { - return "", errors.New("path too deep") - } - for _, seg := range parts { - if seg == "" || seg == "." || seg == ".." || strings.ContainsAny(seg, `:\<>|"?*`) || isIgnoredSharedName(seg) { - return "", errors.New("invalid path segment") - } - } - rootAbs, err := filepath.Abs(rootDir) - if err != nil { - return "", err - } - full := filepath.Join(append([]string{rootAbs}, parts...)...) - relBack, err := filepath.Rel(rootAbs, full) - if err != nil || relBack == "." || strings.HasPrefix(relBack, "..") || filepath.IsAbs(relBack) { - return "", errors.New("path escapes shared root") - } - return full, nil -} - -func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { - vm := s.authenticate(r) - if vm == nil { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - if r.Method != http.MethodGet { - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - return - } - if vm.sharedDir == "" { - w.WriteHeader(http.StatusOK) - return - } - if err := os.MkdirAll(vm.sharedDir, 0o755); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - rootAbs, err := filepath.Abs(vm.sharedDir) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - type entry struct { - mtime int64 - size int64 - rel string - } - var list []entry - _ = filepath.WalkDir(rootAbs, func(p string, d fs.DirEntry, err error) error { - if err != nil { - return nil - } - if p == rootAbs { - return nil - } - name := d.Name() - if isIgnoredSharedName(name) { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - if d.Type()&os.ModeSymlink != 0 { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - rel, err := filepath.Rel(rootAbs, p) - if err != nil { - return nil - } - slash := filepath.ToSlash(rel) - if strings.Count(slash, "/")+1 > MaxSharedDepth { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - if d.IsDir() { - return nil - } - info, err := d.Info() - if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes { - return nil - } - if len(list) >= MaxSharedFiles { - return fs.SkipAll - } - list = append(list, entry{mtime: info.ModTime().Unix(), size: info.Size(), rel: slash}) - return nil - }) - sort.Slice(list, func(i, j int) bool { return list[i].rel < list[j].rel }) - w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8") - for _, e := range list { - _, _ = fmt.Fprintf(w, "%d\t%d\t%s\n", e.mtime, e.size, e.rel) - } -} - -func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) { - vm := s.authenticate(r) - if vm == nil { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - rel := r.URL.Query().Get("path") - full, err := resolveSharedPath(vm.sharedDir, rel) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - switch r.Method { - case http.MethodGet: - info, err := os.Lstat(full) - if err != nil { - if os.IsNotExist(err) { - http.NotFound(w, r) - return - } - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if !info.Mode().IsRegular() { - http.Error(w, "not a regular file", http.StatusBadRequest) - return - } - f, err := os.Open(full) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - defer f.Close() - w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10)) - w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10)) - w.Header().Set("Content-Type", "application/octet-stream") - _, _ = io.Copy(w, f) - case http.MethodPut, http.MethodPost: - if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - tmp, err := os.CreateTemp(filepath.Dir(full), ".reims-upload-*") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - tmpName := tmp.Name() - n, copyErr := io.Copy(tmp, io.LimitReader(r.Body, MaxUploadBytes+1)) - closeErr := tmp.Close() - if copyErr != nil || closeErr != nil || n > MaxUploadBytes { - _ = os.Remove(tmpName) - if n > MaxUploadBytes { - http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge) - return - } - http.Error(w, "write failed", http.StatusInternalServerError) - return - } - if mtimeStr := r.URL.Query().Get("mtime"); mtimeStr != "" { - if ts, perr := strconv.ParseInt(mtimeStr, 10, 64); perr == nil && ts > 0 { - t := time.Unix(ts, 0) - _ = os.Chtimes(tmpName, t, t) - } - } - if err := os.Rename(tmpName, full); err != nil { - _ = os.Remove(tmpName) - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusOK) - default: - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - } -} From 585669e0b3eb34ce103e8a733b32e63b1e0e99c6 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 07:44:35 +0800 Subject: [PATCH 04/23] feat(patches): add Intel WHPX suspend and Win32 mapped-ram I/O patches --- patches/README.md | 18 + patches/qemu-intel-whpx-suspend.patch | 906 +++++++++++++++++++++++++ patches/qemu-win32-mapped-ram-io.patch | 727 ++++++++++++++++++++ patches/series.txt | 2 + 4 files changed, 1653 insertions(+) create mode 100644 patches/qemu-intel-whpx-suspend.patch create mode 100644 patches/qemu-win32-mapped-ram-io.patch diff --git a/patches/README.md b/patches/README.md index 695e20d..93189c4 100644 --- a/patches/README.md +++ b/patches/README.md @@ -30,6 +30,8 @@ | [`qemu-whpx-win10-startup-ipis.patch`](qemu-whpx-win10-startup-ipis.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 在 Win10 开启 `kernel-irqchip` 且多核启动时经 `WHvRequestInterrupt` 转发 INIT/SIPI,避免 XNU 从核卡死(依赖上一项) | 8/12 核冷启动通过;客体软重启待验证,待提 PR | | [`qemu-whpx-nested-virt-nonfatal.patch`](qemu-whpx-nested-virt-nonfatal.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 部分 Win11 宿主设置嵌套虚拟化属性返回 `0x80370302` 时改为警告并清零特性位,保留 `kernel-irqchip=on` 加速(依赖前两项) | 待编入 `alpha` 并在 Win11 真机验证后提 PR | | [`qemu-win32-coroutine-fiber-commit.patch`](qemu-win32-coroutine-fiber-commit.patch) | `vendor/qemu` (`util/coroutine-windows.c`) | 改用 `CreateFiberEx(64 KiB, 1 MiB, ...)` 将协程初始提交降至 1/16,并判空与检查 `IsThreadAFiber()`,避免高并发 I/O 时 `SwitchToFiber(NULL)` 崩溃 | `git apply --check` 通过;待编入 `alpha` 真机验证后提 PR | +| [`qemu-win32-mapped-ram-io.patch`](qemu-win32-mapped-ram-io.patch) | `vendor/qemu` (`io/channel*.c`, `migration/*.c`) | 为 Win32 `QIOChannelFile` 实现 `preadv`/`pwritev`(合并读写路径、零写保护与文件指针恢复),并解除 `mapped-ram` + `multifd` 文件快照在 Windows 下的 POSIX 限制 | Win11 WHPX 真机跨进程及真实宿主重启恢复实测通过;待提 PR | +| [`qemu-intel-whpx-suspend.patch`](qemu-intel-whpx-suspend.patch) | `vendor/qemu` (`accel/whpx/`, `target/i386/whpx/`, `hw/misc/applesmc.c`, `hw/display/reims-graphics-pci.c`, `migration/`) | 为 Intel x86-64 WHPX 实现停机文件挂起(限制在已暂停 VM 的 `MIG_MODE_NORMAL` + `file:` 迁移入口,保留非 `normal`/在线迁移与 `savevm` 拦截)、完整 LAPIC/x2APIC/TSC/AppleSMC 与 `reims-graphics-pci` VMState 保存恢复 | 7 项 QMP 闸门回归 + Win11 WHPX 真机解锁桌面同 PID Metal 读回及真实宿主重启通过;待提 PR | --- @@ -103,6 +105,22 @@ - **最小修复**:仅当磁盘为 `qcow2` 且本地可读有效头时,读取虚拟容量与 `cluster_bits` 计算 `virtual_size / cluster_size * 8` 向上取整至 MiB(上限 32 MiB),大于 8 MiB 时追加 `,l2-cache-size={mib}M`;不存在文件时静默忽略,不影响现有单元测试。 - **实测证据**(128 GiB 镜像 16 MiB L2 缓存):`rand-read-large`(热缓存)QEMU 块层平均读延迟从 128.5 μs 降至 70.6 μs(-45.1%),端到端耗时从 1,623.6 ms 降至 1,498.7 ms(-7.7%),仅增加 8 MiB 内存占用且无稳定性风险。 +### 9. `qemu-win32-mapped-ram-io.patch` +- **建议 PR 标题**:`io/channel-file & migration: support Win32 positioned vector I/O for mapped-ram file snapshots` +- **目标**:`steelbrain/qemu-reims-vgpu`(`io/channel-file.c`, `io/channel*.c`, `migration/file.c`, `migration/ram.c`, `migration/qemu-file.c`, `migration/channel-block.c`) +- **影响环境**:Windows 宿主使用 `mapped-ram` + `multifd` 执行停机文件挂起与恢复的场景。 +- **根因**:上游 `QIOChannelFile` 的 `preadv`/`pwritev` 仅在非 Win32 路径实现,`mapped-ram` 与 `multifd` 文件通道在 Windows 上直接受限。 +- **最小修复**:合并 Win32 定位读写公共逻辑(统一偏移校验、溢出安全分块、EOF/短写语义区分、零字节写入返回 `EIO` 防止死循环以及恢复原文件指针),并开放 Win32 `mapped-ram` + `multifd` 文件路径。 + +### 10. `qemu-intel-whpx-suspend.patch` +- **建议 PR 标题**:`whpx & reims-graphics-pci: support paused-VM file suspend and resume on Intel x86-64` +- **目标**:`steelbrain/qemu-reims-vgpu`(`accel/whpx/whpx-common.c`, `include/system/whpx-common.h`, `target/i386/whpx/whpx-all.c`, `target/i386/whpx/whpx-apic.c`, `hw/misc/applesmc.c`, `hw/display/reims-graphics-pci.c`, `migration/migration.c`, `migration/savevm.c`) +- **影响环境**:Intel x86-64 macOS 客体在 Windows WHPX 上的停机挂起至磁盘与跨进程/跨宿主重启恢复。 +- **最小修复**: + 1. 保留非 `MIG_MODE_NORMAL` 模式的 WHPX migration blocker,并在 `qmp_migrate()`、WHPX `MIG_EVENT_SETUP` 回调与 `save_snapshot()` 强制检查:仅放行已暂停 VM 的 `MIG_MODE_NORMAL` + `file:` 路径,拒绝运行中迁移、非 `file:` 传输、postcopy、background-snapshot、COLO 及 `savevm`。 + 2. 补齐 WHPX x86-64 vCPU/LAPIC/x2APIC/TSC 寄存器与 AppleSMC、`reims-graphics-pci` 设备 VMState 保存恢复回调(含损坏快照向 QMP 返回错误并保留挂起文件)。 +- **实测证据**:7 项 QMP 闸门回归全部通过;Windows 11 WHPX + RTX A5000 + Intel macOS 26.7.3 解锁桌面实测跨完整 QEMU 退出及真实 Windows 重启恢复,首帧 1920×1080 SHA-256 完全一致,原应用 PID / Metal 队列 / Private 资源读回 100% 匹配。 + --- ## 关注中的上游 PR 与演进 diff --git a/patches/qemu-intel-whpx-suspend.patch b/patches/qemu-intel-whpx-suspend.patch new file mode 100644 index 0000000..8bfda58 --- /dev/null +++ b/patches/qemu-intel-whpx-suspend.patch @@ -0,0 +1,906 @@ +diff --git a/accel/whpx/whpx-common.c b/accel/whpx/whpx-common.c +index 63e941496d055f1075e8e860b3785a179bb42edf..13bf3e890a93000e32fd0036fc1fde7a75c46eb4 100644 +--- a/accel/whpx/whpx-common.c ++++ b/accel/whpx/whpx-common.c +@@ -50,8 +50,14 @@ struct WHPDispatch whp_dispatch; + void whpx_flush_cpu_state(CPUState *cpu) + { + if (cpu->vcpu_dirty) { +- whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE); ++ WHPXStateLevel level = (cpu->accel && cpu->accel->loadvm_pending) ++ ? WHPX_LEVEL_FULL_STATE ++ : WHPX_LEVEL_RUNTIME_STATE; ++ whpx_set_registers(cpu, level); + cpu->vcpu_dirty = false; ++ if (cpu->accel) { ++ cpu->accel->loadvm_pending = false; ++ } + } + } + +@@ -207,6 +213,19 @@ static void do_whpx_cpu_synchronize_pre_loadvm(CPUState *cpu, + run_on_cpu_data arg) + { + cpu->vcpu_dirty = true; ++ if (cpu->accel) { ++ cpu->accel->loadvm_pending = true; ++ } ++} ++ ++static void do_whpx_cpu_synchronize_post_loadvm(CPUState *cpu, ++ run_on_cpu_data arg) ++{ ++ if (cpu->accel && cpu->accel->loadvm_pending) { ++ whpx_set_registers(cpu, WHPX_LEVEL_FULL_STATE); ++ cpu->vcpu_dirty = false; ++ cpu->accel->loadvm_pending = false; ++ } + } + + /* +@@ -237,7 +256,36 @@ void whpx_cpu_synchronize_pre_loadvm(CPUState *cpu) + + static void whpx_pre_resume_vm(AccelState *as, bool step_pending) + { ++ CPUState *cpu; ++ bool any_loadvm = false; ++ + whpx_global.step_pending = step_pending; ++ ++ CPU_FOREACH(cpu) { ++ if (cpu->accel && cpu->accel->loadvm_pending) { ++ any_loadvm = true; ++ break; ++ } ++ } ++ if (any_loadvm) { ++ uint64_t max_tsc = 0; ++ CPU_FOREACH(cpu) { ++ uint64_t t = cpu_env(cpu)->tsc; ++ if (t > max_tsc) { ++ max_tsc = t; ++ } ++ } ++ if (whp_dispatch.WHvSuspendPartitionTime) { ++ whp_dispatch.WHvSuspendPartitionTime(whpx_global.partition); ++ } ++ CPU_FOREACH(cpu) { ++ if (cpu->accel && cpu->accel->loadvm_pending) { ++ cpu_env(cpu)->tsc = max_tsc; ++ run_on_cpu(cpu, do_whpx_cpu_synchronize_post_loadvm, ++ RUN_ON_CPU_NULL); ++ } ++ } ++ } + } + + /* +@@ -525,7 +573,7 @@ static void whpx_log_sync(MemoryListener *listener, + { + MemoryRegion *mr = section->mr; + +- if (!memory_region_is_ram(mr)) { ++ if (!memory_region_is_ram(mr) || !runstate_is_running()) { + return; + } + +diff --git a/hw/display/reims-graphics-pci.c b/hw/display/reims-graphics-pci.c +index db10858b65dc0447f7d0e660fca6f1acc3bb7473..976b5d4e3bd4d93d2e9a401fd494eeb2d8e6a442 100644 +--- a/hw/display/reims-graphics-pci.c ++++ b/hw/display/reims-graphics-pci.c +@@ -114,7 +114,9 @@ + #endif + #include "qapi/error.h" + #include "qapi/qapi-commands-ui.h" +-#include "migration/blocker.h" ++#include "migration/misc.h" ++#include "migration/vmstate.h" ++#include "migration/qemu-file-types.h" + #include "hw/core/qdev-properties.h" + #include "hw/pci/pci_device.h" + #include "hw/pci/msix.h" +@@ -232,6 +234,10 @@ struct ReimsGraphicsPCIState { + bool irqfd_made; /* the notifier is initialised */ + RvgGraphicsDevice *device; + VMChangeStateEntry *vm_state; /* the teardown at QEMU's quit */ ++ NotifierWithReturn mig_notifier; ++ bool mig_notifier_added; ++ bool mig_quiesced; ++ bool region_registered; + /* The displays, display i head i: the first `displays` of them. */ + ReimsGraphicsHead heads[RVG_GRAPHICS_DISPLAYS_MAX]; + ThreadPool *pool; /* where the consoles' reads of the displays run */ +@@ -283,7 +289,6 @@ struct ReimsGraphicsPCIState { + + QEMU_BUILD_BUG_ON(RVG_GRAPHICS_MSIX_VECTORS != 1); + +-static Error *reims_graphics_mig_blocker; + + /* ------ Interrupts ------ */ + +@@ -1388,6 +1393,7 @@ static bool reims_graphics_pool_add(ReimsGraphicsPCIState *s, + memory_region_init_ram_ptr(&piece->mr, OBJECT(piece), + "reims-graphics-pci.pool-piece", ask->size, + ask->host); ++ qemu_ram_unset_migratable(piece->mr.ram_block); + /* + * Inside the add's transaction: on its own, set_unmergeable commits + * (and renders every flat view) for a region that is in none yet. +@@ -2111,6 +2117,14 @@ static void reims_graphics_pci_teardown(ReimsGraphicsPCIState *s, bool quit) + ReimsGraphicsHead *head; + uint32_t i; + ++ if (s->mig_notifier_added) { ++ migration_remove_notifier(&s->mig_notifier); ++ s->mig_notifier_added = false; ++ } ++ if (s->region_registered) { ++ vmstate_unregister_ram(&s->region, DEVICE(dev)); ++ s->region_registered = false; ++ } + if (s->vm_state) { + qemu_del_vm_change_state_handler(s->vm_state); + s->vm_state = NULL; +@@ -2477,6 +2491,158 @@ static bool reims_graphics_linux_floor(Error **errp) + return true; + } + ++ ++static int reims_graphics_pci_mig_notify(NotifierWithReturn *notify, ++ MigrationEvent *e, Error **errp) ++{ ++ ReimsGraphicsPCIState *s = ++ container_of(notify, ReimsGraphicsPCIState, mig_notifier); ++ ++ if (!s->device) { ++ return 0; ++ } ++ switch (e->type) { ++ case MIG_EVENT_SETUP: ++ if (!s->mig_quiesced) { ++ RvgStatus status = rvg_graphics_device_quiesce(s->device); ++ if (status != RVG_OK) { ++ error_setg(errp, "%s: rvg_graphics_device_quiesce failed: %s", ++ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); ++ return -1; ++ } ++ reims_graphics_pool_bh(s); ++ s->mig_quiesced = true; ++ } ++ break; ++ case MIG_EVENT_DONE: ++ case MIG_EVENT_FAILED: ++ if (s->mig_quiesced) { ++ rvg_graphics_device_unquiesce(s->device); ++ s->mig_quiesced = false; ++ } ++ break; ++ default: ++ break; ++ } ++ return 0; ++} ++ ++static int reims_graphics_vgpu_snapshot_put(QEMUFile *f, void *pv, size_t size, ++ const VMStateField *field, ++ JSONWriter *vmdesc) ++{ ++ ReimsGraphicsPCIState *s = pv; ++ uint8_t *data = NULL; ++ uintptr_t len = 0; ++ uintptr_t off = 0; ++ RvgStatus status; ++ ++ if (!s->device) { ++ qemu_put_be64(f, 0); ++ return 0; ++ } ++ status = rvg_graphics_device_snapshot_save(s->device, &data, &len); ++ if (status != RVG_OK) { ++ error_report("%s: rvg_graphics_device_snapshot_save failed: %s", ++ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); ++ return -EIO; ++ } ++ qemu_put_be64(f, (uint64_t)len); ++ while (off < len) { ++ size_t chunk = (size_t)MIN(len - off, (uintptr_t)(1 * MiB)); ++ qemu_put_buffer(f, data + off, chunk); ++ off += chunk; ++ } ++ rvg_graphics_snapshot_free(data, len); ++ return qemu_file_get_error(f); ++} ++ ++static int reims_graphics_vgpu_snapshot_get(QEMUFile *f, void *pv, size_t size, ++ const VMStateField *field) ++{ ++ ReimsGraphicsPCIState *s = pv; ++ uint64_t len = qemu_get_be64(f); ++ uint8_t *buf = NULL; ++ uint64_t off = 0; ++ RvgStatus status; ++ ++ if (qemu_file_get_error(f)) { ++ return qemu_file_get_error(f); ++ } ++ if (len == 0) { ++ return 0; ++ } ++ if (len > (uint64_t)8 * GiB || !s->device) { ++ error_report("%s: invalid vgpu snapshot length %" PRIu64, ++ TYPE_REIMS_GRAPHICS_PCI, len); ++ return -EINVAL; ++ } ++ buf = g_try_malloc(len); ++ if (!buf) { ++ return -ENOMEM; ++ } ++ while (off < len) { ++ size_t chunk = (size_t)MIN(len - off, (uint64_t)(1 * MiB)); ++ size_t got = qemu_get_buffer(f, buf + off, chunk); ++ if (got != chunk) { ++ g_free(buf); ++ return -EIO; ++ } ++ off += got; ++ } ++ status = rvg_graphics_device_snapshot_load(s->device, buf, (size_t)len); ++ g_free(buf); ++ if (status != RVG_OK) { ++ error_report("%s: rvg_graphics_device_snapshot_load failed: %s", ++ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); ++ return -EIO; ++ } ++ return 0; ++} ++ ++static const VMStateInfo vmstate_info_reims_vgpu_snapshot = { ++ .name = "reims-vgpu-snapshot", ++ .get = reims_graphics_vgpu_snapshot_get, ++ .put = reims_graphics_vgpu_snapshot_put, ++}; ++ ++static int reims_graphics_pci_post_load(void *opaque, int version_id) ++{ ++ ReimsGraphicsPCIState *s = opaque; ++ PCIDevice *dev = PCI_DEVICE(s); ++ ++ /* Synchronously map all restored Shared Pool pieces into guest GPA before cont. */ ++ reims_graphics_pool_bh(s); ++ ++ if (msix_enabled(dev)) { ++ if (s->irqfd_made) { ++ reims_graphics_pci_irqfd_enable(s); ++ } else if (s->msi_direct_made) { ++ reims_graphics_pci_direct_enable(s); ++ } ++ } ++ return 0; ++} ++ ++static const VMStateDescription vmstate_reims_graphics_pci = { ++ .name = TYPE_REIMS_GRAPHICS_PCI, ++ .version_id = 1, ++ .minimum_version_id = 1, ++ .post_load = reims_graphics_pci_post_load, ++ .fields = (const VMStateField[]) { ++ VMSTATE_PCI_DEVICE(parent_obj, ReimsGraphicsPCIState), ++ VMSTATE_MSIX(parent_obj, ReimsGraphicsPCIState), ++ { ++ .name = "reims_vgpu_snapshot", ++ .info = &vmstate_info_reims_vgpu_snapshot, ++ .flags = VMS_SINGLE, ++ .size = sizeof(ReimsGraphicsPCIState), ++ .offset = 0, ++ }, ++ VMSTATE_END_OF_LIST() ++ } ++}; ++ + static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) + { + ReimsGraphicsPCIState *s = REIMS_GRAPHICS_PCI(dev); +@@ -2577,13 +2743,7 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) + } + reims_graphics_pci_check_low_ram(); + +- if (reims_graphics_mig_blocker == NULL) { +- error_setg(&reims_graphics_mig_blocker, +- "Migration state blocked by reims-graphics-pci"); +- if (migrate_add_blocker(&reims_graphics_mig_blocker, errp) < 0) { +- return; +- } +- } ++ + + /* + * The guest's RAM, through which the GPU uses an IOSurface's own pages in +@@ -2707,6 +2867,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) + base = rvg_graphics_device_region(s->device, &size); + memory_region_init_ram_ptr(&s->region, OBJECT(dev), + "reims-graphics-pci.region", size, base); ++ vmstate_register_ram(&s->region, DEVICE(dev)); ++ s->region_registered = true; + pci_register_bar(dev, RVG_GRAPHICS_PCI_BAR_REGION, + PCI_BASE_ADDRESS_SPACE_MEMORY | + PCI_BASE_ADDRESS_MEM_TYPE_64 | +@@ -2728,6 +2890,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) + } + s->vm_state = qemu_add_vm_change_state_handler( + reims_graphics_pci_vm_state_change, s); ++ migration_add_notifier(&s->mig_notifier, reims_graphics_pci_mig_notify); ++ s->mig_notifier_added = true; + return; + + fail: +@@ -2795,6 +2959,7 @@ static void reims_graphics_pci_class_init(ObjectClass *klass, const void *data) + + rc->phases.hold = reims_graphics_pci_reset; + dc->desc = "reims-graphics GPU"; ++ dc->vmsd = &vmstate_reims_graphics_pci; + dc->hotpluggable = false; + set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories); + device_class_set_props(dc, reims_graphics_pci_properties); +diff --git a/hw/misc/applesmc.c b/hw/misc/applesmc.c +index 84bcf4df0abb15ea73fc03ecc2a2c236ae4a7c8c..2dcc20aa0e28104f5d9fa2e2a4a5ffaee4648821 100644 +--- a/hw/misc/applesmc.c ++++ b/hw/misc/applesmc.c +@@ -37,6 +37,7 @@ + #include "qemu/error-report.h" + #include "qemu/module.h" + #include "qemu/timer.h" ++#include "migration/vmstate.h" + #include "qom/object.h" + #include "hw/acpi/acpi_aml_interface.h" + +@@ -108,7 +109,7 @@ struct AppleSMCState { + uint8_t status; + uint8_t status_1e; + uint8_t last_ret; +- char key[4]; ++ uint8_t key[4]; + uint8_t read_pos; + uint8_t data_len; + uint8_t data_pos; +@@ -407,11 +408,30 @@ static void build_applesmc_aml(AcpiDevAmlIf *adev, Aml *scope) + aml_append(scope, dev); + } + ++static const VMStateDescription vmstate_applesmc = { ++ .name = "applesmc", ++ .version_id = 1, ++ .minimum_version_id = 1, ++ .fields = (const VMStateField[]) { ++ VMSTATE_UINT8(cmd, AppleSMCState), ++ VMSTATE_UINT8(status, AppleSMCState), ++ VMSTATE_UINT8(status_1e, AppleSMCState), ++ VMSTATE_UINT8(last_ret, AppleSMCState), ++ VMSTATE_UINT8_ARRAY(key, AppleSMCState, 4), ++ VMSTATE_UINT8(read_pos, AppleSMCState), ++ VMSTATE_UINT8(data_len, AppleSMCState), ++ VMSTATE_UINT8(data_pos, AppleSMCState), ++ VMSTATE_UINT8_ARRAY(data, AppleSMCState, 255), ++ VMSTATE_END_OF_LIST() ++ } ++}; ++ + static void qdev_applesmc_class_init(ObjectClass *klass, const void *data) + { + DeviceClass *dc = DEVICE_CLASS(klass); + AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass); + ++ dc->vmsd = &vmstate_applesmc; + dc->realize = applesmc_isa_realize; + dc->unrealize = applesmc_unrealize; + device_class_set_legacy_reset(dc, qdev_applesmc_isa_reset); +diff --git a/include/system/whpx-common.h b/include/system/whpx-common.h +index 79710e2fb3c96edda813fadbda5f8ceabcc5afac..a6fcbd2346b8e34a26f868a0ec19250a0fd268a6 100644 +--- a/include/system/whpx-common.h ++++ b/include/system/whpx-common.h +@@ -9,6 +9,7 @@ struct AccelCPUState { + bool ready_for_pic_interrupt; + uint64_t tpr; + bool interruption_pending; ++ bool loadvm_pending; + /* Must be the last field as it may have a tail */ + WHV_RUN_VP_EXIT_CONTEXT exit_ctx; + }; +diff --git a/migration/migration.c b/migration/migration.c +index 5686209ab11b263b20776d79df79baecd26c5970..f105f616d1dbc88daac2c573c9a95cd02305d9ab 100644 +--- a/migration/migration.c ++++ b/migration/migration.c +@@ -63,6 +63,7 @@ + #include "system/dirtylimit.h" + #include "qemu/sockets.h" + #include "system/kvm.h" ++#include "system/whpx.h" + #include "math.h" + + #define NOTIFIER_ELEM_INIT(array, elem) \ +@@ -2174,6 +2175,34 @@ void qmp_migrate(const char *uri, bool has_channels, + return; + } + ++ if (whpx_enabled()) { ++ if (has_resume && resume) { ++ error_setg(errp, "WHPX: migration resume is not supported"); ++ return; ++ } ++ if (migrate_mode() != MIG_MODE_NORMAL) { ++ error_setg(errp, "WHPX: only normal migration mode is supported"); ++ return; ++ } ++ if (runstate_is_running()) { ++ error_setg(errp, ++ "WHPX: live migration is not supported while the VM is running; stop the VM first"); ++ return; ++ } ++ if (main_ch->addr->transport != MIGRATION_ADDRESS_TYPE_FILE) { ++ error_setg(errp, ++ "WHPX: only stopped-VM file suspend (file: URI) is supported"); ++ return; ++ } ++ if (migrate_postcopy() || migrate_background_snapshot() || ++ migrate_colo() || migrate_dirty_bitmaps() || ++ migrate_return_path()) { ++ error_setg(errp, ++ "WHPX: unsupported migration capability for stopped-VM file suspend"); ++ return; ++ } ++ } ++ + if (!migrate_prepare(s, has_resume && resume, errp)) { + /* Error detected, put into errp */ + return; +diff --git a/migration/savevm.c b/migration/savevm.c +index fe94ba96e432c8555bcfc58d97f3830a86eaab60..2a1944010c595995f6d75d3cb4d6ca67525ec1fa 100644 +--- a/migration/savevm.c ++++ b/migration/savevm.c +@@ -64,6 +64,7 @@ + #include "system/runstate.h" + #include "system/system.h" + #include "system/xen.h" ++#include "system/whpx.h" + #include "migration/colo.h" + #include "qemu/bitmap.h" + #include "net/announce.h" +@@ -3317,6 +3318,12 @@ bool save_snapshot(const char *name, bool overwrite, const char *vmstate, + return false; + } + ++ if (whpx_enabled()) { ++ error_setg(errp, ++ "WHPX: internal VM snapshots are not supported; use stopped-VM file migration"); ++ return false; ++ } ++ + if (!replay_can_snapshot()) { + error_setg(errp, "Record/replay does not allow making snapshot " + "right now. Try once more later."); +diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c +index f093b59c0f04e1cdf6a14172d3b059068e61ac00..30b64eb901dcb6d0781c87dfc4241e6b4abe635c 100644 +--- a/target/i386/whpx/whpx-all.c ++++ b/target/i386/whpx/whpx-all.c +@@ -32,6 +32,7 @@ + #include "qapi/qapi-types-common.h" + #include "qapi/qapi-type-infos-common.h" + #include "migration/blocker.h" ++#include "migration/misc.h" + #include "host-cpu.h" + #include "accel/accel-cpu-target.h" + #include +@@ -56,6 +57,24 @@ + #define HV_X64_MSR_VP_ASSIST_PAGE 0x40000073 + #define HV_X64_MSR_GUEST_IDLE 0x400000f0 + ++#define WHPX_MP_STATE_RUNNABLE 0 ++#define WHPX_MP_STATE_UNINITIALIZED 1 ++#define WHPX_MP_STATE_HALTED 3 ++ ++static void whpx_set_reg_optional(CPUState *cpu, WHV_REGISTER_NAME reg, ++ WHV_REGISTER_VALUE val) ++{ ++ whp_dispatch.WHvSetVirtualProcessorRegisters( ++ whpx_global.partition, cpu->cpu_index, ®, 1, &val); ++} ++ ++static bool whpx_get_reg_optional(CPUState *cpu, WHV_REGISTER_NAME reg, ++ WHV_REGISTER_VALUE *val) ++{ ++ return SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorRegisters( ++ whpx_global.partition, cpu->cpu_index, ®, 1, val)); ++} ++ + static bool is_modern_os = true; + static bool whpx_msr_exits_available = true; + static bool whpx_forward_startup_ipis; +@@ -636,18 +655,8 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level) + whpx_set_reg(cpu, WHvX64RegisterCr8, cr8); + } + +- /* 8 Debug Registers - Skipped */ +- +- /* +- * Extended control registers needs to be handled separately depending +- * on whether xsave is supported/enabled or not. +- */ +- whpx_set_xcrs(cpu); +- +- if (whpx_is_xsave_enabled(cpu)) { +- whpx_set_xsave_state(cpu); +- } +- whpx_set_legacy_fp_registers(cpu, level); ++ /* 8 Debug Registers - restored below for FULL_STATE */ ++ /* XCR0/XSAVE/FP restored AFTER CR0/CR4/EFER are committed to WHPX */ + + /* MSRs */ + assert(whpx_register_names[idx] == WHvX64RegisterEfer); +@@ -694,10 +703,77 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level) + hr); + } + ++ if (level > WHPX_LEVEL_FAST_RUNTIME_STATE) { ++ whpx_set_xcrs(cpu); ++ if (!whpx_is_xsave_enabled(cpu) || whpx_set_xsave_state(cpu) != 0) { ++ whpx_set_legacy_fp_registers(cpu, level); ++ } ++ } ++ + if (level >= WHPX_LEVEL_FULL_STATE) { +- WHV_REGISTER_VALUE apic_base = {}; +- apic_base.Reg64 = cpu_get_apic_base(X86_CPU(cpu)->apic_state); +- whpx_set_reg(cpu, WHvX64RegisterApicBase, apic_base); ++ static const WHV_REGISTER_NAME dr_names[6] = { ++ WHvX64RegisterDr0, WHvX64RegisterDr1, WHvX64RegisterDr2, ++ WHvX64RegisterDr3, WHvX64RegisterDr6, WHvX64RegisterDr7, ++ }; ++ WHV_REGISTER_VALUE dr_vals[6] = { ++ { .Reg64 = env->dr[0] }, { .Reg64 = env->dr[1] }, ++ { .Reg64 = env->dr[2] }, { .Reg64 = env->dr[3] }, ++ { .Reg64 = env->dr[6] }, { .Reg64 = env->dr[7] }, ++ }; ++ whp_dispatch.WHvSetVirtualProcessorRegisters( ++ whpx->partition, cpu->cpu_index, dr_names, 6, dr_vals); ++ ++ WHV_REGISTER_VALUE v = {}; ++ v.Reg64 = env->tsc_aux; ++ whpx_set_reg_optional(cpu, WHvX64RegisterTscAux, v); ++ ++ /* Do not write WHvX64RegisterTscAdjust after WHvX64RegisterTsc, ++ * as MSR_IA32_TSC_ADJUST shifts the vCPU TSC offset in Hyper-V. */ ++ if (env->spec_ctrl) { ++ v.Reg64 = env->spec_ctrl; ++ whpx_set_reg_optional(cpu, WHvX64RegisterSpecCtrl, v); ++ } ++ if (env->mtrr_deftype) { ++ v.Reg64 = env->mtrr_deftype; ++ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrDefType, v); ++ for (i = 0; i < MSR_MTRRcap_VCNT; i++) { ++ v.Reg64 = env->mtrr_var[i].base; ++ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysBase0 + i, v); ++ v.Reg64 = env->mtrr_var[i].mask; ++ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysMask0 + i, v); ++ } ++ for (i = 0; i < 11; i++) { ++ v.Reg64 = env->mtrr_fixed[i]; ++ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrFix64k00000 + i, v); ++ } ++ } ++ ++ if (!whpx_irqchip_in_kernel()) { ++ WHV_REGISTER_VALUE apic_base = {}; ++ apic_base.Reg64 = cpu_get_apic_base(X86_CPU(cpu)->apic_state); ++ whpx_set_reg(cpu, WHvX64RegisterApicBase, apic_base); ++ } ++ ++ if (!whpx->tsc_deadline_refused) { ++ WHV_REGISTER_VALUE tsc_deadline = { .Reg64 = env->tsc_deadline }; ++ whpx_set_reg(cpu, WHvX64RegisterTscDeadline, tsc_deadline); ++ } ++ ++ if (whpx_irqchip_in_kernel()) { ++ WHV_REGISTER_VALUE activity = {}; ++ whpx_get_reg_optional(cpu, WHvRegisterInternalActivityState, &activity); ++ activity.InternalActivity.StartupSuspend = ++ (env->mp_state == WHPX_MP_STATE_UNINITIALIZED); ++ activity.InternalActivity.HaltSuspend = 0; ++ whpx_set_reg(cpu, WHvRegisterInternalActivityState, activity); ++ } ++ ++ { ++ WHV_REGISTER_VALUE intr_state = {}; ++ intr_state.InterruptState.InterruptShadow = ++ !!(env->hflags & HF_INHIBIT_IRQ_MASK); ++ whpx_set_reg_optional(cpu, WHvRegisterInterruptState, intr_state); ++ } + } + } + +@@ -940,6 +1016,9 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) + } + + if (!env->tsc_valid) { ++ if (!runstate_is_running() && whp_dispatch.WHvSuspendPartitionTime) { ++ whp_dispatch.WHvSuspendPartitionTime(whpx->partition); ++ } + whpx_get_tsc(cpu); + env->tsc_valid = !runstate_is_running(); + } +@@ -1016,10 +1095,9 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) + */ + whpx_get_xcrs(cpu); + +- if (whpx_is_xsave_enabled(cpu)) { +- whpx_get_xsave_state(cpu); ++ if (!whpx_is_xsave_enabled(cpu) || whpx_get_xsave_state(cpu) != 0) { ++ whpx_get_legacy_fp_registers(cpu, level); + } +- whpx_get_legacy_fp_registers(cpu, level); + + /* MSRs */ + assert(whpx_register_names[idx] == WHvX64RegisterEfer); +@@ -1051,11 +1129,83 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) + + assert(idx == RTL_NUMBER_OF(whpx_register_names)); + ++ if (level >= WHPX_LEVEL_FULL_STATE) { ++ static const WHV_REGISTER_NAME dr_names[6] = { ++ WHvX64RegisterDr0, WHvX64RegisterDr1, WHvX64RegisterDr2, ++ WHvX64RegisterDr3, WHvX64RegisterDr6, WHvX64RegisterDr7, ++ }; ++ WHV_REGISTER_VALUE dr_vals[6] = {}; ++ if (SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorRegisters( ++ whpx->partition, cpu->cpu_index, dr_names, 6, dr_vals))) { ++ env->dr[0] = dr_vals[0].Reg64; ++ env->dr[1] = dr_vals[1].Reg64; ++ env->dr[2] = dr_vals[2].Reg64; ++ env->dr[3] = dr_vals[3].Reg64; ++ env->dr[6] = dr_vals[4].Reg64; ++ env->dr[7] = dr_vals[5].Reg64; ++ } ++ ++ WHV_REGISTER_VALUE v = {}; ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterTscAux, &v)) { ++ env->tsc_aux = v.Reg64; ++ } ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterTscAdjust, &v)) { ++ env->tsc_adjust = v.Reg64; ++ } ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterSpecCtrl, &v)) { ++ env->spec_ctrl = v.Reg64; ++ } ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrDefType, &v)) { ++ env->mtrr_deftype = v.Reg64; ++ for (i = 0; i < MSR_MTRRcap_VCNT; i++) { ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysBase0 + i, &v)) { ++ env->mtrr_var[i].base = v.Reg64; ++ } ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysMask0 + i, &v)) { ++ env->mtrr_var[i].mask = v.Reg64; ++ } ++ } ++ for (i = 0; i < 11; i++) { ++ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrFix64k00000 + i, &v)) { ++ env->mtrr_fixed[i] = v.Reg64; ++ } ++ } ++ } ++ if (!whpx->tsc_deadline_refused && ++ whpx_get_reg_optional(cpu, WHvX64RegisterTscDeadline, &v)) { ++ env->tsc_deadline = v.Reg64; ++ } ++ if (whpx_irqchip_in_kernel() && ++ whpx_get_reg_optional(cpu, WHvRegisterInternalActivityState, &v)) { ++ if (v.InternalActivity.StartupSuspend) { ++ env->mp_state = WHPX_MP_STATE_UNINITIALIZED; ++ } else if (v.InternalActivity.HaltSuspend) { ++ env->mp_state = WHPX_MP_STATE_HALTED; ++ } else { ++ env->mp_state = WHPX_MP_STATE_RUNNABLE; ++ } ++ } ++ if (whpx_get_reg_optional(cpu, WHvRegisterPendingInterruption, &v) && ++ v.PendingInterruption.InterruptionPending) { ++ warn_report("WHPX: vCPU %d saved with PendingInterruption type=%u vec=%u", ++ cpu->cpu_index, ++ (unsigned)v.PendingInterruption.InterruptionType, ++ (unsigned)v.PendingInterruption.InterruptionVector); ++ } ++ } ++ + if (whpx_irqchip_in_kernel()) { + whpx_apic_get(x86_cpu->apic_state); + } + + x86_update_hflags(env); ++ if (level >= WHPX_LEVEL_FULL_STATE) { ++ WHV_REGISTER_VALUE intr_state = {}; ++ if (whpx_get_reg_optional(cpu, WHvRegisterInterruptState, &intr_state) && ++ intr_state.InterruptState.InterruptShadow) { ++ env->hflags |= HF_INHIBIT_IRQ_MASK; ++ } ++ } + } + + static int emulate_instruction(CPUState *cpu, const uint8_t *insn_bytes, size_t insn_len) +@@ -2515,8 +2665,12 @@ int whpx_vcpu_run(CPUState *cpu) + + do { + if (cpu->vcpu_dirty) { +- whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE); ++ WHPXStateLevel level = vcpu->loadvm_pending ++ ? WHPX_LEVEL_FULL_STATE ++ : WHPX_LEVEL_RUNTIME_STATE; ++ whpx_set_registers(cpu, level); + cpu->vcpu_dirty = false; ++ vcpu->loadvm_pending = false; + } + + if (exclusive_step_mode == WHPX_STEP_NONE) { +@@ -2982,6 +3136,28 @@ int whpx_vcpu_run(CPUState *cpu) + */ + + static Error *whpx_migration_blocker; ++static NotifierWithReturn whpx_migration_notifier; ++static bool whpx_migration_notifier_added; ++ ++static int whpx_migration_setup_notifier(NotifierWithReturn *notify, ++ MigrationEvent *e, Error **errp) ++{ ++ if (e->type != MIG_EVENT_SETUP) { ++ return 0; ++ } ++ if (runstate_is_running()) { ++ error_setg(errp, ++ "WHPX: live migration is not supported while the VM is running; stop the VM first"); ++ return -1; ++ } ++ if (migrate_mode() != MIG_MODE_NORMAL || ++ migrate_postcopy_ram() || migrate_background_snapshot()) { ++ error_setg(errp, ++ "WHPX: only stopped-VM normal file suspend is supported"); ++ return -1; ++ } ++ return 0; ++} + + static void whpx_cpu_update_state(void *opaque, bool running, RunState state) + { +@@ -3006,20 +3182,27 @@ int whpx_init_vcpu(CPUState *cpu) + UINT64 freq = 0; + int ret; + +- /* Add migration blockers for all unsupported features of the +- * Windows Hypervisor Platform ++ /* ++ * WHPX lacks dirty-page tracking, so live migration and non-normal modes ++ * remain blocked. Only stopped-VM normal file suspend (stop -> migrate -> ++ * quit) is permitted and enforced both at migration entry and on setup. + */ +- if (whpx_migration_blocker == NULL) { ++ if (!whpx_migration_blocker) { ++ unsigned non_normal_modes = (BIT(MIG_MODE__MAX) - 1) & ++ ~BIT(MIG_MODE_NORMAL); + error_setg(&whpx_migration_blocker, +- "State blocked due to missing dirty memory tracking support," +- "And some system register/state save-restore "); +- +- if (migrate_add_blocker(&whpx_migration_blocker, &local_error) < 0) { +- error_report_err(local_error); +- ret = -EINVAL; +- goto error; ++ "WHPX: migration mode is not supported (only stopped-VM normal file suspend)"); ++ migrate_add_blocker_modes(&whpx_migration_blocker, non_normal_modes, ++ &local_error); ++ if (local_error) { ++ error_propagate(&error_fatal, local_error); + } + } ++ if (!whpx_migration_notifier_added) { ++ migration_add_notifier(&whpx_migration_notifier, ++ whpx_migration_setup_notifier); ++ whpx_migration_notifier_added = true; ++ } + + vcpu = g_new0(AccelCPUState, 1); + +diff --git a/target/i386/whpx/whpx-apic.c b/target/i386/whpx/whpx-apic.c +index 547b1cd2671bb6b8fb5a826ab5af5ef89b0997be..75ecf48feb48b448cb39d5878d9bb86b0fa5746a 100644 +--- a/target/i386/whpx/whpx-apic.c ++++ b/target/i386/whpx/whpx-apic.c +@@ -35,13 +35,17 @@ static void whpx_put_apic_state(APICCommonState *s, + memset(kapic, 0, sizeof(*kapic)); + if (s->apicbase & MSR_IA32_APICBASE_EXTD) { + kapic->fields[0x2].data = s->initial_apic_id; ++ kapic->fields[0xd].data = ++ ((s->initial_apic_id & ~0xfu) << 12) | ++ (1u << (s->initial_apic_id & 0xfu)); ++ kapic->fields[0xe].data = 0; + } else { + kapic->fields[0x2].data = s->id << 24; ++ kapic->fields[0xd].data = s->log_dest << 24; ++ kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff; + } + kapic->fields[0x3].data = s->version | ((APIC_LVT_NB - 1) << 16); + kapic->fields[0x8].data = s->tpr; +- kapic->fields[0xd].data = s->log_dest << 24; +- kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff; + kapic->fields[0xf].data = s->spurious_vec; + for (i = 0; i < 8; i++) { + kapic->fields[0x10 + i].data = s->isr[i]; +@@ -212,10 +216,18 @@ static void whpx_apic_put(CPUState *cs, run_on_cpu_data data) + &kapic, + sizeof(kapic)); + if (FAILED(hr)) { ++ struct whpx_lapic_state cur = {}; ++ whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( ++ whpx_global.partition, cs->cpu_index, &cur, sizeof(cur), NULL); + fprintf(stderr, +- "WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n", +- hr); +- ++ "WHvSetVirtualProcessorInterruptControllerState2 failed: %08lx cpu=%d apicbase=0x%llx\n", ++ hr, cs->cpu_index, (unsigned long long)s->apicbase); ++ for (int idx = 0; idx < 256; idx++) { ++ if (kapic.fields[idx].data || cur.fields[idx].data) { ++ fprintf(stderr, " lapic[0x%02x]: put=0x%08x cur=0x%08x\n", ++ idx, kapic.fields[idx].data, cur.fields[idx].data); ++ } ++ } + abort(); + } + } +@@ -224,8 +236,17 @@ void whpx_apic_get(APICCommonState *s) + { + CPUState *cpu = CPU(s->cpu); + struct whpx_lapic_state kapic; ++ WHV_REGISTER_NAME base_reg = WHvX64RegisterApicBase; ++ WHV_REGISTER_VALUE base_val = {}; ++ HRESULT hr; ++ ++ hr = whp_dispatch.WHvGetVirtualProcessorRegisters( ++ whpx_global.partition, cpu->cpu_index, &base_reg, 1, &base_val); ++ if (SUCCEEDED(hr)) { ++ s->apicbase = base_val.Reg64; ++ } + +- HRESULT hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( ++ hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( + whpx_global.partition, + cpu->cpu_index, + &kapic, +@@ -233,7 +254,7 @@ void whpx_apic_get(APICCommonState *s) + NULL); + if (FAILED(hr)) { + fprintf(stderr, +- "WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n", ++ "WHvGetVirtualProcessorInterruptControllerState2 failed: %08lx\n", + hr); + + abort(); +@@ -242,6 +263,17 @@ void whpx_apic_get(APICCommonState *s) + whpx_get_apic_state(s, &kapic); + } + ++static void do_whpx_apic_get(CPUState *cs, run_on_cpu_data data) ++{ ++ APICCommonState *s = data.host_ptr; ++ whpx_apic_get(s); ++} ++ ++static void whpx_apic_pre_save(APICCommonState *s) ++{ ++ run_on_cpu(CPU(s->cpu), do_whpx_apic_get, RUN_ON_CPU_HOST_PTR(s)); ++} ++ + static void whpx_apic_post_load(APICCommonState *s) + { + run_on_cpu(CPU(s->cpu), whpx_apic_put, RUN_ON_CPU_HOST_PTR(s)); +@@ -379,6 +411,7 @@ static void whpx_apic_class_init(ObjectClass *klass, const void *data) + k->set_base = apic_set_base; + k->set_tpr = whpx_apic_set_tpr; + k->get_tpr = whpx_apic_get_tpr; ++ k->pre_save = whpx_apic_pre_save; + k->post_load = whpx_apic_post_load; + k->vapic_base_update = whpx_apic_vapic_base_update; + k->external_nmi = whpx_apic_external_nmi; diff --git a/patches/qemu-win32-mapped-ram-io.patch b/patches/qemu-win32-mapped-ram-io.patch new file mode 100644 index 0000000..61ebe21 --- /dev/null +++ b/patches/qemu-win32-mapped-ram-io.patch @@ -0,0 +1,727 @@ +diff --git a/include/io/channel.h b/include/io/channel.h +index 834ba7c30986dd48686705da5aa7197eb228cef7..87f751308d6fdd7b87e31be44fca07fe93501aba 100644 +--- a/include/io/channel.h ++++ b/include/io/channel.h +@@ -146,12 +146,12 @@ struct QIOChannelClass { + ssize_t (*io_pwritev)(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + ssize_t (*io_preadv)(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + int (*io_shutdown)(QIOChannel *ioc, + QIOChannelShutdown how, +@@ -160,8 +160,8 @@ struct QIOChannelClass { + bool enabled); + void (*io_set_delay)(QIOChannel *ioc, + bool enabled); +- off_t (*io_seek)(QIOChannel *ioc, +- off_t offset, ++ int64_t (*io_seek)(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp); + void (*io_set_aio_fd_handler)(QIOChannel *ioc, +@@ -579,7 +579,7 @@ int qio_channel_close(QIOChannel *ioc, + * + */ + ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, +- size_t niov, off_t offset, Error **errp); ++ size_t niov, int64_t offset, Error **errp); + + /** + * qio_channel_pwrite +@@ -595,7 +595,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, + * + */ + ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, +- off_t offset, Error **errp); ++ int64_t offset, Error **errp); + + /** + * qio_channel_pwritev_all: +@@ -614,7 +614,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, + int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -635,7 +635,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, + const void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -656,7 +656,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, + * + */ + ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, +- size_t niov, off_t offset, Error **errp); ++ size_t niov, int64_t offset, Error **errp); + + /** + * qio_channel_pread +@@ -672,7 +672,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, + * + */ + ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, +- off_t offset, Error **errp); ++ int64_t offset, Error **errp); + + /** + * qio_channel_preadv_all_eof: +@@ -695,7 +695,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, + int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -717,7 +717,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -741,7 +741,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, + void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -763,7 +763,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc, + void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp); + + /** +@@ -861,10 +861,10 @@ void qio_channel_set_cork(QIOChannel *ioc, + * Not all implementations will support this facility, + * so may report an error. + * +- * Returns: the new position on success, (off_t)-1 on failure ++ * Returns: the new position on success, (int64_t)-1 on failure + */ +-off_t qio_channel_io_seek(QIOChannel *ioc, +- off_t offset, ++int64_t qio_channel_io_seek(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp); + +diff --git a/include/system/ramblock.h b/include/system/ramblock.h +index 24c970d393e9cc3463fa46a9bcace7937e50fde4..981470f59d569181f859718942ecb9a855f33078 100644 +--- a/include/system/ramblock.h ++++ b/include/system/ramblock.h +@@ -68,7 +68,7 @@ struct RAMBlock { + * offset in the file pages belonging to this ramblock are saved, + * used only during migration to a file. + */ +- off_t bitmap_offset; ++ int64_t bitmap_offset; + uint64_t pages_offset; + + /* Bitmap of already received pages. Only used on destination side. */ +diff --git a/io/channel-buffer.c b/io/channel-buffer.c +index 189fa67ac21df8a8dff868a477a8021873bd22c7..873e80faeb8a8496ddb6fb0743a17ad599a60654 100644 +--- a/io/channel-buffer.c ++++ b/io/channel-buffer.c +@@ -124,8 +124,8 @@ static int qio_channel_buffer_set_blocking(QIOChannel *ioc G_GNUC_UNUSED, + } + + +-static off_t qio_channel_buffer_seek(QIOChannel *ioc, +- off_t offset, ++static int64_t qio_channel_buffer_seek(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp) + { +diff --git a/io/channel-file.c b/io/channel-file.c +index 2487adaea2ad7108310b94910153a4ffbf6eb094..2fb80f90e1c6251c1b2b493e8ebb6566b6b0b769 100644 +--- a/io/channel-file.c ++++ b/io/channel-file.c +@@ -27,6 +27,9 @@ + #include "qemu/module.h" + #include "qemu/sockets.h" + #include "trace.h" ++#ifdef WIN32 ++#include ++#endif + + QIOChannelFile * + qio_channel_file_new_fd(int fd) +@@ -42,7 +45,7 @@ qio_channel_file_new_fd(int fd) + + ioc->fd = fd; + +- if (lseek(fd, 0, SEEK_CUR) != (off_t)-1) { ++ if (lseek(fd, 0, SEEK_CUR) != (int64_t)-1) { + qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE); + } + +@@ -74,6 +77,9 @@ qio_channel_file_new_path(const char *path, + + ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE)); + ++#ifdef O_BINARY ++ flags |= O_BINARY; ++#endif + if (flags & O_CREAT) { + ioc->fd = qemu_create(path, flags & ~O_CREAT, mode, errp); + } else { +@@ -84,9 +90,18 @@ qio_channel_file_new_path(const char *path, + return NULL; + } + +- if (lseek(ioc->fd, 0, SEEK_CUR) != (off_t)-1) { ++ if (lseek(ioc->fd, 0, SEEK_CUR) != (int64_t)-1) { + qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE); + } ++#ifdef WIN32 ++ if (flags & O_CREAT) { ++ HANDLE h = (HANDLE)_get_osfhandle(ioc->fd); ++ if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_DISK) { ++ DWORD br = 0; ++ DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &br, NULL); ++ } ++ } ++#endif + + trace_qio_channel_file_new_path(ioc, path, flags, mode, ioc->fd); + +@@ -170,7 +185,7 @@ static ssize_t qio_channel_file_writev(QIOChannel *ioc, + static ssize_t qio_channel_file_preadv(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); +@@ -196,7 +211,7 @@ static ssize_t qio_channel_file_preadv(QIOChannel *ioc, + static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); +@@ -216,6 +231,125 @@ static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, + } + return ret; + } ++#elif defined(WIN32) ++static ssize_t qio_channel_file_prw_win32(QIOChannel *ioc, ++ const struct iovec *iov, ++ size_t niov, ++ int64_t offset, ++ bool is_write, ++ Error **errp) ++{ ++ static const size_t max_chunk = 16U * 1024U * 1024U; ++ QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); ++ HANDLE h = (HANDLE)_get_osfhandle(fioc->fd); ++ LARGE_INTEGER zero = { .QuadPart = 0 }; ++ LARGE_INTEGER saved = { .QuadPart = 0 }; ++ bool have_saved = false; ++ uint64_t cur; ++ ssize_t total = 0; ++ ssize_t ret = -1; ++ size_t i = 0; ++ ++ if (offset < 0) { ++ error_setg_errno(errp, EINVAL, "Invalid negative offset for %s", ++ is_write ? "pwritev" : "preadv"); ++ return -1; ++ } ++ if (h == INVALID_HANDLE_VALUE) { ++ error_setg_errno(errp, EBADF, "Invalid file handle for %s", ++ is_write ? "pwritev" : "preadv"); ++ return -1; ++ } ++ ++ cur = (uint64_t)offset; ++ have_saved = SetFilePointerEx(h, zero, &saved, FILE_CURRENT); ++ ++ while (i < niov) { ++ uint8_t *base = (uint8_t *)iov[i].iov_base; ++ size_t run = iov[i].iov_len; ++ size_t j = i + 1; ++ ++ while (j < niov && (uint8_t *)iov[j].iov_base == base + run && ++ run < max_chunk && iov[j].iov_len <= max_chunk - run) { ++ run += iov[j].iov_len; ++ j++; ++ } ++ if (run == 0) { ++ i = j; ++ continue; ++ } ++ ++ size_t done = 0; ++ while (done < run) { ++ DWORD chunk = (DWORD)MIN(run - done, max_chunk); ++ DWORD xfer = 0; ++ OVERLAPPED ov; ++ BOOL ok; ++ ++ memset(&ov, 0, sizeof(ov)); ++ ov.Offset = (DWORD)(cur & 0xFFFFFFFFULL); ++ ov.OffsetHigh = (DWORD)(cur >> 32); ++ if (is_write) { ++ ok = WriteFile(h, base + done, chunk, &xfer, &ov); ++ } else { ++ ok = ReadFile(h, base + done, chunk, &xfer, &ov); ++ } ++ if (!ok) { ++ DWORD err = GetLastError(); ++ if (!is_write && err == ERROR_HANDLE_EOF) { ++ ret = total; ++ goto out; ++ } ++ error_setg_win32(errp, err, ++ is_write ? "Unable to pwritev to file" ++ : "Unable to preadv from file"); ++ goto out; ++ } ++ if (xfer == 0) { ++ if (!is_write || total > 0) { ++ ret = total; ++ goto out; ++ } ++ error_setg_errno(errp, EIO, "pwritev made no progress"); ++ goto out; ++ } ++ done += xfer; ++ cur += xfer; ++ total += xfer; ++ if (is_write && xfer < chunk) { ++ /* Preserve short-write semantics for caller retry/error handling. */ ++ ret = total; ++ goto out; ++ } ++ } ++ i = j; ++ } ++ ++ ret = total; ++out: ++ if (have_saved) { ++ SetFilePointerEx(h, saved, NULL, FILE_BEGIN); ++ } ++ return ret; ++} ++ ++static ssize_t qio_channel_file_preadv(QIOChannel *ioc, ++ const struct iovec *iov, ++ size_t niov, ++ int64_t offset, ++ Error **errp) ++{ ++ return qio_channel_file_prw_win32(ioc, iov, niov, offset, false, errp); ++} ++ ++static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, ++ const struct iovec *iov, ++ size_t niov, ++ int64_t offset, ++ Error **errp) ++{ ++ return qio_channel_file_prw_win32(ioc, iov, niov, offset, true, errp); ++} + #endif /* CONFIG_PREADV */ + + static int qio_channel_file_set_blocking(QIOChannel *ioc, +@@ -223,7 +357,11 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc, + Error **errp) + { + #ifdef WIN32 +- /* not implemented */ ++ QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); ++ if (enabled || ++ GetFileType((HANDLE)_get_osfhandle(fioc->fd)) == FILE_TYPE_DISK) { ++ return 0; ++ } + error_setg_errno(errp, errno, "Failed to set FD nonblocking"); + return -1; + #else +@@ -237,16 +375,20 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc, + } + + +-static off_t qio_channel_file_seek(QIOChannel *ioc, +- off_t offset, ++static int64_t qio_channel_file_seek(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp) + { + QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); +- off_t ret; ++ int64_t ret; + ++#ifdef WIN32 ++ ret = (int64_t)_lseeki64(fioc->fd, (int64_t)offset, whence); ++#else + ret = lseek(fioc->fd, offset, whence); +- if (ret == (off_t)-1) { ++#endif ++ if (ret == (int64_t)-1) { + error_setg_errno(errp, errno, + "Unable to seek to offset %lld whence %d in file", + (long long int)offset, whence); +@@ -314,7 +456,7 @@ static void qio_channel_file_class_init(ObjectClass *klass, + ioc_klass->io_writev = qio_channel_file_writev; + ioc_klass->io_readv = qio_channel_file_readv; + ioc_klass->io_set_blocking = qio_channel_file_set_blocking; +-#ifdef CONFIG_PREADV ++#if defined(CONFIG_PREADV) || defined(WIN32) + ioc_klass->io_pwritev = qio_channel_file_pwritev; + ioc_klass->io_preadv = qio_channel_file_preadv; + #endif +diff --git a/io/channel-null.c b/io/channel-null.c +index 49f1c80a54e1337aa39010ef39a5ea5de4c5392f..2032d26b3c14a28fc36aedc8a3f0248a4701abb9 100644 +--- a/io/channel-null.c ++++ b/io/channel-null.c +@@ -105,9 +105,9 @@ qio_channel_null_set_blocking(QIOChannel *ioc G_GNUC_UNUSED, + } + + +-static off_t ++static int64_t + qio_channel_null_seek(QIOChannel *ioc G_GNUC_UNUSED, +- off_t offset G_GNUC_UNUSED, ++ int64_t offset G_GNUC_UNUSED, + int whence G_GNUC_UNUSED, + Error **errp G_GNUC_UNUSED) + { +diff --git a/io/channel.c b/io/channel.c +index 620256f310dbeb060113e71055246ca29431d13d..03d721ec0d699d7c9bcbf2866881d53d7e6b25c0 100644 +--- a/io/channel.c ++++ b/io/channel.c +@@ -450,7 +450,7 @@ GSource *qio_channel_add_watch_source(QIOChannel *ioc, + + + ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, +- size_t niov, off_t offset, Error **errp) ++ size_t niov, int64_t offset, Error **errp) + { + QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc); + +@@ -468,7 +468,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, + } + + ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, +- off_t offset, Error **errp) ++ int64_t offset, Error **errp) + { + struct iovec iov = { + .iov_base = buf, +@@ -481,7 +481,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, + int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + int ret = -1; +@@ -519,7 +519,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, + const void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp) + { + struct iovec iov = { .iov_base = (char *)buf, .iov_len = buflen }; +@@ -527,7 +527,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, + } + + ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, +- size_t niov, off_t offset, Error **errp) ++ size_t niov, int64_t offset, Error **errp) + { + QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc); + +@@ -545,7 +545,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, + } + + ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, +- off_t offset, Error **errp) ++ int64_t offset, Error **errp) + { + struct iovec iov = { + .iov_base = buf, +@@ -558,7 +558,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, + int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + int ret = -1; +@@ -609,7 +609,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + int ret = qio_channel_preadv_all_eof(ioc, iov, niov, offset, errp); +@@ -629,7 +629,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, + void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp) + { + struct iovec iov = { .iov_base = buf, .iov_len = buflen }; +@@ -639,7 +639,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, + int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc, + void *buf, + size_t buflen, +- off_t offset, ++ int64_t offset, + Error **errp) + { + struct iovec iov = { .iov_base = buf, .iov_len = buflen }; +@@ -696,8 +696,8 @@ int qio_channel_get_peerpid(QIOChannel *ioc, + return 0; + } + +-off_t qio_channel_io_seek(QIOChannel *ioc, +- off_t offset, ++int64_t qio_channel_io_seek(QIOChannel *ioc, ++ int64_t offset, + int whence, + Error **errp) + { +diff --git a/migration/channel-block.c b/migration/channel-block.c +index 9cf383d4b57728b2561dbb45afd44c72df15061b..8a0893fb7e4d4cb9e5e91d1418e99674f4562c23 100644 +--- a/migration/channel-block.c ++++ b/migration/channel-block.c +@@ -101,7 +101,7 @@ static ssize_t + qio_channel_block_preadv(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc); +@@ -122,7 +122,7 @@ static ssize_t + qio_channel_block_pwritev(QIOChannel *ioc, + const struct iovec *iov, + size_t niov, +- off_t offset, ++ int64_t offset, + Error **errp) + { + QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc); +@@ -152,9 +152,9 @@ qio_channel_block_set_blocking(QIOChannel *ioc, + } + + +-static off_t ++static int64_t + qio_channel_block_seek(QIOChannel *ioc, +- off_t offset, ++ int64_t offset, + int whence, + Error **errp) + { +@@ -169,7 +169,7 @@ qio_channel_block_seek(QIOChannel *ioc, + break; + case SEEK_END: + error_setg(errp, "Size of VMstate region is unknown"); +- return (off_t)-1; ++ return (int64_t)-1; + default: + g_assert_not_reached(); + } +diff --git a/migration/channel-block.h b/migration/channel-block.h +index 31673824e6971398b73f55cfb36a521ca0d91791..b2f6768f6ce5a058dc0a082ccd4d0d9297befd3f 100644 +--- a/migration/channel-block.h ++++ b/migration/channel-block.h +@@ -39,7 +39,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelBlock, QIO_CHANNEL_BLOCK) + struct QIOChannelBlock { + QIOChannel parent; + BlockDriverState *bs; +- off_t offset; ++ int64_t offset; + }; + + +diff --git a/migration/file.c b/migration/file.c +index 8ba1de2006eed5a643b7394b9bc4c83cb8d9b4af..5419455d6d314e7529c20116b274d61ce1e38e99 100644 +--- a/migration/file.c ++++ b/migration/file.c +@@ -108,7 +108,11 @@ QIOChannel *file_connect_outgoing(MigrationState *s, + goto out; + } + ++#ifdef WIN32 ++ if (_chsize_s(fioc->fd, (int64_t)offset) != 0) { ++#else + if (ftruncate(fioc->fd, offset)) { ++#endif + error_setg_errno(errp, errno, + "failed to truncate migration file to offset %" PRIx64, + offset); +diff --git a/migration/multifd.h b/migration/multifd.h +index fbc35702b062fdc3213ce92baed35994f5967c2b..2ce94f07403fe1cbe1655728e13c58eeb53dbbe5 100644 +--- a/migration/multifd.h ++++ b/migration/multifd.h +@@ -133,7 +133,7 @@ struct MultiFDRecvData { + void *opaque; + size_t size; + /* for preadv */ +- off_t file_offset; ++ int64_t file_offset; + }; + + typedef struct { +diff --git a/migration/qemu-file.c b/migration/qemu-file.c +index df3f96fb24005d0fcf397bf8035b460a04eb2490..4aef4856599e83c6bb72012dbea3f163ab838add 100644 +--- a/migration/qemu-file.c ++++ b/migration/qemu-file.c +@@ -532,7 +532,7 @@ void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size) + } + + void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, +- off_t pos) ++ int64_t pos) + { + Error *err = NULL; + +@@ -550,7 +550,7 @@ void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, + } + + +-size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, ++size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos, + Error **errp) + { + if (f->last_error) { +@@ -566,10 +566,10 @@ size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, + return buflen; + } + +-void qemu_set_offset(QEMUFile *f, off_t off, int whence) ++void qemu_set_offset(QEMUFile *f, int64_t off, int whence) + { + Error *err = NULL; +- off_t ret; ++ int64_t ret; + + if (qemu_file_is_writable(f)) { + qemu_fflush(f); +@@ -580,20 +580,20 @@ void qemu_set_offset(QEMUFile *f, off_t off, int whence) + } + + ret = qio_channel_io_seek(f->ioc, off, whence, &err); +- if (ret == (off_t)-1) { ++ if (ret == (int64_t)-1) { + qemu_file_set_error_obj(f, -EIO, err); + } + } + +-off_t qemu_get_offset(QEMUFile *f) ++int64_t qemu_get_offset(QEMUFile *f) + { + Error *err = NULL; +- off_t ret; ++ int64_t ret; + + qemu_fflush(f); + + ret = qio_channel_io_seek(f->ioc, 0, SEEK_CUR, &err); +- if (ret == (off_t)-1) { ++ if (ret == (int64_t)-1) { + qemu_file_set_error_obj(f, -EIO, err); + } + return ret; +diff --git a/migration/qemu-file.h b/migration/qemu-file.h +index 966766788ddfb11e08eb8b059d43c69a66260818..c5d2a984611da615e8561866af954f6e778780bf 100644 +--- a/migration/qemu-file.h ++++ b/migration/qemu-file.h +@@ -72,11 +72,11 @@ QEMUFile *qemu_file_get_return_path(QEMUFile *f); + int qemu_fflush(QEMUFile *f); + bool qemu_file_set_blocking(QEMUFile *f, bool block, Error **errp); + int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size); +-void qemu_set_offset(QEMUFile *f, off_t off, int whence); +-off_t qemu_get_offset(QEMUFile *f); ++void qemu_set_offset(QEMUFile *f, int64_t off, int whence); ++int64_t qemu_get_offset(QEMUFile *f); + void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, +- off_t pos); +-size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, ++ int64_t pos); ++size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos, + Error **errp); + + QIOChannel *qemu_file_get_ioc(QEMUFile *file); +diff --git a/migration/ram.c b/migration/ram.c +index e6db3bf523855ee1ea20e79495326979f00d3192..410cfa6a1c2bfe84308d19c36bd8a00157226581 100644 +--- a/migration/ram.c ++++ b/migration/ram.c +@@ -1010,7 +1010,7 @@ static uint64_t physical_memory_sync_dirty_bitmap(RAMBlock *rb, + unsigned long *dest = rb->bmap; + + /* start address and length is aligned at the start of a word? */ +- if (((word * BITS_PER_LONG) << TARGET_PAGE_BITS) == ++ if ((((ram_addr_t)word * BITS_PER_LONG) << TARGET_PAGE_BITS) == + (start + rb->offset) && + !(length & ((BITS_PER_LONG << TARGET_PAGE_BITS) - 1))) { + int k; +@@ -4137,8 +4137,8 @@ static bool handle_zero_mapped_ram(RAMBlock *block, unsigned long from_bit_idx, + return true; + } + +- size = TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx); +- offset = from_bit_idx << TARGET_PAGE_BITS; ++ size = (size_t)TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx); ++ offset = ((ram_addr_t)from_bit_idx) << TARGET_PAGE_BITS; + host = host_from_ram_block_offset(block, offset); + if (!host) { + error_setg(errp, "zero page outside of ramblock %s range", +@@ -4172,8 +4172,8 @@ static bool read_ramblock_mapped_ram(QEMUFile *f, RAMBlock *block, + /* Non-zero pages */ + clear_bit_idx = find_next_zero_bit(bitmap, num_pages, set_bit_idx + 1); + +- unread = TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx); +- offset = set_bit_idx << TARGET_PAGE_BITS; ++ unread = (size_t)TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx); ++ offset = ((ram_addr_t)set_bit_idx) << TARGET_PAGE_BITS; + + while (unread > 0) { + host = host_from_ram_block_offset(block, offset); diff --git a/patches/series.txt b/patches/series.txt index 1de7565..b499927 100644 --- a/patches/series.txt +++ b/patches/series.txt @@ -14,3 +14,5 @@ vendor/qemu qemu-whpx-win10-compat.patch vendor/qemu qemu-whpx-win10-startup-ipis.patch vendor/qemu qemu-whpx-nested-virt-nonfatal.patch vendor/qemu qemu-win32-coroutine-fiber-commit.patch +vendor/qemu qemu-win32-mapped-ram-io.patch +vendor/qemu qemu-intel-whpx-suspend.patch From 347840490e1a75cf236063aa0c2b607fa672f33a Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 07:48:14 +0800 Subject: [PATCH 05/23] feat(patches): add reims-vgpu/metal2vulkan snapshot replay and build pipeline support --- .github/workflows/build-runtime.yml | 29 +- patches/README.md | 21 +- patches/metal2vulkan-snapshot-replay.patch | 525 +++ patches/reims-vgpu-cargo-lock.patch | 28 - patches/reims-vgpu-snapshot-replay.patch | 4309 ++++++++++++++++++++ patches/series.txt | 29 +- scripts/apply-patch-series.ps1 | 15 +- scripts/pack-runtime.ps1 | 86 +- 8 files changed, 4972 insertions(+), 70 deletions(-) create mode 100644 patches/metal2vulkan-snapshot-replay.patch delete mode 100644 patches/reims-vgpu-cargo-lock.patch create mode 100644 patches/reims-vgpu-snapshot-replay.patch diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 6f6650d..376e939 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -142,6 +142,21 @@ jobs: if ($LASTEXITCODE) { throw 'reims-util fetch failed' } git -C $utilRepo checkout -q --detach FETCH_HEAD if ($LASTEXITCODE) { throw 'reims-util checkout failed' } + $m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan' + $cargoToml = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.toml') + if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') { + $m2vRev = $Matches[1] + } else { + $lockTxt = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.lock') + if ($lockTxt -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' } + $m2vRev = $Matches[1] + } + git init -q $m2vRepo + if ($LASTEXITCODE) { throw 'metal2vulkan init failed' } + git -C $m2vRepo fetch -q --depth 1 https://github.com/steelbrain/metal2vulkan.git $m2vRev + if ($LASTEXITCODE) { throw 'metal2vulkan fetch failed' } + git -C $m2vRepo checkout -q --detach FETCH_HEAD + if ($LASTEXITCODE) { throw 'metal2vulkan checkout failed' } $short = (git -C $work rev-parse --short=7 HEAD).Trim() $releaseId = "$short${{ needs.resolve.outputs.suffix }}" "short=$short" >> $env:GITHUB_OUTPUT @@ -151,7 +166,7 @@ jobs: # conflict without touching the patch (AGENTS.md rule 4). $resultFile = Join-Path $env:RUNNER_TEMP 'patches.json' try { - pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -ResultFile $resultFile + pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -Metal2VulkanRepo $m2vRepo -ResultFile $resultFile $ok = $LASTEXITCODE -eq 0 } finally { if (Test-Path $resultFile) { @@ -163,11 +178,20 @@ jobs: } } if (-not $ok) { throw 'patch queue does not apply' } + $cargoHome = Join-Path $env:RUNNER_TEMP 'cargo' + $m2vFwd = $m2vRepo.Replace('\', '/') + $cargoCfg = @" + [patch."https://github.com/steelbrain/metal2vulkan"] + metal2vulkan = { path = "$m2vFwd/crates/metal2vulkan" } + metal2vulkan-runtime = { path = "$m2vFwd/crates/metal2vulkan-runtime" } + "@ -replace '(?m)^ ', '' + [IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false)) "UPSTREAM_DIR=$work" >> $env:GITHUB_ENV "REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV + "METAL2VULKAN_DIR=$m2vRepo" >> $env:GITHUB_ENV "SHORT_COMMIT=$short" >> $env:GITHUB_ENV "RELEASE_ID=$releaseId" >> $env:GITHUB_ENV - "CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV + "CARGO_HOME=$cargoHome" >> $env:GITHUB_ENV "XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV "XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV @@ -200,6 +224,7 @@ jobs: & ./scripts/pack-runtime.ps1 ` -ReimsRepo $env:UPSTREAM_DIR ` -UtilRepo $env:REIMS_UTIL_DIR ` + -Metal2VulkanRepo $env:METAL2VULKAN_DIR ` -CargoHome $env:CARGO_HOME ` -QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') ` -Msys2 '${{ steps.msys2.outputs.msys2-location }}' ` diff --git a/patches/README.md b/patches/README.md index 93189c4..cfe32b1 100644 --- a/patches/README.md +++ b/patches/README.md @@ -4,12 +4,12 @@ ## 维护原则 -1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu) 和 [`reims-util`](https://github.com/steelbrain/reims-util)。 +1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)、[`reims-util`](https://github.com/steelbrain/reims-util) 和 [`metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。 2. **人工提 PR,冲突即停**:更新上游基线时由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按顺序执行 `git apply --check`。已合入上游(反向检查通过)的补丁会自动跳过并开 Issue 提醒退役;遇到冲突时立刻中止构建,不自动改写补丁。 3. **文件格式约束**:所有 `.patch` 文件必须为 **无 BOM、LF 行尾**(由 `.gitattributes` 中的 `*.patch -text` 约束),避免 `git apply` 在 Windows 上失败。 4. **来源透明与协议兼容**:每个运行时包的 `manifest.json` 与 `patches/` 目录必须如实记录实际应用的全部补丁及哈希;本目录补丁不适用根目录的 Apache-2.0,而是遵循目标上游兼容协议(详见 [`patches/LICENSE`](LICENSE))。 -本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树。用相同的 MSYS2 CLANG64 工具链安装其中的 `reims-util` 后,把同一工作树传给打包脚本。 +本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树,`-Metal2VulkanRepo` 指向 `reims-vgpu/Cargo.toml` 固定版本的 `metal2vulkan` 工作树(并通过 `$CARGO_HOME/config.toml` 的 `[patch."https://github.com/steelbrain/metal2vulkan"]` 覆盖,使 `reims-vgpu/Cargo.lock` 与上游保持逐字节一致)。用相同的 MSYS2 CLANG64 工具链构建后,把同一组工作树传给打包脚本。 --- @@ -19,13 +19,14 @@ | 补丁文件 | 目标仓库与路径 | 解决的问题 | 当前状态 | | :--- | :--- | :--- | :--- | -| [`reims-vgpu-cargo-lock.patch`](reims-vgpu-cargo-lock.patch) | `reims-vgpu` (`Cargo.lock`) | 补齐 `metal2vulkan` 三个 crate 的 `source` 锁定信息,使源码包与实际 Cargo 构建逐字节一致 | 仅用于构建可复现;上游补齐 `Cargo.lock` 后删除 | | [`reims-vgpu-win32-unicode-input.patch`](reims-vgpu-win32-unicode-input.patch) | `reims-vgpu` (`crates/reims-vgpu-window`) | 通过 `SDL_SetWindowsMessageHook` 在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时转发非物理按键的 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`,解决 Windows IME 与中文输入被吞 | 待编入 `alpha` 冒烟验证后提 PR | | [`reims-vgpu-display-fixed-mode.patch`](reims-vgpu-display-fixed-mode.patch) | `reims-vgpu` (`crates/reims-vgpu-window`, `crates/reims-vgpu`) | 新增 `REIMS_VGPU_WINDOW_FIXED_MODE=1` 将全屏/窗口物理尺寸与客体渲染分辨率解耦,按 `scale * (guest_w / drawable_w)` 推导有效 DPI,并在帧尺寸与目标区域不一致时自动走线性采样 GPU 着色器缩放(支持 4K 全屏 1.5× 超采样 `5120×2880` HiDPI) | `git apply --check` 在 `3731afd9` 通过;待编入 `alpha` 真机验证后提 PR | | [`reims-ctl-win32-random-bytes.patch`](reims-ctl-win32-random-bytes.patch) | `reims-vgpu` (`crates/reims-ctl/src/vm.rs`) | 修复 Windows 下打不开 `/dev/urandom` 时回退到低熵时间戳种子的缺陷,改用标准库 `RandomState`(底层调用 `ProcessPrng`)生成 MAC/ROM 随机字节 | `git apply --check` 通过;待编入 `alpha` 验证后提 PR | | [`reims-ctl-virtio-discard-iothread.patch`](reims-ctl-virtio-discard-iothread.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 为 VirtIO 系统盘补齐 `discard=unmap`(与 NVMe 一致透传客体 TRIM)并启用独立 `-object iothread,id=io0`,避免块完成回调与 QEMU 主循环争抢 | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;真机实测与休眠唤醒通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | | [`reims-ctl-qcow2-l2-cache.patch`](reims-ctl-qcow2-l2-cache.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 按 `qcow2` 文件头虚拟容量与簇大小计算全覆盖所需 `l2-cache-size`(上限 32 MiB,仅大于 8 MiB 默认值时追加),避免非 Linux 宿主默认 8 MiB 上限仅覆盖 64 GiB | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;128 GiB 镜像真机实测通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | +| [`reims-vgpu-snapshot-replay.patch`](reims-vgpu-snapshot-replay.patch) | `reims-vgpu` (`crates/reims-vgpu*`) | 实现 GPU 静止、实时对象日志与 `RVGSNAP1` 二进制编解码(含统一计数边界校验、因果父对象保留、`whole_library_key` 索引及未附着延迟 SurfaceCache 持久化)、显存与事件保存/重放及严格错误传播 | 单元测试、双进程 RTX A5000 Vulkan 测试及 Intel macOS 26.7.3 同 PID Metal 读回实测通过;待提 PR | | [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `reims-util` (`src/http.rs`, `src/installer.rs`) | 对有 Apple 分块校验数据的完整离线包并发请求四段,按顺序校验并写入镜像。分段读取失败时用原有单路下载继续 | 待编入 `alpha` 冒烟验证 | +| [`metal2vulkan-snapshot-replay.patch`](metal2vulkan-snapshot-replay.patch) | `metal2vulkan` (`crates/metal2vulkan-runtime/src/`) | 暴露 Private/Shared/Managed 缓冲与纹理(含多层/多 Mip)及事件计数的快照读出与精确地址/内容回写接口 | 随 `reims-vgpu-snapshot-replay.patch` 在干净 checkout 构建并实测通过;待提 PR | | [`qemu-whpx-win10-compat.patch`](qemu-whpx-win10-compat.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 修复 Windows 10 19045 上两处 WHPX 必现崩溃(探测 TSC deadline 污染主分区、`WHvResetPartition` 未判空) | 已在 Win10 19045 真机验证并随稳定运行时发布;待提 PR | | [`qemu-whpx-win10-startup-ipis.patch`](qemu-whpx-win10-startup-ipis.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 在 Win10 开启 `kernel-irqchip` 且多核启动时经 `WHvRequestInterrupt` 转发 INIT/SIPI,避免 XNU 从核卡死(依赖上一项) | 8/12 核冷启动通过;客体软重启待验证,待提 PR | | [`qemu-whpx-nested-virt-nonfatal.patch`](qemu-whpx-nested-virt-nonfatal.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 部分 Win11 宿主设置嵌套虚拟化属性返回 `0x80370302` 时改为警告并清零特性位,保留 `kernel-irqchip=on` 加速(依赖前两项) | 待编入 `alpha` 并在 Win11 真机验证后提 PR | @@ -121,6 +122,20 @@ 2. 补齐 WHPX x86-64 vCPU/LAPIC/x2APIC/TSC 寄存器与 AppleSMC、`reims-graphics-pci` 设备 VMState 保存恢复回调(含损坏快照向 QMP 返回错误并保留挂起文件)。 - **实测证据**:7 项 QMP 闸门回归全部通过;Windows 11 WHPX + RTX A5000 + Intel macOS 26.7.3 解锁桌面实测跨完整 QEMU 退出及真实 Windows 重启恢复,首帧 1920×1080 SHA-256 完全一致,原应用 PID / Metal 队列 / Private 资源读回 100% 匹配。 +### 11. `metal2vulkan-snapshot-replay.patch` +- **建议 PR 标题**:`runtime: add snapshot readback and exact-address restore hooks for buffers, textures, and events` +- **目标**:`steelbrain/metal2vulkan`(`crates/metal2vulkan-runtime/src/{block,device,event,floor,lib,memory,places}.rs`) +- **最小修复**:为 `metal2vulkan-runtime` 增加共享/私有池块分配恢复、Private 缓冲/纹理全子资源(含多 mip/slice)内容读回与回写、以及事件值读写接口,使上层 `reims-vgpu` 可在宿主进程重启后原位重建客体可见 GPU 地址与显存内容。 + +### 12. `reims-vgpu-snapshot-replay.patch` +- **建议 PR 标题**:`graphics & pool: add RVGSNAP1 device quiesce, live object log, and strict snapshot replay` +- **目标**:`steelbrain/reims-vgpu`(`crates/reims-vgpu*`) +- **最小修复**: + 1. 统一 `quiesce_device()` 静止流程(排空传输与编译任务、刷写表面缓存并等待 GPU 空闲),由 `reims-vgpu-c` 暴露保存/加载 C ABI 供 `reims-graphics-pci` VMState 调用。 + 2. 新增 `RVGSNAP1` 二进制快照编解码,由 `Dec::checked_count` / `read_vec` 在分配前统一按剩余字节和最小条目大小校验计数并校验尾部无多余字节。 + 3. 完整保存与回放共享/私有内存池、实时对象日志(含 `whole_library_key` 索引与因果父对象保留,避免 ARC 释放 `MTLLibrary` 后导致活跃管线回放失败)、事件计数、Private 缓冲/纹理与未附着延迟 `SurfaceCache`(含 VA-API P010 视频帧),任何关键对象或显存保存/恢复失败均向 QMP 返回错误且不解除静止。 +- **实测证据**:干净上游 checkout 通过 `reims-vgpu-graphics` 与 `reims-vgpu` 快照单元测试及 `reims-vgpu-c` 零警告 release 构建;RTX A5000 双进程 Vulkan 读回与 Intel macOS 26.7.3 解锁桌面跨进程同 PID Metal 读回(Buffer/Texture/Event/SharedEvent + 恢复后原队列继续 Compute 变异)100% 通过。 + --- ## 关注中的上游 PR 与演进 diff --git a/patches/metal2vulkan-snapshot-replay.patch b/patches/metal2vulkan-snapshot-replay.patch new file mode 100644 index 0000000..549eae8 --- /dev/null +++ b/patches/metal2vulkan-snapshot-replay.patch @@ -0,0 +1,525 @@ +diff --git a/crates/metal2vulkan-runtime/src/block.rs b/crates/metal2vulkan-runtime/src/block.rs +index 0ac77ecac0f3abb9e9b76fb82d17c3536e22f4f5..426d025513a2f04e97f31efa66d1632635f7254d 100644 +--- a/crates/metal2vulkan-runtime/src/block.rs ++++ b/crates/metal2vulkan-runtime/src/block.rs +@@ -54,6 +54,12 @@ impl Block { + Block { claim } + } + ++ /// Returns capture/replay address metadata for this block (if supported). ++ pub fn capture_info(&self) -> Option { ++ let (core, block) = self.held().ok()?; ++ core.pool.capture_info(&block.memory) ++ } ++ + /// Whether the block is of `core`'s device. + pub(crate) fn is_of(&self, core: &Arc) -> bool { + Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core) +diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs +index 8edf1f27202f9a19b19cc4a4484d1e31341b8ab1..68f79440cc7727f2fae6063756380fe7a85ce7f9 100644 +--- a/crates/metal2vulkan-runtime/src/device.rs ++++ b/crates/metal2vulkan-runtime/src/device.rs +@@ -273,6 +273,7 @@ pub(crate) struct Core { + /// every render pipeline takes its colour flag, and a draw reads an attachment of its pass + /// with the image in the feedback layout. + pub(crate) feedback_loop: bool, ++ pub(crate) capture_replay: bool, + /// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists + /// it): a lost device's fault report, read once, at its first loss (`crate::fault`). + pub(crate) fault: Option, +@@ -860,6 +861,7 @@ impl Device { + ticks, + calibrated, + feedback_loop: capabilities.feedback_loop, ++ capture_replay: capabilities.buffer_device_address_capture_replay, + fault, + indirect, + attachment_reads: capabilities.attachment_reads, +@@ -1140,6 +1142,41 @@ impl Device { + /// allocation past the device's count; [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped) + /// where the consumer did not map the allocation the take made; [`Error::Vulkan`] where the + /// device is out of memory or lost; [`Error::Quiesced`]. ++ /// Whether Vulkan `bufferDeviceAddressCaptureReplay` is enabled on this device. ++ pub fn buffer_device_address_capture_replay(&self) -> bool { ++ self.shared.core.capture_replay ++ } ++ ++ /// Waits non-destructively until all in-flight GPU work has completed and retired. ++ pub fn wait_idle(&self) -> Result<(), Error> { ++ let core = &self.shared.core; ++ if core.closed() { ++ return Err(Error::Quiesced); ++ } ++ // Wait for submitted command buffers to retire on the completion thread. ++ let deadline = Instant::now() + Duration::from_secs(10); ++ while core.pool.in_flight() > 0 && Instant::now() < deadline { ++ std::thread::sleep(Duration::from_millis(1)); ++ } ++ // SAFETY: `device` is live and wait_idle synchronizes all host queues. ++ let _q = lock(&core.queues.runtime); ++ unsafe { core.device.device_wait_idle() }.map_err(Error::vulkan("vkDeviceWaitIdle"))?; ++ Ok(()) ++ } ++ ++ /// Replays a previously captured block at its exact Vulkan device address. ++ pub fn take_block_replayed(&self, capture: memory::BlockCaptureInfo) -> Result { ++ let core = &self.shared.core; ++ if core.closed() { ++ return Err(Error::Quiesced); ++ } ++ let memory = core.pool.take_replayed(core, capture, crate::counters::Site::take(capture.class))?; ++ let info = memory.info(); ++ let block = memory::Block::new(memory, Arc::clone(core)); ++ Ok(Block::claim(core, info, block)) ++ } ++ ++ /// Allocates a new GPU memory block of `class` and `len` bytes. + pub fn take_block(&self, class: MemoryClass, len: u64) -> Result { + let core = &self.shared.core; + if core.closed() { +diff --git a/crates/metal2vulkan-runtime/src/event.rs b/crates/metal2vulkan-runtime/src/event.rs +index fe95046625fb1d1c81e2925458c22c4dd3641197..8b47e5604f50dec0549733c515ce80e02dbe348e 100644 +--- a/crates/metal2vulkan-runtime/src/event.rs ++++ b/crates/metal2vulkan-runtime/src/event.rs +@@ -140,6 +140,35 @@ impl Event { + } + } + ++impl Event { ++ /// Reads the current signaled value of this timeline event (for checkpointing). ++ pub fn signaled_value(&self) -> u64 { ++ let inner = &self.inner; ++ let state = lock(&inner.state); ++ let floor = state.observed.max(state.floor); ++ inner.reached(None).map_or(floor, |reached| reached.max(floor)) ++ } ++ ++ /// Restores the timeline semaphore and CPU floor to `value` on a freshly created event. ++ pub fn restore_signaled_value(&self, value: u64) -> Result<(), Error> { ++ if value == 0 { ++ return Ok(()); ++ } ++ let inner = &self.inner; ++ let info = vk::SemaphoreSignalInfo::default() ++ .semaphore(inner.semaphore) ++ .value(value); ++ // SAFETY: `semaphore` is a live timeline semaphore on `inner.core.device`. ++ unsafe { inner.core.device.signal_semaphore(&info) } ++ .map_err(Error::vulkan("vkSignalSemaphore"))?; ++ let mut state = lock(&inner.state); ++ state.floor = state.floor.max(value); ++ state.observed = state.observed.max(value); ++ inner.changed.notify_all(); ++ Ok(()) ++ } ++} ++ + impl SharedEvent { + /// `signaledValue`: the higher of the semaphore's value and the host's floor, the semaphore's + /// value being one a host wait confirmed: a counter read finds it, and a wait with a timeout +diff --git a/crates/metal2vulkan-runtime/src/floor.rs b/crates/metal2vulkan-runtime/src/floor.rs +index 0e165934f4b7534d0a093b1a22bcd763a47db8d7..90c7f9e354af205aa5a6b2fbeb506e58fbba1ab8 100644 +--- a/crates/metal2vulkan-runtime/src/floor.rs ++++ b/crates/metal2vulkan-runtime/src/floor.rs +@@ -1079,6 +1079,8 @@ pub struct Capabilities { + /// [`ATTACHMENT_READ_EXTENSIONS`]: a draw reads an attachment through the attachment feedback + /// loop, the feedback layout its image moves to and the flag every render pipeline takes. + pub feedback_loop: bool, ++ /// Whether `bufferDeviceAddressCaptureReplay` is enabled for checkpoint/restore. ++ pub buffer_device_address_capture_replay: bool, + /// The features device creation enables: every one the floor requires, each of the optional, + /// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment + /// and fault-report ones the device reports, the attachment-read ones where +@@ -1425,6 +1427,10 @@ pub(crate) fn decide(device: &Queried) -> Result { + let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else { + return Err(BelowFloor { missing }); + }; ++ let capture_replay = reported.vulkan12.buffer_device_address_capture_replay == vk::TRUE; ++ if capture_replay { ++ features.vulkan12.buffer_device_address_capture_replay = vk::TRUE; ++ } + for feature in (OPTIONAL.iter().chain(STEP_RATES)) + .chain(MIN_LOD_CLAMPS) + .chain(FILL_MODES) +@@ -1491,6 +1497,7 @@ pub(crate) fn decide(device: &Queried) -> Result { + texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE, + attachment_reads, + feedback_loop, ++ buffer_device_address_capture_replay: capture_replay, + features, + extensions: DEVICE_EXTENSIONS + .iter() +diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs +index a2d59cc6f31eb64307c1a886fe7cf75f401511b1..557a1a4b213773df976895f703cd4c037ad2602b 100644 +--- a/crates/metal2vulkan-runtime/src/lib.rs ++++ b/crates/metal2vulkan-runtime/src/lib.rs +@@ -100,7 +100,7 @@ pub use host_bytes::HostBytes; + pub use import::ImportHandle; + pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType}; + pub use instance::{Instance, PhysicalDevice}; +-pub use memory::{AllocationId, AllocationInfo, BlockId, BlockInfo, BlockMappings, MemoryClass}; ++pub use memory::{AllocationId, AllocationInfo, BlockCaptureInfo, BlockId, BlockInfo, BlockMappings, MemoryClass}; + /// `MTLLibrary`: the translator's, read from AIR or a metallib. + /// `MTLSamplerDescriptor`: the translator's. + pub use metal2vulkan::bind::SamplerDescriptor; +diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs +index 173e0858f2e6d07660cafd5f7893aee280f2dcdc..2864f4ba6b48a4892e6d9651548c75a4babcf395 100644 +--- a/crates/metal2vulkan-runtime/src/memory.rs ++++ b/crates/metal2vulkan-runtime/src/memory.rs +@@ -235,8 +235,28 @@ impl AllocationId { + /// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer + /// usage and a device address, spans it; an imported or exported block is the whole of an + /// allocation of its own. Only an exported block is exportable. ++/// Capture/replay address metadata for restoring a block at its exact Vulkan device address. ++#[derive(Clone, Copy, Debug, PartialEq, Eq)] ++pub struct BlockCaptureInfo { ++ /// Storage mode (`Shared` or `Private`). ++ pub class: MemoryClass, ++ /// Full parent Vulkan allocation length in bytes. ++ pub alloc_len: u64, ++ /// Offset of this block inside its parent allocation. ++ pub offset: u64, ++ /// Block length in bytes. ++ pub len: u64, ++ /// Guest-visible `VkDeviceAddress` of this block's first byte. ++ pub gpu_address: u64, ++ /// Opaque capture address of the parent `VkBuffer`. ++ pub opaque_buffer_address: u64, ++ /// Opaque capture address of the parent `VkDeviceMemory`. ++ pub opaque_memory_address: u64, ++} ++ + #[non_exhaustive] + #[derive(Clone, Copy, Debug)] ++/// Metadata describing an allocated GPU memory block. + pub struct BlockInfo { + /// The block's number. + pub id: BlockId, +@@ -611,6 +631,10 @@ struct Allocation { + buffer: vk::Buffer, + /// The device address of its first byte. + address: u64, ++ /// Opaque capture address of `buffer` (0 if capture-replay unsupported). ++ opaque_buffer_address: u64, ++ /// Opaque capture address of `memory` (0 if capture-replay unsupported). ++ opaque_memory_address: u64, + len: u64, + mapping: Option, + device_local: bool, +@@ -823,6 +847,8 @@ struct State { + /// The internal the block-maker thread took up and is making ([`run`]). + making: Option, + stop: bool, ++ replaying: bool, ++ making_ahead: bool, + next_id: u32, + next_allocation: u32, + /// The allocations [`BlockMappings::map`] accepted whose unmap has not run. +@@ -952,6 +978,8 @@ impl Pool { + asked: [true; INTERNALS], + making: None, + stop: false, ++ replaying: false, ++ making_ahead: false, + next_id: 1, + next_allocation: 1, + mapped: HashSet::new(), +@@ -1368,6 +1396,158 @@ impl Pool { + } + } + ++ /// Returns capture/replay info for a pool block, if capture-replay is enabled. ++ pub(crate) fn capture_info(&self, memory: &Memory) -> Option { ++ if memory.own.is_some() { ++ return None; ++ } ++ let state = self.lock(); ++ let alloc = state.allocations[memory.class.index()] ++ .iter() ++ .find(|a| a.memory == memory.memory)?; ++ ++ Some(BlockCaptureInfo { ++ class: memory.class, ++ alloc_len: alloc.len, ++ offset: memory.base, ++ len: memory.len, ++ gpu_address: memory.address, ++ opaque_buffer_address: alloc.opaque_buffer_address, ++ opaque_memory_address: alloc.opaque_memory_address, ++ }) ++ } ++ ++ /// Replays a previously captured pool block at its exact Vulkan device address. ++ pub(crate) fn take_replayed( ++ &self, ++ core: &Core, ++ cap: BlockCaptureInfo, ++ site: Site, ++ ) -> Result { ++ let index = cap.class.index(); ++ // 1. Check if the parent allocation is already present (e.g. another sub-block restored it, ++ // or a pre-stocked idle reserve landed at the exact same address!). ++ { ++ let mut state = self.lock(); ++ if state.stop { ++ return Err(Error::Quiesced); ++ } ++ let id = number(&mut state)?; ++ let want_base = cap.gpu_address.saturating_sub(cap.offset); ++ if let Some(alloc) = state.allocations[index].iter_mut().find(|a| { ++ a.address == want_base ++ && a.opaque_buffer_address == cap.opaque_buffer_address ++ && a.opaque_memory_address == cap.opaque_memory_address ++ && a.len == cap.alloc_len ++ }) { ++ if alloc.free.take_at(cap.offset, cap.len) { ++ let carve = alloc.carve(cap.offset); ++ alloc.live += 1; ++ alloc.placed += cap.len; ++ alloc.ahead = false; ++ self.counters.rise_by(cap.class.placed_gauge(), cap.len); ++ self.settle(&mut state, cap.class); ++ self.changed.notify_all(); ++ return Ok(carve.block(id, cap.class, cap.len)); ++ } ++ } ++ } ++ // 2. Pause block-maker ahead allocations, wait for any in-flight ahead make, ++ // and purge idle reserve slabs so none collide with the target opaque VA! ++ let idle_allocs: Vec = { ++ let mut state = self.lock(); ++ state.replaying = true; ++ while state.making_ahead { ++ state = self.wait(state); ++ } ++ // Re-check if an ahead allocation that just finished landed at the exact target VA! ++ let want_base = cap.gpu_address.saturating_sub(cap.offset); ++ let hit = state.allocations[index].iter_mut().find_map(|a| { ++ if a.address == want_base ++ && a.opaque_buffer_address == cap.opaque_buffer_address ++ && a.opaque_memory_address == cap.opaque_memory_address ++ && a.len == cap.alloc_len ++ && a.free.take_at(cap.offset, cap.len) ++ { ++ let carve = a.carve(cap.offset); ++ a.live += 1; ++ a.placed += cap.len; ++ a.ahead = false; ++ Some(carve) ++ } else { ++ None ++ } ++ }); ++ if let Some(carve) = hit { ++ let id = number(&mut state)?; ++ state.replaying = false; ++ self.counters.rise_by(cap.class.placed_gauge(), cap.len); ++ self.settle(&mut state, cap.class); ++ self.changed.notify_all(); ++ return Ok(carve.block(id, cap.class, cap.len)); ++ } ++ let mut drained = Vec::new(); ++ for c in MemoryClass::ALL { ++ let ci = c.index(); ++ let mut kept = Vec::new(); ++ for a in state.allocations[ci].drain(..) { ++ if a.live == 0 { ++ drained.push(a); ++ } else { ++ kept.push(a); ++ } ++ } ++ state.allocations[ci] = kept; ++ self.settle(&mut state, c); ++ } ++ drained ++ }; ++ for a in idle_allocs { ++ free_idle(core, a); ++ } ++ // 3. Allocate at the exact captured opaque buffer + memory addresses. ++ let alloc_res = make_allocation_ex( ++ core, ++ cap.class, ++ cap.alloc_len, ++ Some(site), ++ Some((cap.opaque_buffer_address, cap.opaque_memory_address)), ++ ); ++ let mut allocation = match alloc_res { ++ Ok(a) => a, ++ Err(e) => { ++ let mut state = self.lock(); ++ state.replaying = false; ++ self.changed.notify_all(); ++ return Err(e); ++ } ++ }; ++ let mapped = self.map(&allocation, cap.class, true); ++ if !mapped { ++ free_allocation(core, allocation); ++ let mut state = self.lock(); ++ state.replaying = false; ++ self.changed.notify_all(); ++ return Err(Error::Limit(Limit::AllocationNotMapped { ++ class: cap.class, ++ len: cap.alloc_len, ++ })); ++ } ++ let ok = allocation.free.take_at(cap.offset, cap.len); ++ debug_assert!(ok, "fresh allocation must contain captured block range"); ++ let mut state = self.lock(); ++ let id = number(&mut state)?; ++ let memory = allocation.carve(cap.offset).block(id, cap.class, cap.len); ++ allocation.live = 1; ++ allocation.placed = cap.len; ++ state.allocations[index].push(allocation); ++ state.replaying = false; ++ self.counters.rise_by(cap.class.placed_gauge(), cap.len); ++ self.settle(&mut state, cap.class); ++ self.changed.notify_all(); ++ Ok(memory) ++ } ++ + /// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its + /// allocation at once. + pub(crate) fn give_back(&self, memory: Memory) { +@@ -1788,12 +1968,16 @@ pub(crate) fn run(core: Arc) { + state = pool.lock(); + continue; + } +- let wanted = (MemoryClass::ALL.into_iter()) +- .find(|&class| !state.failed[class.index()] && !state.whole(class)); ++ let wanted = (!state.replaying).then(|| { ++ (MemoryClass::ALL.into_iter()) ++ .find(|&class| !state.failed[class.index()] && !state.whole(class)) ++ }).flatten(); + if let Some(class) = wanted { ++ state.making_ahead = true; + drop(state); + let made = ahead(&core, class); + state = pool.lock(); ++ state.making_ahead = false; + match made { + // Idle from now: the reserve, which the idle rule does not weigh. + Some(mut allocation) => { +@@ -2022,6 +2206,16 @@ fn make_allocation( + class: MemoryClass, + len: u64, + site: Option, ++) -> Result { ++ make_allocation_ex(core, class, len, site, None) ++} ++ ++fn make_allocation_ex( ++ core: &Core, ++ class: MemoryClass, ++ len: u64, ++ site: Option, ++ replay: Option<(u64, u64)>, + ) -> Result { + let device = &core.device; + let (id, freed_at) = { +@@ -2031,22 +2225,38 @@ fn make_allocation( + state.freed_at[class.index()], + ) + }; +- let info = vk::BufferCreateInfo::default() ++ let mut buf_opaque = vk::BufferOpaqueCaptureAddressCreateInfo::default() ++ .opaque_capture_address(replay.map_or(0, |(b, _)| b)); ++ let mut info = vk::BufferCreateInfo::default() + .size(len) + .usage(floor::BUFFER_USAGE) + .sharing_mode(vk::SharingMode::EXCLUSIVE); ++ if core.capture_replay { ++ info = info.flags(vk::BufferCreateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY); ++ if replay.is_some_and(|(b, _)| b != 0) { ++ info = info.push_next(&mut buf_opaque); ++ } ++ } + // SAFETY: the device is live, and the create info valid: `len` is at most its + // `maxBufferSize`. + let buffer = + unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?; + // SAFETY: the buffer is the device's. + let requirements = unsafe { device.get_buffer_memory_requirements(buffer) }; +- let mut flags = +- vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); +- let allocate_info = vk::MemoryAllocateInfo::default() ++ let mut mem_flags = vk::MemoryAllocateFlags::DEVICE_ADDRESS; ++ if core.capture_replay { ++ mem_flags |= vk::MemoryAllocateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY; ++ } ++ let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(mem_flags); ++ let mut mem_opaque = vk::MemoryOpaqueCaptureAddressAllocateInfo::default() ++ .opaque_capture_address(replay.map_or(0, |(_, m)| m)); ++ let mut allocate_info = vk::MemoryAllocateInfo::default() + .allocation_size(requirements.size.max(len)) + .memory_type_index(core.memory_type(class)) + .push_next(&mut flags); ++ if core.capture_replay && replay.is_some_and(|(_, m)| m != 0) { ++ allocate_info = allocate_info.push_next(&mut mem_opaque); ++ } + let bits = requirements.memory_type_bits; + // SAFETY: the floor chose the memory type for buffers of this usage on this device, and + // `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow. +@@ -2065,6 +2275,8 @@ fn make_allocation( + memory, + buffer, + address: 0, ++ opaque_buffer_address: 0, ++ opaque_memory_address: 0, + len, + mapping: None, + device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0, +@@ -2101,6 +2313,13 @@ fn make_allocation( + let of = vk::BufferDeviceAddressInfo::default().buffer(buffer); + // SAFETY: the buffer has device-address usage and is bound. + allocation.address = unsafe { device.get_buffer_device_address(&of) }; ++ if core.capture_replay { ++ allocation.opaque_buffer_address = ++ unsafe { device.get_buffer_opaque_capture_address(&of) }; ++ let mof = vk::DeviceMemoryOpaqueCaptureAddressInfo::default().memory(memory); ++ allocation.opaque_memory_address = ++ unsafe { device.get_device_memory_opaque_capture_address(&mof) }; ++ } + (core.spans).made( + buffer, + allocation.address, +diff --git a/crates/metal2vulkan-runtime/src/places.rs b/crates/metal2vulkan-runtime/src/places.rs +index 137fb5790de850552affd179497df69d9912266a..3d679bbaa5285e87d1639a7cc140e0025b49e84f 100644 +--- a/crates/metal2vulkan-runtime/src/places.rs ++++ b/crates/metal2vulkan-runtime/src/places.rs +@@ -248,6 +248,33 @@ impl Ranges { + Some(at) + } + ++ /// Takes the exact range `at..at + len` if it is completely free. ++ pub(crate) fn take_at(&mut self, at: u64, len: u64) -> bool { ++ let Some(stop) = at.checked_add(len) else { ++ return false; ++ }; ++ let Some(index) = self ++ .free ++ .iter() ++ .position(|&(start, end)| start <= at && stop <= end) ++ else { ++ return false; ++ }; ++ let (start, end) = self.free[index]; ++ match (start < at, stop < end) { ++ (false, false) => { ++ self.free.remove(index); ++ } ++ (true, false) => self.free[index] = (start, at), ++ (false, true) => self.free[index] = (stop, end), ++ (true, true) => { ++ self.free[index] = (start, at); ++ self.free.insert(index + 1, (stop, end)); ++ } ++ } ++ true ++ } ++ + /// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it. + pub(crate) fn give(&mut self, offset: u64, len: u64) { + let end = offset + len; diff --git a/patches/reims-vgpu-cargo-lock.patch b/patches/reims-vgpu-cargo-lock.patch deleted file mode 100644 index 4efd9a2..0000000 --- a/patches/reims-vgpu-cargo-lock.patch +++ /dev/null @@ -1,28 +0,0 @@ -diff --git a/Cargo.lock b/Cargo.lock -index 106e75e..01bf052 100644 ---- a/Cargo.lock -+++ b/Cargo.lock -@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - [[package]] - name = "metal2vulkan" - version = "0.2.0" -+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" - dependencies = [ - "ash", - "metal2vulkan-air", -@@ -223,6 +224,7 @@ dependencies = [ - [[package]] - name = "metal2vulkan-air" - version = "0.2.0" -+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" - dependencies = [ - "sha2 0.11.1", - ] -@@ -230,6 +232,7 @@ dependencies = [ - [[package]] - name = "metal2vulkan-runtime" - version = "0.2.0" -+source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" - dependencies = [ - "ash", - "libc", diff --git a/patches/reims-vgpu-snapshot-replay.patch b/patches/reims-vgpu-snapshot-replay.patch new file mode 100644 index 0000000..95593fd --- /dev/null +++ b/patches/reims-vgpu-snapshot-replay.patch @@ -0,0 +1,4309 @@ +diff --git a/crates/reims-vgpu-c/src/graphics.rs b/crates/reims-vgpu-c/src/graphics.rs +index 89ab1d0bae44537dcbca5653ac5e6f0690dcdaee..fcb5067c345f9769c216a6756701e9a8fea2429b 100644 +--- a/crates/reims-vgpu-c/src/graphics.rs ++++ b/crates/reims-vgpu-c/src/graphics.rs +@@ -1180,5 +1180,124 @@ 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; +diff --git a/crates/reims-vgpu-graphics/src/device.rs b/crates/reims-vgpu-graphics/src/device.rs +index ae1d87d621a121feff29ac4f427193f7bc129994..e17ccb80c0fba49246ae22fede135c3c8c51fb88 100644 +--- a/crates/reims-vgpu-graphics/src/device.rs ++++ b/crates/reims-vgpu-graphics/src/device.rs +@@ -1104,6 +1104,8 @@ pub(crate) struct Shared { + reset_owed: AtomicBool, + /// Set at the device's end. + ending: AtomicBool, ++ /// Set while quiesced for checkpointing. ++ quiesced: AtomicBool, + /// The control thread's own wake. + wake: Wake, + /// The host's doorbell file for ring 0, once given. +@@ -1874,6 +1876,7 @@ impl Device { + epoch: AtomicU64::new(0), + reset_owed: AtomicBool::new(false), + ending: AtomicBool::new(false), ++ quiesced: AtomicBool::new(false), + wake: Wake::new()?, + doorbell: OnceLock::new(), + submit: Mutex::new(Submit { +@@ -2119,6 +2122,26 @@ impl Device { + pub fn reset(&self) { + self.shared.reset(); + } ++ ++ /// Quiesces the device for stopped-VM checkpointing. ++ pub fn quiesce(&self) { ++ self.shared.quiesce(); ++ } ++ ++ /// Resumes VBLANK ticks and ring consumption after quiesce. ++ pub fn unquiesce(&self) { ++ self.shared.unquiesce(); ++ } ++ ++ /// Exports the quiescent device's BAR0/ring/display/queue/region state. ++ pub fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot { ++ self.shared.export_snapshot() ++ } ++ ++ /// Restores device state on a freshly created device (after QEMU restored BAR2). ++ pub fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> { ++ self.shared.import_snapshot(snap) ++ } + } + + /// The `COMPLETE` a ring-0 command owes, which the host gives from any thread once it has carried +@@ -2577,6 +2600,219 @@ impl Shared { + /// The reset (the module doc). It waits for the message the control thread is taking, and + /// for a take of a queue's ring or a post onto one under way, none of which waits for the + /// host; the host is told on the control thread ([`Self::tell_reset`]). ++ fn quiesce(&self) { ++ self.quiesced.store(true, Ordering::Release); ++ self.wake.wake(); ++ let active_queues: Vec> = { ++ 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> = { ++ 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 = self.pages.iter().map(|p| p.load(Ordering::Acquire)).collect(); ++ let displays: Vec = 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> = ++ self.queues.lock().by_obj.values().cloned().collect(); ++ queue_list.sort_by_key(|q| q.obj_id); ++ let queues: Vec = queue_list ++ .iter() ++ .map(|q| { ++ let s = q.submit.lock(); ++ let c = q.complete.lock(); ++ QueueSnapshot { ++ create_bytes: q.create.as_bytes().to_vec(), ++ flags: q.flags, ++ taken_seqno: q.taken_seqno.load(Ordering::Acquire), ++ taken_buffer_seqno: q.taken_buffer_seqno.load(Ordering::Acquire), ++ submit_count: s.consumer.consumed(), ++ submit_broken: s.broken, ++ complete_count: c.produced(), ++ } ++ }) ++ .collect(); ++ DeviceSnapshot { ++ status, ++ driver_features, ++ control_done, ++ control_submit_count, ++ control_submit_broken, ++ control_completion_count, ++ vt_ring_count, ++ pages, ++ displays, ++ region_blocks, ++ queues, ++ } ++ } ++ ++ fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> { ++ self.quiesced.store(true, Ordering::Release); ++ self.region.import_blocks(&snap.region_blocks); ++ self.driver_features.store(snap.driver_features, Ordering::Release); ++ if snap.driver_features != 0 { ++ self.host.driver_ready(snap.driver_features); ++ } ++ let mut any_page = false; ++ for (dst, &val) in self.pages.iter().zip(snap.pages.iter()) { ++ dst.store(val, Ordering::Release); ++ if val != 0 { ++ any_page = true; ++ } ++ } ++ if any_page { ++ self.pages_bound.store(true, Ordering::Release); ++ } ++ { ++ let mut submit = self.submit.lock(); ++ submit.consumer.set_count(snap.control_submit_count); ++ submit.broken = snap.control_submit_broken; ++ submit.backlog.clear(); ++ } ++ self.control_done.store(snap.control_done, Ordering::Release); ++ self.completion.lock().set_count(snap.control_completion_count); ++ self.vt_ring.lock().set_count(snap.vt_ring_count); ++ self.reset_owed.store(false, Ordering::Release); ++ for (display, ds) in self.displays.iter().zip(snap.displays.iter()) { ++ { ++ let mut st = display.state.lock(); ++ st.scanout = ds.scanout; ++ st.vblank = ds.vblank; ++ st.asleep = ds.asleep; ++ st.refreshes = ds.refreshes; ++ st.told = ds.told; ++ st.changed = ds.changed; ++ st.cursor_image = ds.cursor_image.clone(); ++ } ++ display.screen.scanout(ds.scanout); ++ display.screen.cursor_image(ds.cursor_image.clone()); ++ display.screen.power(!ds.asleep); ++ } ++ self.status.store(snap.status, Ordering::Release); ++ let epoch = self.epoch.load(Ordering::Acquire); ++ for qs in &snap.queues { ++ let Ok(q) = RgfxQueueCreate::read_from_bytes(&qs.create_bytes) else { ++ return Err("malformed RgfxQueueCreate in snapshot"); ++ }; ++ let Some((submit_at, complete_at)) = self.validate_rings(&q) else { ++ return Err("queue rings invalid against restored BAR2 block ledger"); ++ }; ++ let Some(me) = self.weak_self.get().and_then(Weak::upgrade) else { ++ return Err("device weak_self missing"); ++ }; ++ let Some(wake) = Wake::new() else { ++ return Err("queue wake allocation failed"); ++ }; ++ let bell = if self.driver_took(RGFX_FEATURE_DOORBELL_ASKS) { ++ wake::bell() ++ } else { ++ None ++ }; ++ let mut consumer = Consumer::new(submit_at); ++ consumer.set_count(qs.submit_count); ++ let mut producer = Producer::new(complete_at); ++ producer.set_count(qs.complete_count); ++ let queue = Arc::new(QueueShared { ++ obj_id: q.obj_id, ++ context: (q.obj_id >> RGFX_CONTEXT_OBJ_ID_SHIFT) as u32, ++ create: q, ++ flags: qs.flags, ++ epoch, ++ ring_id: q.submit_offset, ++ vector: q.vector, ++ submit: Mutex::new(Submit { ++ consumer, ++ broken: qs.submit_broken, ++ backlog: Backlog::default(), ++ asleep: false, ++ }), ++ taken_seqno: AtomicU64::new(qs.taken_seqno), ++ taken_buffer_seqno: AtomicU64::new(qs.taken_buffer_seqno), ++ consuming: Mutex::new(None), ++ complete: Mutex::new(producer), ++ room: Room::default(), ++ full: AtomicBool::new(false), ++ untold: Mutex::new(Untold::default()), ++ handed: Mutex::new(Handed::default()), ++ handing: AtomicBool::new(false), ++ wake, ++ bell, ++ route: AtomicU64::new(0), ++ route_page: AtomicU32::new(u32::MAX), ++ ending: AtomicBool::new(false), ++ trip: trip::Queue::default(), ++ }); ++ { ++ let mut queues = self.queues.lock(); ++ queues.by_obj.insert(q.obj_id, Arc::clone(&queue)); ++ queues.by_ring.insert(q.submit_offset, Arc::clone(&queue)); ++ } ++ let service = Arc::clone(&queue); ++ std::thread::Builder::new() ++ .name(format!("reims-vgpu.graphics-queue-{:#x}", q.obj_id)) ++ .spawn(move || me.queue_service_restored(&service)) ++ .map_err(|_| "failed to spawn restored queue thread")?; ++ self.route(&queue); ++ self.host.queue_made(&self.queue_poster(&queue)); ++ } ++ Ok(()) ++ } ++ + fn reset(&self) { + self.status.store(RGFX_STATUS_RESET, Ordering::Release); + self.driver_features.store(0, Ordering::Release); +@@ -3254,6 +3490,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); +@@ -4438,6 +4678,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) { ++ 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::() as u32, ++ seqno: 0, ++ }, ++ obj_id: queue.obj_id, ++ }; ++ self.host.stage3_message(&poster, destroy.as_bytes()); ++ } ++ } ++ + fn queue_service(&self, queue: &Arc) { + let poster = self.queue_poster(queue); + // The host makes the queue's handle first, so a command buffer on it can name it. +@@ -4464,6 +4721,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, 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) { +@@ -5074,6 +5335,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; + }; +diff --git a/crates/reims-vgpu-graphics/src/device/lanes.rs b/crates/reims-vgpu-graphics/src/device/lanes.rs +index 110cbb6a4cbaf7e2450fa7040d365c3de73d9026..12b201509a9f574c8ed20f831e04d4961e66e541 100644 +--- a/crates/reims-vgpu-graphics/src/device/lanes.rs ++++ b/crates/reims-vgpu-graphics/src/device/lanes.rs +@@ -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) { +diff --git a/crates/reims-vgpu-graphics/src/lib.rs b/crates/reims-vgpu-graphics/src/lib.rs +index ae8a328435c264e712b4d34e5153cdfcce1ca55b..40214d647726016d9aabbcc21122b3931e18493f 100644 +--- a/crates/reims-vgpu-graphics/src/lib.rs ++++ b/crates/reims-vgpu-graphics/src/lib.rs +@@ -31,6 +31,7 @@ pub mod keep; + pub mod managed; + pub mod ops; + pub mod region; ++pub mod snapshot; + mod ring; + // The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header. + /// cbindgen:ignore +diff --git a/crates/reims-vgpu-graphics/src/region.rs b/crates/reims-vgpu-graphics/src/region.rs +index c6032c91cb349f4a9c5e22931f46908de2eef86b..e986d707926a9d0ac524abc9499ae013bfca1442 100644 +--- a/crates/reims-vgpu-graphics/src/region.rs ++++ b/crates/reims-vgpu-graphics/src/region.rs +@@ -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, ++ /// 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 { ++ 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(); + } +diff --git a/crates/reims-vgpu-graphics/src/ring.rs b/crates/reims-vgpu-graphics/src/ring.rs +index 36585f35100fa121406d92c019f8172755a5cb18..12f3f11703ab5175cd90f0e6a919bb8fda017a97 100644 +--- a/crates/reims-vgpu-graphics/src/ring.rs ++++ b/crates/reims-vgpu-graphics/src/ring.rs +@@ -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); +diff --git a/crates/reims-vgpu-graphics/src/snapshot.rs b/crates/reims-vgpu-graphics/src/snapshot.rs +new file mode 100644 +index 0000000000000000000000000000000000000000..00ddc52e940a6cd246a777ee74073007e91ad006 +--- /dev/null ++++ b/crates/reims-vgpu-graphics/src/snapshot.rs +@@ -0,0 +1,293 @@ ++//! 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, ++ /// 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, ++ /// Whether a `DISPLAY_CHANGED` event is owed. ++ pub changed: bool, ++ /// Current guest cursor image, if any. ++ pub cursor_image: Option, ++} ++ ++/// Serializable per-command-queue ring state. ++#[derive(Clone, Debug, PartialEq, Eq)] ++pub struct QueueSnapshot { ++ /// Raw `RgfxQueueCreate` wire message bytes. ++ pub create_bytes: Vec, ++ /// Accepted `RGFX_QUEUE_*` flags. ++ pub flags: u32, ++ /// Highest message seqno taken off the queue's submission ring. ++ pub taken_seqno: u64, ++ /// Highest command-buffer seqno taken off the queue's submission ring. ++ pub taken_buffer_seqno: u64, ++ /// Host consumer byte count on the queue's submission ring. ++ pub submit_count: u64, ++ /// Whether the queue's submission ring was marked broken. ++ pub submit_broken: bool, ++ /// Host producer byte count on the queue's completion ring. ++ pub complete_count: u64, ++} ++ ++/// Complete serializable snapshot of `reims_vgpu_graphics::Device` (BAR0/rings/displays/queues). ++#[derive(Clone, Debug, PartialEq, Eq)] ++pub struct DeviceSnapshot { ++ /// `STATUS` register value. ++ pub status: u32, ++ /// Negotiated `DRIVER_FEATURES` bitmask. ++ pub driver_features: u64, ++ /// Control submission ring `control_done` count. ++ pub control_done: u64, ++ /// Control submission ring consumer byte count. ++ pub control_submit_count: u64, ++ /// Whether control submission ring is broken. ++ pub control_submit_broken: bool, ++ /// Control completion ring producer byte count. ++ pub control_completion_count: u64, ++ /// VideoToolbox ring producer byte count. ++ pub vt_ring_count: u64, ++ /// Doorbell page context bindings (`RGFX_REG_DOORBELL_PAGE_BIND`). ++ pub pages: Vec, ++ /// Per-display state. ++ pub displays: Vec, ++ /// Active BAR2 granted/shared blocks. ++ pub region_blocks: Vec, ++ /// Active per-queue rings. ++ pub queues: Vec, ++} ++ ++fn put_u8(o: &mut Vec, v: u8) { o.push(v); } ++fn put_u32(o: &mut Vec, v: u32) { o.extend_from_slice(&v.to_le_bytes()); } ++fn put_u64(o: &mut Vec, v: u64) { o.extend_from_slice(&v.to_le_bytes()); } ++fn put_bytes(o: &mut Vec, b: &[u8]) { ++ put_u64(o, b.len() as u64); ++ o.extend_from_slice(b); ++} ++ ++fn get_u8(i: &mut &[u8]) -> Option { ++ let (&b, rest) = i.split_first()?; ++ *i = rest; ++ Some(b) ++} ++fn get_u32(i: &mut &[u8]) -> Option { ++ 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 { ++ 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> { ++ 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 { ++ 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( ++ i: &mut &[u8], ++ min_item_bytes: usize, ++ mut f: impl FnMut(&mut &[u8]) -> Option, ++) -> Option> { ++ 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) { ++ put_u32(o, 1); ++ put_u32(o, self.status); ++ put_u64(o, self.driver_features); ++ put_u64(o, self.control_done); ++ put_u64(o, self.control_submit_count); ++ put_u8(o, u8::from(self.control_submit_broken)); ++ put_u64(o, self.control_completion_count); ++ put_u64(o, self.vt_ring_count); ++ ++ put_u32(o, self.pages.len() as u32); ++ for &p in &self.pages { put_u32(o, p); } ++ ++ put_u32(o, self.displays.len() as u32); ++ for d in &self.displays { ++ match d.scanout { ++ Some(s) => { ++ put_u8(o, 1); ++ put_u32(o, s.width); put_u32(o, s.height); ++ put_u32(o, s.stride); put_u64(o, s.offset); ++ } ++ None => put_u8(o, 0), ++ } ++ put_u8(o, u8::from(d.vblank)); ++ put_u8(o, u8::from(d.asleep)); ++ put_u64(o, d.refreshes); ++ match d.told { ++ Some(m) => { ++ put_u8(o, 1); ++ put_u32(o, m.width); put_u32(o, m.height); ++ put_u32(o, m.refresh_mhz); put_u32(o, m.scale_120ths); ++ } ++ None => put_u8(o, 0), ++ } ++ put_u8(o, u8::from(d.changed)); ++ match &d.cursor_image { ++ Some(c) => { ++ put_u8(o, 1); ++ put_u32(o, c.width); put_u32(o, c.height); ++ put_u32(o, c.hot_spot.0); put_u32(o, c.hot_spot.1); ++ put_bytes(o, &c.rgba); ++ } ++ None => put_u8(o, 0), ++ } ++ } ++ ++ put_u32(o, self.region_blocks.len() as u32); ++ for b in &self.region_blocks { ++ put_u64(o, b.offset); put_u64(o, b.size); ++ put_u8(o, u8::from(b.shared)); ++ put_u32(o, b.holders.len() as u32); ++ for &h in &b.holders { put_u32(o, h); } ++ } ++ ++ put_u32(o, self.queues.len() as u32); ++ for q in &self.queues { ++ put_bytes(o, &q.create_bytes); ++ put_u32(o, q.flags); ++ put_u64(o, q.taken_seqno); ++ put_u64(o, q.taken_buffer_seqno); ++ put_u64(o, q.submit_count); ++ put_u8(o, u8::from(q.submit_broken)); ++ put_u64(o, q.complete_count); ++ } ++ } ++ ++ /// Decodes a device snapshot from `i`. ++ pub fn decode(i: &mut &[u8]) -> Option { ++ if get_u32(i)? != 1 { return None; } ++ let status = get_u32(i)?; ++ let driver_features = get_u64(i)?; ++ let control_done = get_u64(i)?; ++ let control_submit_count = get_u64(i)?; ++ let control_submit_broken = get_u8(i)? != 0; ++ let control_completion_count = get_u64(i)?; ++ let vt_ring_count = get_u64(i)?; ++ ++ let pages = read_vec(i, 4, get_u32)?; ++ let displays = read_vec(i, 14, |i| { ++ let scanout = if get_u8(i)? != 0 { ++ Some(Scanout { ++ width: get_u32(i)?, height: get_u32(i)?, ++ stride: get_u32(i)?, offset: get_u64(i)?, ++ }) ++ } else { None }; ++ let vblank = get_u8(i)? != 0; ++ let asleep = get_u8(i)? != 0; ++ let refreshes = get_u64(i)?; ++ let told = if get_u8(i)? != 0 { ++ Some(Mode { ++ width: get_u32(i)?, height: get_u32(i)?, ++ refresh_mhz: get_u32(i)?, scale_120ths: get_u32(i)?, ++ }) ++ } else { None }; ++ let changed = get_u8(i)? != 0; ++ let cursor_image = if get_u8(i)? != 0 { ++ Some(CursorImage { ++ width: get_u32(i)?, height: get_u32(i)?, ++ hot_spot: (get_u32(i)?, get_u32(i)?), ++ rgba: get_bytes(i)?, ++ }) ++ } else { None }; ++ Some(DisplaySnapshot { scanout, vblank, asleep, refreshes, told, changed, cursor_image }) ++ })?; ++ let region_blocks = read_vec(i, 21, |i| { ++ let offset = get_u64(i)?; ++ let size = get_u64(i)?; ++ let shared = get_u8(i)? != 0; ++ let holders = read_vec(i, 4, get_u32)?; ++ Some(RegionBlockSnapshot { offset, size, holders, shared }) ++ })?; ++ let queues = read_vec(i, 45, |i| { ++ Some(QueueSnapshot { ++ create_bytes: get_bytes(i)?, ++ flags: get_u32(i)?, ++ taken_seqno: get_u64(i)?, ++ taken_buffer_seqno: get_u64(i)?, ++ submit_count: get_u64(i)?, ++ submit_broken: get_u8(i)? != 0, ++ complete_count: get_u64(i)?, ++ }) ++ })?; ++ ++ Some(DeviceSnapshot { ++ status, driver_features, control_done, ++ control_submit_count, control_submit_broken, ++ control_completion_count, vt_ring_count, ++ pages, displays, region_blocks, queues, ++ }) ++ } ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ #[test] ++ fn decode_rejects_oversized_counts_without_allocating() { ++ // Minimal valid header (version=1 + fixed scalar fields = 49 bytes). ++ let mut base = Vec::new(); ++ let empty = DeviceSnapshot { ++ status: 1, ++ driver_features: 2, ++ control_done: 3, ++ control_submit_count: 4, ++ control_submit_broken: false, ++ control_completion_count: 5, ++ vt_ring_count: 6, ++ pages: vec![], ++ displays: vec![], ++ region_blocks: vec![], ++ queues: vec![], ++ }; ++ empty.encode(&mut base); ++ let mut s = base.as_slice(); ++ assert_eq!(DeviceSnapshot::decode(&mut s), Some(empty)); ++ assert!(s.is_empty()); ++ ++ // Overwrite each of the 4 top-level collection counts with u32::MAX. ++ // Header length before pages count: 4 + 4 + 8 + 8 + 8 + 1 + 8 + 8 = 49. ++ for offset in [49usize, 53, 57, 61] { ++ let mut bad = base.clone(); ++ bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes()); ++ let mut sl = bad.as_slice(); ++ assert!(DeviceSnapshot::decode(&mut sl).is_none(), "offset {offset} must fail"); ++ } ++ } ++} +diff --git a/crates/reims-vgpu-vulkan/src/core/platform/device.rs b/crates/reims-vgpu-vulkan/src/core/platform/device.rs +index 50b24be4d3d3cfb3a3305694ef8e948d7c41b72d..e737f7260b9407aa886eec0370af670b1519c806 100644 +--- a/crates/reims-vgpu-vulkan/src/core/platform/device.rs ++++ b/crates/reims-vgpu-vulkan/src/core/platform/device.rs +@@ -564,4 +564,44 @@ pub trait GpuDevice: Handle { + &self, + desc: &FullComputePipelineDesc<'_, P>, + ) -> Result, 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>, &'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>, &'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 ++ } + } +diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/device.rs b/crates/reims-vgpu-vulkan/src/rt_platform/device.rs +index 2a87bbc65e5c2093e3d1c06b1abbd297abbcc7da..4df542484ffe702a5837a5dd7f765bbb50e07531 100644 +--- a/crates/reims-vgpu-vulkan/src/rt_platform/device.rs ++++ b/crates/reims-vgpu-vulkan/src/rt_platform/device.rs +@@ -2625,6 +2625,327 @@ impl GpuDevice for RtObj { + 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: &::Event) -> u64 { ++ event.signaled_value() ++ } ++ ++ fn event_restore_signaled_value( ++ &self, ++ event: &::Event, ++ value: u64, ++ ) -> bool { ++ if value > 0 { ++ event.restore_signaled_value(value).is_ok() ++ } else { ++ true ++ } ++ } ++ ++ fn read_standalone_buffer( ++ &self, ++ buffer: &::Buffer, ++ ) -> Result>, &'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, &'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: &::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: &::Texture, ++ ) -> Result>, &'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, &'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: &::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, 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 +diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs +index 8cac38c823e4bbd3d76eafa0ac3bc2f3461bd5f4..a4715175ae46687face600f1ed683c4c628570c0 100644 +--- a/crates/reims-vgpu/src/graphics.rs ++++ b/crates/reims-vgpu/src/graphics.rs +@@ -93,7 +93,8 @@ use reims_vgpu_graphics::wire::{ + RGFX_FEATURE_TEXTURE_DID_MODIFY_DATA, RGFX_FEATURE_UNCHANGING_PAGES, + RGFX_FEATURE_UNSHARED_QUEUES, RGFX_FEATURE_UPLOADS_WRITTEN, RGFX_FEATURE_VT_MESSAGES, + RGFX_RESOURCE_ID_CHUNK, RGFX_RESOURCE_ID_CHUNKS, RGFX_STATUS_INVALID_ARGUMENT, +- RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED, RGFX_VIDEO_CAPS_CODECS, ++ RGFX_STATUS_CACHE, 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, +@@ -190,6 +191,7 @@ mod present; + mod read; + mod rt_window; + mod sink; ++mod snapshot; + mod slow_answers; + mod summary; + mod trip; +@@ -1035,6 +1037,7 @@ impl GraphicsDevice

{ + 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> = (0..count) + .map(|display| { +@@ -1350,6 +1353,242 @@ impl GraphicsDevice

{ + (self.cursors.get(display as usize)).map_or((0, 0), |cursor| cursor.position()) + }) + } ++ ++ fn quiesce_device(&self) -> Option>> { ++ self.device.quiesce(); ++ if let Some(pool) = &self.pool { ++ pool.quiesce(); ++ } ++ let control = self.ending.upgrade()?; ++ control.pool.wait_idle(); ++ control.icb_worker.flush(); ++ let decoder = control.decoder(); ++ decoder.flush_workers(); ++ decoder.flush_all_surface_caches(&control.device); ++ control.device.wait_idle(); ++ Some(control) ++ } ++ ++ /// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings, ++ /// drains pending compiles and workers, flushes dirty device-cached IOSurfaces back to Guest ++ /// RAM, and waits for GPU idle. ++ pub fn quiesce(&self) -> Result<(), Error> { ++ entry::run(|_| { ++ let _ = self.quiesce_device(); ++ Ok(()) ++ }) ++ } ++ ++ /// Resumes VBLANK and ring service threads after a snapshot completes or aborts. ++ pub fn unquiesce(&self) { ++ entry::run(|_| { ++ self.device.unquiesce(); ++ }); ++ } ++ ++ /// Serializes the full graphics device state (device rings/displays/queues, Shared Pool, ++ /// Private Blocks + VRAM, live Metal/Vulkan objects, timeline events, and standalone GPU ++ /// buffers/textures) into a portable byte blob for suspend-to-disk. ++ pub fn snapshot_save(&self) -> Result, Error> { ++ entry::run(|_| { ++ let t0 = std::time::Instant::now(); ++ let control = self.quiesce_device().ok_or(Error::HostResources)?; ++ let decoder = control.decoder(); ++ ++ let mut device_snapshot = Vec::new(); ++ self.device.export_snapshot().encode(&mut device_snapshot); ++ let shared_pool = self.pool.as_ref().map(|p| p.export_snapshot()).transpose()?; ++ let private_blocks = control.private_blocks.export_snapshot()?; ++ let id_chunks = decoder.export_id_chunks(); ++ let (live_records, surface_pages, standalone_tex_set, presented_surfaces) = ++ control.live_log.export(); ++ ++ let mut known_ranges: Vec<(u64, u64)> = Vec::new(); ++ if let Some(sp) = &shared_pool { ++ for piece in &sp.pieces { ++ if piece.gpu_address != 0 { ++ known_ranges.push((piece.gpu_address, piece.len)); ++ } ++ } ++ } ++ for pb in &private_blocks.blocks { ++ if pb.gpu_address != 0 { ++ known_ranges.push((pb.gpu_address, pb.len)); ++ } ++ } ++ let live_values = decoder ++ .export_live_values(&control.device, &known_ranges, &standalone_tex_set) ++ .map_err(|_| Error::HostResources)?; ++ let mut standalone_textures: Vec = standalone_tex_set.into_iter().collect(); ++ standalone_textures.sort_unstable(); ++ ++ let snap = snapshot::VgpuSnapshot { ++ device_snapshot, ++ shared_pool, ++ private_blocks, ++ id_chunks, ++ surface_pages, ++ live_records, ++ standalone_textures, ++ presented_surfaces, ++ live_values, ++ }; ++ let t_exp = t0.elapsed(); ++ let n_tex = snap.live_values.textures.len(); ++ let tex_bytes: usize = snap.live_values.textures.iter().map(|(_, b)| b.len()).sum(); ++ let n_caches = snap.live_values.surface_caches.len(); ++ let cache_bytes: usize = snap ++ .live_values ++ .surface_caches ++ .iter() ++ .map(|(_, b)| b.len()) ++ .sum(); ++ let encoded = snap.encode(); ++ log::info!( ++ target: "reims_vgpu::graphics", ++ "snapshot_save done in {:.2}s (export={:.2}s): total={} B, textures={} ({:.1} MiB), unattached_caches={} ({:.1} MiB)", ++ t0.elapsed().as_secs_f64(), ++ t_exp.as_secs_f64(), ++ encoded.len(), ++ n_tex, ++ tex_bytes as f64 / (1024.0 * 1024.0), ++ n_caches, ++ cache_bytes as f64 / (1024.0 * 1024.0), ++ ); ++ Ok(encoded) ++ }) ++ } ++ ++ /// Restores the full graphics device state from a snapshot produced by [`Self::snapshot_save`] ++ /// in a fresh host process. ++ pub fn snapshot_load(&self, data: &[u8]) -> Result<(), Error> { ++ entry::run(|_| { ++ let snap = snapshot::VgpuSnapshot::decode(data).ok_or(Error::InvalidArgument)?; ++ let mut dev_slice: &[u8] = &snap.device_snapshot; ++ let dev_snap = reims_vgpu_graphics::snapshot::DeviceSnapshot::decode(&mut dev_slice) ++ .ok_or(Error::InvalidArgument)?; ++ if !dev_slice.is_empty() { ++ return Err(Error::InvalidArgument); ++ } ++ let control = self.ending.upgrade().ok_or(Error::HostResources)?; ++ ++ // Keep device rings and VBLANK paused until full object table replay finishes. ++ // Any error below returns without unquiescing so partial restores never report success. ++ self.device.quiesce(); ++ ++ match (&self.pool, &snap.shared_pool) { ++ (Some(pool), Some(ps)) => pool.import_snapshot(ps)?, ++ (None, Some(ps)) if !ps.pieces.is_empty() => return Err(Error::HostResources), ++ _ => {} ++ } ++ control.private_blocks.import_snapshot(&snap.private_blocks)?; ++ ++ self.device.import_snapshot(&dev_snap).map_err(|_| Error::InvalidArgument)?; ++ control ++ .decoder() ++ .set_managed_at_copy(dev_snap.driver_features & RGFX_FEATURE_MANAGED_AT_COPY != 0); ++ ++ { ++ let decoder = control.decoder(); ++ decoder.import_id_chunks(&snap.id_chunks); ++ for sp in &snap.surface_pages { ++ decoder ++ .replay_surface_pages( ++ &control.device, ++ &sp.pages, ++ &sp.runs, ++ sp.flags, ++ sp.layout, ++ ) ++ .map_err(|_| Error::HostResources)?; ++ } ++ } ++ ++ let mut records = snap.live_records; ++ records.sort_by_key(|r| r.seq); ++ for rec in &records { ++ control.replay_record(rec)?; ++ } ++ ++ let n_surface_pages = snap.surface_pages.len(); ++ let n_records = records.len(); ++ let standalone_set: std::collections::HashSet = ++ 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 Drop for GraphicsDevice

{ +@@ -1543,6 +1782,7 @@ struct GraphicsControl { + /// 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 +@@ -2196,6 +2436,7 @@ impl GraphicsControl

{ + 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() +@@ -2286,6 +2527,7 @@ impl GraphicsControl

{ + } + // 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 { +@@ -2348,6 +2590,7 @@ impl GraphicsControl

{ + 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); +@@ -2648,6 +2891,10 @@ impl GraphicsControl

{ + let _carried = me.reset_gate.read_recursive(); + let status = (me.decoder()) + .carry_out_surface_pages(&me.device, &pages, &runs, flags, layout, &settle); ++ if matches!(status, Some(RGFX_STATUS_OK | RGFX_STATUS_CACHE)) { ++ me.live_log ++ .record_surface_pages(pages, runs.clone(), flags, layout); ++ } + // Where the guest took IMPORT_ADDRESSES_LATER, answered now, with no address, + // before the view is made and given one below. + let answer = match status { +@@ -2746,6 +2993,197 @@ impl GraphicsControl

{ + /// ([`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 = 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::

(&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::

(&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, + poster: &CompletionPoster, +@@ -2753,6 +3191,7 @@ impl GraphicsControl

{ + claim: Option<&mut QueueClaim<'_>>, + ) { + let message: &[u8] = &bytes; ++ self.live_log.record_stage3(sender_context(poster, message), message); + let r#type = RgfxMsgHeader::read_from_prefix(message).map_or(0, |(h, _)| h.r#type); + // A queue's command buffer taken from its ring: the presents' late-show lines keep when + // the host first saw it (`present`). +@@ -3632,6 +4071,10 @@ impl GraphicsControl

{ + "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()); + } +@@ -4141,7 +4584,15 @@ impl GraphicsControl

{ + .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); +@@ -4214,6 +4665,7 @@ impl GraphicsControl

{ + 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); +@@ -4245,6 +4697,7 @@ impl GraphicsControl

{ + 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); +@@ -4788,6 +5241,7 @@ fn vt_decoders(caps: &RgfxVideoCaps) -> Vec { + /// 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(f: impl FnOnce() -> T) -> T { + let Some(_step) = reims_vgpu_vulkan::exit_gate::step() else { + reims_vgpu_vulkan::exit_gate::stay() +diff --git a/crates/reims-vgpu/src/graphics/compile.rs b/crates/reims-vgpu/src/graphics/compile.rs +index 1c5bb492f943fe8ba303b6ac5c0af130efb41243..8813dc8627b78e865730c9d084765c6a83006d42 100644 +--- a/crates/reims-vgpu/src/graphics/compile.rs ++++ b/crates/reims-vgpu/src/graphics/compile.rs +@@ -582,6 +582,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::() > 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; +@@ -672,10 +683,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)); + } + +diff --git a/crates/reims-vgpu/src/graphics/decode/library.rs b/crates/reims-vgpu/src/graphics/decode/library.rs +index 8c626c80aefb48b6f36e828a2d911021213a4bc4..f426f5365fdd5f996cff52d90b168d94c6719139 100644 +--- a/crates/reims-vgpu/src/graphics/decode/library.rs ++++ b/crates/reims-vgpu/src/graphics/decode/library.rs +@@ -402,9 +402,9 @@ pub(crate) struct LibraryJob { + pub(crate) obj_id: u64, + /// The create's seqno, which its `COMPLETE` carries. + pub(crate) seqno: u64, +- bytes: Vec, ++ pub(crate) bytes: Vec, + /// The key the guest sent with the bytes. +- guest_key: Option, ++ pub(crate) guest_key: Option, + slot: Arc>, + /// The device's resets when it was prepared. + resets: u64, +@@ -697,6 +697,29 @@ impl GraphicsDecoder

{ + }) + } + ++ /// Prepares a [`LibraryJob`] directly from snapshotted library bytes for silent replay. ++ pub(crate) fn prepare_library_bytes( ++ &self, ++ obj_id: u64, ++ bytes: Vec, ++ guest_key: Option, ++ ) -> LibraryJob

{ ++ 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 +diff --git a/crates/reims-vgpu/src/graphics/decode/mod.rs b/crates/reims-vgpu/src/graphics/decode/mod.rs +index b39feceac6e4360b1a678c40d5468e5a893fc44a..8929bacedd1a1dc3f248c7a11c3816e8044e973e 100644 +--- a/crates/reims-vgpu/src/graphics/decode/mod.rs ++++ b/crates/reims-vgpu/src/graphics/decode/mod.rs +@@ -220,6 +220,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; +@@ -264,6 +265,7 @@ pub(crate) use library::verified_key as test_key; + #[cfg(test)] + pub(crate) use library::whole_key as test_whole_key; + use library::{Libraries, LibraryRef}; ++pub(crate) use library::LibraryKey; + pub(crate) use library::{LibraryJob, LibraryStart, MadeLibrary, complete, make_library}; + use managed::{STORAGE_MODE_MANAGED, storage_mode}; + pub(crate) use pipeline_key::PipelineKey; +@@ -608,6 +610,16 @@ fn new_sampler( + /// 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)>, ++ pub(crate) textures: Vec<(u64, Vec)>, ++ pub(crate) surface_caches: Vec<(u64, Vec)>, ++} ++ + enum ObjHandle { + Event(P::Event), + Fence(P::Fence), +@@ -3538,6 +3550,285 @@ impl GraphicsDecoder

{ + } + + /// 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 { ++ 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, ++ ) -> 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, ++ ) -> Result { ++ let mut values = LiveValues::default(); ++ let mut first_err: Option<&'static str> = None; ++ let mut contexts: Vec>> = ++ 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>> = +@@ -6539,6 +6830,11 @@ impl CompiledPipeline

{ + } + } + ++ /// 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

, reflection: RgfxPipelineReflection) -> Self { + CompiledPipeline { +diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs +index 27e49048da96c560f0cdafe794a526fec2186f08..e57b0ce603eb3b4ad28803102c92a09793ba252f 100644 +--- a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs ++++ b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs +@@ -3589,6 +3589,18 @@ impl SurfaceCaches

{ + .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) { ++ 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 +@@ -8337,6 +8349,171 @@ impl Caches

{ + /// `trace`: `done` once the pages hold the cache, or `failed` where the platform raised at + /// the copy. + #[allow(clippy::too_many_arguments)] // the download's, and its trace ++ /// Returns all currently tracked surface cache block offsets for pre-snapshot flushing. ++ pub(crate) fn attached_live_blocks(&self) -> Vec { ++ 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)>, &'static str> { ++ let need_mem: Vec = { ++ let state = self.lock(); ++ state ++ .by_block ++ .values() ++ .filter(|c| { ++ c.pages.is_none() ++ && !c.device.memory_made() ++ && c.shapes.iter().any(|s| s.dirty) ++ }) ++ .map(|c| c.device.clone_ref()) ++ .collect() ++ }; ++ self.make_memory(need_mem, MemoryFor::WriteBack); ++ ++ let mut flushed_any = false; ++ { ++ let mut state = self.lock(); ++ let dirty_blocks: Vec = state ++ .by_block ++ .iter() ++ .filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty)) ++ .map(|(&b, _)| b) ++ .collect(); ++ if !dirty_blocks.is_empty() { ++ if !state ++ .make_transfer(device) ++ .map_err(|_| "snapshot_save: surface cache transfer init failed")? ++ { ++ return Err("snapshot_save: surface cache transfer queue unavailable"); ++ } ++ for block in dirty_blocks { ++ let cb_opt = { ++ let transfer = state ++ .transfer ++ .as_mut() ++ .ok_or("snapshot_save: surface cache transfer missing")?; ++ transfer ++ .queue ++ .command_buffer(ON) ++ .map_err(|_| "snapshot_save: surface cache command buffer failed")? ++ }; ++ let Some(cb) = cb_opt else { ++ return Err("snapshot_save: surface cache command buffer unavailable"); ++ }; ++ let Some(cache) = state.by_block.get_mut(&block) else { ++ continue; ++ }; ++ if !cache.copy_through(MemoryFor::WriteBack) { ++ return Err("snapshot_save: deferred surface cache allocation failed"); ++ } ++ let back = shapes::write_back::

(&cb, &cache.device, &cache.shapes, |s| { ++ s.dirty ++ }) ++ .map_err(|_| "snapshot_save: surface cache shape write_back failed")?; ++ cache.wrote_shapes(&back); ++ state.owed_commits.push(cb); ++ flushed_any = true; ++ } ++ } ++ } ++ if flushed_any { ++ device.wait_idle(); ++ } ++ ++ let mut to_read: Vec<(u64, P::Buffer)> = { ++ let state = self.lock(); ++ state ++ .by_block ++ .iter() ++ .filter(|(_, c)| c.pages.is_none() && c.device.memory_made()) ++ .map(|(&block, c)| (block, c.device.clone_ref())) ++ .collect() ++ }; ++ to_read.sort_by_key(|(block, _)| *block); ++ ++ let mut out = Vec::with_capacity(to_read.len()); ++ for (block, buf) in to_read { ++ match device.read_standalone_buffer(&buf)? { ++ Some(bytes) => out.push((block, bytes)), ++ None => return Err("snapshot_save: unattached surface cache buffer unreadable"), ++ } ++ } ++ Ok(out) ++ } ++ ++ /// Restores GPU buffer contents for deferred unattached IOSurface device caches. ++ pub(crate) fn import_unattached( ++ &self, ++ device: &P::Device, ++ entries: &[(u64, Vec)], ++ ) -> 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 = targets ++ .iter() ++ .filter(|(_, b)| !b.memory_made()) ++ .map(|(_, b)| b.clone_ref()) ++ .collect(); ++ self.make_memory(need_mem, MemoryFor::Fill); ++ ++ for ((block, buf), (_, bytes)) in targets.iter().zip(entries.iter()) { ++ if !buf.memory_made() { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: failed to allocate memory for unattached surface cache {block:#x}" ++ ); ++ return Err("snapshot_load: surface cache memory allocation failed"); ++ } ++ if !device.write_standalone_buffer(buf, bytes) { ++ log::error!( ++ target: "reims_vgpu::graphics", ++ "snapshot_load: failed to upload unattached surface cache {block:#x} ({} bytes)", ++ bytes.len() ++ ); ++ return Err("snapshot_load: surface cache upload failed"); ++ } ++ } ++ ++ let mut state = self.lock(); ++ for (block, _) in entries { ++ if let Some(cache) = state.by_block.get_mut(block) { ++ let _ = cache.copy_through(MemoryFor::Fill); ++ cache.written = true; ++ cache.first_fill = None; ++ cache.zeros = false; ++ cache.lacks = false; ++ cache.changed = Changed::All; ++ cache.shapes.mark_owed_all(); ++ } ++ } ++ Ok(()) ++ } ++ + pub(crate) fn download( + &self, + device: &P::Device, +diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs +index eef3c5ef0e1297204a7344bc10eea333182b5ac1..f98695af9b83e699b9f7e87219baf9eb2246b3a6 100644 +--- a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs ++++ b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs +@@ -914,6 +914,23 @@ impl ShapeTable { + shape.map(|s| s.dirty = true).is_some() + } + ++ /// Marks a shape whose pixels were directly uploaded during snapshot restore as valid & dirty. ++ pub(crate) fn mark_restored(&mut self, id: u64) { ++ if let Some(s) = self.shapes.iter_mut().find(|s| s.id() == id) { ++ s.owed = false; ++ s.dirty = true; ++ s.cleared = false; ++ } ++ } ++ ++ pub(crate) fn mark_owed_all(&mut self) { ++ for s in &mut self.shapes { ++ s.owed = true; ++ s.cleared = false; ++ s.clean(); ++ } ++ } ++ + /// A video command buffer wrote the buffer, its decodes' pictures, not the images: every + /// shape owes a fill from it, its own write before the buffer's lost (the decode writes its + /// planes whole, and a write it does not cover was copied into the buffer before it ran); +diff --git a/crates/reims-vgpu/src/graphics/decode/surface_order.rs b/crates/reims-vgpu/src/graphics/decode/surface_order.rs +index ad08151f5256e959c46bf08f79cff98b0140b70e..c315b96ed11d9116e1c54e118f33d417a419795b 100644 +--- a/crates/reims-vgpu/src/graphics/decode/surface_order.rs ++++ b/crates/reims-vgpu/src/graphics/decode/surface_order.rs +@@ -292,6 +292,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. +@@ -862,6 +873,19 @@ impl SurfaceOrder

{ + q.buffers = Some(buffers); + } + ++ /// Restores a queue's commit/surface-order watermarks and timeline event value after snapshot load. ++ pub(crate) fn restore_queue_watermark(&mut self, queue: u64, seqno: u64) { ++ if seqno == 0 { ++ return; ++ } ++ if let Some(q) = self.queues.get(&queue) { ++ q.marks.restore_watermark(seqno); ++ if let Some(ev) = &q.event { ++ let _ = ev.set_signaled_value(seqno); ++ } ++ } ++ } ++ + /// What a removal from context `context`'s table waits for before its entry is let go of + /// ([`super::tables`], "After the buffers posted before it"): each queue of the context the + /// decoder made and that has not ended, whose ring published a command buffer its commit mark +diff --git a/crates/reims-vgpu/src/graphics/present.rs b/crates/reims-vgpu/src/graphics/present.rs +index a1fc887bd509b6c90d82b7a134be162bfc7a6ccc..20e3f7496d65d713e518ebe0d1e3e43748770766 100644 +--- a/crates/reims-vgpu/src/graphics/present.rs ++++ b/crates/reims-vgpu/src/graphics/present.rs +@@ -272,6 +272,16 @@ impl PresentQueue

{ + 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 +diff --git a/crates/reims-vgpu/src/graphics/snapshot.rs b/crates/reims-vgpu/src/graphics/snapshot.rs +new file mode 100644 +index 0000000000000000000000000000000000000000..70a3cec742ef2a3c75d074749593fe6f58f37067 +--- /dev/null ++++ b/crates/reims-vgpu/src/graphics/snapshot.rs +@@ -0,0 +1,1151 @@ ++//! Full GPU device snapshot (`LiveLog` + `RVGSNAP1` binary codec) for suspend-to-disk & resume. ++ ++use std::collections::{BTreeMap, HashMap, HashSet}; ++ ++use reims_vgpu_graphics::wire::{ ++ RGFX_CMD_BUFFER_AT_OFFSET, RGFX_CMD_BUFFER_CREATE, RGFX_CMD_BUFFER_ESCAPED, ++ RGFX_CMD_BUFFER_MANAGED_AT_OFFSET, RGFX_CMD_BUFFER_OVER_HOST_MEMORY, ++ RGFX_CMD_BUFFER_OVER_PAGES, RGFX_CMD_BUFFER_OVER_SURFACE_PAGES, ++ RGFX_CMD_COMPUTE_PIPELINE_CREATE, RGFX_CMD_DEPTH_STENCIL_CREATE, ++ RGFX_CMD_DYNAMIC_LIBRARY_CREATE, RGFX_CMD_EVENT_CREATE, RGFX_CMD_FENCE_CREATE, ++ RGFX_CMD_FUNCTION_HANDLE_CREATE, RGFX_CMD_FUNCTION_TABLE_CREATE, ++ RGFX_CMD_FUNCTION_TABLE_SET, RGFX_CMD_HEAP_CREATE, RGFX_CMD_HEAP_OVER_HOST_MEMORY, ++ RGFX_CMD_HEAP_OVER_PAGES, RGFX_CMD_HEAP_OVER_POOL, RGFX_CMD_ICB_CREATE, ++ RGFX_CMD_ICB_SLOTS, RGFX_CMD_ICB_SLOTS_IN_PAGES, RGFX_CMD_ICB_WRITE, ++ RGFX_CMD_LIBRARY_LOOKUP, RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER, RGFX_CMD_MANAGED_BUFFER_CREATE, ++ RGFX_CMD_MANAGED_TEXTURE_CREATE, RGFX_CMD_MESH_RENDER_PIPELINE_CREATE, ++ RGFX_CMD_OBJECT_DESTROY, RGFX_CMD_QUEUE_CREATE, RGFX_CMD_RATE_MAP_CREATE, ++ RGFX_CMD_RATE_MAP_RESET, RGFX_CMD_RENDER_PIPELINE_CREATE, RGFX_CMD_SAMPLER_CREATE, ++ RGFX_CMD_SHARED_EVENT_CREATE, RGFX_CMD_SHARED_EVENT_IMPORT, RGFX_CMD_SHARED_EVENT_NAME, ++ RGFX_CMD_SHARED_EVENT_UNNAME, RGFX_CMD_TEXTURE_CREATE, RGFX_CMD_TEXTURE_FROM_BUFFER, ++ RGFX_CMD_TEXTURE_FROM_IOSURFACE, RGFX_CMD_TEXTURE_VIEW, RGFX_SURFACE_PAGES_ATTACH, ++ RgfxComputePipelineCreate, RgfxDynamicLibraryCreate, RgfxFunctionHandleCreate, ++ RgfxFunctionTableSet, RgfxLibraryLookup, RgfxLinearTextureFromBuffer, RgfxLinkedFunction, ++ RgfxMeshRenderPipelineCreate, RgfxMsgHeader, RgfxObjectDestroy, RgfxPageRun, ++ RgfxPipelineLibrary, RgfxRenderPipelineCreate, RgfxSharedEventImport, RgfxSharedEventName, ++ RgfxSharedEventUnname, RgfxSurfacePages, RgfxSurfacePagesLayout, RgfxTextureCreate, ++ RgfxTextureFromBuffer, RgfxTextureView, ++}; ++use reims_vgpu_vulkan::core::sync::Mutex; ++use zerocopy::{FromBytes, IntoBytes}; ++ ++use crate::pool::{ ++ BlockCapture, MemoryClass, PoolCarveSnapshot, PoolPieceSnapshot, PoolSnapshot, ++ PrivateBlockSnapshot, PrivateBlocksSnapshot, ++}; ++ ++use super::decode::{LibraryKey, LiveValues}; ++ ++pub(crate) const SNAPSHOT_MAGIC: &[u8; 8] = b"RVGSNAP1"; ++pub(crate) const SNAPSHOT_VERSION: u32 = 1; ++ ++/// Synthetic tag stored in [`LogRecord::msg_type`] for assembled libraries (covers both inline ++/// `LIBRARY_CREATE` and chunked `LIBRARY_FROM_REGION`). ++pub(crate) const LOG_TAG_ASSEMBLED_LIBRARY: u32 = 0xFFFF_0001; ++ ++/// A recorded live object creation or persistent state mutation. ++#[derive(Clone, Debug)] ++pub(crate) struct LogRecord { ++ pub(crate) seq: u64, ++ pub(crate) context: u32, ++ pub(crate) obj_id: u64, ++ pub(crate) msg_type: u32, ++ /// Raw wire message bytes (or for `LOG_TAG_ASSEMBLED_LIBRARY`, optional 32-byte key if present). ++ pub(crate) bytes: Vec, ++ /// Assembled library bytes (for `LOG_TAG_ASSEMBLED_LIBRARY`), empty otherwise. ++ pub(crate) inline_bytes: Vec, ++} ++ ++/// Recorded `SURFACE_PAGES` registration for an active shared guest-RAM block. ++#[derive(Clone, Debug)] ++pub(crate) struct SurfacePagesRecord { ++ pub(crate) pages: RgfxSurfacePages, ++ pub(crate) runs: Vec, ++ pub(crate) flags: u32, ++ pub(crate) layout: Option, ++} ++ ++#[derive(Default)] ++struct LiveLogState { ++ next_seq: u64, ++ records: Vec, ++ surface_pages: BTreeMap>, ++ standalone_textures: HashSet, ++ presented_surfaces: Vec, ++ library_bytes_by_key: HashMap>, ++} ++ ++/// Records live guest GPU object creations & persistent mutations so a fresh host process can ++/// reconstruct the exact Metal/Vulkan object table without re-executing past draws or dispatches. ++pub(crate) struct LiveLog { ++ state: Mutex, ++} ++ ++impl LiveLog { ++ pub(crate) fn new(displays: usize) -> Self { ++ Self { ++ state: Mutex::new(LiveLogState { ++ presented_surfaces: vec![0; displays], ++ ..LiveLogState::default() ++ }), ++ } ++ } ++ ++ pub(crate) fn record_stage3(&self, context: u32, message: &[u8]) { ++ let Ok((hdr, _)) = RgfxMsgHeader::read_from_prefix(message) else { ++ return; ++ }; ++ match hdr.r#type { ++ RGFX_CMD_OBJECT_DESTROY => { ++ if let Ok((m, _)) = RgfxObjectDestroy::read_from_prefix(message) { ++ let mut st = self.state.lock(); ++ st.standalone_textures.remove(&m.obj_id); ++ let prev_destroy = st ++ .records ++ .iter() ++ .rposition(|r| { ++ r.obj_id == m.obj_id && r.msg_type == RGFX_CMD_OBJECT_DESTROY ++ }); ++ let search_from = prev_destroy.map_or(0, |i| i + 1); ++ let Some(inc_rel) = st.records[search_from..] ++ .iter() ++ .position(|r| r.obj_id == m.obj_id) ++ else { ++ return; ++ }; ++ let inc_start = search_from + inc_rel; ++ let inc_seq = st.records[inc_start].seq; ++ let mut named_events: Vec = Vec::new(); ++ for r in &st.records[inc_start..] { ++ if r.obj_id == m.obj_id && r.msg_type == RGFX_CMD_SHARED_EVENT_NAME { ++ if let Ok((n, _)) = RgfxSharedEventName::read_from_prefix(&r.bytes) { ++ named_events.push(n.name); ++ } ++ } ++ } ++ let referenced = st.records[inc_start + 1..].iter().any(|r| { ++ if r.obj_id == m.obj_id { ++ return false; ++ } ++ if record_parent_ids(r).contains(&m.obj_id) { ++ return true; ++ } ++ if !named_events.is_empty() && r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT { ++ if let Ok((imp, _)) = RgfxSharedEventImport::read_from_prefix(&r.bytes) ++ { ++ return named_events.contains(&imp.name); ++ } ++ } ++ false ++ }); ++ if referenced { ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id: m.obj_id, ++ msg_type: RGFX_CMD_OBJECT_DESTROY, ++ bytes: message.to_vec(), ++ inline_bytes: Vec::new(), ++ }); ++ } else { ++ st.records ++ .retain(|r| !(r.obj_id == m.obj_id && r.seq >= inc_seq)); ++ } ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_UNNAME => { ++ if let Ok((m, _)) = RgfxSharedEventUnname::read_from_prefix(message) { ++ let mut st = self.state.lock(); ++ let name_pos = st.records.iter().rposition(|r| { ++ r.msg_type == RGFX_CMD_SHARED_EVENT_NAME ++ && RgfxSharedEventName::read_from_prefix(&r.bytes) ++ .is_ok_and(|(n, _)| n.name == m.name) ++ }); ++ let Some(pos) = name_pos else { ++ return; ++ }; ++ let imported = st.records[pos + 1..].iter().any(|r| { ++ r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT ++ && RgfxSharedEventImport::read_from_prefix(&r.bytes) ++ .is_ok_and(|(imp, _)| imp.name == m.name) ++ }); ++ if imported { ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id: 0, ++ msg_type: RGFX_CMD_SHARED_EVENT_UNNAME, ++ bytes: message.to_vec(), ++ inline_bytes: Vec::new(), ++ }); ++ } else { ++ st.records.remove(pos); ++ } ++ } ++ } ++ ty if is_persistent_stage3(ty) => { ++ let obj_id = message ++ .get(16..24) ++ .and_then(|b| b.try_into().ok()) ++ .map(u64::from_le_bytes) ++ .unwrap_or(0); ++ let mut st = self.state.lock(); ++ if matches!( ++ ty, ++ RGFX_CMD_TEXTURE_CREATE ++ | RGFX_CMD_MANAGED_TEXTURE_CREATE ++ | RGFX_CMD_TEXTURE_FROM_BUFFER ++ | RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER ++ ) && obj_id != 0 ++ { ++ st.standalone_textures.insert(obj_id); ++ } ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id, ++ msg_type: ty, ++ bytes: message.to_vec(), ++ inline_bytes: Vec::new(), ++ }); ++ } ++ _ => {} ++ } ++ } ++ ++ pub(crate) fn record_library( ++ &self, ++ context: u32, ++ obj_id: u64, ++ bytes: Vec, ++ guest_key: Option, ++ ) { ++ let mut st = self.state.lock(); ++ if let Some(k) = guest_key { ++ st.library_bytes_by_key.insert(k, bytes.clone()); ++ if let Some(wk) = super::decode::whole_library_key(&bytes) ++ && wk != k ++ { ++ st.library_bytes_by_key.insert(wk, bytes.clone()); ++ } ++ } ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id, ++ msg_type: LOG_TAG_ASSEMBLED_LIBRARY, ++ bytes: guest_key.map(|k| k.to_vec()).unwrap_or_default(), ++ inline_bytes: bytes, ++ }); ++ } ++ ++ pub(crate) fn record_library_lookup(&self, context: u32, message: &[u8]) { ++ let Ok((m, _)) = RgfxLibraryLookup::read_from_prefix(message) else { ++ return; ++ }; ++ let mut st = self.state.lock(); ++ let seq = st.next_seq; ++ st.next_seq = st.next_seq.wrapping_add(1); ++ if let Some(inline_bytes) = st.library_bytes_by_key.get(&m.key).cloned() { ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id: m.obj_id, ++ msg_type: LOG_TAG_ASSEMBLED_LIBRARY, ++ bytes: m.key.to_vec(), ++ inline_bytes, ++ }); ++ } else { ++ st.records.push(LogRecord { ++ seq, ++ context, ++ obj_id: m.obj_id, ++ msg_type: RGFX_CMD_LIBRARY_LOOKUP, ++ bytes: message.to_vec(), ++ inline_bytes: Vec::new(), ++ }); ++ } ++ } ++ ++ pub(crate) fn record_surface_pages( ++ &self, ++ pages: RgfxSurfacePages, ++ runs: Vec, ++ flags: u32, ++ layout: Option, ++ ) { ++ let rec = SurfacePagesRecord { ++ pages, ++ runs, ++ flags, ++ layout, ++ }; ++ let mut st = self.state.lock(); ++ if flags & RGFX_SURFACE_PAGES_ATTACH != 0 { ++ st.surface_pages.entry(pages.block_offset).or_default().push(rec); ++ } else { ++ st.surface_pages.insert(pages.block_offset, vec![rec]); ++ } ++ } ++ ++ pub(crate) fn forget_surface_pages(&self, block_offset: u64) { ++ self.state.lock().surface_pages.remove(&block_offset); ++ } ++ ++ pub(crate) fn record_present(&self, display: usize, iosurface_id: u32) { ++ let mut st = self.state.lock(); ++ if let Some(slot) = st.presented_surfaces.get_mut(display) { ++ *slot = iosurface_id; ++ } ++ } ++ ++ pub(crate) fn close_context(&self, context: u32) { ++ let mut st = self.state.lock(); ++ let removed: HashSet = st ++ .records ++ .iter() ++ .filter(|r| r.context == context) ++ .map(|r| r.obj_id) ++ .collect(); ++ st.records.retain(|r| r.context != context); ++ st.standalone_textures.retain(|id| !removed.contains(id)); ++ st.surface_pages.retain(|_, v| { ++ v.retain(|sp| sp.pages.context != context); ++ !v.is_empty() ++ }); ++ } ++ ++ pub(crate) fn reset(&self) { ++ let mut st = self.state.lock(); ++ st.records.clear(); ++ st.surface_pages.clear(); ++ st.standalone_textures.clear(); ++ for slot in &mut st.presented_surfaces { ++ *slot = 0; ++ } ++ } ++ ++ pub(crate) fn export( ++ &self, ++ ) -> ( ++ Vec, ++ Vec, ++ HashSet, ++ Vec, ++ ) { ++ let st = self.state.lock(); ++ ( ++ compact_records(&st.records), ++ st.surface_pages.values().flatten().cloned().collect(), ++ st.standalone_textures.clone(), ++ st.presented_surfaces.clone(), ++ ) ++ } ++ ++ pub(crate) fn restore( ++ &self, ++ records: Vec, ++ surface_pages: Vec, ++ standalone_textures: HashSet, ++ presented_surfaces: Vec, ++ ) { ++ let mut st = self.state.lock(); ++ let max_seq = records.iter().map(|r| r.seq).max().unwrap_or(0); ++ st.next_seq = max_seq.wrapping_add(1); ++ st.library_bytes_by_key.clear(); ++ for r in &records { ++ if r.msg_type == LOG_TAG_ASSEMBLED_LIBRARY ++ && r.bytes.len() == 32 ++ && !r.inline_bytes.is_empty() ++ && let Ok(k) = <[u8; 32]>::try_from(r.bytes.as_slice()) ++ { ++ st.library_bytes_by_key.insert(k, r.inline_bytes.clone()); ++ if let Some(wk) = super::decode::whole_library_key(&r.inline_bytes) ++ && wk != k ++ { ++ st.library_bytes_by_key.insert(wk, r.inline_bytes.clone()); ++ } ++ } ++ } ++ st.records = records; ++ st.surface_pages.clear(); ++ for sp in surface_pages { ++ st.surface_pages.entry(sp.pages.block_offset).or_default().push(sp); ++ } ++ st.standalone_textures = standalone_textures; ++ let n = st.presented_surfaces.len().min(presented_surfaces.len()); ++ st.presented_surfaces[..n].copy_from_slice(&presented_surfaces[..n]); ++ } ++} ++ ++fn is_persistent_stage3(ty: u32) -> bool { ++ matches!( ++ ty, ++ RGFX_CMD_EVENT_CREATE ++ | RGFX_CMD_FENCE_CREATE ++ | RGFX_CMD_SHARED_EVENT_CREATE ++ | RGFX_CMD_SHARED_EVENT_IMPORT ++ | RGFX_CMD_SHARED_EVENT_NAME ++ | RGFX_CMD_QUEUE_CREATE ++ | RGFX_CMD_DYNAMIC_LIBRARY_CREATE ++ | RGFX_CMD_SAMPLER_CREATE ++ | RGFX_CMD_DEPTH_STENCIL_CREATE ++ | RGFX_CMD_BUFFER_CREATE ++ | RGFX_CMD_BUFFER_OVER_HOST_MEMORY ++ | RGFX_CMD_BUFFER_OVER_SURFACE_PAGES ++ | RGFX_CMD_BUFFER_OVER_PAGES ++ | RGFX_CMD_BUFFER_MANAGED_AT_OFFSET ++ | RGFX_CMD_MANAGED_BUFFER_CREATE ++ | RGFX_CMD_BUFFER_AT_OFFSET ++ | RGFX_CMD_BUFFER_ESCAPED ++ | RGFX_CMD_HEAP_CREATE ++ | RGFX_CMD_HEAP_OVER_HOST_MEMORY ++ | RGFX_CMD_HEAP_OVER_POOL ++ | RGFX_CMD_HEAP_OVER_PAGES ++ | RGFX_CMD_TEXTURE_CREATE ++ | RGFX_CMD_MANAGED_TEXTURE_CREATE ++ | RGFX_CMD_TEXTURE_VIEW ++ | RGFX_CMD_TEXTURE_FROM_BUFFER ++ | RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER ++ | RGFX_CMD_TEXTURE_FROM_IOSURFACE ++ | RGFX_CMD_RENDER_PIPELINE_CREATE ++ | RGFX_CMD_MESH_RENDER_PIPELINE_CREATE ++ | RGFX_CMD_COMPUTE_PIPELINE_CREATE ++ | RGFX_CMD_ICB_CREATE ++ | RGFX_CMD_ICB_WRITE ++ | RGFX_CMD_ICB_SLOTS ++ | RGFX_CMD_ICB_SLOTS_IN_PAGES ++ | RGFX_CMD_RATE_MAP_CREATE ++ | RGFX_CMD_RATE_MAP_RESET ++ | RGFX_CMD_FUNCTION_HANDLE_CREATE ++ | RGFX_CMD_FUNCTION_TABLE_CREATE ++ | RGFX_CMD_FUNCTION_TABLE_SET ++ ) ++} ++ ++fn push_linked_libraries(out: &mut Vec, bytes: &[u8], offset: u32, count: u32) { ++ let Ok(start) = usize::try_from(offset) else { ++ return; ++ }; ++ let Ok(n) = usize::try_from(count) else { ++ return; ++ }; ++ let elem = std::mem::size_of::(); ++ for i in 0..n { ++ let Some(at) = i.checked_mul(elem).and_then(|d| start.checked_add(d)) else { ++ break; ++ }; ++ let Some(slice) = bytes.get(at..) else { ++ break; ++ }; ++ let Ok((lf, _)) = RgfxLinkedFunction::read_from_prefix(slice) else { ++ break; ++ }; ++ if lf.library_obj_id != 0 { ++ out.push(lf.library_obj_id); ++ } ++ } ++} ++ ++fn push_pipeline_libraries(out: &mut Vec, bytes: &[u8], end_of_fixed: usize, count: u32) { ++ let Ok(n) = usize::try_from(count) else { ++ return; ++ }; ++ let elem = std::mem::size_of::(); ++ let Some(total) = n.checked_mul(elem) else { ++ return; ++ }; ++ let Some(start) = bytes.len().checked_sub(total) else { ++ return; ++ }; ++ if start < end_of_fixed { ++ return; ++ } ++ for i in 0..n { ++ let Some(slice) = bytes.get(start + i * elem..) else { ++ break; ++ }; ++ let Ok((pl, _)) = RgfxPipelineLibrary::read_from_prefix(slice) else { ++ break; ++ }; ++ if pl.obj_id != 0 { ++ out.push(pl.obj_id); ++ } ++ } ++} ++ ++/// Returns all parent object IDs referenced when replaying `rec`. ++fn record_parent_ids(rec: &LogRecord) -> Vec { ++ let mut out = Vec::new(); ++ let b = &rec.bytes; ++ match rec.msg_type { ++ RGFX_CMD_RENDER_PIPELINE_CREATE => { ++ if let Ok((m, _)) = RgfxRenderPipelineCreate::read_from_prefix(b) { ++ if m.vertex_library_obj_id != 0 { ++ out.push(m.vertex_library_obj_id); ++ } ++ if m.fragment_library_obj_id != 0 { ++ out.push(m.fragment_library_obj_id); ++ } ++ push_linked_libraries(&mut out, b, m.vertex_linked_offset, m.vertex_linked_count); ++ push_linked_libraries( ++ &mut out, ++ b, ++ m.fragment_linked_offset, ++ m.fragment_linked_count, ++ ); ++ } ++ } ++ RGFX_CMD_MESH_RENDER_PIPELINE_CREATE => { ++ if let Ok((m, _)) = RgfxMeshRenderPipelineCreate::read_from_prefix(b) { ++ if m.object_library_obj_id != 0 { ++ out.push(m.object_library_obj_id); ++ } ++ if m.mesh_library_obj_id != 0 { ++ out.push(m.mesh_library_obj_id); ++ } ++ if m.fragment_library_obj_id != 0 { ++ out.push(m.fragment_library_obj_id); ++ } ++ push_linked_libraries(&mut out, b, m.object_linked_offset, m.object_linked_count); ++ push_linked_libraries(&mut out, b, m.mesh_linked_offset, m.mesh_linked_count); ++ push_linked_libraries( ++ &mut out, ++ b, ++ m.fragment_linked_offset, ++ m.fragment_linked_count, ++ ); ++ } ++ } ++ RGFX_CMD_COMPUTE_PIPELINE_CREATE => { ++ if let Ok((m, _)) = RgfxComputePipelineCreate::read_from_prefix(b) { ++ if m.function_library_obj_id != 0 { ++ out.push(m.function_library_obj_id); ++ } ++ push_linked_libraries(&mut out, b, m.linked_offset, m.linked_count); ++ push_pipeline_libraries( ++ &mut out, ++ b, ++ std::mem::size_of::(), ++ m.library_count, ++ ); ++ } ++ } ++ RGFX_CMD_DYNAMIC_LIBRARY_CREATE => { ++ if let Ok((m, _)) = RgfxDynamicLibraryCreate::read_from_prefix(b) ++ && m.library_obj_id != 0 ++ { ++ out.push(m.library_obj_id); ++ } ++ } ++ RGFX_CMD_FUNCTION_HANDLE_CREATE => { ++ if let Ok((m, _)) = RgfxFunctionHandleCreate::read_from_prefix(b) { ++ if m.pipeline_obj_id != 0 { ++ out.push(m.pipeline_obj_id); ++ } ++ if m.function.library_obj_id != 0 { ++ out.push(m.function.library_obj_id); ++ } ++ } ++ } ++ RGFX_CMD_FUNCTION_TABLE_SET => { ++ if let Ok((m, rest)) = RgfxFunctionTableSet::read_from_prefix(b) { ++ let count = m.count as usize; ++ for chunk in rest.chunks_exact(8).take(count) { ++ if let Ok(arr) = <[u8; 8]>::try_from(chunk) { ++ let id = u64::from_le_bytes(arr); ++ if id != 0 { ++ out.push(id); ++ } ++ } ++ } ++ } ++ } ++ RGFX_CMD_TEXTURE_VIEW => { ++ if let Ok((m, _)) = RgfxTextureView::read_from_prefix(b) ++ && m.parent_obj_id != 0 ++ { ++ out.push(m.parent_obj_id); ++ } ++ } ++ RGFX_CMD_TEXTURE_CREATE => { ++ if let Ok((m, _)) = RgfxTextureCreate::read_from_prefix(b) ++ && m.heap_obj_id != 0 ++ { ++ out.push(m.heap_obj_id); ++ } ++ } ++ RGFX_CMD_TEXTURE_FROM_BUFFER => { ++ if let Ok((m, _)) = RgfxTextureFromBuffer::read_from_prefix(b) ++ && m.buffer_obj_id != 0 ++ { ++ out.push(m.buffer_obj_id); ++ } ++ } ++ RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER => { ++ if let Ok((m, _)) = RgfxLinearTextureFromBuffer::read_from_prefix(b) ++ && m.buffer_obj_id != 0 ++ { ++ out.push(m.buffer_obj_id); ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_NAME => { ++ if let Ok((m, _)) = RgfxSharedEventName::read_from_prefix(b) ++ && m.listen_queue_obj_id != 0 ++ { ++ out.push(m.listen_queue_obj_id); ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_IMPORT => { ++ if let Ok((m, _)) = RgfxSharedEventImport::read_from_prefix(b) ++ && m.listen_queue_obj_id != 0 ++ { ++ out.push(m.listen_queue_obj_id); ++ } ++ } ++ _ => {} ++ } ++ out ++} ++ ++/// Drops destroyed incarnations that are no longer transitively referenced by any live object. ++fn compact_records(records: &[LogRecord]) -> Vec { ++ let mut active_inc: HashMap = HashMap::new(); ++ let mut active_name_inc: HashMap = HashMap::new(); ++ let mut destroyed: Vec = Vec::new(); ++ let mut deps: Vec> = Vec::new(); ++ let mut rec_inc: Vec> = Vec::with_capacity(records.len()); ++ ++ for r in records { ++ match r.msg_type { ++ RGFX_CMD_OBJECT_DESTROY => { ++ if let Some(inc) = active_inc.remove(&r.obj_id) { ++ destroyed[inc] = true; ++ rec_inc.push(Some(inc)); ++ } else { ++ rec_inc.push(None); ++ } ++ } ++ RGFX_CMD_SHARED_EVENT_UNNAME => { ++ let inc = RgfxSharedEventUnname::read_from_prefix(&r.bytes) ++ .ok() ++ .and_then(|(m, _)| active_name_inc.remove(&m.name)); ++ rec_inc.push(inc); ++ } ++ _ => { ++ let inc = if r.obj_id != 0 { ++ *active_inc.entry(r.obj_id).or_insert_with(|| { ++ let id = destroyed.len(); ++ destroyed.push(false); ++ deps.push(Vec::new()); ++ id ++ }) ++ } else { ++ let id = destroyed.len(); ++ destroyed.push(false); ++ deps.push(Vec::new()); ++ id ++ }; ++ for pid in record_parent_ids(r) { ++ if let Some(&pinc) = active_inc.get(&pid) ++ && pinc != inc ++ { ++ deps[inc].push(pinc); ++ } ++ } ++ if r.msg_type == RGFX_CMD_SHARED_EVENT_NAME { ++ if let Ok((m, _)) = RgfxSharedEventName::read_from_prefix(&r.bytes) { ++ active_name_inc.insert(m.name, inc); ++ } ++ } else if r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT { ++ if let Ok((m, _)) = RgfxSharedEventImport::read_from_prefix(&r.bytes) ++ && let Some(&ninc) = active_name_inc.get(&m.name) ++ && ninc != inc ++ { ++ deps[inc].push(ninc); ++ } ++ } ++ rec_inc.push(Some(inc)); ++ } ++ } ++ } ++ ++ let mut keep = vec![false; destroyed.len()]; ++ let mut stack: Vec = Vec::new(); ++ for (inc, &is_dead) in destroyed.iter().enumerate() { ++ if !is_dead { ++ keep[inc] = true; ++ stack.push(inc); ++ } ++ } ++ while let Some(inc) = stack.pop() { ++ for &pinc in &deps[inc] { ++ if !keep[pinc] { ++ keep[pinc] = true; ++ stack.push(pinc); ++ } ++ } ++ } ++ ++ records ++ .iter() ++ .zip(rec_inc) ++ .filter_map(|(r, inc)| inc.filter(|&i| keep[i]).map(|_| r.clone())) ++ .collect() ++} ++ ++/// Complete serialized snapshot of a [`super::GraphicsDevice`]. ++pub(crate) struct VgpuSnapshot { ++ pub(crate) device_snapshot: Vec, ++ pub(crate) shared_pool: Option, ++ pub(crate) private_blocks: PrivateBlocksSnapshot, ++ pub(crate) id_chunks: Vec, ++ pub(crate) surface_pages: Vec, ++ pub(crate) live_records: Vec, ++ pub(crate) standalone_textures: Vec, ++ pub(crate) presented_surfaces: Vec, ++ pub(crate) live_values: LiveValues, ++} ++ ++struct Enc(Vec); ++ ++impl Enc { ++ fn u8(&mut self, v: u8) { ++ self.0.push(v); ++ } ++ fn u32(&mut self, v: u32) { ++ self.0.extend_from_slice(&v.to_le_bytes()); ++ } ++ fn u64(&mut self, v: u64) { ++ self.0.extend_from_slice(&v.to_le_bytes()); ++ } ++ fn bytes(&mut self, b: &[u8]) { ++ self.u64(b.len() as u64); ++ self.0.extend_from_slice(b); ++ } ++ fn capture(&mut self, c: Option) { ++ match c { ++ None => self.u8(0), ++ Some(c) => { ++ self.u8(1); ++ self.u8(match c.class { ++ MemoryClass::Shared => 0, ++ MemoryClass::Private => 1, ++ }); ++ self.u64(c.alloc_len); ++ self.u64(c.offset); ++ self.u64(c.len); ++ self.u64(c.gpu_address); ++ self.u64(c.opaque_buffer_address); ++ self.u64(c.opaque_memory_address); ++ } ++ } ++ } ++} ++ ++struct Dec<'a> { ++ buf: &'a [u8], ++ pos: usize, ++} ++ ++impl<'a> Dec<'a> { ++ fn remaining(&self) -> usize { ++ self.buf.len().saturating_sub(self.pos) ++ } ++ fn take(&mut self, n: usize) -> Option<&'a [u8]> { ++ let end = self.pos.checked_add(n)?; ++ let s = self.buf.get(self.pos..end)?; ++ self.pos = end; ++ Some(s) ++ } ++ fn checked_count(&mut self, min_item_bytes: usize) -> Option { ++ let count = usize::try_from(self.u32()?).ok()?; ++ let min_bytes = min_item_bytes.max(1); ++ if count > self.remaining() / min_bytes { ++ return None; ++ } ++ Some(count) ++ } ++ fn read_vec( ++ &mut self, ++ min_item_bytes: usize, ++ mut f: impl FnMut(&mut Self) -> Option, ++ ) -> Option> { ++ let count = self.checked_count(min_item_bytes)?; ++ let mut out = Vec::with_capacity(count); ++ for _ in 0..count { ++ out.push(f(self)?); ++ } ++ Some(out) ++ } ++ fn u8(&mut self) -> Option { ++ Some(self.take(1)?[0]) ++ } ++ fn u32(&mut self) -> Option { ++ Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) ++ } ++ fn u64(&mut self) -> Option { ++ Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?)) ++ } ++ fn bytes(&mut self) -> Option> { ++ let n = usize::try_from(self.u64()?).ok()?; ++ Some(self.take(n)?.to_vec()) ++ } ++ fn capture(&mut self) -> Option> { ++ match self.u8()? { ++ 0 => Some(None), ++ 1 => { ++ let class = match self.u8()? { ++ 0 => MemoryClass::Shared, ++ 1 => MemoryClass::Private, ++ _ => return None, ++ }; ++ Some(Some(BlockCapture { ++ class, ++ alloc_len: self.u64()?, ++ offset: self.u64()?, ++ len: self.u64()?, ++ gpu_address: self.u64()?, ++ opaque_buffer_address: self.u64()?, ++ opaque_memory_address: self.u64()?, ++ })) ++ } ++ _ => None, ++ } ++ } ++} ++ ++impl VgpuSnapshot { ++ pub(crate) fn encode(&self) -> Vec { ++ let mut e = Enc(Vec::with_capacity(64 * 1024)); ++ e.0.extend_from_slice(SNAPSHOT_MAGIC); ++ e.u32(SNAPSHOT_VERSION); ++ e.bytes(&self.device_snapshot); ++ ++ match &self.shared_pool { ++ None => e.u8(0), ++ Some(pool) => { ++ e.u8(1); ++ e.u64(pool.serial); ++ e.u32(pool.pieces.len() as u32); ++ for p in &pool.pieces { ++ e.u64(p.gpa); ++ e.u64(p.len); ++ e.u64(p.gpu_address); ++ e.capture(p.capture); ++ e.bytes(&p.bytes); ++ } ++ e.u32(pool.carves.len() as u32); ++ for c in &pool.carves { ++ e.u64(c.gpa); ++ e.u32(c.context); ++ e.u64(c.len); ++ e.u64(c.serial); ++ e.u64(c.gpu_address); ++ e.u8(u8::from(c.picked_address)); ++ } ++ } ++ } ++ ++ e.u64(self.private_blocks.serial); ++ e.u32(self.private_blocks.blocks.len() as u32); ++ for b in &self.private_blocks.blocks { ++ e.u64(b.gpu_address); ++ e.u32(b.context); ++ e.u64(b.len); ++ e.u64(b.serial); ++ e.capture(b.capture); ++ e.bytes(&b.bytes); ++ } ++ ++ e.u32(self.id_chunks.len() as u32); ++ for &c in &self.id_chunks { ++ e.u32(c); ++ } ++ ++ e.u32(self.surface_pages.len() as u32); ++ for sp in &self.surface_pages { ++ e.bytes(sp.pages.as_bytes()); ++ e.u32(sp.runs.len() as u32); ++ for r in &sp.runs { ++ e.bytes(r.as_bytes()); ++ } ++ e.u32(sp.flags); ++ match &sp.layout { ++ None => e.u8(0), ++ Some(l) => { ++ e.u8(1); ++ e.bytes(l.as_bytes()); ++ } ++ } ++ } ++ ++ e.u32(self.live_records.len() as u32); ++ for r in &self.live_records { ++ e.u64(r.seq); ++ e.u32(r.context); ++ e.u64(r.obj_id); ++ e.u32(r.msg_type); ++ e.bytes(&r.bytes); ++ e.bytes(&r.inline_bytes); ++ } ++ ++ e.u32(self.standalone_textures.len() as u32); ++ for &id in &self.standalone_textures { ++ e.u64(id); ++ } ++ ++ e.u32(self.presented_surfaces.len() as u32); ++ for &id in &self.presented_surfaces { ++ e.u32(id); ++ } ++ ++ e.u32(self.live_values.events.len() as u32); ++ for &(id, val) in &self.live_values.events { ++ e.u64(id); ++ e.u64(val); ++ } ++ e.u32(self.live_values.shared_events.len() as u32); ++ for &(id, val) in &self.live_values.shared_events { ++ e.u64(id); ++ e.u64(val); ++ } ++ e.u32(self.live_values.buffers.len() as u32); ++ for (id, bytes) in &self.live_values.buffers { ++ e.u64(*id); ++ e.bytes(bytes); ++ } ++ e.u32(self.live_values.textures.len() as u32); ++ for (id, bytes) in &self.live_values.textures { ++ e.u64(*id); ++ e.bytes(bytes); ++ } ++ e.u32(self.live_values.surface_caches.len() as u32); ++ for (block, bytes) in &self.live_values.surface_caches { ++ e.u64(*block); ++ e.bytes(bytes); ++ } ++ e.0 ++ } ++ ++ pub(crate) fn decode(data: &[u8]) -> Option { ++ let mut d = Dec { buf: data, pos: 0 }; ++ if d.take(8)? != SNAPSHOT_MAGIC { ++ return None; ++ } ++ if d.u32()? != SNAPSHOT_VERSION { ++ return None; ++ } ++ let device_snapshot = d.bytes()?; ++ ++ let shared_pool = match d.u8()? { ++ 0 => None, ++ 1 => { ++ let serial = d.u64()?; ++ let pieces = d.read_vec(33, |d| { ++ Some(PoolPieceSnapshot { ++ gpa: d.u64()?, ++ len: d.u64()?, ++ gpu_address: d.u64()?, ++ capture: d.capture()?, ++ bytes: d.bytes()?, ++ }) ++ })?; ++ let carves = d.read_vec(37, |d| { ++ Some(PoolCarveSnapshot { ++ gpa: d.u64()?, ++ context: d.u32()?, ++ len: d.u64()?, ++ serial: d.u64()?, ++ gpu_address: d.u64()?, ++ picked_address: d.u8()? != 0, ++ }) ++ })?; ++ Some(PoolSnapshot { ++ serial, ++ pieces, ++ carves, ++ }) ++ } ++ _ => return None, ++ }; ++ ++ let pb_serial = d.u64()?; ++ let blocks = d.read_vec(37, |d| { ++ Some(PrivateBlockSnapshot { ++ gpu_address: d.u64()?, ++ context: d.u32()?, ++ len: d.u64()?, ++ serial: d.u64()?, ++ capture: d.capture()?, ++ bytes: d.bytes()?, ++ }) ++ })?; ++ let private_blocks = PrivateBlocksSnapshot { ++ serial: pb_serial, ++ blocks, ++ }; ++ ++ let id_chunks = d.read_vec(4, Dec::u32)?; ++ ++ let surface_pages = d.read_vec(17, |d| { ++ let pages_b = d.bytes()?; ++ let (pages, _) = RgfxSurfacePages::read_from_prefix(&pages_b).ok()?; ++ let runs = d.read_vec(8 + std::mem::size_of::(), |d| { ++ let rb = d.bytes()?; ++ let (r, _) = RgfxPageRun::read_from_prefix(&rb).ok()?; ++ Some(r) ++ })?; ++ let flags = d.u32()?; ++ let layout = match d.u8()? { ++ 0 => None, ++ 1 => { ++ let lb = d.bytes()?; ++ let (l, _) = RgfxSurfacePagesLayout::read_from_prefix(&lb).ok()?; ++ Some(l) ++ } ++ _ => return None, ++ }; ++ Some(SurfacePagesRecord { ++ pages, ++ runs, ++ flags, ++ layout, ++ }) ++ })?; ++ ++ let live_records = d.read_vec(40, |d| { ++ Some(LogRecord { ++ seq: d.u64()?, ++ context: d.u32()?, ++ obj_id: d.u64()?, ++ msg_type: d.u32()?, ++ bytes: d.bytes()?, ++ inline_bytes: d.bytes()?, ++ }) ++ })?; ++ ++ let standalone_textures = d.read_vec(8, Dec::u64)?; ++ let presented_surfaces = d.read_vec(4, Dec::u32)?; ++ ++ let live_values = LiveValues { ++ events: d.read_vec(16, |d| Some((d.u64()?, d.u64()?)))?, ++ shared_events: d.read_vec(16, |d| Some((d.u64()?, d.u64()?)))?, ++ buffers: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, ++ textures: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, ++ surface_caches: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, ++ }; ++ if d.remaining() != 0 { ++ return None; ++ } ++ ++ Some(VgpuSnapshot { ++ device_snapshot, ++ shared_pool, ++ private_blocks, ++ id_chunks, ++ surface_pages, ++ live_records, ++ standalone_textures, ++ presented_surfaces, ++ live_values, ++ }) ++ } ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ fn empty_snapshot() -> VgpuSnapshot { ++ VgpuSnapshot { ++ device_snapshot: Vec::new(), ++ shared_pool: Some(PoolSnapshot { ++ serial: 1, ++ pieces: Vec::new(), ++ carves: Vec::new(), ++ }), ++ private_blocks: PrivateBlocksSnapshot { ++ serial: 2, ++ blocks: Vec::new(), ++ }, ++ id_chunks: Vec::new(), ++ surface_pages: Vec::new(), ++ live_records: Vec::new(), ++ standalone_textures: Vec::new(), ++ presented_surfaces: Vec::new(), ++ live_values: LiveValues::default(), ++ } ++ } ++ ++ #[test] ++ fn decode_rejects_oversized_counts_and_trailing_bytes() { ++ let encoded = empty_snapshot().encode(); ++ assert!(VgpuSnapshot::decode(&encoded).is_some()); ++ ++ let mut with_tail = encoded.clone(); ++ with_tail.push(0xAA); ++ assert!(VgpuSnapshot::decode(&with_tail).is_none()); ++ ++ assert_eq!(encoded.len(), 89); ++ for offset in [29usize, 33, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85] { ++ let mut bad = encoded.clone(); ++ bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes()); ++ assert!( ++ VgpuSnapshot::decode(&bad).is_none(), ++ "oversized count at offset {offset} must fail cleanly" ++ ); ++ } ++ } ++ ++ #[test] ++ fn live_log_retains_destroyed_parent_library_for_live_pipeline() { ++ let log = LiveLog::new(1); ++ let ctx = 7u32; ++ ++ // Create two libraries: obj 10 (needed by pipeline 20) and obj 11 (unused). ++ let lib_bytes = b"MTLB_DUMMY_PAYLOAD".to_vec(); ++ log.record_library(ctx, 10, lib_bytes.clone(), Some([0x11; 32])); ++ log.record_library(ctx, 11, lib_bytes, Some([0x22; 32])); ++ ++ // Create a compute pipeline (obj 20) referencing library 10. ++ let mut pipe = zerocopy::FromZeros::new_zeroed(); ++ let pipe_ref: &mut RgfxComputePipelineCreate = &mut pipe; ++ pipe_ref.header.r#type = RGFX_CMD_COMPUTE_PIPELINE_CREATE; ++ pipe_ref.header.size = std::mem::size_of::() as u32; ++ pipe_ref.obj_id = 20; ++ pipe_ref.function_library_obj_id = 10; ++ log.record_stage3(ctx, pipe_ref.as_bytes()); ++ ++ // Destroy both libraries (e.g. ARC releasing MTLLibrary after compiling pipeline). ++ for dead in [10u64, 11u64] { ++ let mut d = zerocopy::FromZeros::new_zeroed(); ++ let d_ref: &mut RgfxObjectDestroy = &mut d; ++ d_ref.header.r#type = RGFX_CMD_OBJECT_DESTROY; ++ d_ref.header.size = std::mem::size_of::() as u32; ++ d_ref.obj_id = dead; ++ log.record_stage3(ctx, d_ref.as_bytes()); ++ } ++ ++ let (records, _, _, _) = log.export(); ++ let summary: Vec<(u64, u32)> = records.iter().map(|r| (r.obj_id, r.msg_type)).collect(); ++ // Library 10 and its trailing destroy must be kept so pipeline 20 can replay; ++ // unused library 11 and its destroy must be compacted away. ++ assert_eq!( ++ summary, ++ vec![ ++ (10, LOG_TAG_ASSEMBLED_LIBRARY), ++ (20, RGFX_CMD_COMPUTE_PIPELINE_CREATE), ++ (10, RGFX_CMD_OBJECT_DESTROY), ++ ] ++ ); ++ } ++} +diff --git a/crates/reims-vgpu/src/pool.rs b/crates/reims-vgpu/src/pool.rs +index e915869056a8c7ac9f81f2a5b7d18b90290c542c..58deecf094f39ab8f8d3aaf6b988ed3c43a3937c 100644 +--- a/crates/reims-vgpu/src/pool.rs ++++ b/crates/reims-vgpu/src/pool.rs +@@ -85,6 +85,7 @@ + mod addresses; + mod host_blocks; + mod private_blocks; ++pub(crate) use private_blocks::{PrivateBlockSnapshot, PrivateBlocksSnapshot}; + mod rt_blocks; + mod takes; + +@@ -309,6 +310,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, ++ pub bytes: Vec, ++} ++ ++/// 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, ++ pub carves: Vec, ++} ++ + pub trait BlockSource: Send + Sync { + /// A block of `class` at least `len` long ([`BlockInfo::len`]). Waits only when no block is + /// ready. +@@ -317,6 +359,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 { ++ None ++ } ++ ++ /// Replays a previously captured block at its exact Vulkan device address. ++ fn take_block_replayed(&self, _cap: BlockCapture) -> Result { ++ 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>, 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. +@@ -1087,6 +1150,146 @@ impl Pool { + dead_code, + reason = "the guest's side of the pool (its ring messages) calls it once it lands" + )] ++ /// Waits until in-flight pool take workers and zeroer are idle. ++ pub(crate) fn quiesce(&self) { ++ let deadline = std::time::Instant::now() + Duration::from_secs(5); ++ loop { ++ let busy = { ++ let st = self.shared.state.lock(); ++ st.workers > 0 || st.zeroer || st.serving > 0 || !st.asks.is_empty() ++ }; ++ if !busy || std::time::Instant::now() >= deadline { ++ break; ++ } ++ std::thread::sleep(Duration::from_millis(2)); ++ } ++ } ++ ++ /// Exports all live Shared Pool pieces (with raw bytes & BDA capture metadata) and carves. ++ pub(crate) fn export_snapshot(&self) -> Result { ++ self.quiesce(); ++ let st = self.shared.state.lock(); ++ let source = st.source.clone(); ++ let mut pieces = Vec::new(); ++ for (&gpa, p) in &st.pieces { ++ if !matches!(p.mapped, Mapped::Live | Mapped::Adding) { ++ continue; ++ } ++ let cap = source.as_ref().and_then(|s| s.capture_block(p.block.id)); ++ let ptr = p.block.contents.ok_or(Error::HostResources)?; ++ let bytes = unsafe { ++ std::slice::from_raw_parts(ptr.as_ptr(), p.block.len as usize).to_vec() ++ }; ++ pieces.push(PoolPieceSnapshot { ++ gpa, ++ len: p.block.len, ++ gpu_address: p.block.gpu_address, ++ capture: cap, ++ bytes, ++ }); ++ } ++ let carves = takes::export_carves(&st.carves); ++ Ok(PoolSnapshot { ++ serial: st.serial, ++ pieces, ++ carves, ++ }) ++ } ++ ++ /// Restores Shared Pool pieces at their exact GPAs and Vulkan BDAs, and asks host to map them. ++ pub(crate) fn import_snapshot(&self, snap: &PoolSnapshot) -> Result<(), Error> { ++ self.quiesce(); ++ let source = { ++ let st = self.shared.state.lock(); ++ st.source.clone() ++ }; ++ let Some(source) = source else { ++ return if snap.pieces.is_empty() { ++ Ok(()) ++ } else { ++ Err(Error::HostResources) ++ }; ++ }; ++ // First release any pre-existing empty pieces if any (fresh device has none). ++ let mut restored_pieces: Vec<(u64, BlockInfo)> = Vec::with_capacity(snap.pieces.len()); ++ for ps in &snap.pieces { ++ let blk = if let Some(cap) = ps.capture { ++ source ++ .take_block_replayed(cap) ++ .map_err(|_| Error::HostResources)? ++ } else { ++ source ++ .take_block(MemoryClass::Shared, ps.len) ++ .map_err(|_| Error::HostResources)? ++ }; ++ let ptr = blk.contents.ok_or(Error::HostResources)?; ++ if ps.bytes.len() as u64 != blk.len { ++ return Err(Error::InvalidArgument); ++ } ++ unsafe { ++ std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len()); ++ } ++ restored_pieces.push((ps.gpa, blk)); ++ } ++ { ++ let mut st = self.shared.state.lock(); ++ st.serial = st.serial.max(snap.serial); ++ for (gpa, blk) in &restored_pieces { ++ let piece_carves = snap ++ .carves ++ .iter() ++ .filter(|c| c.gpa >= *gpa && c.gpa < *gpa + blk.len) ++ .count() as u64; ++ st.by_block.insert(blk.id, *gpa); ++ st.pieces.insert( ++ *gpa, ++ Piece { ++ block: *blk, ++ mapped: Mapped::Adding, ++ empty_since: if piece_carves == 0 { ++ Some((self.shared.now)()) ++ } else { ++ None ++ }, ++ holds: 0, ++ kept: Arc::new(()), ++ carves: piece_carves, ++ zeros: takes::Ranges::new(), ++ zero_pending: false, ++ going: None, ++ }, ++ ); ++ } ++ let state = &mut *st; ++ takes::import_carves(&mut state.carves, &mut state.addresses, &snap.carves); ++ } ++ for (gpa, blk) in &restored_pieces { ++ if let Some(ptr) = blk.contents { ++ (self.shared.host.add)(*gpa, ptr.as_ptr(), blk.len); ++ } ++ } ++ self.shared.wake(); ++ Ok(()) ++ } ++ ++ /// Re-copies snapshotted Shared Pool piece bytes after LiveLog replay (so any `new_buffer` ++ /// zero-initialization during replay cannot clobber saved guest/GPU contents). ++ pub(crate) fn restore_bytes(&self, snap: &PoolSnapshot) -> Result<(), Error> { ++ let st = self.shared.state.lock(); ++ for ps in &snap.pieces { ++ let piece = st.pieces.get(&ps.gpa).ok_or(Error::HostResources)?; ++ let ptr = piece.block.contents.ok_or(Error::HostResources)?; ++ if ps.bytes.len() as u64 != piece.block.len { ++ return Err(Error::InvalidArgument); ++ } ++ unsafe { ++ std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len()); ++ } ++ } ++ Ok(()) ++ } ++ ++ #[cfg(any(test, feature = "testkit"))] + pub fn live(&self) -> Vec<(u64, u64)> { + let st = self.shared.state.lock(); + (st.pieces.iter()) +diff --git a/crates/reims-vgpu/src/pool/private_blocks.rs b/crates/reims-vgpu/src/pool/private_blocks.rs +index ebe6e77b899a55b102dc0d9fc07b9d57a315c44e..5a42f97cb40d4b3d067b9283d1e2232a7eecc6a5 100644 +--- a/crates/reims-vgpu/src/pool/private_blocks.rs ++++ b/crates/reims-vgpu/src/pool/private_blocks.rs +@@ -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, ++ pub(crate) bytes: Vec, ++} ++ ++/// Complete snapshot of all contexts' Private blocks. ++#[derive(Clone, Debug, Default)] ++pub(crate) struct PrivateBlocksSnapshot { ++ pub(crate) serial: u64, ++ pub(crate) blocks: Vec, ++} ++ + #[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 { ++ let deadline = std::time::Instant::now() + Duration::from_secs(5); ++ loop { ++ let busy = { ++ let st = self.inner.state.lock(); ++ st.takers.values().any(|t| t.busy || !t.jobs.is_empty()) ++ }; ++ if !busy { ++ break; ++ } ++ if std::time::Instant::now() >= deadline { ++ return Err(super::Error::HostResources); ++ } ++ std::thread::sleep(Duration::from_millis(2)); ++ } ++ let entries: Vec<(u64, u32, u64, u64, Option)> = { ++ 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(); +diff --git a/crates/reims-vgpu/src/pool/rt_blocks.rs b/crates/reims-vgpu/src/pool/rt_blocks.rs +index ea0ae46f22cbaaeca83f3b205d5bd34ab02fb10d..91676ea8ef346cc4f35dea1c79c6c9e51a33d943 100644 +--- a/crates/reims-vgpu/src/pool/rt_blocks.rs ++++ b/crates/reims-vgpu/src/pool/rt_blocks.rs +@@ -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 { ++ 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 { ++ 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>, 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, 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 { +diff --git a/crates/reims-vgpu/src/pool/takes.rs b/crates/reims-vgpu/src/pool/takes.rs +index d724a3413c17940834fae97b41cb025089b6e164..1c9ea6db4f9d47e151454c128caf41ea5254c383 100644 +--- a/crates/reims-vgpu/src/pool/takes.rs ++++ b/crates/reims-vgpu/src/pool/takes.rs +@@ -191,6 +191,47 @@ enum GpuAddress { + Picked(u64), + } + ++pub(super) fn export_carves(carves: &BTreeMap) -> Vec { ++ 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, ++ _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 { diff --git a/patches/series.txt b/patches/series.txt index b499927..0b43011 100644 --- a/patches/series.txt +++ b/patches/series.txt @@ -1,18 +1,19 @@ # Patch queue, in the order the patches are applied (see patches/README.md). # One patch per line: . -# Targets are "reims-vgpu", "vendor/qemu", and "reims-util". +# Targets are "reims-vgpu", "vendor/qemu", "reims-util", and "metal2vulkan". # CI (build-runtime.yml via scripts/apply-patch-series.ps1) and # scripts/pack-runtime.ps1 both read this file; add or retire patches here. -reims-vgpu reims-vgpu-cargo-lock.patch -reims-vgpu reims-vgpu-win32-unicode-input.patch -reims-vgpu reims-vgpu-display-fixed-mode.patch -reims-vgpu reims-ctl-win32-random-bytes.patch -reims-vgpu reims-ctl-virtio-discard-iothread.patch -reims-vgpu reims-ctl-qcow2-l2-cache.patch -reims-util reims-util-parallel-offline-download.patch -vendor/qemu qemu-whpx-win10-compat.patch -vendor/qemu qemu-whpx-win10-startup-ipis.patch -vendor/qemu qemu-whpx-nested-virt-nonfatal.patch -vendor/qemu qemu-win32-coroutine-fiber-commit.patch -vendor/qemu qemu-win32-mapped-ram-io.patch -vendor/qemu qemu-intel-whpx-suspend.patch +reims-vgpu reims-vgpu-win32-unicode-input.patch +reims-vgpu reims-vgpu-display-fixed-mode.patch +reims-vgpu reims-ctl-win32-random-bytes.patch +reims-vgpu reims-ctl-virtio-discard-iothread.patch +reims-vgpu reims-ctl-qcow2-l2-cache.patch +reims-vgpu reims-vgpu-snapshot-replay.patch +reims-util reims-util-parallel-offline-download.patch +metal2vulkan metal2vulkan-snapshot-replay.patch +vendor/qemu qemu-whpx-win10-compat.patch +vendor/qemu qemu-whpx-win10-startup-ipis.patch +vendor/qemu qemu-whpx-nested-virt-nonfatal.patch +vendor/qemu qemu-win32-coroutine-fiber-commit.patch +vendor/qemu qemu-win32-mapped-ram-io.patch +vendor/qemu qemu-intel-whpx-suspend.patch diff --git a/scripts/apply-patch-series.ps1 b/scripts/apply-patch-series.ps1 index e04aeaa..7f6ef99 100644 --- a/scripts/apply-patch-series.ps1 +++ b/scripts/apply-patch-series.ps1 @@ -16,23 +16,25 @@ was really applied, AGENTS.md rule 5) and report merged or conflicting patches. .EXAMPLE - pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -ResultFile patches.json + pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -Metal2VulkanRepo $env:RUNNER_TEMP\metal2vulkan -ResultFile patches.json #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ReimsRepo, [string]$ResultFile = '', - [string]$UtilRepo = '' + [string]$UtilRepo = '', + [string]$Metal2VulkanRepo = '' ) $ErrorActionPreference = 'Stop' $repoRoot = Split-Path -Parent $PSScriptRoot $patchesDir = Join-Path $repoRoot 'patches' $repositories = @{ - 'reims-vgpu' = $ReimsRepo - 'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu' - 'reims-util' = $UtilRepo + 'reims-vgpu' = $ReimsRepo + 'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu' + 'reims-util' = $UtilRepo + 'metal2vulkan' = $Metal2VulkanRepo } function Read-PatchSeries { @@ -59,6 +61,9 @@ $series = @(Read-PatchSeries) if (-not $UtilRepo -and $series.Target -contains 'reims-util') { throw 'Pass -UtilRepo with a checkout at the reims-util revision pinned by reims-ctl.' } +if (-not $Metal2VulkanRepo -and $series.Target -contains 'metal2vulkan') { + throw 'Pass -Metal2VulkanRepo with a checkout at the metal2vulkan revision pinned by reims-vgpu.' +} foreach ($p in $series) { $file = Join-Path $patchesDir $p.Name diff --git a/scripts/pack-runtime.ps1 b/scripts/pack-runtime.ps1 index 40928b9..1294bb7 100644 --- a/scripts/pack-runtime.ps1 +++ b/scripts/pack-runtime.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Pack a portable reims-vgpu runtime for Windows x64, its matching source package, and SHA256SUMS.txt, ready to publish as a GitHub Release. @@ -29,13 +29,14 @@ .EXAMPLE pwsh -File scripts/pack-runtime.ps1 -Channel alpha - pwsh -File scripts/pack-runtime.ps1 -Patches reims-vgpu-cargo-lock.patch,qemu-whpx-win10-compat.patch + pwsh -File scripts/pack-runtime.ps1 -Patches reims-vgpu-snapshot-replay.patch,metal2vulkan-snapshot-replay.patch,qemu-whpx-win10-compat.patch #> [CmdletBinding(PositionalBinding = $false)] param( - [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', - [string]$UtilRepo = '', - [string]$CargoHome = 'D:\DevTools\cargo', + [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', + [string]$UtilRepo = '', + [string]$Metal2VulkanRepo = '', + [string]$CargoHome = 'D:\DevTools\cargo', [string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current', [string]$Msys2 = 'D:\DevTools\msys64', [string]$OutDir = 'D:\Data\reims-go\releases', @@ -139,19 +140,35 @@ if (-not $utilTree) { throw "reims-util source at $utilCommit not found" } $actualUtil = git -C $utilTree rev-parse HEAD if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" } -# metal2vulkan's git rev as built (Cargo.lock in the build tree). -$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock') -if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.lock' } -$m2vCommit = $Matches[1] +# metal2vulkan's pinned commit (workspace Cargo.toml, falling back to Cargo.lock). +$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.toml') +if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') { + $m2vCommit = $Matches[1] +} else { + $lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock') + if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' } + $m2vCommit = $Matches[1] +} +$m2vTree = if ($Metal2VulkanRepo) { + (Resolve-Path -LiteralPath $Metal2VulkanRepo).Path +} else { + Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' -ErrorAction SilentlyContinue | + ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | + Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +} +if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found (pass -Metal2VulkanRepo or check $checkouts)" } +$actualM2v = (git -C $m2vTree rev-parse HEAD).Trim() +if ($LASTEXITCODE -ne 0 -or $actualM2v -ne $m2vCommit) { throw "metal2vulkan checkout must be at $m2vCommit (got $actualM2v)" } $qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim() $utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim() # ── 2. Patches must equal the build tree's diffs ───────────── $repositories = @{ - 'reims-vgpu' = $ReimsRepo - 'vendor/qemu' = $qemuRepo - 'reims-util' = $utilTree + 'reims-vgpu' = $ReimsRepo + 'vendor/qemu' = $qemuRepo + 'reims-util' = $utilTree + 'metal2vulkan' = $m2vTree } $series = @(foreach ($line in Get-Content -LiteralPath (Join-Path $patchesDir 'series.txt')) { $t = $line.Trim() @@ -257,6 +274,20 @@ foreach ($targetName in $byTarget.Keys) { Write-Host "Expected patch stack diff --stat:`n$expStat" throw "Patch stack ($(($group | ForEach-Object { $_.Name }) -join ', ')) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)." } + # Also verify newly created (untracked) files added by patches byte-for-byte. + $addedFiles = @(& git -C $verifyDir ls-files --others --exclude-standard | Where-Object { $_ }) + foreach ($rel in $addedFiles) { + $expPath = Join-Path $verifyDir ($rel -replace '/', '\') + $treePath = Join-Path $repo ($rel -replace '/', '\') + if (-not (Test-Path -LiteralPath $treePath -PathType Leaf)) { + throw "Patch stack expected new file $rel in $repo, but it is missing." + } + $expText = [IO.File]::ReadAllText($expPath).Replace("`r`n", "`n") + $treeText = [IO.File]::ReadAllText($treePath).Replace("`r`n", "`n") + if ($treeText -cne $expText) { + throw "New file $rel in $repo does not match the declared patch stack. Stop: don't edit patches automatically (AGENTS.md rule 4)." + } + } } finally { if (Test-Path -LiteralPath $verifyDir) { Remove-Item -Recurse -Force -LiteralPath $verifyDir } } @@ -273,8 +304,10 @@ $otherCtl = Get-Undeclared $ReimsRepo 'reims-vgpu' @('--ignore-submodules=all' $otherQemu = Get-Undeclared $qemuRepo 'vendor/qemu' @('--untracked-files=no') $utilStatusArgs = if ($UtilRepo) { '--untracked-files=all' } else { '--untracked-files=no' } $otherUtil = Get-Undeclared $utilTree 'reims-util' @($utilStatusArgs) -if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count) { - throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil -join "`n")" +$m2vStatusArgs = if ($Metal2VulkanRepo) { '--untracked-files=all' } else { '--untracked-files=no' } +$otherM2v = Get-Undeclared $m2vTree 'metal2vulkan' @($m2vStatusArgs) +if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count -or $otherM2v.Count) { + throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil + $otherM2v -join "`n")" } $bundleName = "reims-runtime-win-x64-$id" @@ -306,7 +339,7 @@ if (Test-Path -LiteralPath (Join-Path $patchesDir 'LICENSE')) { Copy-Item -LiteralPath (Join-Path $patchesDir 'LICENSE') -Destination "$bundleDir\patches\LICENSE" } # The order the patches above were applied in (only those really applied). -Write-Utf8 "$bundleDir\patches\series.txt" ((($patchSpecs | ForEach-Object { '{0,-11} {1}' -f $_.Target, $_.Name }) -join "`n") + "`n") +Write-Utf8 "$bundleDir\patches\series.txt" ((($patchSpecs | ForEach-Object { '{0,-12} {1}' -f $_.Target, $_.Name }) -join "`n") + "`n") $licenses = @{ 'reims-vgpu-LICENSE.txt' = (Join-Path $ReimsRepo 'LICENSE') 'qemu-COPYING.txt' = (Join-Path $qemuRepo 'COPYING') @@ -388,8 +421,6 @@ Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory | Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } | ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force } -$m2vTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' | ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 -if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found under $checkouts" } Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))") Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))") foreach ($extra in @( @@ -411,6 +442,23 @@ New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\" Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt" Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md" +$m2vBuildSteps = if ($byTarget.Contains('metal2vulkan')) { + $m2vDir = "metal2vulkan-$($m2vCommit.Substring(0, 7))" + $m2vApply = ($byTarget['metal2vulkan'] | ForEach-Object { " git -C $m2vDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n" +@" + +Before running ``scripts/install-ctl.sh``, apply the ``metal2vulkan`` patches +and point Cargo at the patched checkout via ```$CARGO_HOME/config.toml``: + +$m2vApply + cat >> "`${CARGO_HOME:-`$HOME/.cargo}/config.toml" < Date: Tue, 1 Dec 2026 08:05:05 +0800 Subject: [PATCH 06/23] feat: integrate Intel VM suspend and instant resume across backend, CLI, and UI --- frontend/src/App.tsx | 58 +++- frontend/src/components/Sidebar.tsx | 28 +- frontend/src/components/TitleMenus.tsx | 15 +- frontend/src/components/VMPage.tsx | 111 ++++++-- frontend/src/i18n/domains/vm.gen.ts | 38 +++ frontend/src/i18n/keys.gen.ts | 19 ++ frontend/src/styles/app.css | 5 + frontend/src/types.ts | 3 +- frontend/src/ui/controls.tsx | 5 +- frontend/wailsjs/go/app/App.d.ts | 6 + frontend/wailsjs/go/app/App.js | 12 + frontend/wailsjs/go/models.ts | 66 +++++ internal/app/app.go | 48 +++- internal/app/clone_flow.go | 3 + internal/app/disk_flow.go | 6 + internal/app/snapshot_flow.go | 3 + internal/app/suspend_flow.go | 356 +++++++++++++++++++++++++ internal/app/suspend_flow_test.go | 58 ++++ internal/cli/cli.go | 36 ++- internal/cli/start.go | 4 + internal/cli/suspend.go | 179 +++++++++++++ internal/driver/reims/reims.go | 9 +- internal/driver/reims/suspend.go | 240 +++++++++++++++++ internal/driver/reims/suspend_test.go | 114 ++++++++ internal/i18n/catalog_gen.go | 52 ++++ internal/qmp/client.go | 24 +- internal/qmp/migrate.go | 275 +++++++++++++++++++ internal/qmp/migrate_test.go | 229 ++++++++++++++++ internal/runtime/kinds.go | 10 + internal/runtime/kinds_test.go | 35 +++ internal/tray/tray.go | 126 +++++++-- internal/tray/tray_test.go | 33 ++- internal/vmstart/vmstart.go | 5 + locales/en-US/native.json | 72 +++++ locales/en-US/vm.json | 19 ++ locales/zh-CN/native.json | 72 +++++ locales/zh-CN/vm.json | 19 ++ 37 files changed, 2311 insertions(+), 82 deletions(-) create mode 100644 internal/app/suspend_flow.go create mode 100644 internal/app/suspend_flow_test.go create mode 100644 internal/cli/suspend.go create mode 100644 internal/driver/reims/suspend.go create mode 100644 internal/driver/reims/suspend_test.go create mode 100644 internal/qmp/migrate.go create mode 100644 internal/qmp/migrate_test.go diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2f43c0b..ceda025 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -41,6 +41,9 @@ const errText = (e: unknown) => parseAppError(e).summary const failKey: Record = { start: 'failStart', + suspend: 'failSuspend', + resume: 'failResume', + discardSuspend: 'failDiscardSuspend', focus: 'failFocus', fullscreen: 'failFullscreen', screenshot: 'failScreenshot', @@ -85,6 +88,7 @@ export const App: React.FC = () => { const [affinityTarget, setAffinityTarget] = useState(null) const [affinityVersion, setAffinityVersion] = useState(0) const [deleteTarget, setDeleteTarget] = useState(null) + const [discardSuspendTarget, setDiscardSuspendTarget] = useState(null) const [cloneSource, setCloneSource] = useState(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) @@ -331,6 +335,15 @@ export const App: React.FC = () => { const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : '' const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : [] const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime + const activeManifest = state?.active_runtime?.manifest + const canSuspend = Boolean( + activeManifest?.capabilities?.some((c) => c.toLowerCase() === 'vm-suspend') + || ( + activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('win32-mapped-ram-io')) + && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('intel-whpx-suspend')) + && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('reims-vgpu-snapshot-replay')) + ), + ) onTaskRef.current = (task: Task) => { if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) { @@ -667,6 +680,9 @@ export const App: React.FC = () => { } switch (action) { case 'start': return runVMAction(name, action, () => api.StartVM(name)) + case 'suspend': return runVMAction(name, action, () => api.SuspendVM(name), tr('toastSuspended', { name })) + case 'resume': return runVMAction(name, action, () => api.ResumeVM(name), tr('toastResumed', { name })) + case 'discardSuspend': return setDiscardSuspendTarget(name) case 'focus': return api.FocusVMWindow(name).catch((e) => fail(tr('failFocus'), e)) case 'fullscreen': return runVMAction(name, action, async () => { @@ -705,23 +721,25 @@ export const App: React.FC = () => { } const onSidebarContextAction = (name: string, action: VMAction | 'settings') => { + const vm = vms.find((v) => v.name === name) + const st = state?.transitions[name] ?? vm?.state ?? 'stopped' if (action === 'settings') { + if (st === 'suspended' || st === 'suspending' || st === 'resuming') return setSelected(name) api.GetVMDetail(name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e)) return } - const vm = vms.find((v) => v.name === name) - const st = state?.transitions[name] ?? vm?.state ?? 'stopped' onVMActionFor(name, action, st === 'running') } - // The state's own main action (Start, or Show Window while running), shared by + // The state's own main action (Start, Resume while suspended, or Show Window while running), shared by // Ctrl+Enter and a double-click in the sidebar. const primaryAction = (name: string) => { const vm = vms.find((v) => v.name === name) if (!vm || activeVMBusy(name)) return const st = state?.transitions[name] ?? vm.state if (st === 'stopped') onVMActionFor(name, 'start', false) + else if (st === 'suspended') onVMActionFor(name, 'resume', false) else if (st === 'running') onVMActionFor(name, 'focus', true) } @@ -731,6 +749,12 @@ export const App: React.FC = () => { if (name) runVMAction(name, 'delete', () => api.DeleteVM(name, keepFiles), tr('toastDeleted', { name })) } + const confirmDiscardSuspend = () => { + const name = discardSuspendTarget + setDiscardSuspendTarget(null) + if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspend(name), tr('toastDiscardSuspend', { name })) + } + const confirmOnlineRecovery = () => { const name = onlineRecoveryTarget setOnlineRecoveryTarget(null) @@ -859,11 +883,11 @@ export const App: React.FC = () => { const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return - if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return + if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return const k = e.key.toLowerCase() if (k === 'n') { e.preventDefault(); openWizard() } - else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) } + else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) } else if (k === 'l') { e.preventDefault(); toggleLogs() } else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() } else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(selectedVM.name) } @@ -950,10 +974,11 @@ export const App: React.FC = () => { state: effectiveState, busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name), graphics: detail?.name === selectedVM.name ? detail.graphics : undefined, + canSuspend, } : null} onNewVM={openWizard} onVMAction={onVMAction} - onVMSettings={() => { if (detail) setShowSettings(true) }} + onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }} onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }} onNavigate={setSelected} onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }} @@ -1019,6 +1044,7 @@ export const App: React.FC = () => { busyActions={busy} selected={selected} hostReady={hostReady} + canSuspend={canSuspend} onSelect={setSelected} displayNames={displayNames} macosMajors={macosMajors} @@ -1077,6 +1103,7 @@ export const App: React.FC = () => { onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))} macosMajor={macosMajors[selectedVM.name] ?? null} state={effectiveState} + canSuspend={canSuspend} guideActive={state.active_guides?.includes(selectedVM.name) ?? false} installGuideEnabled={!!state.install_guide_enabled} detail={detail} @@ -1281,6 +1308,25 @@ export const App: React.FC = () => { setDeleteTarget(null)} onConfirm={confirmDelete} /> )} + {discardSuspendTarget && ( + setDiscardSuspendTarget(null)} + > +

+

{tr('discardSuspendDesc')}

+
+
+ + + + + +
+ + )} + {cloneSource && ( selected: string hostReady: boolean + /** Whether the active runtime supports VM suspend/resume. */ + canSuspend?: boolean onSelect: (id: string) => void /** VM name → display name (its note); empty or missing shows the name. */ displayNames?: Record @@ -44,7 +46,7 @@ interface Props { } export const Sidebar: React.FC = ({ - locale, vms, transitions, busyActions = {}, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, + locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, }) => { const tr = (k: I18nKey) => t(locale, k) const listRef = useRef(null) @@ -118,7 +120,8 @@ export const Sidebar: React.FC = ({ const st = transitions[vm.name] ?? vm.state const running = st === 'running' const stopped = st === 'stopped' - const transitioning = st === 'starting' || st === 'stopping' + const suspended = st === 'suspended' + const transitioning = st === 'starting' || st === 'stopping' || st === 'suspending' || st === 'resuming' const busyAction = Object.prototype.hasOwnProperty.call(busyActions, vm.name) ? busyActions[vm.name] : undefined const vmBusy = !!busyAction const label = displayNames[vm.name] || vm.name @@ -159,6 +162,16 @@ export const Sidebar: React.FC = ({ {tr('start')} )} + {suspended && ( + <> + onVMContextAction(vm.name, 'resume')}> + {tr('resume')} + + onVMContextAction(vm.name, 'discardSuspend')}> + {tr('discardSuspend')} + + + )} {running && ( <> onVMContextAction(vm.name, 'focus')}> @@ -170,6 +183,11 @@ export const Sidebar: React.FC = ({ onVMContextAction(vm.name, 'screenshot')}> {tr('copyScreenshot')} + {canSuspend && ( + onVMContextAction(vm.name, 'suspend')}> + {tr('suspend')} + + )} onVMContextAction(vm.name, 'stop')}> {tr('stop')} @@ -184,7 +202,7 @@ export const Sidebar: React.FC = ({ )} - onVMContextAction(vm.name, 'settings')}> + onVMContextAction(vm.name, 'settings')}> {tr('settingsEllipsis')} onVMContextAction(vm.name, 'openSharedFolder')}> @@ -199,7 +217,7 @@ export const Sidebar: React.FC = ({ {tr('openFolder')} - onVMContextAction(vm.name, 'delete')}> + onVMContextAction(vm.name, 'delete')}> {tr('delete')} diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index 79560e4..4253d95 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -27,7 +27,7 @@ interface Props { canDark?: boolean onThemeMode: (mode: ThemeMode) => void /** The selected VM and its current state, or null on the system pages. */ - vm: { name: string; state: string; busy: boolean; graphics?: string } | null + vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend?: boolean } | null onNewVM: () => void onVMAction: (action: VMAction) => void onVMSettings: () => void @@ -62,7 +62,8 @@ export const TitleMenus: React.FC = ({ const running = vm?.state === 'running' const stopped = vm?.state === 'stopped' - const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' + const suspended = vm?.state === 'suspended' + const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming' const vmBusy = !vm || vm.busy const canFullscreen = running && vm?.graphics !== 'vmware-svga' const stats = useVMStats(canFullscreen && vm ? vm.name : null, running) @@ -218,17 +219,21 @@ export const TitleMenus: React.FC = ({ {running ? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) - : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} + : suspended + ? item(tr('resume'), () => onVMAction('resume'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) + : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} {item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })} + {item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })} {item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })} {item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })} {item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })} - {item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm })} + {item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })} {item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })} + {suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })} {item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })} - {item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || transitioning })} + {item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })} ))} {menu('view', tr('menuView'), ( diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e8b60ea..f42998f 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -27,6 +27,7 @@ import { Minimize2, Monitor, Network, + Pause, Pencil, Play, Plus, @@ -55,6 +56,9 @@ import { VersionArt } from './VersionArt' export type VMAction = | 'start' + | 'suspend' + | 'resume' + | 'discardSuspend' | 'stop' | 'forceStop' | 'restart' @@ -92,6 +96,8 @@ interface Props { /** macOS major version (26, 15, …) for the artwork shown before a first frame; null if unknown. */ macosMajor: number | null state: string + /** Whether the active runtime supports VM suspend/resume. */ + canSuspend?: boolean /** Whether the native VM-window installation guide is currently active for this boot. */ guideActive: boolean /** Whether the builtin.install-guide plugin is enabled. */ @@ -132,13 +138,14 @@ interface Spec { } export const VMPage: React.FC = ({ - locale, name, displayName, onDisplayNameSaved, macosMajor, state, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, + locale, name, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const busy = busyAction !== undefined const running = state === 'running' + const suspended = state === 'suspended' const installing = !!detail && (detail.has_installer || detail.recovery_mode) - const transitioning = state === 'starting' || state === 'stopping' + const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' // Polled here rather than in App so each tick re-renders only this page. const stats = useVMStats(name, running) @@ -318,7 +325,7 @@ export const VMPage: React.FC = ({ } // One primary action per state (docs/design-guidelines.md §4): Start while - // stopped, Show Window while running. Ctrl+Enter triggers it (App.tsx). + // stopped, Resume while suspended, Show Window while running. Ctrl+Enter triggers it (App.tsx). let primary: React.ReactNode = null let secondary: React.ReactNode = null if (state === 'stopped') { @@ -329,10 +336,27 @@ export const VMPage: React.FC = ({ ) + } else if (suspended) { + primary = ( + + + + ) + secondary = ( + + ) } else if (state === 'starting') { primary = } else if (state === 'stopping') { primary = + } else if (state === 'suspending') { + primary = + } else if (state === 'resuming') { + primary = } else if (running) { const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow') primary = ( @@ -343,7 +367,14 @@ export const VMPage: React.FC = ({ ) secondary = ( - + <> + {canSuspend && ( + + )} + + ) } else if (state === 'broken') { primary = @@ -413,6 +444,11 @@ export const VMPage: React.FC = ({ : <> {tr('enterFullscreen')}} )} + {canSuspend && ( + onAction('suspend')}> + {tr('suspend')} + + )} onAction('restart')}> {tr('restart')} @@ -431,15 +467,15 @@ export const VMPage: React.FC = ({ {detail && ( <> {installing ? ( - onAction('finishInstall')}> + onAction('finishInstall')}> {tr('finishInstall')} ) : ( <> - onAction('enterRecovery')}> + onAction('enterRecovery')}> {tr('enterRecovery')} - onAction('cloneVM')}> + onAction('cloneVM')}> {tr('cloneVM')} @@ -478,12 +514,17 @@ export const VMPage: React.FC = ({ ))} + {suspended && ( + onAction('discardSuspend')}> + {tr('discardSuspend')} + + )} {(running || transitioning) && ( onAction('forceStop')}> {tr('forceStop')} )} - + {tr('delete')} @@ -563,11 +604,23 @@ export const VMPage: React.FC = ({ onCopy(rows.join('\n')) } - const pillClass = running ? ' is-running' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : '' + const pillClass = running ? ' is-running' : suspended ? ' is-suspended' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : '' const dropStyle = detail && !installing ? ({ '--wails-drop-target': 'drop' } as React.CSSProperties) : undefined + const formatSuspendTime = (iso?: string) => { + if (!iso) return '' + const ms = Date.parse(iso) + if (!Number.isFinite(ms)) return '' + try { + const loc = locale === 'en-XA' ? 'en-US' : locale + return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(ms)) + } catch { + return '' + } + } + return (
{dropping && ( @@ -588,10 +641,10 @@ export const VMPage: React.FC = ({ thumb={thumb} art={} running={running} - startLabel={tr('start')} + startLabel={suspended ? tr('resume') : tr('start')} showLabel={tr('showWindow')} shotLabel={tr('copyScreenshot')} - onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined} + onStart={!busy && (state === 'stopped' || suspended) ? () => onAction(suspended ? 'resume' : 'start') : undefined} onShow={running && !busy ? () => onAction('focus') : undefined} onScreenshot={running && !busy ? () => onAction('screenshot') : undefined} /> @@ -631,8 +684,10 @@ export const VMPage: React.FC = ({
{primary} {secondary} - - + + + + {menu}
@@ -667,6 +722,28 @@ export const VMPage: React.FC = ({
)} + {suspended && (() => { + const suspTime = formatSuspendTime(detail?.suspend_info?.created_at) + const suspSize = detail?.suspend_info?.vmstate_size + ? formatBytes(detail.suspend_info.vmstate_size, locale) + : (detail?.memory ? formatMemory(detail.memory, locale) : '—') + return ( +
+ + +
+ ) + })()} + {pending.length > 0 && (
@@ -1041,12 +1118,12 @@ export const VMPage: React.FC = ({ {tr('snapshotsTitle')} · {tr('snapshotHint')} - +
diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index ecfcaed..312faa3 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -24,6 +24,10 @@ export const vmZh: Record = { "diagBackingChainWarn": "当前系统盘 CoW 派生链深度为 {depth} 层(≥ 2),未分配簇读穿透会拖慢小文件 I/O,建议合并为独立镜像或基于基础镜像重新派生", "diagExternalDriveWarn": "数据目录在外置或网络盘上({dir}),读写会明显变慢", "diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿", + "discardSuspend": "放弃挂起状态", + "discardSuspendConfirm": "放弃并关机", + "discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。", + "discardSuspendTitle": "放弃「{name}」的挂起状态?", "displayNameEdit": "点按以修改显示名称", "displayNameEditEllipsis": "修改显示名称…", "displayNameLabel": "显示名称", @@ -41,6 +45,7 @@ export const vmZh: Record = { "failAttachInstaller": "挂载镜像失败", "failCloneVM": "派生 CoW 副本失败", "failDelete": "删除失败", + "failDiscardSuspend": "放弃挂起状态失败", "failEject": "弹出安装盘失败", "failEnterRecovery": "进入恢复模式失败", "failExportDiagnostics": "导出排障日志失败", @@ -50,10 +55,12 @@ export const vmZh: Record = { "failGuestTools": "Guest Tools 操作失败", "failOpenFolder": "无法打开文件夹", "failRestart": "重启失败", + "failResume": "恢复失败", "failScreenshot": "截屏失败", "failSnapshot": "恢复点操作失败", "failStart": "启动失败", "failStop": "关机失败", + "failSuspend": "挂起失败", "failType": "键入失败", "failUpgradeNVMe": "升级到 NVMe 失败", "fieldAudio": "音频", @@ -111,6 +118,7 @@ export const vmZh: Record = { "pendingTitle": "下次启动生效", "pickRecoveryTitle": "选择离线镜像(.img / .dmg)", "restartToApply": "重启以应用", + "resume": "恢复", "sendText": "发送文本到虚拟机…", "sendTextConfirm": "发送 (Ctrl+Enter)", "sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。", @@ -155,14 +163,23 @@ export const vmZh: Record = { "state_broken": "出错", "state_creating": "正在创建", "state_driver_unavailable": "驱动不可用", + "state_resuming": "恢复中", "state_running": "运行中", "state_starting": "启动中", "state_stopped": "已停止", "state_stopping": "停止中", + "state_suspended": "已挂起", + "state_suspending": "挂起中", + "suspend": "挂起", + "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeTitle": "已保存运行状态", + "suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置", "techInfo": "技术信息", "toastCloned": "已派生 CoW 副本「{name}」", "toastDeleted": "已删除 {name}", "toastDiagExported": "已导出脱敏排障日志包 (.zip)", + "toastDiscardSuspend": "已放弃 {name} 的挂起状态", "toastEjected": "已弹出安装盘", "toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery", "toastEnterRecoveryNextStart": "已准备进入恢复模式,重启后显示引导菜单", @@ -182,11 +199,13 @@ export const vmZh: Record = { "toastOnlineRecoveryStarted": "正在拉取在线恢复镜像(约 1 GB),完成后自动挂载", "toastPreventSleepOff": "已关闭 macOS 防休眠守护", "toastPreventSleepOn": "已开启 macOS 防休眠守护", + "toastResumed": "{name} 已恢复", "toastScreenshotCopied": "已复制虚拟机画面", "toastSnapshotCreated": "已创建恢复点 {name}", "toastSnapshotDeleted": "已删除恢复点 {name}", "toastSnapshotRestored": "已回滚到 {name}", "toastStopped": "{name} 已关机", + "toastSuspended": "{name} 已挂起", "toastTyped": "{n, plural, other {已键入 # 个字符}}", "toggleFullscreen": "切换全屏", "typeClipboard": "粘贴剪贴板到虚拟机", @@ -219,6 +238,10 @@ export const vmEn: Record = { "diagBackingChainWarn": "System disk CoW backing chain is {depth} layers deep (\u003e= 2); read-through slows small-file I/O — consider flattening or re-deriving from the base image", "diagExternalDriveWarn": "The data folder is on an external or network drive ({dir}); disk access will be slow", "diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter", + "discardSuspend": "Discard saved state", + "discardSuspendConfirm": "Discard \u0026 Power Off", + "discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.", + "discardSuspendTitle": "Discard saved state for “{name}”?", "displayNameEdit": "Click to change the display name", "displayNameEditEllipsis": "Change Display Name…", "displayNameLabel": "Display name", @@ -236,6 +259,7 @@ export const vmEn: Record = { "failAttachInstaller": "Couldn’t attach the image", "failCloneVM": "Couldn’t create CoW clone", "failDelete": "Couldn’t delete", + "failDiscardSuspend": "Couldn’t discard saved state", "failEject": "Couldn’t eject the installer", "failEnterRecovery": "Couldn’t enter recovery mode", "failExportDiagnostics": "Couldn’t export diagnostics", @@ -245,10 +269,12 @@ export const vmEn: Record = { "failGuestTools": "Guest Tools operation failed", "failOpenFolder": "Couldn’t open the folder", "failRestart": "Couldn’t restart", + "failResume": "Couldn’t resume", "failScreenshot": "Screenshot failed", "failSnapshot": "Restore point failed", "failStart": "Couldn’t start", "failStop": "Couldn’t shut down", + "failSuspend": "Couldn’t suspend", "failType": "Couldn’t type into the VM", "failUpgradeNVMe": "Couldn’t upgrade to NVMe", "fieldAudio": "Audio", @@ -306,6 +332,7 @@ export const vmEn: Record = { "pendingTitle": "Applies on next start", "pickRecoveryTitle": "Choose an offline image (.img / .dmg)", "restartToApply": "Restart to apply", + "resume": "Resume", "sendText": "Send text to VM…", "sendTextConfirm": "Send (Ctrl+Enter)", "sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.", @@ -350,14 +377,23 @@ export const vmEn: Record = { "state_broken": "Error", "state_creating": "Creating", "state_driver_unavailable": "Driver unavailable", + "state_resuming": "Resuming", "state_running": "Running", "state_starting": "Starting", "state_stopped": "Stopped", "state_stopping": "Stopping", + "state_suspended": "Suspended", + "state_suspending": "Suspending", + "suspend": "Suspend", + "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", + "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", + "suspendedNoticeTitle": "Saved state ready", + "suspendedSettingsHint": "Resume or discard saved state before changing settings", "techInfo": "Technical details", "toastCloned": "CoW clone “{name}” created", "toastDeleted": "{name} deleted", "toastDiagExported": "Redacted diagnostics archive exported (.zip)", + "toastDiscardSuspend": "Discarded saved state for {name}", "toastEjected": "Installer ejected", "toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start", "toastEnterRecoveryNextStart": "Recovery mode ready — restart to open the boot menu", @@ -377,11 +413,13 @@ export const vmEn: Record = { "toastOnlineRecoveryStarted": "Downloading online recovery image (~1 GB); will attach when ready", "toastPreventSleepOff": "Prevent-sleep guard disabled", "toastPreventSleepOn": "Prevent-sleep guard enabled", + "toastResumed": "{name} resumed", "toastScreenshotCopied": "VM screenshot copied", "toastSnapshotCreated": "Created restore point {name}", "toastSnapshotDeleted": "Deleted restore point {name}", "toastSnapshotRestored": "Restored to {name}", "toastStopped": "{name} shut down", + "toastSuspended": "{name} suspended", "toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}", "toggleFullscreen": "Toggle full screen", "typeClipboard": "Send clipboard to VM", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 5b2752c..ffd4062 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -137,6 +137,10 @@ export type I18nKey = | "diagBackingChainWarn" | "diagExternalDriveWarn" | "diagHighMemWarn" + | "discardSuspend" + | "discardSuspendConfirm" + | "discardSuspendDesc" + | "discardSuspendTitle" | "diskCompactAction" | "diskCompactDesc" | "diskCompactDone" @@ -202,6 +206,7 @@ export type I18nKey = | "failCloneVM" | "failCreate" | "failDelete" + | "failDiscardSuspend" | "failDownload" | "failEject" | "failEnterRecovery" @@ -213,12 +218,14 @@ export type I18nKey = | "failGuestTools" | "failOpenFolder" | "failRestart" + | "failResume" | "failRuntime" | "failSSH" | "failScreenshot" | "failSnapshot" | "failStart" | "failStop" + | "failSuspend" | "failType" | "failUpgradeNVMe" | "fieldAudio" @@ -617,6 +624,7 @@ export type I18nKey = | "resolution" | "restart" | "restartToApply" + | "resume" | "runtimeAlpha" | "runtimeAlphaHint" | "runtimeChannel_alpha" @@ -740,10 +748,13 @@ export type I18nKey = | "state_broken" | "state_creating" | "state_driver_unavailable" + | "state_resuming" | "state_running" | "state_starting" | "state_stopped" | "state_stopping" + | "state_suspended" + | "state_suspending" | "statsCPU" | "statsDisk" | "statsDiskSub" @@ -774,6 +785,11 @@ export type I18nKey = | "summarySSH" | "summarySSHPort" | "summarySource" + | "suspend" + | "suspendedNoticeDesc" + | "suspendedNoticeDescWithTime" + | "suspendedNoticeTitle" + | "suspendedSettingsHint" | "taskAppUpdate" | "taskCreate" | "taskDownload" @@ -800,6 +816,7 @@ export type I18nKey = | "toastCreated" | "toastDeleted" | "toastDiagExported" + | "toastDiscardSuspend" | "toastDownloadPaused" | "toastEjected" | "toastEnterRecovery" @@ -822,6 +839,7 @@ export type I18nKey = | "toastPreventSleepOff" | "toastPreventSleepOn" | "toastQueueCanceled" + | "toastResumed" | "toastRuntimeReady" | "toastSSHConfigWritten" | "toastSSHUserSaved" @@ -832,6 +850,7 @@ export type I18nKey = | "toastSnapshotDeleted" | "toastSnapshotRestored" | "toastStopped" + | "toastSuspended" | "toastTyped" | "toggleFullscreen" | "typeClipboard" diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 9be43de..d8c5c50 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -292,6 +292,10 @@ h1, h2, h3, p { margin: 0; } .status { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; display: inline-block; } .status-running { background: var(--status-running); } .status-stopped { border: 1.5px solid var(--status-idle); } +.status-suspended { + width: 7px; height: 8px; border-radius: 0; + background: linear-gradient(90deg, var(--status-busy) 0 2.5px, transparent 2.5px 4.5px, var(--status-busy) 4.5px 7px); +} .status-busy { background: conic-gradient(var(--status-busy) 0 50%, transparent 50% 100%); border: 1.5px solid var(--status-busy); animation: pulse 1.4s ease-in-out infinite; } .status-warn { background: var(--status-busy); } .status-broken { background: var(--status-error); border-radius: 1.5px; transform: rotate(45deg); width: 7px; height: 7px; } @@ -366,6 +370,7 @@ h1, h2, h3, p { margin: 0; } .vm-hero-pill.is-running { background: var(--ok-soft); border-color: transparent; color: var(--ok-text); } +.vm-hero-pill.is-suspended, .vm-hero-pill.is-busy { background: var(--warn-soft); border-color: transparent; color: var(--warn-text); } diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 49822da..92b48b5 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -48,7 +48,7 @@ export type RemoteRuntime = Model & { } export type VMListItem = Model & { - state: 'running' | 'stopped' | 'broken' + state: 'running' | 'stopped' | 'suspended' | 'broken' } export type PendingChange = app.PendingChange @@ -63,6 +63,7 @@ export type AppState = Omit, 'config' | 'host' | 'optimizati } export type AppUpdateInfo = version.UpdateInfo +export type SuspendInfo = reims.SuspendInfo export type VMDetail = reims.VMDetail export type VMStats = app.VMStats export type DriveShareSettings = Model diff --git a/frontend/src/ui/controls.tsx b/frontend/src/ui/controls.tsx index c014fe2..f7db8c9 100644 --- a/frontend/src/ui/controls.tsx +++ b/frontend/src/ui/controls.tsx @@ -87,11 +87,12 @@ export const IconButton = React.forwardRef( ) IconButton.displayName = 'IconButton' -export type StatusKind = 'running' | 'stopped' | 'busy' | 'broken' | 'warn' +export type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn' export function statusKind(state: string): StatusKind { if (state === 'running') return 'running' - if (state === 'starting' || state === 'stopping' || state === 'creating') return 'busy' + if (state === 'suspended') return 'suspended' + if (state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' || state === 'creating') return 'busy' if (state === 'driver_unavailable') return 'warn' if (state === 'broken') return 'broken' return 'stopped' diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index e4d401a..ded8dce 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -47,6 +47,8 @@ export function DeleteSnapshot(arg1:string,arg2:string):Promise; export function DeleteVM(arg1:string,arg2:boolean):Promise; +export function DiscardSuspend(arg1:string):Promise; + export function DeliverFileToGuest(arg1:string):Promise; export function DeliverPathsToGuest(arg1:string,arg2:Array):Promise>; @@ -183,6 +185,8 @@ export function ResizeVMDisk(arg1:string,arg2:string):Promise; +export function ResumeVM(arg1:string):Promise; + export function RestoreSnapshot(arg1:string,arg2:string):Promise; export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise; @@ -225,6 +229,8 @@ export function SuggestDataRoots():Promise>; export function SuggestLanguagePack():Promise; +export function SuspendVM(arg1:string):Promise; + export function ToggleBorderless(arg1:string,arg2:boolean):Promise; export function ToggleVMFullscreen(arg1:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 2de951a..da78976 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -78,6 +78,10 @@ export function DeleteVM(arg1, arg2) { return window['go']['app']['App']['DeleteVM'](arg1, arg2); } +export function DiscardSuspend(arg1) { + return window['go']['app']['App']['DiscardSuspend'](arg1); +} + export function DeliverFileToGuest(arg1) { return window['go']['app']['App']['DeliverFileToGuest'](arg1); } @@ -350,6 +354,10 @@ export function RestartVM(arg1) { return window['go']['app']['App']['RestartVM'](arg1); } +export function ResumeVM(arg1) { + return window['go']['app']['App']['ResumeVM'](arg1); +} + export function RestoreSnapshot(arg1, arg2) { return window['go']['app']['App']['RestoreSnapshot'](arg1, arg2); } @@ -434,6 +442,10 @@ export function SuggestLanguagePack() { return window['go']['app']['App']['SuggestLanguagePack'](); } +export function SuspendVM(arg1) { + return window['go']['app']['App']['SuspendVM'](arg1); +} + export function ToggleBorderless(arg1, arg2) { return window['go']['app']['App']['ToggleBorderless'](arg1, arg2); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 9883e88..bd48390 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -2296,6 +2296,52 @@ export namespace reims { this.guest_lang = source["guest_lang"]; } } + export class SuspendInfo { + schema_version: number; + vm_name: string; + cpus: number; + memory: string; + graphics: string; + displays: number; + resolution: string; + disk_controller: string; + cpu_model?: string; + audio: boolean; + audio_backend?: string; + network: boolean; + ssh_port: number; + extra_args?: string; + runtime_commit: string; + vendor_qemu_commit?: string; + created_at: string; + vmstate_size: number; + + static createFrom(source: any = {}) { + return new SuspendInfo(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.schema_version = source["schema_version"]; + this.vm_name = source["vm_name"]; + this.cpus = source["cpus"]; + this.memory = source["memory"]; + this.graphics = source["graphics"]; + this.displays = source["displays"]; + this.resolution = source["resolution"]; + this.disk_controller = source["disk_controller"]; + this.cpu_model = source["cpu_model"]; + this.audio = source["audio"]; + this.audio_backend = source["audio_backend"]; + this.network = source["network"]; + this.ssh_port = source["ssh_port"]; + this.extra_args = source["extra_args"]; + this.runtime_commit = source["runtime_commit"]; + this.vendor_qemu_commit = source["vendor_qemu_commit"]; + this.created_at = source["created_at"]; + this.vmstate_size = source["vmstate_size"]; + } + } export class VMDetail { name: string; state: string; @@ -2337,6 +2383,7 @@ export namespace reims { guest_tools_disabled?: boolean; shared_dir?: string; guest_lang?: string; + suspend_info?: SuspendInfo; static createFrom(source: any = {}) { return new VMDetail(source); @@ -2384,7 +2431,26 @@ export namespace reims { this.guest_tools_disabled = source["guest_tools_disabled"]; this.shared_dir = source["shared_dir"]; this.guest_lang = source["guest_lang"]; + this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo); } + + convertValues(a: any, classs: any, asMap: boolean = false): any { + if (!a) { + return a; + } + if (a.slice && a.map) { + return (a as any[]).map(elem => this.convertValues(elem, classs)); + } else if ("object" === typeof a) { + if (asMap) { + for (const key of Object.keys(a)) { + a[key] = new classs(a[key]); + } + return a; + } + return new classs(a); + } + return a; + } } export class VMListItem { name: string; diff --git a/internal/app/app.go b/internal/app/app.go index 061e539..310bfdd 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -265,6 +265,7 @@ func (a *App) pollVMs(ctx context.Context) { if err != nil { continue } + enrichVMListStates(vms) watchExits(ctx, vms, exitWatched, a.wakePoll) type pinCandidate struct { name string @@ -291,7 +292,10 @@ func (a *App) pollVMs(ctx context.Context) { } } if tr, ok := a.transitions[vm.Name]; ok { - if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") { + if (tr == "starting" && vm.State == "running") || + (tr == "stopping" && vm.State == "stopped") || + (tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) || + (tr == "resuming" && vm.State == "running") { delete(a.transitions, vm.Name) if vm.State == "stopped" { delete(a.pendingChanges, vm.Name) @@ -454,7 +458,12 @@ func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) { if err != nil { return nil, err } - return c.List(ctx) + vms, err := c.List(ctx) + if err != nil { + return nil, err + } + enrichVMListStates(vms) + return vms, nil } // qemuImage is the executable reims-ctl reports as a running VM's PID. @@ -676,6 +685,7 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) { d.RecoveryMode = isRecoveryModeActive(d) a.populateGuestToolsDetail(&d) a.populateGuestLangDetail(&d) + a.populateSuspendDetail(&d) return d, nil } @@ -767,6 +777,7 @@ func (a *App) startTray() { }, GetSnapshot: func() tray.Snapshot { a.mu.Lock() + cfgCopy := *a.cfg loc := a.cfg.Locale cached := append([]reims.VMListItem(nil), a.lastVMs...) transitions := make(map[string]string, len(a.transitions)) @@ -774,6 +785,10 @@ func (a *App) startTray() { transitions[k] = v } a.mu.Unlock() + canSuspend := false + if active, err := rt.ResolveActive(&cfgCopy); err == nil && active != nil { + canSuspend = active.Manifest.HasCapability("vm-suspend") + } if len(cached) == 0 { if vms, err := a.listVMsInternal(context.Background()); err == nil { cached = vms @@ -797,9 +812,10 @@ func (a *App) startTray() { } effLoc := i18n.EffectiveLocale(loc) return tray.Snapshot{ - Locale: effLoc, - LocaleZh: effLoc == i18n.ZhCN, - VMs: items, + Locale: effLoc, + LocaleZh: effLoc == i18n.ZhCN, + CanSuspend: canSuspend, + VMs: items, } }, }) @@ -827,6 +843,12 @@ func (a *App) trayVMAction(name string, act tray.Action) { switch act { case tray.ActStart: err, failTitle = a.StartVM(name), i18n.M(loc, "tray.notify.start_fail", vars) + case tray.ActSuspend: + err, failTitle = a.SuspendVM(name), i18n.M(loc, "tray.notify.suspend_fail", vars) + case tray.ActResume: + err, failTitle = a.ResumeVM(name), i18n.M(loc, "tray.notify.resume_fail", vars) + case tray.ActDiscardSuspend: + err, failTitle = a.DiscardSuspend(name), i18n.M(loc, "tray.notify.discard_suspend_fail", vars) case tray.ActStop: err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars) case tray.ActForceStop: @@ -878,7 +900,13 @@ func (a *App) SetDataRoot(dir string) error { curAppUpdateChannel := a.cfg.AppUpdateChannel curMinToTray := a.cfg.MinimizeToTray for _, v := range a.lastVMs { - if v.State == "running" || v.State == "starting" || v.State == "stopping" { + if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil) + } + } + for _, tr := range a.transitions { + if tr != "" { a.mu.Unlock() return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil) } @@ -1235,7 +1263,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { a.mu.Lock() tr := a.transitions[name] a.mu.Unlock() - if tr == "stopping" { + if tr == "stopping" || tr == "suspending" { return } @@ -1313,6 +1341,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string { s := reims.StripGuestToolsArgs(extraArgs) s = reims.StripOfflineHelperArgs(s) s = qmp.StripLegacyWin10RebootArgs(s) + s = reims.StripIncomingDeferArgs(s) return strings.TrimSpace(s) } @@ -1322,6 +1351,10 @@ func (a *App) StartVM(name string) error { return err } c := prep.Client + curDetail, _ := c.Show(context.Background(), name) + if curDetail.State == "stopped" && reims.HasSuspendState(curDetail.Directory) { + return a.ResumeVM(name) + } a.mu.Lock() root := a.cfg.DataRoot tmpDir := a.cfg.TempDir() @@ -1331,7 +1364,6 @@ func (a *App) StartVM(name string) error { a.emitLog(name, "Start refused: "+err.Error()) return err } - curDetail, _ := c.Show(context.Background(), name) if err := prep.CheckMemory(curDetail.Memory, rep); err != nil { a.emitLog(name, "Start refused: "+err.Error()) return err diff --git a/internal/app/clone_flow.go b/internal/app/clone_flow.go index 42ca1d1..1ab10e6 100644 --- a/internal/app/clone_flow.go +++ b/internal/app/clone_flow.go @@ -46,6 +46,9 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error { if a.isVMRunning(ctx, c, sourceName, src) { return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil) } + if a.isVMSuspended(src) { + return i18n.NewCodedError(loc, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil) + } if src.HasInstaller { return i18n.NewCodedError(loc, "E_VM_CLONE_RECOVERY", "err.clone.in_recovery", i18n.Vars{"name": sourceName}, nil) } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index f1bf3cf..fc3e7ed 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -31,6 +31,9 @@ func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) if a.isVMRunning(ctx, c, name, d) { return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name) } + if a.isVMSuspended(d) { + return reims.DiskResizeResult{}, fmt.Errorf("resume or discard suspend state for %s before resizing its disk", name) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return reims.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name) @@ -77,6 +80,9 @@ func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) { if a.isVMRunning(ctx, c, name, d) { return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name) } + if a.isVMSuspended(d) { + return reims.DiskCompactResult{}, fmt.Errorf("resume or discard suspend state for %s before reclaiming disk space", name) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return reims.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name) diff --git a/internal/app/snapshot_flow.go b/internal/app/snapshot_flow.go index 306aa7b..426fc75 100644 --- a/internal/app/snapshot_flow.go +++ b/internal/app/snapshot_flow.go @@ -85,6 +85,9 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error { if a.isVMRunning(ctx, c, name, d) { return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil) } + if a.isVMSuspended(d) { + return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) + } diskPath := resolveVMDiskPath(d) if diskPath == "" { return i18n.NewCodedError(loc, "E_SNAPSHOT_NO_DISK", "err.clone.no_disk", i18n.Vars{"name": name}, nil) diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go new file mode 100644 index 0000000..dc9ee8c --- /dev/null +++ b/internal/app/suspend_flow.go @@ -0,0 +1,356 @@ +package app + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/plugin/builtin" + "github.com/Nwflower/reims-go/internal/qmp" + "github.com/Nwflower/reims-go/internal/vmstart" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +// enrichVMListStates overlays state="suspended" onto stopped VMs that have a +// complete suspend snapshot (suspend.vmstate + suspend.json) in their folder. +func enrichVMListStates(vms []reims.VMListItem) { + for i := range vms { + if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) { + vms[i].State = "suspended" + } + } +} + +func (a *App) populateSuspendDetail(d *reims.VMDetail) { + if d == nil || d.Directory == "" { + return + } + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + d.State = "suspended" + if info, err := reims.ReadSuspendInfo(d.Directory); err == nil { + d.SuspendInfo = info + } + } +} + +func (a *App) isVMSuspended(d reims.VMDetail) bool { + return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory)) +} + +// SuspendVM pauses a running Intel VM, saves its RAM, CPU, device, and vGPU +// state to suspend.vmstate, and cleanly exits QEMU so the host can close +// Reims-Go or reboot Windows and later resume instantaneously. +func (a *App) SuspendVM(name string) error { + loc := a.locale() + prep, err := a.prep(name) + if err != nil { + return err + } + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + + a.mu.Lock() + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + a.mu.Unlock() + + ctx := a.baseCtx() + c := prep.Client + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if !a.isVMRunning(ctx, c, name, d) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) + } + if d.Directory == "" { + return fmt.Errorf("VM %s has no directory", name) + } + if memGB, ok := reims.ParseSizeGB(d.Memory); ok { + dirRep := host.Inspect(d.Directory) + needGB := memGB + 1.0 + if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { + return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ + "need": fmt.Sprintf("%.1f", needGB), + "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), + }, nil) + } + } + + oldPID := a.cachedVMPID(name) + a.cancelRebootWatcher(name) + stopVMMonitor(name) + + a.mu.Lock() + mgr := a.pluginMgr + gt := a.guestTools + a.transitions[name] = "suspending" + a.mu.Unlock() + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.emitStateChanged() + + tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" + _ = os.Remove(tmpPath) + + a.emitLog(name, fmt.Sprintf("Suspending %s to disk (%s)...", name, reims.SuspendStateFileName)) + lastPct := -1 + err = qmp.SuspendToFile(ctx, d.Directory, tmpPath, func(p qmp.MigrateProgress) { + if p.Total > 0 { + pct := int(p.Transferred * 100 / p.Total) + if pct >= lastPct+25 || p.Status == "completed" { + lastPct = pct + a.emitLog(name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct)) + } + } + }) + if err != nil { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.emitLog(name, "Suspend error: "+err.Error()) + a.wakePoll() + a.emitStateChanged() + return err + } + + a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout) + + st, statErr := os.Stat(tmpPath) + if statErr != nil || st.Size() <= 0 { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + if statErr != nil { + return fmt.Errorf("suspend snapshot missing after save: %w", statErr) + } + return fmt.Errorf("suspend snapshot is empty after save") + } + + finalPath := reims.SuspendStatePath(d.Directory) + _ = os.Remove(finalPath) + if err := os.Rename(tmpPath, finalPath); err != nil { + _ = os.Remove(tmpPath) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return fmt.Errorf("finalize suspend snapshot: %w", err) + } + + info := reims.BuildSuspendInfo(d, prep.Runtime, st.Size()) + if err := reims.WriteSuspendInfo(d.Directory, info); err != nil { + _ = reims.RemoveSuspendState(d.Directory) + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return fmt.Errorf("write suspend metadata: %w", err) + } + + if gt != nil { + gt.UnregisterVM(name) + } + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.clearTransition(name) + a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(st.Size())/float64(1<<30))) + a.wakePoll() + a.emitStateChanged() + return nil +} + +// ResumeVM launches a fresh QEMU process in `-incoming defer` mode (via +// `reims-ctl set --extra-args`), restores the VM's RAM, CPU, devices, and vGPU +// state from suspend.vmstate, and resumes guest execution. On any restore +// failure, suspend.vmstate and suspend.json are preserved so the user can retry. +func (a *App) ResumeVM(name string) error { + loc := a.locale() + prep, err := a.prep(name) + if err != nil { + return err + } + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + + a.mu.Lock() + root := a.cfg.DataRoot + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + mgr := a.pluginMgr + a.mu.Unlock() + + ctx := a.baseCtx() + c := prep.Client + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if a.isVMRunning(ctx, c, name, d) { + return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) + } + if !reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) + } + meta, err := reims.ReadSuspendInfo(d.Directory) + if err != nil { + return fmt.Errorf("read suspend metadata: %w", err) + } + if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { + return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ + "diffs": strings.Join(diffs, ", "), + }, nil) + } + + rep := host.Inspect(root) + if err := prep.CheckWHPX(rep); err != nil { + a.emitLog(name, "Resume refused: "+err.Error()) + return err + } + if err := prep.CheckMemory(d.Memory, rep); err != nil { + a.emitLog(name, "Resume refused: "+err.Error()) + return err + } + + a.cancelRebootWatcher(name) + + if prep.Runtime.Manifest.HasCapability("win32-unicode-input") { + if env := a.inputBridgeEnv(name, d.Directory); len(env) > 0 { + c.Env = append(c.Env, env...) + } + } + if prep.Runtime.Manifest.HasCapability("display-fixed-mode") && + host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) { + c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") + } + + origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) + incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) + if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { + return fmt.Errorf("prepare incoming extra-args: %w", err) + } + restoredExtra := false + restoreExtra := func() { + if restoredExtra { + return + } + restoredExtra = true + if rerr := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard); rerr != nil { + a.emitLog(name, "Warning: could not restore extra-args after incoming launch: "+rerr.Error()) + } + } + defer restoreExtra() + + a.mu.Lock() + a.transitions[name] = "resuming" + a.mu.Unlock() + a.emitStateChanged() + + startAt := time.Now() + w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) + a.emitLog(name, fmt.Sprintf("Resuming %s from %s...", name, reims.SuspendStateFileName)) + if err := c.Start(ctx, name, w, w); err != nil { + restoreExtra() + a.clearTransition(name) + a.emitLog(name, "Resume launch error: "+err.Error()) + a.wakePoll() + a.emitStateChanged() + return err + } + restoreExtra() + + if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { + a.emitLog(name, "Resume snapshot error (suspend state preserved for retry): "+err.Error()) + // Clean up the paused incoming QEMU process without touching suspend.vmstate. + if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { + _ = c.StopForce(context.Background(), name, io.Discard, io.Discard) + } + a.clearTransition(name) + a.wakePoll() + a.emitStateChanged() + return err + } + + if rerr := reims.RemoveSuspendState(d.Directory); rerr != nil { + a.emitLog(name, "Warning: could not remove consumed suspend files: "+rerr.Error()) + } + + if mgr != nil { + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{ + VMName: name, + VMDir: d.Directory, + DriverID: builtin.IDDriverReimsMacOS, + }) + } + a.startVMMonitor(name, d, startAt) + a.clearTransition(name) + a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds())) + a.wakePoll() + a.emitStateChanged() + return nil +} + +// DiscardSuspend deletes a suspended VM's saved RAM/device snapshot so the VM +// returns to the ordinary stopped state (equivalent to powering off). +func (a *App) DiscardSuspend(name string) error { + loc := a.locale() + c, err := a.client() + if err != nil { + return err + } + a.mu.Lock() + if tr := a.transitions[name]; tr != "" { + a.mu.Unlock() + return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + a.mu.Unlock() + + ctx := a.baseCtx() + d, err := c.Show(ctx, name) + if err != nil { + return err + } + if a.isVMRunning(ctx, c, name, d) { + return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) + } + if err := reims.RemoveSuspendState(d.Directory); err != nil { + return err + } + a.emitLog(name, "Discarded suspend state for "+name) + a.wakePoll() + a.emitStateChanged() + return nil +} + +func (a *App) clearTransition(name string) { + a.mu.Lock() + delete(a.transitions, name) + a.mu.Unlock() +} + +func (a *App) emitStateChanged() { + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } +} diff --git a/internal/app/suspend_flow_test.go b/internal/app/suspend_flow_test.go new file mode 100644 index 0000000..686c25f --- /dev/null +++ b/internal/app/suspend_flow_test.go @@ -0,0 +1,58 @@ +package app + +import ( + "os" + "testing" + + "github.com/Nwflower/reims-go/internal/driver/reims" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) { + suspendedDir := t.TempDir() + stoppedDir := t.TempDir() + + if err := os.WriteFile(reims.SuspendStatePath(suspendedDir), []byte("0123456789"), 0o644); err != nil { + t.Fatal(err) + } + if err := reims.WriteSuspendInfo(suspendedDir, reims.BuildSuspendInfo( + reims.VMDetail{Name: "mac-a", CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"}, + rt.Installed{Commit: "3731afd"}, + 10, + )); err != nil { + t.Fatal(err) + } + + vms := []reims.VMListItem{ + {Name: "mac-a", Dir: suspendedDir, State: "stopped"}, + {Name: "mac-b", Dir: stoppedDir, State: "stopped"}, + {Name: "mac-c", Dir: suspendedDir, State: "running"}, + } + enrichVMListStates(vms) + if vms[0].State != "suspended" { + t.Fatalf("mac-a state = %q, want suspended", vms[0].State) + } + if vms[1].State != "stopped" { + t.Fatalf("mac-b state = %q, want stopped", vms[1].State) + } + if vms[2].State != "running" { + t.Fatalf("running VM must stay running, got %q", vms[2].State) + } + + a := &App{} + det := reims.VMDetail{Name: "mac-a", Directory: suspendedDir, State: "stopped"} + a.populateSuspendDetail(&det) + if det.State != "suspended" || det.SuspendInfo == nil || det.SuspendInfo.VMStateSize != 10 { + t.Fatalf("populateSuspendDetail failed: %+v", det) + } + if !a.isVMSuspended(det) { + t.Fatal("expected isVMSuspended=true") + } +} + +func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) { + got := stripLegacyManagedExtraArgs("-machine kernel-irqchip=on -incoming defer") + if got != "-machine kernel-irqchip=on" { + t.Fatalf("stripLegacyManagedExtraArgs = %q", got) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index cc733c6..5242e24 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -134,6 +134,9 @@ func printUsage(loc i18n.Locale) { "cli.usage.cmd_vm_compact", "cli.usage.cmd_vm_start", "cli.usage.cmd_vm_stop", + "cli.usage.cmd_vm_suspend", + "cli.usage.cmd_vm_resume", + "cli.usage.cmd_vm_discard_suspend", "cli.usage.cmd_vm_type", "cli.usage.cmd_inst_list", "cli.usage.cmd_inst_dl", @@ -370,7 +373,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go vm ") + return fmt.Errorf("usage: reims-go vm ") } prep, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) }) if err != nil { @@ -389,6 +392,13 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e fmt.Println(i18n.T(loc, "vm.empty")) return nil } + for i := range vms { + if st, _ := vms[i]["state"].(string); st == "stopped" { + if dir, _ := vms[i]["dir"].(string); reims.HasSuspendState(dir) { + vms[i]["state"] = "suspended" + } + } + } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") return enc.Encode(vms) @@ -519,6 +529,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e AudioBackend: strings.TrimSpace(*audioBackend), GuestLang: strings.TrimSpace(*guestLang), } + if d, serr := client.Show(ctx, setOpts.Name); serr == nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SET_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": setOpts.Name}, nil) + } if reims.HasCtlSetChanges(setOpts) { if err := client.Set(ctx, setOpts, os.Stdout, os.Stderr); err != nil { return err @@ -544,6 +557,21 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e return fmt.Errorf("usage: reims-go vm stop ") } return client.Stop(ctx, args[1], os.Stdout, os.Stderr) + case "suspend": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm suspend ") + } + return suspendVM(ctx, cfg, prep, args[1]) + case "resume": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm resume ") + } + return resumeVM(ctx, cfg, prep, args[1]) + case "discard-suspend": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm discard-suspend ") + } + return discardSuspendVM(ctx, cfg, prep, args[1]) case "eject": if len(args) < 2 { return fmt.Errorf("usage: reims-go vm eject ") @@ -583,6 +611,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1])) } + if reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_RESIZE_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil) + } diskPath := resolveCLIDiskPath(d) res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), client.Env, diskPath, args[2], os.Stdout, os.Stderr) if err != nil { @@ -602,6 +633,9 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1])) } + if reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_COMPACT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil) + } diskPath := resolveCLIDiskPath(d) res, err := reims.CompactDisk(ctx, active.QemuImgPath(), client.Env, diskPath, os.Stdout, os.Stderr) if err != nil { diff --git a/internal/cli/start.go b/internal/cli/start.go index d81ed1a..b6b215c 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/plugin" @@ -49,6 +50,9 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s if viaWindow && windowHandoffWorks { return startInWindow(ctx, cfg, name) } + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + return resumeVM(ctx, cfg, prep, name) + } // Honour the core plugin's WHPX setting, as the window does. st := plugin.ReadState(cfg.DataRoot) diff --git a/internal/cli/suspend.go b/internal/cli/suspend.go new file mode 100644 index 0000000..e120f83 --- /dev/null +++ b/internal/cli/suspend.go @@ -0,0 +1,179 @@ +package cli + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/qmp" + "github.com/Nwflower/reims-go/internal/vmstart" +) + +func suspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State != "running" { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) + } + if memGB, ok := reims.ParseSizeGB(d.Memory); ok { + dirRep := host.Inspect(d.Directory) + needGB := memGB + 1.0 + if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { + return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ + "need": fmt.Sprintf("%.1f", needGB), + "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), + }, nil) + } + } + var oldPID int + if vms, lerr := prep.Client.List(ctx); lerr == nil { + for _, vm := range vms { + if vm.Name == name && vm.PID != nil && *vm.PID > 0 { + oldPID = *vm.PID + break + } + } + } + + tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" + _ = os.Remove(tmpPath) + fmt.Fprintf(os.Stderr, "Suspending %s to %s...\n", name, reims.SuspendStateFileName) + if err := qmp.SuspendToFile(ctx, d.Directory, tmpPath, nil); err != nil { + _ = os.Remove(tmpPath) + return err + } + if oldPID > 0 { + waitCtx, cancel := context.WithTimeout(ctx, 12*time.Second) + _ = host.WaitProcessExit(waitCtx, uint32(oldPID), "qemu-system-x86_64.exe") + cancel() + } + st, err := os.Stat(tmpPath) + if err != nil || st.Size() <= 0 { + _ = os.Remove(tmpPath) + if err != nil { + return err + } + return fmt.Errorf("suspend snapshot is empty after save") + } + finalPath := reims.SuspendStatePath(d.Directory) + _ = os.Remove(finalPath) + if err := os.Rename(tmpPath, finalPath); err != nil { + _ = os.Remove(tmpPath) + return err + } + if err := reims.WriteSuspendInfo(d.Directory, reims.BuildSuspendInfo(d, prep.Runtime, st.Size())); err != nil { + _ = reims.RemoveSuspendState(d.Directory) + return err + } + fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(st.Size())/float64(1<<30)) + return nil +} + +func resumeVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + if !prep.Runtime.Manifest.HasCapability("vm-suspend") { + return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + rep := host.Inspect(cfg.DataRoot) + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State == "running" { + return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) + } + if !reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) + } + meta, err := reims.ReadSuspendInfo(d.Directory) + if err != nil { + return err + } + if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { + return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ + "diffs": strings.Join(diffs, ", "), + }, nil) + } + if err := prep.CheckWHPX(rep); err != nil { + return err + } + if err := prep.CheckMemory(d.Memory, rep); err != nil { + return err + } + + origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) + incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) + if err := prep.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { + return err + } + restored := false + restoreExtra := func() { + if restored { + return + } + restored = true + _ = prep.Client.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard) + } + defer restoreExtra() + + fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", name, reims.SuspendStateFileName) + startAt := time.Now() + if err := prep.Client.Start(ctx, name, os.Stdout, os.Stderr); err != nil { + restoreExtra() + return err + } + restoreExtra() + + if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { + if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { + _ = prep.Client.StopForce(context.Background(), name, io.Discard, io.Discard) + } + return err + } + _ = reims.RemoveSuspendState(d.Directory) + + if vms, lerr := prep.Client.List(ctx); lerr == nil { + for _, vm := range vms { + if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { + vmDir := vm.Dir + if vmDir == "" { + vmDir = d.Directory + } + if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" { + fmt.Fprintln(os.Stderr, line) + } + } + } + } + fmt.Printf("Resumed %s in %.1fs\n", name, time.Since(startAt).Seconds()) + return nil +} + +func discardSuspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { + loc := cfg.Locale + d, err := prep.Client.Show(ctx, name) + if err != nil { + return err + } + if d.State == "running" { + return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) + } + if err := reims.RemoveSuspendState(d.Directory); err != nil { + return err + } + fmt.Printf("Discarded suspend state for %s\n", name) + return nil +} diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 17dcc5d..06b51de 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -88,8 +88,9 @@ type VMDetail struct { GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` // GuestToolsDisabled is set when the Guest Tools plugin is switched off. GuestToolsDisabled bool `json:"guest_tools_disabled,omitempty"` - SharedDir string `json:"shared_dir,omitempty"` - GuestLang string `json:"guest_lang,omitempty"` + SharedDir string `json:"shared_dir,omitempty"` + GuestLang string `json:"guest_lang,omitempty"` + SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"` } type ValidationIssue struct { @@ -258,6 +259,10 @@ func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n if strings.TrimSpace(o.Name) == "" { issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: i18n.T(loc, "validate.missing_name")}) } + if current.State == "suspended" { + issues = append(issues, ValidationIssue{Field: "state", Code: "vm_suspended", Message: i18n.T(loc, "validate.vm_suspended")}) + return issues + } if o.CPUs != 0 && (o.CPUs < 1 || (rep.LogicalCPUs > 0 && o.CPUs > rep.LogicalCPUs)) { issues = append(issues, ValidationIssue{Field: "cpus", Code: "invalid_cpus", Message: i18n.T(loc, "validate.invalid_cpus", max(rep.LogicalCPUs, 1))}) } diff --git a/internal/driver/reims/suspend.go b/internal/driver/reims/suspend.go new file mode 100644 index 0000000..b4035d4 --- /dev/null +++ b/internal/driver/reims/suspend.go @@ -0,0 +1,240 @@ +package reims + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +const ( + // SuspendStateFileName holds the QEMU mapped-ram + device VMState snapshot. + SuspendStateFileName = "suspend.vmstate" + // SuspendMetaFileName records the hardware and runtime fingerprint used to + // create suspend.vmstate so incompatible resumes are caught before launch. + SuspendMetaFileName = "suspend.json" + // SuspendSchemaVersion is the current metadata schema version. + SuspendSchemaVersion = 1 +) + +// SuspendInfo describes a VM's saved suspend-to-disk state inside its VM folder. +type SuspendInfo struct { + SchemaVersion int `json:"schema_version"` + VMName string `json:"vm_name"` + CPUs int `json:"cpus"` + Memory string `json:"memory"` + Graphics string `json:"graphics"` + Displays int `json:"displays"` + Resolution string `json:"resolution"` + DiskController string `json:"disk_controller"` + CPUModel string `json:"cpu_model,omitempty"` + Audio bool `json:"audio"` + AudioBackend string `json:"audio_backend,omitempty"` + Network bool `json:"network"` + SSHPort int `json:"ssh_port"` + ExtraArgs string `json:"extra_args,omitempty"` + RuntimeCommit string `json:"runtime_commit"` + VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"` + CreatedAt string `json:"created_at"` + VMStateSize int64 `json:"vmstate_size"` +} + +// SuspendStatePath returns the path to a VM's suspend snapshot file. +func SuspendStatePath(vmDir string) string { + return filepath.Join(vmDir, SuspendStateFileName) +} + +// SuspendMetaPath returns the path to a VM's suspend metadata JSON file. +func SuspendMetaPath(vmDir string) string { + return filepath.Join(vmDir, SuspendMetaFileName) +} + +// HasSuspendState reports whether vmDir contains a complete suspend snapshot +// (both a non-empty suspend.vmstate and its suspend.json metadata). +func HasSuspendState(vmDir string) bool { + if strings.TrimSpace(vmDir) == "" { + return false + } + st, err := os.Stat(SuspendStatePath(vmDir)) + if err != nil || st.IsDir() || st.Size() <= 0 { + return false + } + mst, err := os.Stat(SuspendMetaPath(vmDir)) + if err != nil || mst.IsDir() || mst.Size() <= 0 { + return false + } + return true +} + +// ReadSuspendInfo reads suspend.json from vmDir and refreshes VMStateSize from +// the actual suspend.vmstate file on disk. +func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) { + b, err := os.ReadFile(SuspendMetaPath(vmDir)) + if err != nil { + return nil, err + } + var info SuspendInfo + if err := json.Unmarshal(b, &info); err != nil { + return nil, fmt.Errorf("parse %s: %w", SuspendMetaFileName, err) + } + if st, err := os.Stat(SuspendStatePath(vmDir)); err == nil && !st.IsDir() { + info.VMStateSize = st.Size() + } + return &info, nil +} + +// WriteSuspendInfo atomically writes suspend.json inside vmDir. +func WriteSuspendInfo(vmDir string, info SuspendInfo) error { + if info.SchemaVersion == 0 { + info.SchemaVersion = SuspendSchemaVersion + } + if info.CreatedAt == "" { + info.CreatedAt = time.Now().UTC().Format(time.RFC3339) + } + info.ExtraArgs = StripIncomingDeferArgs(info.ExtraArgs) + b, err := json.MarshalIndent(info, "", " ") + if err != nil { + return err + } + b = append(b, '\n') + tmp := SuspendMetaPath(vmDir) + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + return os.Rename(tmp, SuspendMetaPath(vmDir)) +} + +// BuildSuspendInfo snapshots a VM's hardware and runtime fingerprint for suspend.json. +func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) SuspendInfo { + return SuspendInfo{ + SchemaVersion: SuspendSchemaVersion, + VMName: d.Name, + CPUs: d.CPUs, + Memory: strings.TrimSpace(d.Memory), + Graphics: strings.TrimSpace(d.Graphics), + Displays: d.Displays, + Resolution: strings.TrimSpace(d.Resolution), + DiskController: strings.TrimSpace(d.DiskController), + CPUModel: strings.TrimSpace(d.CPUModel), + Audio: d.Audio, + AudioBackend: strings.TrimSpace(d.AudioBackend), + Network: d.Network, + SSHPort: d.SSHPort, + ExtraArgs: StripIncomingDeferArgs(d.ExtraArgs), + RuntimeCommit: strings.TrimSpace(active.Commit), + VendorQemuCommit: strings.TrimSpace(active.Manifest.VendorQemuCommit), + CreatedAt: time.Now().UTC().Format(time.RFC3339), + VMStateSize: vmstateSize, + } +} + +// RemoveSuspendState deletes suspend.vmstate, suspend.json, and any partial +// temporary files inside vmDir. +func RemoveSuspendState(vmDir string) error { + if strings.TrimSpace(vmDir) == "" { + return nil + } + var firstErr error + for _, name := range []string{ + SuspendMetaFileName, + SuspendMetaFileName + ".tmp", + SuspendStateFileName, + SuspendStateFileName + ".tmp", + } { + if err := os.Remove(filepath.Join(vmDir, name)); err != nil && !os.IsNotExist(err) && firstErr == nil { + firstErr = err + } + } + return firstErr +} + +// ValidateSuspendCompatibility checks that the VM hardware and runtime match +// the fingerprint stored when the VM was suspended. Returns human-readable +// mismatch descriptions; an empty slice means compatible. +func ValidateSuspendCompatibility(meta SuspendInfo, cur VMDetail, active rt.Installed) []string { + var diffs []string + if meta.CPUs > 0 && cur.CPUs > 0 && meta.CPUs != cur.CPUs { + diffs = append(diffs, fmt.Sprintf("CPUs (%d -> %d)", meta.CPUs, cur.CPUs)) + } + if meta.Memory != "" && cur.Memory != "" && !strings.EqualFold(strings.TrimSpace(meta.Memory), strings.TrimSpace(cur.Memory)) { + diffs = append(diffs, fmt.Sprintf("Memory (%s -> %s)", meta.Memory, cur.Memory)) + } + if meta.Graphics != "" && cur.Graphics != "" && !strings.EqualFold(strings.TrimSpace(meta.Graphics), strings.TrimSpace(cur.Graphics)) { + diffs = append(diffs, fmt.Sprintf("Graphics (%s -> %s)", meta.Graphics, cur.Graphics)) + } + if meta.Displays > 0 && cur.Displays > 0 && meta.Displays != cur.Displays { + diffs = append(diffs, fmt.Sprintf("Displays (%d -> %d)", meta.Displays, cur.Displays)) + } + if meta.DiskController != "" && cur.DiskController != "" && !strings.EqualFold(strings.TrimSpace(meta.DiskController), strings.TrimSpace(cur.DiskController)) { + diffs = append(diffs, fmt.Sprintf("Disk controller (%s -> %s)", meta.DiskController, cur.DiskController)) + } + if meta.Audio != cur.Audio { + diffs = append(diffs, fmt.Sprintf("Audio (%v -> %v)", meta.Audio, cur.Audio)) + } + if meta.Network != cur.Network { + diffs = append(diffs, fmt.Sprintf("Network (%v -> %v)", meta.Network, cur.Network)) + } + if meta.VendorQemuCommit != "" && active.Manifest.VendorQemuCommit != "" && + !strings.EqualFold(strings.TrimSpace(meta.VendorQemuCommit), strings.TrimSpace(active.Manifest.VendorQemuCommit)) { + diffs = append(diffs, fmt.Sprintf("QEMU commit (%s -> %s)", shortRev(meta.VendorQemuCommit), shortRev(active.Manifest.VendorQemuCommit))) + } else if meta.RuntimeCommit != "" && active.Commit != "" && + !strings.EqualFold(strings.TrimSpace(meta.RuntimeCommit), strings.TrimSpace(active.Commit)) { + diffs = append(diffs, fmt.Sprintf("Runtime (%s -> %s)", meta.RuntimeCommit, active.Commit)) + } + return diffs +} + +func shortRev(rev string) string { + rev = strings.TrimSpace(rev) + if len(rev) > 8 { + return rev[:8] + } + return rev +} + +// HasIncomingDeferArg reports whether extraArgs contains `-incoming defer`. +func HasIncomingDeferArg(extraArgs string) bool { + tokens := splitShellTokens(extraArgs) + for i := 0; i < len(tokens); i++ { + tok := tokens[i] + if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" { + return true + } + if tok == "-incoming=defer" { + return true + } + } + return false +} + +// StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer` +// arguments from QEMU extra-args while leaving all other arguments intact. +func StripIncomingDeferArgs(existing string) string { + tokens := splitShellTokens(existing) + cleaned := make([]string, 0, len(tokens)) + for i := 0; i < len(tokens); i++ { + tok := tokens[i] + if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" { + i++ + continue + } + if tok == "-incoming=defer" { + continue + } + cleaned = append(cleaned, tok) + } + return strings.Join(cleaned, " ") +} + +// MergeIncomingDeferArgs idempotently appends `-incoming defer` to extra-args. +func MergeIncomingDeferArgs(existing string) string { + base := StripIncomingDeferArgs(existing) + if base == "" { + return "-incoming defer" + } + return base + " -incoming defer" +} diff --git a/internal/driver/reims/suspend_test.go b/internal/driver/reims/suspend_test.go new file mode 100644 index 0000000..4401ca6 --- /dev/null +++ b/internal/driver/reims/suspend_test.go @@ -0,0 +1,114 @@ +package reims + +import ( + "os" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func TestSuspendStateLifecycle(t *testing.T) { + dir := t.TempDir() + if HasSuspendState(dir) { + t.Fatal("empty dir should not have suspend state") + } + + // Only vmstate without meta -> incomplete. + if err := os.WriteFile(SuspendStatePath(dir), []byte("vmstate-bytes"), 0o644); err != nil { + t.Fatal(err) + } + if HasSuspendState(dir) { + t.Fatal("vmstate without suspend.json should not count as complete suspend state") + } + + active := rt.Installed{ + Commit: "3731afd-p9", + Manifest: rt.Manifest{ + VendorQemuCommit: "4571bc5fecb039e8cfd6837e077810fbe074e11b", + }, + } + detail := VMDetail{ + Name: "tahoe", + CPUs: 8, + Memory: "8G", + Graphics: "reims-vgpu", + Displays: 1, + Resolution: "1920x1080", + DiskController: "nvme", + Audio: true, + Network: true, + ExtraArgs: "-machine kernel-irqchip=on -incoming defer", + } + info := BuildSuspendInfo(detail, active, 13) + if err := WriteSuspendInfo(dir, info); err != nil { + t.Fatalf("WriteSuspendInfo: %v", err) + } + if !HasSuspendState(dir) { + t.Fatal("expected HasSuspendState=true after writing both files") + } + + got, err := ReadSuspendInfo(dir) + if err != nil { + t.Fatalf("ReadSuspendInfo: %v", err) + } + if got.VMStateSize != 13 || got.CPUs != 8 || got.ExtraArgs != "-machine kernel-irqchip=on" { + t.Fatalf("unexpected suspend info: %+v", got) + } + + // Compatible check passes. + if diffs := ValidateSuspendCompatibility(*got, detail, active); len(diffs) != 0 { + t.Fatalf("expected compatible, got %v", diffs) + } + + // Hardware and runtime mismatch checks trigger. + changedDetail := detail + changedDetail.CPUs = 12 + changedDetail.Memory = "16G" + changedRT := active + changedRT.Manifest.VendorQemuCommit = "deadbeef00000000000000000000000000000000" + diffs := ValidateSuspendCompatibility(*got, changedDetail, changedRT) + if len(diffs) != 3 { + t.Fatalf("expected 3 diffs, got %v", diffs) + } + + if err := RemoveSuspendState(dir); err != nil { + t.Fatalf("RemoveSuspendState: %v", err) + } + if HasSuspendState(dir) { + t.Fatal("expected HasSuspendState=false after RemoveSuspendState") + } +} + +func TestIncomingDeferArgsIdempotent(t *testing.T) { + if HasIncomingDeferArg("") || HasIncomingDeferArg("-machine q35") { + t.Fatal("unexpected HasIncomingDeferArg=true") + } + m := MergeIncomingDeferArgs(`-drive "id=x,file=C:/a b/c.img"`) + if !HasIncomingDeferArg(m) { + t.Fatalf("expected -incoming defer in %q", m) + } + if m2 := MergeIncomingDeferArgs(m); m2 != m { + t.Fatalf("MergeIncomingDeferArgs not idempotent: %q vs %q", m2, m) + } + if s := StripIncomingDeferArgs(m + " -incoming=defer"); s != `-drive "id=x,file=C:/a b/c.img"` { + t.Fatalf("StripIncomingDeferArgs = %q", s) + } +} + +func TestValidateSetRejectsSuspendedVM(t *testing.T) { + issues := ValidateSetLocalized( + SetOpts{Name: "tahoe", CPUs: 6}, + VMDetail{Name: "tahoe", State: "suspended", CPUs: 8, Memory: "8G"}, + host.Report{LogicalCPUs: 16, TotalRAMGB: 32}, + i18n.EnUS, + ) + if len(issues) == 0 || issues[0].Code != "vm_suspended" { + t.Fatalf("expected vm_suspended validation issue, got %+v", issues) + } + if !strings.Contains(strings.ToLower(issues[0].Message), "suspend") { + t.Fatalf("unexpected message: %q", issues[0].Message) + } +} diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 25560a6..edc8c67 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -45,11 +45,14 @@ var catalog = map[Locale]map[string]string{ "cli.usage.cmd_version": " version 查看当前版本", "cli.usage.cmd_vm_compact": " vm compact 停机回收 .qcow2 磁盘未用空间", "cli.usage.cmd_vm_create": " vm create [options] 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend 放弃已保存的挂起状态并回到关机状态", "cli.usage.cmd_vm_list": " vm list 列出已创建的虚拟机", "cli.usage.cmd_vm_resize": " vm resize <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)", + "cli.usage.cmd_vm_resume": " vm resume 从磁盘挂起状态恢复虚拟机", "cli.usage.cmd_vm_set": " vm set [options] 修改虚拟机配置(下次启动生效)", "cli.usage.cmd_vm_start": " vm start 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动", "cli.usage.cmd_vm_stop": " vm stop|eject 停止 / 弹出安装盘", + "cli.usage.cmd_vm_suspend": " vm suspend 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)", "cli.usage.cmd_vm_type": " vm type [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)", "cli.usage.header": "reims-go - Windows 一站式免编译 reims-vgpu 启动器", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] <命令> [参数]", @@ -134,6 +137,14 @@ var catalog = map[Locale]map[string]string{ "err.snapshot.qcow2_only": "恢复点仅支持 .qcow2 格式磁盘", "err.snapshot.qemu_img_failed": "恢复点操作未完成({snap})", "err.snapshot.vm_running": "请先停止「{name}」再创建、回滚或删除恢复点", + "err.suspend.action_blocked": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作", + "err.suspend.busy": "虚拟机「{name}」正在执行状态切换,请稍后再试", + "err.suspend.discard_running": "虚拟机「{name}」正在运行,无法放弃挂起状态", + "err.suspend.disk_space": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)", + "err.suspend.incompatible": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动", + "err.suspend.not_found": "未找到「{name}」的完整挂起状态文件", + "err.suspend.not_running": "虚拟机「{name}」未在运行,无法挂起", + "err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本", "err.update_changed": "已下载的更新文件被改动过,请重新下载", "err.update_dev_build": "开发版本不支持应用内更新", "err.update_no_asset": "这个版本没有提供 Windows 程序文件,请到发布页手动下载", @@ -429,35 +440,44 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "已保存 SSH 用户名", "toastSaved": "已保存", "toastSavedNextStart": "已保存,下次启动生效", + "tray.menu.discard_suspend": "放弃挂起状态(&X)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.new_vm": "新建虚拟机(&N)…", "tray.menu.open_in_app": "在 Reims-Go 中查看(&V)", "tray.menu.quit": "退出 Reims-Go(&Q)", "tray.menu.restart": "重启(&R)", + "tray.menu.resume": "恢复(&U)", "tray.menu.screenshot": "复制屏幕截图(&C)", "tray.menu.shared_folder": "打开共享文件夹(&H)", "tray.menu.show": "显示 Reims-Go(&O)", "tray.menu.show_window": "显示窗口(&W)", "tray.menu.start": "启动(&S)", "tray.menu.stop": "关机(&D)", + "tray.menu.suspend": "挂起(&P)", "tray.menu.toggle_fullscreen": "切换全屏", + "tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态", "tray.notify.focus_fail": "找不到 {name} 的窗口", "tray.notify.force_stop_fail": "无法强制关机 {name}", "tray.notify.fullscreen_fail": "无法切换 {name} 全屏", "tray.notify.restart_fail": "无法重启 {name}", + "tray.notify.resume_fail": "无法恢复 {name}", "tray.notify.screenshot_fail": "截图失败:{name}", "tray.notify.screenshot_ok": "已复制屏幕截图", "tray.notify.shared_fail": "无法打开共享文件夹", "tray.notify.start_fail": "无法启动 {name}", "tray.notify.stop_fail": "无法关机 {name}", + "tray.notify.suspend_fail": "无法挂起 {name}", "tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}", "tray.running.many": "Reims-Go — {count} 台虚拟机运行中", "tray.running.one": "Reims-Go — 1 台虚拟机运行中", "tray.state.broken": "配置损坏", + "tray.state.resuming": "正在恢复…", "tray.state.running": "运行中", "tray.state.starting": "启动中…", "tray.state.stopped": "已停止", "tray.state.stopping": "正在关机…", + "tray.state.suspended": "已挂起", + "tray.state.suspending": "正在挂起…", "tray.state.unknown": "未知", "updateCancel": "取消下载", "updateCapsuleAvailable": "{v} 可用", @@ -498,6 +518,7 @@ var catalog = map[Locale]map[string]string{ "validate.missing_name": "虚拟机名称不能为空", "validate.missing_release": "请选择要离线安装的 macOS 版本", "validate.name_taken": "已存在名为 {name} 的虚拟机", + "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", "viewLogs": "查看日志", "vm.already_running": "{name} 已在运行中", "vm.compact.done": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)", @@ -557,11 +578,14 @@ var catalog = map[Locale]map[string]string{ "cli.usage.cmd_version": " version Show current version", "cli.usage.cmd_vm_compact": " vm compact Compact stopped .qcow2 disk to reclaim unused space", "cli.usage.cmd_vm_create": " vm create [options] Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend Discard a saved suspend state and return the VM to powered off", "cli.usage.cmd_vm_list": " vm list List virtual machines", "cli.usage.cmd_vm_resize": " vm resize Expand stopped VM disk (e.g. 256G or +64G)", + "cli.usage.cmd_vm_resume": " vm resume Resume a suspended VM from disk", "cli.usage.cmd_vm_set": " vm set [options] Update VM settings (applies on next start)", "cli.usage.cmd_vm_start": " vm start Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process", "cli.usage.cmd_vm_stop": " vm stop|eject Stop / eject installer", + "cli.usage.cmd_vm_suspend": " vm suspend Suspend a running VM to disk for fast resume across restarts", "cli.usage.cmd_vm_type": " vm type [text] Type text into a running VM as US-keyboard keys (stdin if no text)", "cli.usage.header": "reims-go - Portable one-stop reims-vgpu launcher for Windows", "cli.usage.line_cmd": " reims-go [--lang ] [--data-root DIR] [args]", @@ -646,6 +670,14 @@ var catalog = map[Locale]map[string]string{ "err.snapshot.qcow2_only": "Restore points are only supported on .qcow2 disks", "err.snapshot.qemu_img_failed": "Restore point operation could not finish ({snap})", "err.snapshot.vm_running": "Stop “{name}” before creating, restoring or deleting a restore point", + "err.suspend.action_blocked": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this", + "err.suspend.busy": "VM “{name}” is busy transitioning; try again in a moment", + "err.suspend.discard_running": "VM “{name}” is currently running; suspend state cannot be discarded", + "err.suspend.disk_space": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)", + "err.suspend.incompatible": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state", + "err.suspend.not_found": "No complete suspend state found for “{name}”", + "err.suspend.not_running": "VM “{name}” is not running and cannot be suspended", + "err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support", "err.update_changed": "The downloaded update changed on disk; download it again", "err.update_dev_build": "In-app update is disabled in development builds", "err.update_no_asset": "This release has no Windows executable; download it from the release page", @@ -941,35 +973,44 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "Saved SSH username", "toastSaved": "Saved", "toastSavedNextStart": "Saved — applies on next start", + "tray.menu.discard_suspend": "Discard Saved Stat&e", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.new_vm": "&New Virtual Machine…", "tray.menu.open_in_app": "Show in &Reims-Go", "tray.menu.quit": "&Quit Reims-Go", "tray.menu.restart": "&Restart", + "tray.menu.resume": "Res&ume", "tray.menu.screenshot": "&Copy Screenshot", "tray.menu.shared_folder": "Open S&hared Folder", "tray.menu.show": "&Show Reims-Go", "tray.menu.show_window": "Show &Window", "tray.menu.start": "&Start", "tray.menu.stop": "Shut &Down", + "tray.menu.suspend": "Sus&pend", "tray.menu.toggle_fullscreen": "Toggle full screen", + "tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}", "tray.notify.focus_fail": "Couldn't find the window of {name}", "tray.notify.force_stop_fail": "Couldn't force shut down {name}", "tray.notify.fullscreen_fail": "Couldn’t toggle full screen for {name}", "tray.notify.restart_fail": "Couldn't restart {name}", + "tray.notify.resume_fail": "Couldn't resume {name}", "tray.notify.screenshot_fail": "Screenshot failed: {name}", "tray.notify.screenshot_ok": "Screenshot copied", "tray.notify.shared_fail": "Couldn't open the shared folder", "tray.notify.start_fail": "Couldn't start {name}", "tray.notify.stop_fail": "Couldn't shut down {name}", + "tray.notify.suspend_fail": "Couldn't suspend {name}", "tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}", "tray.running.many": "Reims-Go — {count} VMs running", "tray.running.one": "Reims-Go — 1 VM running", "tray.state.broken": "Broken", + "tray.state.resuming": "Resuming…", "tray.state.running": "Running", "tray.state.starting": "Starting…", "tray.state.stopped": "Stopped", "tray.state.stopping": "Shutting down…", + "tray.state.suspended": "Suspended", + "tray.state.suspending": "Suspending…", "tray.state.unknown": "Unknown", "updateCancel": "Cancel download", "updateCapsuleAvailable": "{v} available", @@ -1010,6 +1051,7 @@ var catalog = map[Locale]map[string]string{ "validate.missing_name": "VM name is required", "validate.missing_release": "Choose the macOS release to install offline", "validate.name_taken": "A VM named {name} already exists", + "validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings", "viewLogs": "View logs", "vm.already_running": "{name} is already running", "vm.compact.done": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)", @@ -1074,6 +1116,13 @@ var paramOrder = map[string][]string{ "err.plugin.system_locked": {"id"}, "err.snapshot.qemu_img_failed": {"snap"}, "err.snapshot.vm_running": {"name"}, + "err.suspend.action_blocked": {"name"}, + "err.suspend.busy": {"name"}, + "err.suspend.discard_running": {"name"}, + "err.suspend.disk_space": {"need", "avail"}, + "err.suspend.incompatible": {"diffs"}, + "err.suspend.not_found": {"name"}, + "err.suspend.not_running": {"name"}, "err.update_not_writable": {"dir"}, "err.vm_not_running": {"name"}, "err.vm_window_not_found": {"name"}, @@ -1145,13 +1194,16 @@ var paramOrder = map[string][]string{ "toastInstallerReady": {"v"}, "toastRuntimeReady": {"v"}, "toastSSHConfigWritten": {"alias"}, + "tray.notify.discard_suspend_fail": {"name"}, "tray.notify.focus_fail": {"name"}, "tray.notify.force_stop_fail": {"name"}, "tray.notify.fullscreen_fail": {"name"}, "tray.notify.restart_fail": {"name"}, + "tray.notify.resume_fail": {"name"}, "tray.notify.screenshot_fail": {"name"}, "tray.notify.start_fail": {"name"}, "tray.notify.stop_fail": {"name"}, + "tray.notify.suspend_fail": {"name"}, "tray.running": {"count"}, "tray.running.many": {"count"}, "updateCapsuleAvailable": {"v"}, diff --git a/internal/qmp/client.go b/internal/qmp/client.go index f593836..bc7ba3b 100644 --- a/internal/qmp/client.go +++ b/internal/qmp/client.go @@ -52,8 +52,15 @@ type qmpReply struct { Event string `json:"event"` } -// Query runs one command and waits for its JSON return value, skipping async events. +// Query runs one command with the default 5-second timeout and waits for its +// JSON return value, skipping async events. func (c *Conn) Query(command string, args any) (json.RawMessage, error) { + return c.QueryWithTimeout(command, args, 5*time.Second) +} + +// QueryWithTimeout runs one command and waits up to timeout for its JSON return +// value, skipping async events. +func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration) (json.RawMessage, error) { req := map[string]any{"execute": command} if args != nil { req["arguments"] = args @@ -62,7 +69,10 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) { if err != nil { return nil, err } - _ = c.nc.SetDeadline(time.Now().Add(5 * time.Second)) + if timeout <= 0 { + timeout = 5 * time.Second + } + _ = c.nc.SetDeadline(time.Now().Add(timeout)) if _, err := c.nc.Write(append(b, '\n')); err != nil { return nil, fmt.Errorf("QMP %s: %w", command, err) } @@ -84,8 +94,16 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) { return nil, fmt.Errorf("QMP %s: connection closed", command) } -// Execute runs one command and waits for its reply, skipping async events. +// Execute runs one command with the default timeout and waits for its reply, +// skipping async events. func (c *Conn) Execute(command string, args any) error { _, err := c.Query(command, args) return err } + +// ExecuteWithTimeout runs one command and waits up to timeout for its reply, +// skipping async events. +func (c *Conn) ExecuteWithTimeout(command string, args any, timeout time.Duration) error { + _, err := c.QueryWithTimeout(command, args, timeout) + return err +} diff --git a/internal/qmp/migrate.go b/internal/qmp/migrate.go new file mode 100644 index 0000000..effe1d1 --- /dev/null +++ b/internal/qmp/migrate.go @@ -0,0 +1,275 @@ +package qmp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "strings" + "time" +) + +const ( + // DefaultMultifdChannels is the parallel I/O channel count used for + // mapped-ram file snapshots on Windows. + DefaultMultifdChannels = 4 + + migratePollInterval = 200 * time.Millisecond + migrateCmdTimeout = 2 * time.Minute + migrateTotalTimeout = 15 * time.Minute +) + +// MigrateProgress carries the latest snapshot save/load progress from QMP +// `query-migrate`. +type MigrateProgress struct { + Status string `json:"status"` + Transferred int64 `json:"transferred"` + Remaining int64 `json:"remaining"` + Total int64 `json:"total"` + TotalTimeMs int64 `json:"total_time_ms"` +} + +type migrateInfo struct { + Status string `json:"status"` + ErrorDesc string `json:"error-desc"` + TotalTimeMs int64 `json:"total-time"` + RAM *struct { + Transferred int64 `json:"transferred"` + Remaining int64 `json:"remaining"` + Total int64 `json:"total"` + } `json:"ram"` +} + +type vmStatusReply struct { + Running bool `json:"running"` + Status string `json:"status"` +} + +// SuspendToFile pauses a running Intel VM via QMP, writes a mapped-ram + +// multifd file snapshot to vmstatePath, waits for completion, and shuts down +// QEMU cleanly via `quit`. +// +// If migration fails before reaching completion while the VM is merely paused +// (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so +// the running VM is not left frozen. +func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { + c, err := Dial(ctx, "unix", SocketPath(vmDir)) + if err != nil { + return err + } + defer c.Close() + return suspendToFileConn(ctx, c, vmstatePath, onProgress) +} + +func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { + if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil { + return fmt.Errorf("pause VM before suspend: %w", err) + } + st, err := queryVMStatus(c) + if err != nil { + tryResumePaused(c) + return fmt.Errorf("verify paused state: %w", err) + } + if st.Running { + return fmt.Errorf("VM remained running after stop (status=%s)", st.Status) + } + + if err := configureMappedRAM(c); err != nil { + tryResumePaused(c) + return err + } + + args := map[string]any{ + "channels": fileChannels(vmstatePath), + } + if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil { + tryResumePaused(c) + return fmt.Errorf("start snapshot save: %w", err) + } + + if err := waitMigrateDone(ctx, c, onProgress); err != nil { + tryResumePaused(c) + return fmt.Errorf("save snapshot: %w", err) + } + + // Migration completed (RUN_STATE_POSTMIGRATE): never send `cont` here; + // exit QEMU cleanly so the disk and WHPX partition close. + if err := c.ExecuteWithTimeout("quit", nil, 15*time.Second); err != nil { + // QEMU may close the QMP socket immediately upon receiving `quit`. + if !isConnClosedErr(err) { + return fmt.Errorf("quit QEMU after suspend: %w", err) + } + } + return nil +} + +// ResumeFromFile connects to a QEMU process started with `-incoming defer`, +// loads the mapped-ram + multifd file snapshot from vmstatePath, waits for +// completion, and resumes execution with `cont`. +// +// On any error, vmstatePath is left untouched so the caller can retry. +func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { + c, err := dialMigrateConnWithRetry(ctx, "unix", SocketPath(vmDir), 10*time.Second) + if err != nil { + return err + } + defer c.Close() + return resumeFromFileConn(ctx, c, vmstatePath, onProgress) +} + +func resumeFromFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { + if err := configureMappedRAM(c); err != nil { + return err + } + args := map[string]any{ + "channels": fileChannels(vmstatePath), + "exit-on-error": false, + } + if err := c.ExecuteWithTimeout("migrate-incoming", args, migrateCmdTimeout); err != nil { + return fmt.Errorf("start snapshot restore: %w", err) + } + if err := waitMigrateDone(ctx, c, onProgress); err != nil { + return fmt.Errorf("restore snapshot: %w", err) + } + if err := c.ExecuteWithTimeout("cont", nil, 30*time.Second); err != nil { + return fmt.Errorf("resume VM execution after restore: %w", err) + } + return nil +} + +// QuitVM sends QMP `quit` to the VM's QMP socket (best-effort cleanup for a +// failed incoming-resume QEMU process). +func QuitVM(ctx context.Context, vmDir string) error { + c, err := Dial(ctx, "unix", SocketPath(vmDir)) + if err != nil { + return err + } + defer c.Close() + if err := c.ExecuteWithTimeout("quit", nil, 10*time.Second); err != nil && !isConnClosedErr(err) { + return err + } + return nil +} + +func configureMappedRAM(c *Conn) error { + caps := map[string]any{ + "capabilities": []map[string]any{ + {"capability": "mapped-ram", "state": true}, + {"capability": "multifd", "state": true}, + }, + } + if err := c.ExecuteWithTimeout("migrate-set-capabilities", caps, 15*time.Second); err != nil { + return fmt.Errorf("enable mapped-ram/multifd capabilities: %w", err) + } + params := map[string]any{ + "multifd-channels": DefaultMultifdChannels, + } + if err := c.ExecuteWithTimeout("migrate-set-parameters", params, 15*time.Second); err != nil { + return fmt.Errorf("set multifd-channels: %w", err) + } + return nil +} + +func fileChannels(vmstatePath string) []map[string]any { + return []map[string]any{ + { + "channel-type": "main", + "addr": map[string]any{ + "transport": "file", + "filename": filepath.Clean(vmstatePath), + "offset": 0, + }, + }, + } +} + +func queryVMStatus(c *Conn) (vmStatusReply, error) { + raw, err := c.QueryWithTimeout("query-status", nil, 15*time.Second) + if err != nil { + return vmStatusReply{}, err + } + var st vmStatusReply + if err := json.Unmarshal(raw, &st); err != nil { + return vmStatusReply{}, fmt.Errorf("parse query-status: %w", err) + } + return st, nil +} + +func tryResumePaused(c *Conn) { + st, err := queryVMStatus(c) + if err != nil || st.Running { + return + } + // Only resume when QEMU is still in ordinary paused state (never postmigrate). + if st.Status == "paused" { + _ = c.ExecuteWithTimeout("cont", nil, 10*time.Second) + } +} + +func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgress)) error { + deadline := time.Now().Add(migrateTotalTimeout) + for { + if err := ctx.Err(); err != nil { + return err + } + if time.Now().After(deadline) { + return errors.New("timed out waiting for migration to finish") + } + raw, err := c.QueryWithTimeout("query-migrate", nil, migrateCmdTimeout) + if err != nil { + return err + } + var info migrateInfo + if err := json.Unmarshal(raw, &info); err != nil { + return fmt.Errorf("parse query-migrate: %w", err) + } + prog := MigrateProgress{ + Status: info.Status, + TotalTimeMs: info.TotalTimeMs, + } + if info.RAM != nil { + prog.Transferred = info.RAM.Transferred + prog.Remaining = info.RAM.Remaining + prog.Total = info.RAM.Total + } + if onProgress != nil { + onProgress(prog) + } + switch info.Status { + case "completed": + return nil + case "failed", "cancelled": + desc := strings.TrimSpace(info.ErrorDesc) + if desc != "" { + return fmt.Errorf("migration %s: %s", info.Status, desc) + } + return fmt.Errorf("migration %s", info.Status) + } + sleep(ctx, migratePollInterval) + } +} + +func dialMigrateConnWithRetry(ctx context.Context, network, addr string, timeout time.Duration) (*Conn, error) { + deadline := time.Now().Add(timeout) + var lastErr error + for { + c, err := Dial(ctx, network, addr) + if err == nil { + return c, nil + } + lastErr = err + if ctx.Err() != nil || time.Now().After(deadline) { + return nil, lastErr + } + sleep(ctx, 100*time.Millisecond) + } +} + +func isConnClosedErr(err error) bool { + if err == nil { + return false + } + s := strings.ToLower(err.Error()) + return strings.Contains(s, "connection closed") || strings.Contains(s, "eof") || strings.Contains(s, "wsarecv") || strings.Contains(s, "broken pipe") +} diff --git a/internal/qmp/migrate_test.go b/internal/qmp/migrate_test.go new file mode 100644 index 0000000..0c863d2 --- /dev/null +++ b/internal/qmp/migrate_test.go @@ -0,0 +1,229 @@ +package qmp + +import ( + "bufio" + "context" + "encoding/json" + "net" + "strings" + "sync" + "testing" +) + +type mockQMPReq struct { + Execute string `json:"execute"` + Arguments json.RawMessage `json:"arguments"` +} + +func startMockQMP(t *testing.T, handle func(req mockQMPReq) (reply map[string]any, closeAfter bool)) (string, func() []mockQMPReq) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen mock QMP: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + + var mu sync.Mutex + var recorded []mockQMPReq + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func(nc net.Conn) { + defer nc.Close() + _, _ = nc.Write([]byte(`{"QMP":{"version":{"qemu":{"major":9,"minor":2,"micro":0}},"capabilities":[]}}` + "\n")) + sc := bufio.NewScanner(nc) + for sc.Scan() { + var req mockQMPReq + if err := json.Unmarshal(sc.Bytes(), &req); err != nil { + return + } + if req.Execute == "qmp_capabilities" { + _, _ = nc.Write([]byte(`{"return":{}}` + "\n")) + continue + } + mu.Lock() + recorded = append(recorded, req) + mu.Unlock() + reply, closeAfter := handle(req) + if reply != nil { + b, _ := json.Marshal(reply) + _, _ = nc.Write(append(b, '\n')) + } + if closeAfter { + return + } + } + }(conn) + } + }() + return ln.Addr().String(), func() []mockQMPReq { + mu.Lock() + defer mu.Unlock() + return append([]mockQMPReq(nil), recorded...) + } +} + +func TestSuspendToFileHappyPath(t *testing.T) { + polls := 0 + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "stop", "migrate-set-capabilities", "migrate-set-parameters", "migrate": + return map[string]any{"return": map[string]any{}}, false + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + case "query-migrate": + polls++ + if polls == 1 { + return map[string]any{"return": map[string]any{ + "status": "active", + "ram": map[string]any{"transferred": 1024, "remaining": 1024, "total": 2048}, + }}, false + } + return map[string]any{"return": map[string]any{ + "status": "completed", + "total-time": 4500, + "ram": map[string]any{"transferred": 2048, "remaining": 0, "total": 2048}, + }}, false + case "quit": + return map[string]any{"return": map[string]any{}}, true + default: + t.Errorf("unexpected QMP command: %s", req.Execute) + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + var progress []MigrateProgress + if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) { + progress = append(progress, p) + }); err != nil { + t.Fatalf("suspendToFileConn: %v", err) + } + if len(progress) != 2 || progress[1].Status != "completed" { + t.Fatalf("unexpected progress: %+v", progress) + } + got := cmds() + var names []string + for _, r := range got { + names = append(names, r.Execute) + } + want := "stop,query-status,migrate-set-capabilities,migrate-set-parameters,migrate,query-migrate,query-migrate,quit" + if strings.Join(names, ",") != want { + t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want) + } +} + +func TestSuspendToFileFailureResumesPausedVM(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "stop", "migrate-set-capabilities", "migrate-set-parameters", "cont": + return map[string]any{"return": map[string]any{}}, false + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + case "migrate": + return map[string]any{"error": map[string]any{"class": "GenericError", "desc": "disk full"}}, false + default: + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil) + if err == nil || !strings.Contains(err.Error(), "disk full") { + t.Fatalf("expected disk full error, got %v", err) + } + var sawCont bool + for _, r := range cmds() { + if r.Execute == "cont" { + sawCont = true + } + if r.Execute == "quit" { + t.Fatal("must not quit QEMU when migrate fails") + } + } + if !sawCont { + t.Fatal("expected cont rollback when migrate fails while paused") + } +} + +func TestResumeFromFileHappyPath(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming", "cont": + return map[string]any{"return": map[string]any{}}, false + case "query-migrate": + return map[string]any{"return": map[string]any{"status": "completed", "total-time": 1900}}, false + default: + t.Errorf("unexpected QMP command: %s", req.Execute) + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + if err := resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil); err != nil { + t.Fatalf("resumeFromFileConn: %v", err) + } + got := cmds() + var names []string + var sawExitOnErrorFalse bool + for _, r := range got { + names = append(names, r.Execute) + if r.Execute == "migrate-incoming" && strings.Contains(string(r.Arguments), `"exit-on-error":false`) { + sawExitOnErrorFalse = true + } + } + want := "migrate-set-capabilities,migrate-set-parameters,migrate-incoming,query-migrate,cont" + if strings.Join(names, ",") != want { + t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want) + } + if !sawExitOnErrorFalse { + t.Fatal("expected migrate-incoming to pass exit-on-error:false") + } +} + +func TestResumeFromFileFailedDoesNotCont(t *testing.T) { + addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming": + return map[string]any{"return": map[string]any{}}, false + case "query-migrate": + return map[string]any{"return": map[string]any{"status": "failed", "error-desc": "corrupt RVGSNAP1 snapshot"}}, false + default: + return map[string]any{"return": map[string]any{}}, false + } + }) + + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatalf("Dial: %v", err) + } + defer c.Close() + + err = resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil) + if err == nil || !strings.Contains(err.Error(), "corrupt RVGSNAP1 snapshot") { + t.Fatalf("expected corrupt snapshot error, got %v", err) + } + for _, r := range cmds() { + if r.Execute == "cont" { + t.Fatal("must not issue cont when restore failed") + } + } +} diff --git a/internal/runtime/kinds.go b/internal/runtime/kinds.go index 97eeeb7..cf09333 100644 --- a/internal/runtime/kinds.go +++ b/internal/runtime/kinds.go @@ -152,6 +152,7 @@ func (m Manifest) EffectiveCapabilities() []string { for _, c := range m.Capabilities { add(c) } + var hasWin32MappedRAM, hasIntelWHPXSuspend, hasVGPUSnapshotReplay bool for _, p := range m.Patches { low := strings.ToLower(p.Name) switch { @@ -169,8 +170,17 @@ func (m Manifest) EffectiveCapabilities() []string { } case strings.Contains(low, "display-fixed-mode"): add("display-fixed-mode") + case strings.Contains(low, "win32-mapped-ram-io"): + hasWin32MappedRAM = true + case strings.Contains(low, "intel-whpx-suspend"): + hasIntelWHPXSuspend = true + case strings.Contains(low, "reims-vgpu-snapshot-replay"): + hasVGPUSnapshotReplay = true } } + if hasWin32MappedRAM && hasIntelWHPXSuspend && hasVGPUSnapshotReplay { + add("vm-suspend") + } return out } diff --git a/internal/runtime/kinds_test.go b/internal/runtime/kinds_test.go index 9e5bffd..2f2422b 100644 --- a/internal/runtime/kinds_test.go +++ b/internal/runtime/kinds_test.go @@ -85,6 +85,41 @@ func TestKindRegistryAndCapabilities(t *testing.T) { t.Fatalf("%s: HasCapability(win32-unicode-input) = %v, want %v", tc.name, got, tc.want) } } + + // vm-suspend requires all three runtime pieces (Win32 mapped-ram I/O, Intel WHPX suspend, + // and vGPU snapshot replay) unless explicitly declared in Capabilities. + for _, tc := range []struct { + name string + m Manifest + want bool + }{ + { + name: "partial-suspend-patches", + m: Manifest{Patches: []Patch{ + {Name: "qemu-win32-mapped-ram-io.patch"}, + {Name: "qemu-intel-whpx-suspend.patch"}, + }}, + want: false, + }, + { + name: "all-suspend-patches", + m: Manifest{Patches: []Patch{ + {Name: "qemu-win32-mapped-ram-io.patch"}, + {Name: "qemu-intel-whpx-suspend.patch"}, + {Name: "reims-vgpu-snapshot-replay.patch"}, + }}, + want: true, + }, + { + name: "explicit-vm-suspend-capability", + m: Manifest{Capabilities: []string{"vm-suspend"}}, + want: true, + }, + } { + if got := tc.m.HasCapability("vm-suspend"); got != tc.want { + t.Fatalf("%s: HasCapability(vm-suspend) = %v, want %v", tc.name, got, tc.want) + } + } } func TestMultiKindCoexistenceAndCompatibility(t *testing.T) { diff --git a/internal/tray/tray.go b/internal/tray/tray.go index a13a046..4523320 100644 --- a/internal/tray/tray.go +++ b/internal/tray/tray.go @@ -25,9 +25,10 @@ func (v VMItem) title() string { // Snapshot holds the live state read each time the user opens the tray menu. type Snapshot struct { - Locale i18n.Locale - LocaleZh bool // legacy fallback when Locale is empty - VMs []VMItem + Locale i18n.Locale + LocaleZh bool // legacy fallback when Locale is empty + CanSuspend bool + VMs []VMItem } // Action is a per-VM command picked from the tray menu. @@ -43,6 +44,9 @@ const ( ActSharedFolder ActOpenInApp ActToggleFullscreen + ActSuspend + ActResume + ActDiscardSuspend ) // Callbacks wires tray actions back into the Wails application. Each runs @@ -72,6 +76,7 @@ const ( dotNone dotKind = iota dotRunning dotStopped + dotSuspended dotBusy dotBroken ) @@ -91,8 +96,11 @@ type menuEntry struct { type texts struct { show, newVM, quit string start, stop, forceStop, restart, showWindow, shot string + suspend, resume, discardSuspend string shared, openInApp string - running, stopped, starting, stopping, broken, unknown string + running, stopped, suspended string + starting, stopping, suspending, resuming string + broken, unknown string toggleFullscreen string } @@ -107,23 +115,29 @@ func menuTexts(snap Snapshot) texts { } } return texts{ - show: i18n.T(loc, "tray.menu.show"), - newVM: i18n.T(loc, "tray.menu.new_vm"), - quit: i18n.T(loc, "tray.menu.quit"), - start: i18n.T(loc, "tray.menu.start"), - stop: i18n.T(loc, "tray.menu.stop"), - forceStop: i18n.T(loc, "tray.menu.force_stop"), - restart: i18n.T(loc, "tray.menu.restart"), - showWindow: i18n.T(loc, "tray.menu.show_window"), - shot: i18n.T(loc, "tray.menu.screenshot"), - shared: i18n.T(loc, "tray.menu.shared_folder"), - openInApp: i18n.T(loc, "tray.menu.open_in_app"), - running: i18n.T(loc, "tray.state.running"), - stopped: i18n.T(loc, "tray.state.stopped"), - starting: i18n.T(loc, "tray.state.starting"), - stopping: i18n.T(loc, "tray.state.stopping"), - broken: i18n.T(loc, "tray.state.broken"), - unknown: i18n.T(loc, "tray.state.unknown"), + show: i18n.T(loc, "tray.menu.show"), + newVM: i18n.T(loc, "tray.menu.new_vm"), + quit: i18n.T(loc, "tray.menu.quit"), + start: i18n.T(loc, "tray.menu.start"), + stop: i18n.T(loc, "tray.menu.stop"), + forceStop: i18n.T(loc, "tray.menu.force_stop"), + restart: i18n.T(loc, "tray.menu.restart"), + suspend: i18n.T(loc, "tray.menu.suspend"), + resume: i18n.T(loc, "tray.menu.resume"), + discardSuspend: i18n.T(loc, "tray.menu.discard_suspend"), + showWindow: i18n.T(loc, "tray.menu.show_window"), + shot: i18n.T(loc, "tray.menu.screenshot"), + shared: i18n.T(loc, "tray.menu.shared_folder"), + openInApp: i18n.T(loc, "tray.menu.open_in_app"), + running: i18n.T(loc, "tray.state.running"), + stopped: i18n.T(loc, "tray.state.stopped"), + suspended: i18n.T(loc, "tray.state.suspended"), + starting: i18n.T(loc, "tray.state.starting"), + stopping: i18n.T(loc, "tray.state.stopping"), + suspending: i18n.T(loc, "tray.state.suspending"), + resuming: i18n.T(loc, "tray.state.resuming"), + broken: i18n.T(loc, "tray.state.broken"), + unknown: i18n.T(loc, "tray.state.unknown"), toggleFullscreen: i18n.T(loc, "tray.menu.toggle_fullscreen"), } @@ -138,7 +152,7 @@ func decodeVMCmd(id int) (int, Action, bool) { } off := id - cmdVMBase act := Action(off % vmSlot) - if act < ActStart || act > ActToggleFullscreen { + if act < ActStart || act > ActDiscardSuspend { return 0, 0, false } return off / vmSlot, act, true @@ -174,13 +188,34 @@ func buildMenu(snap Snapshot) []menuEntry { sub = []menuEntry{ show, cmd(ActToggleFullscreen, t.toggleFullscreen), cmd(ActScreenshot, t.shot), cmd(ActSharedFolder, t.shared), sep, + } + if snap.CanSuspend { + sub = append(sub, cmd(ActSuspend, t.suspend)) + } + sub = append(sub, cmd(ActRestart, t.restart), cmd(ActStop, t.stop), cmd(ActForceStop, t.forceStop), sep, cmd(ActOpenInApp, t.openInApp), + ) + case "suspended": + dot, state = dotSuspended, t.suspended + resume := cmd(ActResume, t.resume) + resume.Default = true + sub = []menuEntry{ + resume, cmd(ActDiscardSuspend, t.discardSuspend), sep, + cmd(ActSharedFolder, t.shared), sep, + cmd(ActOpenInApp, t.openInApp), } - case "starting", "stopping": - dot, state = dotBusy, t.starting - if vm.State == "stopping" { + case "starting", "stopping", "suspending", "resuming": + dot = dotBusy + switch vm.State { + case "stopping": state = t.stopping + case "suspending": + state = t.suspending + case "resuming": + state = t.resuming + default: + state = t.starting } sub = []menuEntry{cmd(ActForceStop, t.forceStop), sep, cmd(ActOpenInApp, t.openInApp)} case "broken": @@ -209,6 +244,8 @@ func dotPixels(size int, kind dotKind) []byte { switch kind { case dotRunning: r, g, b = 0x30, 0xD1, 0x58 + case dotSuspended: + r, g, b = 0xFF, 0x9F, 0x0A case dotBusy: r, g, b = 0xFF, 0x9F, 0x0A case dotBroken: @@ -219,12 +256,49 @@ func dotPixels(size int, kind dotKind) []byte { return px } c := float64(size) / 2 + const ss = 4 // 4×4 supersampling for smooth edges + if kind == dotSuspended { + halfH := float64(size) * 0.28 + barW := maxf(1.8, float64(size)*0.15) + gap := maxf(1.2, float64(size)*0.12) + for y := 0; y < size; y++ { + for x := 0; x < size; x++ { + hits := 0 + for sy := 0; sy < ss; sy++ { + for sx := 0; sx < ss; sx++ { + dx := float64(x) + (float64(sx)+0.5)/ss - c + dy := float64(y) + (float64(sy)+0.5)/ss - c + adx := dx + if adx < 0 { + adx = -adx + } + ady := dy + if ady < 0 { + ady = -ady + } + if ady <= halfH && adx >= gap/2 && adx <= gap/2+barW { + hits++ + } + } + } + if hits == 0 { + continue + } + a := hits * 255 / (ss * ss) + off := (y*size + x) * 4 + px[off+0] = uint8(int(b) * a / 255) + px[off+1] = uint8(int(g) * a / 255) + px[off+2] = uint8(int(r) * a / 255) + px[off+3] = uint8(a) + } + } + return px + } outer := float64(size) * 0.28 // dot diameter ≈ 56% of the check-mark cell inner := 0.0 if kind == dotStopped { inner = outer - maxf(1.4, float64(size)*0.09) } - const ss = 4 // 4×4 supersampling for smooth edges for y := 0; y < size; y++ { for x := 0; x < size; x++ { hits := 0 diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go index 7365594..ced0237 100644 --- a/internal/tray/tray_test.go +++ b/internal/tray/tray_test.go @@ -18,10 +18,11 @@ func findEntry(entries []menuEntry, label string) *menuEntry { } func TestBuildMenuPerState(t *testing.T) { - menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{ + menu := buildMenu(Snapshot{LocaleZh: true, CanSuspend: true, VMs: []VMItem{ {Name: "macos-tahoe", Label: "日常", State: "running"}, {Name: "macos-dev", State: "stopped"}, {Name: "macos-busy", State: "starting"}, + {Name: "macos-sleep", State: "suspended"}, }}) if !menu[0].Default || menu[0].ID != cmdShow { t.Fatalf("first item should be the default Show, got %+v", menu[0]) @@ -40,6 +41,15 @@ func TestBuildMenuPerState(t *testing.T) { if len(run.Sub) < 2 || run.Sub[1].ID != vmCmd(0, ActToggleFullscreen) || run.Sub[1].Label != "切换全屏" || run.Sub[1].Default { t.Fatalf("running VM should offer Toggle Fullscreen after Show Window: %+v", run.Sub) } + var hasSuspend bool + for _, e := range run.Sub { + if e.ID == vmCmd(0, ActSuspend) { + hasSuspend = true + } + } + if !hasSuspend { + t.Fatalf("running VM with CanSuspend should offer Suspend: %+v", run.Sub) + } stop := findEntry(menu, "macos-dev\t已停止") if stop == nil || stop.Dot != dotStopped || stop.Sub[0].ID != vmCmd(1, ActStart) || !stop.Sub[0].Default { @@ -55,18 +65,23 @@ func TestBuildMenuPerState(t *testing.T) { if busy == nil || busy.Dot != dotBusy || busy.Sub[0].ID != vmCmd(2, ActForceStop) { t.Fatalf("starting VM should only offer force stop first: %+v", busy) } + + susp := findEntry(menu, "macos-sleep\t已挂起") + if susp == nil || susp.Dot != dotSuspended || susp.Sub[0].ID != vmCmd(3, ActResume) || !susp.Sub[0].Default { + t.Fatalf("suspended VM should default to Resume: %+v", susp) + } } func TestDecodeVMCmdRoundTrip(t *testing.T) { for i := 0; i < maxTrayVMs; i++ { - for act := ActStart; act <= ActToggleFullscreen; act++ { + for act := ActStart; act <= ActDiscardSuspend; act++ { gi, ga, ok := decodeVMCmd(vmCmd(i, act)) if !ok || gi != i || ga != act { t.Fatalf("vmCmd(%d,%d) decoded to (%d,%d,%v)", i, act, gi, ga, ok) } } } - for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActToggleFullscreen+1), cmdVMBase + maxTrayVMs*vmSlot} { + for _, id := range []int{cmdShow, cmdQuit, cmdNewVM, cmdVMBase, vmCmd(0, ActDiscardSuspend+1), cmdVMBase + maxTrayVMs*vmSlot} { if _, _, ok := decodeVMCmd(id); ok { t.Fatalf("id %d should not decode as a VM command", id) } @@ -84,9 +99,15 @@ func TestDotPixels(t *testing.T) { if alpha(ring, size/2, size/2) != 0 { t.Fatal("stopped dot should be a ring with a clear centre") } - for i := 0; i < len(run); i += 4 { - if run[i] > run[i+3] || run[i+1] > run[i+3] || run[i+2] > run[i+3] { - t.Fatal("pixels must be premultiplied (colour ≤ alpha)") + paused := dotPixels(size, dotSuspended) + if alpha(paused, 0, 0) != 0 || alpha(paused, size/2-2, size/2) == 0 || alpha(paused, size/2+2, size/2) == 0 { + t.Fatal("suspended mark should draw two visible vertical pause bars") + } + for _, buf := range [][]byte{run, paused} { + for i := 0; i < len(buf); i += 4 { + if buf[i] > buf[i+3] || buf[i+1] > buf[i+3] || buf[i+2] > buf[i+3] { + t.Fatal("pixels must be premultiplied (colour ≤ alpha)") + } } } } diff --git a/internal/vmstart/vmstart.go b/internal/vmstart/vmstart.go index 6f85da2..6250d60 100644 --- a/internal/vmstart/vmstart.go +++ b/internal/vmstart/vmstart.go @@ -147,6 +147,11 @@ func waitForCommitMemory( // language preset and the WHPX nested-virtualization fallback. cur is updated // to match what was written through `reims-ctl set`. func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { + if stripped := reims.StripIncomingDeferArgs(cur.ExtraArgs); stripped != cur.ExtraArgs { + if err := p.setExtraArgs(ctx, name, stripped); err == nil { + cur.ExtraArgs = stripped + } + } p.syncOfflineHelper(ctx, name, cur) p.syncRecoveryBootPicker(ctx, name, cur) p.ReplayGuestLang(ctx, cur.Directory) diff --git a/locales/en-US/native.json b/locales/en-US/native.json index a39e657..0b80880 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -407,6 +407,9 @@ "tray.menu.new_vm": "&New Virtual Machine…", "tray.menu.quit": "&Quit Reims-Go", "tray.menu.start": "&Start", + "tray.menu.suspend": "Sus&pend", + "tray.menu.resume": "Res&ume", + "tray.menu.discard_suspend": "Discard Saved Stat&e", "tray.menu.stop": "Shut &Down", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.restart": "&Restart", @@ -417,8 +420,11 @@ "tray.menu.open_in_app": "Show in &Reims-Go", "tray.state.running": "Running", "tray.state.stopped": "Stopped", + "tray.state.suspended": "Suspended", "tray.state.starting": "Starting…", "tray.state.stopping": "Shutting down…", + "tray.state.suspending": "Suspending…", + "tray.state.resuming": "Resuming…", "tray.state.broken": "Broken", "tray.state.unknown": "Unknown", "tray.notify.start_fail": { @@ -427,6 +433,24 @@ "name" ] }, + "tray.notify.suspend_fail": { + "message": "Couldn't suspend {name}", + "$params": [ + "name" + ] + }, + "tray.notify.resume_fail": { + "message": "Couldn't resume {name}", + "$params": [ + "name" + ] + }, + "tray.notify.discard_suspend_fail": { + "message": "Couldn't discard saved state for {name}", + "$params": [ + "name" + ] + }, "tray.notify.stop_fail": { "message": "Couldn't shut down {name}", "$params": [ @@ -820,6 +844,9 @@ "cli.usage.cmd_vm_compact": " vm compact Compact stopped .qcow2 disk to reclaim unused space", "cli.usage.cmd_vm_start": " vm start Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process", "cli.usage.cmd_vm_stop": " vm stop|eject Stop / eject installer", + "cli.usage.cmd_vm_suspend": " vm suspend Suspend a running VM to disk for fast resume across restarts", + "cli.usage.cmd_vm_resume": " vm resume Resume a suspended VM from disk", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend Discard a saved suspend state and return the VM to powered off", "cli.usage.cmd_vm_type": " vm type [text] Type text into a running VM as US-keyboard keys (stdin if no text)", "cli.usage.cmd_inst_list": " installer list List offline macOS installers Apple offers (needs network)", "cli.usage.cmd_inst_dl": " installer download Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)", @@ -954,6 +981,51 @@ }, "core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically", "validate.invalid_guest_lang": "Invalid guest language code (expected format like zh-Hans:0 or en-US:0)", + "validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings", + "err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support", + "err.suspend.busy": { + "message": "VM “{name}” is busy transitioning; try again in a moment", + "$params": [ + "name" + ] + }, + "err.suspend.not_running": { + "message": "VM “{name}” is not running and cannot be suspended", + "$params": [ + "name" + ] + }, + "err.suspend.disk_space": { + "message": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)", + "$params": [ + "need", + "avail" + ] + }, + "err.suspend.not_found": { + "message": "No complete suspend state found for “{name}”", + "$params": [ + "name" + ] + }, + "err.suspend.incompatible": { + "message": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state", + "$params": [ + "diffs" + ] + }, + "err.suspend.discard_running": { + "message": "VM “{name}” is currently running; suspend state cannot be discarded", + "$params": [ + "name" + ] + }, + "err.suspend.action_blocked": { + "message": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this", + "$params": [ + "name" + ] + }, "err.dataroot.busy_vms": "Stop all running virtual machines before switching the data folder", "err.dataroot.busy_tasks": "Wait for active download or creation tasks to finish before switching the data folder", "font.script.zh_hant": "Traditional Chinese (繁體中文)", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index b3b8382..f5bfc2c 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -43,9 +43,28 @@ "fieldVMName": "VM name", "state_running": "Running", "state_stopped": "Stopped", + "state_suspended": "Suspended", "state_starting": "Starting", "state_stopping": "Stopping", + "state_suspending": "Suspending", + "state_resuming": "Resuming", "state_broken": "Error", + "suspend": "Suspend", + "resume": "Resume", + "discardSuspend": "Discard saved state", + "discardSuspendTitle": "Discard saved state for “{name}”?", + "discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.", + "discardSuspendConfirm": "Discard & Power Off", + "suspendedNoticeTitle": "Saved state ready", + "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", + "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", + "suspendedSettingsHint": "Resume or discard saved state before changing settings", + "toastSuspended": "{name} suspended", + "toastResumed": "{name} resumed", + "toastDiscardSuspend": "Discarded saved state for {name}", + "failSuspend": "Couldn’t suspend", + "failResume": "Couldn’t resume", + "failDiscardSuspend": "Couldn’t discard saved state", "pendingTitle": "Applies on next start", "restartToApply": "Restart to apply", "guideTitle": "Recovery mode", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index ca93bef..b36a181 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -407,6 +407,9 @@ "tray.menu.new_vm": "新建虚拟机(&N)…", "tray.menu.quit": "退出 Reims-Go(&Q)", "tray.menu.start": "启动(&S)", + "tray.menu.suspend": "挂起(&P)", + "tray.menu.resume": "恢复(&U)", + "tray.menu.discard_suspend": "放弃挂起状态(&X)", "tray.menu.stop": "关机(&D)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.restart": "重启(&R)", @@ -417,8 +420,11 @@ "tray.menu.open_in_app": "在 Reims-Go 中查看(&V)", "tray.state.running": "运行中", "tray.state.stopped": "已停止", + "tray.state.suspended": "已挂起", "tray.state.starting": "启动中…", "tray.state.stopping": "正在关机…", + "tray.state.suspending": "正在挂起…", + "tray.state.resuming": "正在恢复…", "tray.state.broken": "配置损坏", "tray.state.unknown": "未知", "tray.notify.start_fail": { @@ -427,6 +433,24 @@ "name" ] }, + "tray.notify.suspend_fail": { + "message": "无法挂起 {name}", + "$params": [ + "name" + ] + }, + "tray.notify.resume_fail": { + "message": "无法恢复 {name}", + "$params": [ + "name" + ] + }, + "tray.notify.discard_suspend_fail": { + "message": "无法放弃 {name} 的挂起状态", + "$params": [ + "name" + ] + }, "tray.notify.stop_fail": { "message": "无法关机 {name}", "$params": [ @@ -820,6 +844,9 @@ "cli.usage.cmd_vm_compact": " vm compact 停机回收 .qcow2 磁盘未用空间", "cli.usage.cmd_vm_start": " vm start 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动", "cli.usage.cmd_vm_stop": " vm stop|eject 停止 / 弹出安装盘", + "cli.usage.cmd_vm_suspend": " vm suspend 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)", + "cli.usage.cmd_vm_resume": " vm resume 从磁盘挂起状态恢复虚拟机", + "cli.usage.cmd_vm_discard_suspend": " vm discard-suspend 放弃已保存的挂起状态并回到关机状态", "cli.usage.cmd_vm_type": " vm type [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)", "cli.usage.cmd_inst_list": " installer list 列出 Apple 提供的离线安装包版本(需联网)", "cli.usage.cmd_inst_dl": " installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)", @@ -954,6 +981,51 @@ }, "core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数", "validate.invalid_guest_lang": "客户机系统语言标识格式无效(如 zh-Hans:0、en-US:0)", + "validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置", + "err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本", + "err.suspend.busy": { + "message": "虚拟机「{name}」正在执行状态切换,请稍后再试", + "$params": [ + "name" + ] + }, + "err.suspend.not_running": { + "message": "虚拟机「{name}」未在运行,无法挂起", + "$params": [ + "name" + ] + }, + "err.suspend.disk_space": { + "message": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)", + "$params": [ + "need", + "avail" + ] + }, + "err.suspend.not_found": { + "message": "未找到「{name}」的完整挂起状态文件", + "$params": [ + "name" + ] + }, + "err.suspend.incompatible": { + "message": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动", + "$params": [ + "diffs" + ] + }, + "err.suspend.discard_running": { + "message": "虚拟机「{name}」正在运行,无法放弃挂起状态", + "$params": [ + "name" + ] + }, + "err.suspend.action_blocked": { + "message": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作", + "$params": [ + "name" + ] + }, "err.dataroot.busy_vms": "仍有虚拟机正在运行,请先全部关机后再切换数据目录", "err.dataroot.busy_tasks": "仍有后台下载或创建任务进行中,请等待任务结束或取消后再切换数据目录", "font.script.zh_hant": "繁体中文(繁體中文)", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index c50d9cf..3a68042 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -43,9 +43,28 @@ "fieldVMName": "虚拟机名称", "state_running": "运行中", "state_stopped": "已停止", + "state_suspended": "已挂起", "state_starting": "启动中", "state_stopping": "停止中", + "state_suspending": "挂起中", + "state_resuming": "恢复中", "state_broken": "出错", + "suspend": "挂起", + "resume": "恢复", + "discardSuspend": "放弃挂起状态", + "discardSuspendTitle": "放弃「{name}」的挂起状态?", + "discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。", + "discardSuspendConfirm": "放弃并关机", + "suspendedNoticeTitle": "已保存运行状态", + "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", + "suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置", + "toastSuspended": "{name} 已挂起", + "toastResumed": "{name} 已恢复", + "toastDiscardSuspend": "已放弃 {name} 的挂起状态", + "failSuspend": "挂起失败", + "failResume": "恢复失败", + "failDiscardSuspend": "放弃挂起状态失败", "pendingTitle": "下次启动生效", "restartToApply": "重启以应用", "guideTitle": "恢复模式", From 552d6e4cada0822749577053343b88296f42f41f Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:06:43 +0800 Subject: [PATCH 07/23] fix(guesttools): confine sync to the current shared folders --- internal/guesttools/file_sync.go | 164 ++++++++++++------ internal/guesttools/file_sync.sh | 12 +- .../guesttools/file_sync_identity_other.go | 12 ++ .../guesttools/file_sync_identity_unix.go | 18 ++ .../guesttools/file_sync_identity_windows.go | 16 ++ internal/guesttools/file_sync_test.go | 59 ++++++- 6 files changed, 223 insertions(+), 58 deletions(-) create mode 100644 internal/guesttools/file_sync_identity_other.go create mode 100644 internal/guesttools/file_sync_identity_unix.go create mode 100644 internal/guesttools/file_sync_identity_windows.go diff --git a/internal/guesttools/file_sync.go b/internal/guesttools/file_sync.go index 76ba4d8..ad6733d 100644 --- a/internal/guesttools/file_sync.go +++ b/internal/guesttools/file_sync.go @@ -1,6 +1,7 @@ package guesttools import ( + "crypto/rand" "crypto/sha256" "errors" "fmt" @@ -8,6 +9,7 @@ import ( "io/fs" "net/http" "os" + "path" "path/filepath" "sort" "strconv" @@ -20,8 +22,38 @@ const ( syncDigestHeader = "X-Reims-File-SHA256" ) -func syncFileScope(token, root string) string { - return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root))) +func syncFileScope(token string, root *os.Root) (string, error) { + // A replacement directory at the same path must start fresh sync history. + dir, err := root.Open(".") + if err != nil { + return "", err + } + defer dir.Close() + id, err := sharedDirectoryID(dir) + if err != nil { + return "", err + } + return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root.Name()+"\n"+id))), nil +} + +func openSharedRoot(dir string) (*os.Root, error) { + info, err := os.Lstat(dir) + if err != nil { + return nil, err + } + if !info.IsDir() { + return nil, fs.ErrInvalid + } + root, err := os.OpenRoot(dir) + if err != nil { + return nil, err + } + opened, err := root.Stat(".") + if err != nil || !os.SameFile(info, opened) { + _ = root.Close() + return nil, errors.New("shared directory changed") + } + return root, nil } func syncFileTag(info fs.FileInfo) string { @@ -73,27 +105,38 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { } return } - root, err := filepath.Abs(vm.sharedDir) + dir, err := filepath.Abs(vm.sharedDir) if err != nil { http.Error(w, "shared directory unavailable", http.StatusInternalServerError) return } if !versioned { - if err := os.MkdirAll(root, 0o755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } + root, err := openSharedRoot(dir) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + defer root.Close() + var scope string + if versioned { + scope, err = syncFileScope(vm.token, root) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + } type entry struct { name string info fs.FileInfo } var files []entry - err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { - if p == root { - if versioned && err == nil && !d.IsDir() { - return fs.ErrInvalid - } + err = fs.WalkDir(root.FS(), ".", func(name string, d fs.DirEntry, err error) error { + if name == "." { return err } if err != nil { @@ -105,11 +148,6 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { } return nil } - rel, err := filepath.Rel(root, p) - if err != nil { - return nil - } - name := filepath.ToSlash(rel) if strings.Count(name, "/")+1 > MaxSharedDepth { if d.IsDir() { return filepath.SkipDir @@ -134,7 +172,7 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) { http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) return } - w.Header().Set(syncScopeHeader, syncFileScope(vm.token, root)) + w.Header().Set(syncScopeHeader, scope) } sort.Slice(files, func(i, j int) bool { return files[i].name < files[j].name }) w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8") @@ -165,23 +203,49 @@ func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) { return } scope := r.Header.Get(syncScopeHeader) - if scope != "" && (!validSyncFileName(rawName) || scope != syncFileScope(vm.token, dir)) { - http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed) - return - } + writing := r.Method == http.MethodPut || r.Method == http.MethodPost switch r.Method { case http.MethodHead, http.MethodDelete: if scope == "" { http.Error(w, "sync scope required", http.StatusPreconditionRequired) return } - fallthrough - case http.MethodGet: - s.readSharedFile(w, r, dir, name, scope != "") - case http.MethodPut, http.MethodPost: - s.writeSharedFile(w, r, filepath.Join(dir, filepath.FromSlash(name)), scope != "") + case http.MethodGet, http.MethodPut, http.MethodPost: default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + if scope == "" && writing { + if err := os.MkdirAll(dir, 0o755); err != nil { + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + return + } + } + root, err := openSharedRoot(dir) + if err != nil { + if scope == "" && !writing && errors.Is(err, fs.ErrNotExist) { + http.NotFound(w, r) + } else { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + } + return + } + defer root.Close() + if scope != "" { + current, err := syncFileScope(vm.token, root) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + if !validSyncFileName(rawName) || scope != current { + http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed) + return + } + } + if writing { + s.writeSharedFile(w, r, root, name, scope != "") + } else { + s.readSharedFile(w, r, root, name, scope != "") } } @@ -214,7 +278,7 @@ func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) { return info, err } -func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, name string, versioned bool) { +func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) { deleting := r.Method == http.MethodDelete expectedDigest := r.Header.Get(syncDigestHeader) if deleting && (r.Header.Get("If-Match") == "" || expectedDigest == "") { @@ -222,19 +286,6 @@ func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, nam return } - root, err := os.OpenRoot(dir) - if err != nil { - switch { - case versioned: - http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) - case errors.Is(err, fs.ErrNotExist): - http.NotFound(w, r) - default: - http.Error(w, "shared directory unavailable", http.StatusInternalServerError) - } - return - } - defer root.Close() info, err := statSharedFile(root, name) switch { case errors.Is(err, fs.ErrNotExist): @@ -315,18 +366,19 @@ func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, nam } } -func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, full string, versioned bool) { - dir := filepath.Dir(full) - if err := os.MkdirAll(dir, 0o755); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) +func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) { + dir := path.Dir(name) + if err := root.MkdirAll(dir, 0o755); err != nil { + http.Error(w, "upload directory unavailable", http.StatusInternalServerError) return } - tmp, err := os.CreateTemp(dir, ".reims-upload-*") + tmpName := path.Join(dir, ".reims-upload-"+rand.Text()) + tmp, err := root.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + http.Error(w, "upload file unavailable", http.StatusInternalServerError) return } - defer os.Remove(tmp.Name()) + defer root.Remove(tmpName) h := sha256.New() var dst io.Writer = tmp if versioned { @@ -344,30 +396,34 @@ func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, full st } if ts, err := strconv.ParseInt(r.URL.Query().Get("mtime"), 10, 64); err == nil && ts > 0 { t := time.Unix(ts, 0) - _ = os.Chtimes(tmp.Name(), t, t) + _ = root.Chtimes(tmpName, t, t) } s.fileMu.Lock() defer s.fileMu.Unlock() + info, err := statSharedFile(root, name) + if errors.Is(err, fs.ErrInvalid) { + http.Error(w, "path is not a regular file", http.StatusConflict) + return + } + if err != nil && !errors.Is(err, fs.ErrNotExist) { + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + } var uploadedTag string if versioned { - info, err := os.Lstat(full) - if err != nil && !errors.Is(err, fs.ErrNotExist) { - http.Error(w, "file unavailable", http.StatusInternalServerError) - return - } if !matchSyncFile(r, info) { http.Error(w, "file changed", http.StatusPreconditionFailed) return } - uploaded, err := os.Stat(tmp.Name()) + uploaded, err := root.Stat(tmpName) if err != nil { http.Error(w, "uploaded file unavailable", http.StatusInternalServerError) return } uploadedTag = syncFileTag(uploaded) } - if err := os.Rename(tmp.Name(), full); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + if err := root.Rename(tmpName, name); err != nil { + http.Error(w, "publish uploaded file failed", http.StatusInternalServerError) return } if versioned { diff --git a/internal/guesttools/file_sync.sh b/internal/guesttools/file_sync.sh index f6ecf65..58397ca 100644 --- a/internal/guesttools/file_sync.sh +++ b/internal/guesttools/file_sync.sh @@ -1,7 +1,7 @@ -# Keep confirmed pairs outside the share, scoped to the VM and host directory. +# Keep confirmed pairs scoped to the current shared directories on both sides. sync_files() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 - [ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] || return 0 + sync_guest_root=$(sync_guest_root_id) || return 0 sync_remote="$TMP_DIR/sync-remote.tsv" sync_local="$TMP_DIR/sync-local.tsv" @@ -16,7 +16,7 @@ sync_files() { case "$sync_scope" in "") ;; *[!0-9a-f]*) return 0 ;; - *) sync_state="$APP_DIR/file-sync-$sync_scope.tsv" ;; + *) sync_state="$APP_DIR/file-sync-$sync_scope-$sync_guest_root.tsv" ;; esac sync_previous="$sync_state" [ -f "$sync_state" ] || sync_previous=/dev/null @@ -106,7 +106,13 @@ sync_header() { awk -v name="$1:" 'tolower($1) == tolower(name) { sub(/\r$/, "", $2); print $2; exit }' "$sync_headers" } +sync_guest_root_id() { + [ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] && + stat -f '%d-%i-%B' "$SHARE_SYNC" 2>/dev/null +} + sync_guest_revision() { + [ "$(sync_guest_root_id)" = "$sync_guest_root" ] || return 1 sync_check=$1 while [ "$sync_check" != "$SHARE_SYNC" ]; do [ ! -L "$sync_check" ] || return 1 diff --git a/internal/guesttools/file_sync_identity_other.go b/internal/guesttools/file_sync_identity_other.go new file mode 100644 index 0000000..4c0ec4e --- /dev/null +++ b/internal/guesttools/file_sync_identity_other.go @@ -0,0 +1,12 @@ +//go:build !windows && !unix + +package guesttools + +import ( + "errors" + "os" +) + +func sharedDirectoryID(*os.File) (string, error) { + return "", errors.ErrUnsupported +} diff --git a/internal/guesttools/file_sync_identity_unix.go b/internal/guesttools/file_sync_identity_unix.go new file mode 100644 index 0000000..fa2d0b5 --- /dev/null +++ b/internal/guesttools/file_sync_identity_unix.go @@ -0,0 +1,18 @@ +//go:build unix + +package guesttools + +import ( + "fmt" + "os" + "syscall" +) + +func sharedDirectoryID(dir *os.File) (string, error) { + info, err := dir.Stat() + if err != nil { + return "", err + } + stat := info.Sys().(*syscall.Stat_t) + return fmt.Sprintf("%x:%x", stat.Dev, stat.Ino), nil +} diff --git a/internal/guesttools/file_sync_identity_windows.go b/internal/guesttools/file_sync_identity_windows.go new file mode 100644 index 0000000..5545b15 --- /dev/null +++ b/internal/guesttools/file_sync_identity_windows.go @@ -0,0 +1,16 @@ +package guesttools + +import ( + "fmt" + "os" + "syscall" +) + +func sharedDirectoryID(dir *os.File) (string, error) { + var info syscall.ByHandleFileInformation + if err := syscall.GetFileInformationByHandle(syscall.Handle(dir.Fd()), &info); err != nil { + return "", err + } + return fmt.Sprintf("%x:%08x%08x:%x", info.VolumeSerialNumber, info.FileIndexHigh, + info.FileIndexLow, info.CreationTime.Nanoseconds()), nil +} diff --git a/internal/guesttools/file_sync_test.go b/internal/guesttools/file_sync_test.go index 99b79e1..b6ba2a8 100644 --- a/internal/guesttools/file_sync_test.go +++ b/internal/guesttools/file_sync_test.go @@ -3,11 +3,15 @@ package guesttools import ( "context" "crypto/sha256" + "errors" "fmt" "io" "net/http" + "net/http/httptest" "os" + "os/exec" "path/filepath" + "runtime" "strings" "testing" ) @@ -93,9 +97,62 @@ func TestFileSyncRequiresConfirmedRevisionAndContent(t *testing.T) { conditions.Set(syncDigestHeader, fmt.Sprintf("%x", sha256.Sum256([]byte(got)))) request(http.MethodDelete, fileURL, "", conditions, http.StatusNoContent) request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound) - if err := os.Remove(shared); err != nil { + if err := os.Rename(shared, filepath.Join(root, "old-share")); err != nil { t.Fatal(err) } request(http.MethodGet, "/v1/files?sync=1", "", conditions, http.StatusServiceUnavailable) request(http.MethodHead, fileURL, "", conditions, http.StatusServiceUnavailable) + srv.RegisterVM(cfg) + list, _ = request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK) + newScope := list.Get(syncScopeHeader) + if newScope == "" || newScope == scope { + t.Fatalf("recreated share must have a new scope: %q", newScope) + } + request(http.MethodHead, fileURL, "", conditions, http.StatusPreconditionFailed) + request(http.MethodPut, fileURL, "stale upload", conditions, http.StatusPreconditionFailed) + conditions = http.Header{syncScopeHeader: {newScope}} + request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound) + request(http.MethodPut, "/v1/file?path=nested/file.txt", contents, conditions, http.StatusOK) + _, got = request(http.MethodGet, "/v1/file?path=nested/file.txt", "", conditions, http.StatusOK) + if got != contents { + t.Fatalf("nested file contents: %q", got) + } +} + +func TestFileSyncConfinesUploadToShare(t *testing.T) { + shared, outside := t.TempDir(), t.TempDir() + link := filepath.Join(shared, "linked") + if err := os.Symlink(outside, link); err != nil { + if runtime.GOOS != "windows" { + t.Skipf("directory symlink unavailable: %v", err) + } + output, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput() + if err != nil { + t.Fatalf("create test junction: %v: %s", err, output) + } + } + srv := NewTransportServer(&memClipboard{}) + token := strings.Repeat("a", 64) + srv.RegisterVM(VMConfig{VMName: "sync-test", Token: token, SharedDir: shared}) + list := httptest.NewRequest(http.MethodGet, "/v1/files?sync=1", nil) + list.Header.Set("Authorization", "Bearer "+token) + listed := httptest.NewRecorder() + srv.handleListFiles(listed, list) + scope := listed.Header().Get(syncScopeHeader) + if listed.Code != http.StatusOK || scope == "" { + t.Fatalf("listing failed: %d: %s", listed.Code, listed.Body) + } + for _, version := range []string{"", scope} { + req := httptest.NewRequest(http.MethodPut, "/v1/file?path=linked/upload.txt", strings.NewReader("test upload")) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set(syncScopeHeader, version) + res := httptest.NewRecorder() + srv.handleFile(res, req) + if res.Code < http.StatusBadRequest { + t.Fatalf("upload through an out-of-share link succeeded: %d", res.Code) + } + if _, err := os.Stat(filepath.Join(outside, "upload.txt")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("upload escaped share: %v", err) + } + } } From 790a42912e68d7c66583fd27a4edadad24031c47 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:22:58 +0800 Subject: [PATCH 08/23] fix(installer): expand home paths from reims-ctl show --- internal/config/config.go | 16 ++++++++++++++ internal/driver/reims/reims.go | 5 +++-- internal/driver/reims/reims_test.go | 21 +++++++++++++++++++ internal/installguide/progress.go | 6 +++++- internal/installguide/session_windows_test.go | 15 +++++++++++++ 5 files changed, 60 insertions(+), 3 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 347ea29..fbaae72 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "github.com/Nwflower/reims-go/internal/i18n" ) @@ -53,6 +54,21 @@ func DefaultDataRoot() string { return filepath.Join(home, "reims-go-data") } +// ExpandHomePath resolves a leading ~ for the current user. +func ExpandHomePath(path string) string { + if path != "~" && !strings.HasPrefix(path, "~/") && !strings.HasPrefix(path, `~\`) { + return path + } + home, err := os.UserHomeDir() + if err != nil { + return path + } + if path == "~" { + return home + } + return filepath.Join(home, path[2:]) +} + // CurrentDataRoot is the data folder in effect: REIMS_GO_DATA_ROOT, else the // folder chosen at first launch (LocationPath), else DefaultDataRoot. func CurrentDataRoot() string { diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 17dcc5d..4785cac 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -548,6 +548,7 @@ func parseDisplayCount(v string) int { } // ParseShow parses the text output of `reims-ctl show ` while redacting MAC addresses. +// Paths under the user's home are abbreviated upstream (3731afd, cli.rs:1117,1189-1192). func ParseShow(name, text string) VMDetail { d := VMDetail{ Name: name, @@ -577,7 +578,7 @@ func ParseShow(name, text string) VMDetail { case "kind": d.Kind = v case "directory": - d.Directory = v + d.Directory = config.ExpandHomePath(v) case "cpus": d.CPUs, _ = strconv.Atoi(v) case "memory": @@ -622,7 +623,7 @@ func ParseShow(name, text string) VMDetail { d.HasOpenCore = v != "" case "installer": d.HasInstaller = v != "" && !strings.EqualFold(v, "none") - d.InstallerPath = v + d.InstallerPath = config.ExpandHomePath(v) case "cpu model": d.CPUModel = v case "audio": diff --git a/internal/driver/reims/reims_test.go b/internal/driver/reims/reims_test.go index 3f11d31..e399834 100644 --- a/internal/driver/reims/reims_test.go +++ b/internal/driver/reims/reims_test.go @@ -1,6 +1,7 @@ package reims import ( + "path/filepath" "reflect" "strings" "testing" @@ -63,6 +64,26 @@ func TestParseShowRedactsMACAndDetectsInstaller(t *testing.T) { } } +func TestParseShowExpandsHomeRelativePaths(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + vm := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "vms", "macos-15") + image := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "installers", "macOS-Sequoia-15.7-offline-installer.img") + tilde := "~" + string(filepath.Separator) + d := ParseShow("macos-15", " directory "+tilde+vm+"\n installer "+tilde+image+"\n") + if want := filepath.Join(home, vm); d.Directory != want { + t.Errorf("VM directory = %q, want %q", d.Directory, want) + } + if want := filepath.Join(home, image); !d.HasInstaller || d.InstallerPath != want { + t.Errorf("installer attached = %t, path = %q, want attached at %q", d.HasInstaller, d.InstallerPath, want) + } + d = ParseShow("macos-15", " directory ~\n installer none\n") + if d.Directory != home || d.HasInstaller { + t.Errorf("VM directory = %q, want %q, installer attached = %t, want false", d.Directory, home, d.HasInstaller) + } +} + func TestOfflineCreateTurnsNetworkOff(t *testing.T) { args, err := BuildCreateArgs(CreateOpts{Name: "m1", MacOS: "26.7.3", Offline: true}) if err != nil { diff --git a/internal/installguide/progress.go b/internal/installguide/progress.go index f03ff4e..ca44f8f 100644 --- a/internal/installguide/progress.go +++ b/internal/installguide/progress.go @@ -6,6 +6,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/Nwflower/reims-go/internal/config" ) const progressFile = ".reims-go-install-guide.json" @@ -55,7 +57,9 @@ func (g *Guide) Resume(dir, media string, recovery bool) bool { return recovery } if recovery { - if cp.Kind == g.Kind && strings.EqualFold(cp.Media, media) && cp.Step.recoveryStep(g.Kind) { + // Older checkpoints may contain the abbreviated installer path from show. + sameMedia := strings.EqualFold(config.ExpandHomePath(cp.Media), media) + if cp.Kind == g.Kind && sameMedia && cp.Step.recoveryStep(g.Kind) { g.initial = cp.Step } return true diff --git a/internal/installguide/session_windows_test.go b/internal/installguide/session_windows_test.go index 4e9edef..b6040ff 100644 --- a/internal/installguide/session_windows_test.go +++ b/internal/installguide/session_windows_test.go @@ -2,6 +2,7 @@ package installguide import ( "errors" + "path/filepath" "testing" "time" ) @@ -148,3 +149,17 @@ func TestGuideKeepsMediaAndVMProgressSeparate(t *testing.T) { t.Fatal("clone inherited source disk preparation") } } + +func TestGuideResumesWithExpandedInstallerPath(t *testing.T) { + home := t.TempDir() + t.Setenv("USERPROFILE", home) + dir := t.TempDir() + g := Guide{Name: "macos-15", Kind: Offline, PID: 33} + g.Resume(dir, `~\macOS-15-offline-installer.img`, true) + if err := g.save(command, 0); err != nil { + t.Fatal(err) + } + if !g.Resume(dir, filepath.Join(home, "macOS-15-offline-installer.img"), true) || g.initial != command { + t.Fatalf("guide resumed at %s, want %s", g.initial, command) + } +} From 4cc4b6c02c4a256e80fdf62ac8d66f70dadadad7 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:37:30 +0800 Subject: [PATCH 09/23] fix: make Intel VM suspend and resume transactional --- internal/app/app.go | 47 ++- internal/app/suspend_flow.go | 287 ++++-------------- internal/app/suspend_flow_test.go | 17 +- internal/cli/cli.go | 20 +- internal/cli/start.go | 10 +- internal/cli/suspend.go | 154 ++-------- internal/driver/reims/suspend.go | 65 ++-- internal/driver/reims/suspend_lock_other.go | 26 ++ internal/driver/reims/suspend_lock_windows.go | 39 +++ internal/driver/reims/suspend_test.go | 15 +- internal/driver/reims/suspend_transaction.go | 185 +++++++++++ .../driver/reims/suspend_transaction_test.go | 89 ++++++ internal/qmp/media.go | 59 ++++ internal/qmp/migrate.go | 24 +- internal/qmp/migrate_test.go | 79 ++++- internal/vmstart/suspend.go | 198 ++++++++++++ 16 files changed, 892 insertions(+), 422 deletions(-) create mode 100644 internal/driver/reims/suspend_lock_other.go create mode 100644 internal/driver/reims/suspend_lock_windows.go create mode 100644 internal/driver/reims/suspend_transaction.go create mode 100644 internal/driver/reims/suspend_transaction_test.go create mode 100644 internal/qmp/media.go create mode 100644 internal/vmstart/suspend.go diff --git a/internal/app/app.go b/internal/app/app.go index 310bfdd..048e2eb 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -220,7 +220,7 @@ func (a *App) shutdown(ctx context.Context) { // stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`. // Start, stop and delete call wakePoll so their result shows up at once. const ( - pollBusy = 2 * time.Second + pollBusy = 2 * time.Second // Exits are caught at once by watchExits and GUI actions call wakePoll, so // the steady tick only has to notice VMs started or removed elsewhere (CLI). pollSteady = 10 * time.Second @@ -682,13 +682,17 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) { if err != nil { return d, err } - d.RecoveryMode = isRecoveryModeActive(d) - a.populateGuestToolsDetail(&d) - a.populateGuestLangDetail(&d) - a.populateSuspendDetail(&d) + a.populateVMDetail(&d) return d, nil } +func (a *App) populateVMDetail(d *reims.VMDetail) { + d.RecoveryMode = isRecoveryModeActive(*d) + a.populateGuestToolsDetail(d) + a.populateGuestLangDetail(d) + a.populateSuspendDetail(d) +} + func (a *App) SetLocale(raw string) error { a.mu.Lock() a.cfg.Locale = i18n.ParsePreference(raw) @@ -1091,10 +1095,16 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) { } func (a *App) ApplyVMSettings(opts reims.SetOpts) error { - cur, err := a.GetVMDetail(opts.Name) + c, err := a.client() if err != nil { return err } + cur, release, err := vmstart.LockVM(a.baseCtx(), c, opts.Name) + if err != nil { + return err + } + defer release() + a.populateVMDetail(&cur) a.mu.Lock() root := a.cfg.DataRoot loc := a.cfg.Locale @@ -1102,10 +1112,6 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error { if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 { return fmt.Errorf("%s", issues[0].Message) } - c, err := a.client() - if err != nil { - return err - } w := vmstart.LineWriter(func(line string) { a.emitLog(opts.Name, line) }) if reims.HasCtlSetChanges(opts) { if err := c.Set(context.Background(), opts, w, w); err != nil { @@ -1351,9 +1357,13 @@ func (a *App) StartVM(name string) error { return err } c := prep.Client - curDetail, _ := c.Show(context.Background(), name) + curDetail, release, err := vmstart.LockVM(a.baseCtx(), c, name) + if err != nil { + return err + } + defer release() if curDetail.State == "stopped" && reims.HasSuspendState(curDetail.Directory) { - return a.ResumeVM(name) + return a.resumeLocked(prep, curDetail) } a.mu.Lock() root := a.cfg.DataRoot @@ -1502,6 +1512,11 @@ func (a *App) StopVM(name string, force bool) error { if err != nil { return err } + _, release, err := vmstart.LockVM(a.baseCtx(), c, name) + if err != nil { + return err + } + defer release() a.cancelRebootWatcher(name) stopVMMonitor(name) a.mu.Lock() @@ -1570,6 +1585,14 @@ func (a *App) EjectInstaller(name string) error { if err != nil { return err } + d, release, err := vmstart.LockVM(a.baseCtx(), c, name) + if err != nil { + return err + } + defer release() + if a.isVMSuspended(d) { + return i18n.NewCodedError(a.locale(), "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) + } w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) a.emitLog(name, "Ejecting installer from "+name+"...") if err := c.Eject(context.Background(), name, w, w); err != nil { diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index dc9ee8c..90abdc0 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -1,11 +1,7 @@ package app import ( - "context" "fmt" - "io" - "os" - "strings" "time" "github.com/Nwflower/reims-go/internal/driver/reims" @@ -18,8 +14,6 @@ import ( wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) -// enrichVMListStates overlays state="suspended" onto stopped VMs that have a -// complete suspend snapshot (suspend.vmstate + suspend.json) in their folder. func enrichVMListStates(vms []reims.VMListItem) { for i := range vms { if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) { @@ -29,10 +23,7 @@ func enrichVMListStates(vms []reims.VMListItem) { } func (a *App) populateSuspendDetail(d *reims.VMDetail) { - if d == nil || d.Directory == "" { - return - } - if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) { d.State = "suspended" if info, err := reims.ReadSuspendInfo(d.Directory); err == nil { d.SuspendInfo = info @@ -44,73 +35,33 @@ func (a *App) isVMSuspended(d reims.VMDetail) bool { return d.State == "suspended" || (d.State == "stopped" && reims.HasSuspendState(d.Directory)) } -// SuspendVM pauses a running Intel VM, saves its RAM, CPU, device, and vGPU -// state to suspend.vmstate, and cleanly exits QEMU so the host can close -// Reims-Go or reboot Windows and later resume instantaneously. +// SuspendVM saves a VM's running state and closes its QEMU process. func (a *App) SuspendVM(name string) error { - loc := a.locale() prep, err := a.prep(name) if err != nil { return err } - if !prep.Runtime.Manifest.HasCapability("vm-suspend") { - return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) - } - - a.mu.Lock() - if tr := a.transitions[name]; tr != "" { - a.mu.Unlock() - return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) - } - a.mu.Unlock() - ctx := a.baseCtx() - c := prep.Client - d, err := c.Show(ctx, name) + d, release, err := vmstart.LockVM(ctx, prep.Client, name) if err != nil { return err } - if !a.isVMRunning(ctx, c, name, d) { - return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) + defer release() + end, err := a.beginSuspendTransition(name, "suspending") + if err != nil { + return err } - if d.Directory == "" { - return fmt.Errorf("VM %s has no directory", name) - } - if memGB, ok := reims.ParseSizeGB(d.Memory); ok { - dirRep := host.Inspect(d.Directory) - needGB := memGB + 1.0 - if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { - return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ - "need": fmt.Sprintf("%.1f", needGB), - "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), - }, nil) - } - } - - oldPID := a.cachedVMPID(name) - a.cancelRebootWatcher(name) - stopVMMonitor(name) + defer end() a.mu.Lock() - mgr := a.pluginMgr - gt := a.guestTools - a.transitions[name] = "suspending" + mgr, gt := a.pluginMgr, a.guestTools a.mu.Unlock() + event := plugin.VMEventPayload{VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS} if mgr != nil { - mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{ - VMName: name, - VMDir: d.Directory, - DriverID: builtin.IDDriverReimsMacOS, - }) + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, event) } - a.emitStateChanged() - - tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" - _ = os.Remove(tmpPath) - - a.emitLog(name, fmt.Sprintf("Suspending %s to disk (%s)...", name, reims.SuspendStateFileName)) lastPct := -1 - err = qmp.SuspendToFile(ctx, d.Directory, tmpPath, func(p qmp.MigrateProgress) { + info, err := prep.SuspendSnapshot(ctx, d, func(p qmp.MigrateProgress) { if p.Total > 0 { pct := int(p.Transferred * 100 / p.Total) if pct >= lastPct+25 || p.Status == "completed" { @@ -120,221 +71,84 @@ func (a *App) SuspendVM(name string) error { } }) if err != nil { - _ = os.Remove(tmpPath) - a.clearTransition(name) a.emitLog(name, "Suspend error: "+err.Error()) - a.wakePoll() - a.emitStateChanged() return err } - - a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout) - - st, statErr := os.Stat(tmpPath) - if statErr != nil || st.Size() <= 0 { - _ = os.Remove(tmpPath) - a.clearTransition(name) - a.wakePoll() - a.emitStateChanged() - if statErr != nil { - return fmt.Errorf("suspend snapshot missing after save: %w", statErr) - } - return fmt.Errorf("suspend snapshot is empty after save") - } - - finalPath := reims.SuspendStatePath(d.Directory) - _ = os.Remove(finalPath) - if err := os.Rename(tmpPath, finalPath); err != nil { - _ = os.Remove(tmpPath) - a.clearTransition(name) - a.wakePoll() - a.emitStateChanged() - return fmt.Errorf("finalize suspend snapshot: %w", err) - } - - info := reims.BuildSuspendInfo(d, prep.Runtime, st.Size()) - if err := reims.WriteSuspendInfo(d.Directory, info); err != nil { - _ = reims.RemoveSuspendState(d.Directory) - a.clearTransition(name) - a.wakePoll() - a.emitStateChanged() - return fmt.Errorf("write suspend metadata: %w", err) - } - + a.cancelRebootWatcher(name) + stopVMMonitor(name) if gt != nil { gt.UnregisterVM(name) } if mgr != nil { - mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{ - VMName: name, - VMDir: d.Directory, - DriverID: builtin.IDDriverReimsMacOS, - }) + mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, event) } - a.clearTransition(name) - a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(st.Size())/float64(1<<30))) - a.wakePoll() - a.emitStateChanged() + a.emitLog(name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", name, float64(info.VMStateSize)/float64(1<<30))) return nil } -// ResumeVM launches a fresh QEMU process in `-incoming defer` mode (via -// `reims-ctl set --extra-args`), restores the VM's RAM, CPU, devices, and vGPU -// state from suspend.vmstate, and resumes guest execution. On any restore -// failure, suspend.vmstate and suspend.json are preserved so the user can retry. +// ResumeVM restores a suspended VM with its original media and devices. func (a *App) ResumeVM(name string) error { - loc := a.locale() prep, err := a.prep(name) if err != nil { return err } - if !prep.Runtime.Manifest.HasCapability("vm-suspend") { - return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + d, release, err := vmstart.LockVM(a.baseCtx(), prep.Client, name) + if err != nil { + return err } + defer release() + return a.resumeLocked(prep, d) +} + +func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error { + name := d.Name + end, err := a.beginSuspendTransition(name, "resuming") + if err != nil { + return err + } + defer end() a.mu.Lock() - root := a.cfg.DataRoot - if tr := a.transitions[name]; tr != "" { - a.mu.Unlock() - return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) - } - mgr := a.pluginMgr + root, mgr := a.cfg.DataRoot, a.pluginMgr a.mu.Unlock() - - ctx := a.baseCtx() - c := prep.Client - d, err := c.Show(ctx, name) - if err != nil { - return err - } - if a.isVMRunning(ctx, c, name, d) { - return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) - } - if !reims.HasSuspendState(d.Directory) { - return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) - } - meta, err := reims.ReadSuspendInfo(d.Directory) - if err != nil { - return fmt.Errorf("read suspend metadata: %w", err) - } - if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { - return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ - "diffs": strings.Join(diffs, ", "), - }, nil) - } - rep := host.Inspect(root) - if err := prep.CheckWHPX(rep); err != nil { - a.emitLog(name, "Resume refused: "+err.Error()) - return err - } - if err := prep.CheckMemory(d.Memory, rep); err != nil { - a.emitLog(name, "Resume refused: "+err.Error()) - return err - } - a.cancelRebootWatcher(name) - if prep.Runtime.Manifest.HasCapability("win32-unicode-input") { - if env := a.inputBridgeEnv(name, d.Directory); len(env) > 0 { - c.Env = append(c.Env, env...) - } + prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...) } if prep.Runtime.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) { - c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") + prep.Client.Env = append(prep.Client.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") } - origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) - incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) - if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { - return fmt.Errorf("prepare incoming extra-args: %w", err) - } - restoredExtra := false - restoreExtra := func() { - if restoredExtra { - return - } - restoredExtra = true - if rerr := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard); rerr != nil { - a.emitLog(name, "Warning: could not restore extra-args after incoming launch: "+rerr.Error()) - } - } - defer restoreExtra() - - a.mu.Lock() - a.transitions[name] = "resuming" - a.mu.Unlock() - a.emitStateChanged() - startAt := time.Now() - w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) - a.emitLog(name, fmt.Sprintf("Resuming %s from %s...", name, reims.SuspendStateFileName)) - if err := c.Start(ctx, name, w, w); err != nil { - restoreExtra() - a.clearTransition(name) - a.emitLog(name, "Resume launch error: "+err.Error()) - a.wakePoll() - a.emitStateChanged() + out := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) + if err := prep.ResumeSnapshot(a.baseCtx(), d, rep, out, out); err != nil { + a.emitLog(name, "Resume error: "+err.Error()) return err } - restoreExtra() - - if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { - a.emitLog(name, "Resume snapshot error (suspend state preserved for retry): "+err.Error()) - // Clean up the paused incoming QEMU process without touching suspend.vmstate. - if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { - _ = c.StopForce(context.Background(), name, io.Discard, io.Discard) - } - a.clearTransition(name) - a.wakePoll() - a.emitStateChanged() - return err - } - - if rerr := reims.RemoveSuspendState(d.Directory); rerr != nil { - a.emitLog(name, "Warning: could not remove consumed suspend files: "+rerr.Error()) - } - if mgr != nil { mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{ - VMName: name, - VMDir: d.Directory, - DriverID: builtin.IDDriverReimsMacOS, + VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, }) } a.startVMMonitor(name, d, startAt) - a.clearTransition(name) a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds())) - a.wakePoll() - a.emitStateChanged() return nil } -// DiscardSuspend deletes a suspended VM's saved RAM/device snapshot so the VM -// returns to the ordinary stopped state (equivalent to powering off). +// DiscardSuspend deletes a stopped VM's saved execution state. func (a *App) DiscardSuspend(name string) error { - loc := a.locale() c, err := a.client() if err != nil { return err } - a.mu.Lock() - if tr := a.transitions[name]; tr != "" { - a.mu.Unlock() - return i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) - } - a.mu.Unlock() - - ctx := a.baseCtx() - d, err := c.Show(ctx, name) + d, release, err := vmstart.LockVM(a.baseCtx(), c, name) if err != nil { return err } - if a.isVMRunning(ctx, c, name, d) { - return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) - } - if err := reims.RemoveSuspendState(d.Directory); err != nil { + defer release() + if err := vmstart.DiscardSnapshot(a.locale(), d); err != nil { return err } a.emitLog(name, "Discarded suspend state for "+name) @@ -343,10 +157,23 @@ func (a *App) DiscardSuspend(name string) error { return nil } -func (a *App) clearTransition(name string) { +func (a *App) beginSuspendTransition(name, state string) (func(), error) { a.mu.Lock() - delete(a.transitions, name) + loc := a.cfg.Locale + if a.transitions[name] != "" { + a.mu.Unlock() + return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + a.transitions[name] = state a.mu.Unlock() + a.emitStateChanged() + return func() { + a.mu.Lock() + delete(a.transitions, name) + a.mu.Unlock() + a.wakePoll() + a.emitStateChanged() + }, nil } func (a *App) emitStateChanged() { diff --git a/internal/app/suspend_flow_test.go b/internal/app/suspend_flow_test.go index 686c25f..a102794 100644 --- a/internal/app/suspend_flow_test.go +++ b/internal/app/suspend_flow_test.go @@ -2,6 +2,7 @@ package app import ( "os" + "path/filepath" "testing" "github.com/Nwflower/reims-go/internal/driver/reims" @@ -12,14 +13,20 @@ func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) { suspendedDir := t.TempDir() stoppedDir := t.TempDir() - if err := os.WriteFile(reims.SuspendStatePath(suspendedDir), []byte("0123456789"), 0o644); err != nil { + if err := os.WriteFile(reims.SuspendStatePath(suspendedDir)+".tmp", []byte("0123456789"), 0o600); err != nil { t.Fatal(err) } - if err := reims.WriteSuspendInfo(suspendedDir, reims.BuildSuspendInfo( - reims.VMDetail{Name: "mac-a", CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"}, + media := filepath.Join(suspendedDir, "disk.qcow2") + for _, path := range []string{media, filepath.Join(suspendedDir, "vm.toml")} { + if err := os.WriteFile(path, []byte("state"), 0o600); err != nil { + t.Fatal(err) + } + } + if _, err := reims.SealSuspend( + reims.VMDetail{Name: "mac-a", Directory: suspendedDir, CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"}, rt.Installed{Commit: "3731afd"}, - 10, - )); err != nil { + []string{media}, + ); err != nil { t.Fatal(err) } diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 5242e24..27e6c07 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -529,7 +529,12 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e AudioBackend: strings.TrimSpace(*audioBackend), GuestLang: strings.TrimSpace(*guestLang), } - if d, serr := client.Show(ctx, setOpts.Name); serr == nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) { + d, release, err := vmstart.LockVM(ctx, client, setOpts.Name) + if err != nil { + return err + } + defer release() + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { return i18n.NewCodedError(loc, "E_SET_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": setOpts.Name}, nil) } if reims.HasCtlSetChanges(setOpts) { @@ -556,6 +561,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 2 { return fmt.Errorf("usage: reims-go vm stop ") } + _, release, err := vmstart.LockVM(ctx, client, args[1]) + if err != nil { + return err + } + defer release() return client.Stop(ctx, args[1], os.Stdout, os.Stderr) case "suspend": if len(args) < 2 { @@ -576,6 +586,14 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 2 { return fmt.Errorf("usage: reims-go vm eject ") } + d, release, err := vmstart.LockVM(ctx, client, args[1]) + if err != nil { + return err + } + defer release() + if d.State == "stopped" && reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(loc, "E_VM_EJECT_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": args[1]}, nil) + } return client.Eject(ctx, args[1], os.Stdout, os.Stderr) case "type": // Paste as keystrokes: the text argument, else stdin. diff --git a/internal/cli/start.go b/internal/cli/start.go index b6b215c..3cbf862 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -50,8 +50,16 @@ func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name s if viaWindow && windowHandoffWorks { return startInWindow(ctx, cfg, name) } + d, release, err := vmstart.LockVM(ctx, prep.Client, name) + if err != nil { + return err + } + defer release() + if d.State == "running" { + return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name)) + } if d.State == "stopped" && reims.HasSuspendState(d.Directory) { - return resumeVM(ctx, cfg, prep, name) + return resumeLocked(ctx, cfg, prep, d, rep) } // Honour the core plugin's WHPX setting, as the window does. diff --git a/internal/cli/suspend.go b/internal/cli/suspend.go index e120f83..08ced68 100644 --- a/internal/cli/suspend.go +++ b/internal/cli/suspend.go @@ -3,175 +3,67 @@ package cli import ( "context" "fmt" - "io" "os" - "strings" "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/qmp" "github.com/Nwflower/reims-go/internal/vmstart" ) -func suspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { - loc := cfg.Locale - if !prep.Runtime.Manifest.HasCapability("vm-suspend") { - return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) - } - d, err := prep.Client.Show(ctx, name) +func suspendVM(ctx context.Context, _ *config.Config, prep *vmstart.Prep, name string) error { + d, release, err := vmstart.LockVM(ctx, prep.Client, name) if err != nil { return err } - if d.State != "running" { - return i18n.NewCodedError(loc, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": name}, nil) - } - if memGB, ok := reims.ParseSizeGB(d.Memory); ok { - dirRep := host.Inspect(d.Directory) - needGB := memGB + 1.0 - if dirRep.FreeDiskGB > 0 && dirRep.FreeDiskGB < needGB { - return i18n.NewCodedError(loc, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ - "need": fmt.Sprintf("%.1f", needGB), - "avail": fmt.Sprintf("%.1f", dirRep.FreeDiskGB), - }, nil) - } - } - var oldPID int - if vms, lerr := prep.Client.List(ctx); lerr == nil { - for _, vm := range vms { - if vm.Name == name && vm.PID != nil && *vm.PID > 0 { - oldPID = *vm.PID - break - } - } - } + defer release() - tmpPath := reims.SuspendStatePath(d.Directory) + ".tmp" - _ = os.Remove(tmpPath) fmt.Fprintf(os.Stderr, "Suspending %s to %s...\n", name, reims.SuspendStateFileName) - if err := qmp.SuspendToFile(ctx, d.Directory, tmpPath, nil); err != nil { - _ = os.Remove(tmpPath) + info, err := prep.SuspendSnapshot(ctx, d, nil) + if err != nil { return err } - if oldPID > 0 { - waitCtx, cancel := context.WithTimeout(ctx, 12*time.Second) - _ = host.WaitProcessExit(waitCtx, uint32(oldPID), "qemu-system-x86_64.exe") - cancel() - } - st, err := os.Stat(tmpPath) - if err != nil || st.Size() <= 0 { - _ = os.Remove(tmpPath) - if err != nil { - return err - } - return fmt.Errorf("suspend snapshot is empty after save") - } - finalPath := reims.SuspendStatePath(d.Directory) - _ = os.Remove(finalPath) - if err := os.Rename(tmpPath, finalPath); err != nil { - _ = os.Remove(tmpPath) - return err - } - if err := reims.WriteSuspendInfo(d.Directory, reims.BuildSuspendInfo(d, prep.Runtime, st.Size())); err != nil { - _ = reims.RemoveSuspendState(d.Directory) - return err - } - fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(st.Size())/float64(1<<30)) + fmt.Printf("Suspended %s (%.2f GiB saved)\n", name, float64(info.VMStateSize)/float64(1<<30)) return nil } func resumeVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { - loc := cfg.Locale - if !prep.Runtime.Manifest.HasCapability("vm-suspend") { - return i18n.NewCodedError(loc, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) - } - rep := host.Inspect(cfg.DataRoot) - d, err := prep.Client.Show(ctx, name) + d, release, err := vmstart.LockVM(ctx, prep.Client, name) if err != nil { return err } - if d.State == "running" { - return fmt.Errorf("%s", i18n.T(loc, "vm.already_running", name)) - } - if !reims.HasSuspendState(d.Directory) { - return i18n.NewCodedError(loc, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": name}, nil) - } - meta, err := reims.ReadSuspendInfo(d.Directory) - if err != nil { - return err - } - if diffs := reims.ValidateSuspendCompatibility(*meta, d, prep.Runtime); len(diffs) > 0 { - return i18n.NewCodedError(loc, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{ - "diffs": strings.Join(diffs, ", "), - }, nil) - } - if err := prep.CheckWHPX(rep); err != nil { - return err - } - if err := prep.CheckMemory(d.Memory, rep); err != nil { - return err - } + defer release() + return resumeLocked(ctx, cfg, prep, d, host.Inspect(cfg.DataRoot)) +} - origExtraArgs := reims.StripIncomingDeferArgs(d.ExtraArgs) - incomingArgs := reims.MergeIncomingDeferArgs(origExtraArgs) - if err := prep.Client.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &incomingArgs}, io.Discard, io.Discard); err != nil { - return err - } - restored := false - restoreExtra := func() { - if restored { - return - } - restored = true - _ = prep.Client.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &origExtraArgs}, io.Discard, io.Discard) - } - defer restoreExtra() - - fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", name, reims.SuspendStateFileName) +func resumeLocked(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, d reims.VMDetail, rep host.Report) error { + fmt.Fprintf(os.Stderr, "Resuming %s from %s...\n", d.Name, reims.SuspendStateFileName) startAt := time.Now() - if err := prep.Client.Start(ctx, name, os.Stdout, os.Stderr); err != nil { - restoreExtra() + if err := prep.ResumeSnapshot(ctx, d, rep, os.Stdout, os.Stderr); err != nil { return err } - restoreExtra() - - if err := qmp.ResumeFromFile(ctx, d.Directory, reims.SuspendStatePath(d.Directory), nil); err != nil { - if qerr := qmp.QuitVM(context.Background(), d.Directory); qerr != nil { - _ = prep.Client.StopForce(context.Background(), name, io.Discard, io.Discard) - } - return err - } - _ = reims.RemoveSuspendState(d.Directory) - - if vms, lerr := prep.Client.List(ctx); lerr == nil { + if vms, err := prep.Client.List(ctx); err == nil { for _, vm := range vms { - if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { - vmDir := vm.Dir - if vmDir == "" { - vmDir = d.Directory - } - if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" { - fmt.Fprintln(os.Stderr, line) - } + if vm.Name != d.Name || vm.State != "running" || vm.PID == nil || *vm.PID <= 0 { + continue + } + if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, d.Directory, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" { + fmt.Fprintln(os.Stderr, line) } } } - fmt.Printf("Resumed %s in %.1fs\n", name, time.Since(startAt).Seconds()) + fmt.Printf("Resumed %s in %.1fs\n", d.Name, time.Since(startAt).Seconds()) return nil } func discardSuspendVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string) error { - loc := cfg.Locale - d, err := prep.Client.Show(ctx, name) + d, release, err := vmstart.LockVM(ctx, prep.Client, name) if err != nil { return err } - if d.State == "running" { - return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": name}, nil) - } - if err := reims.RemoveSuspendState(d.Directory); err != nil { + defer release() + if err := vmstart.DiscardSnapshot(cfg.Locale, d); err != nil { return err } fmt.Printf("Discarded suspend state for %s\n", name) diff --git a/internal/driver/reims/suspend.go b/internal/driver/reims/suspend.go index b4035d4..202565f 100644 --- a/internal/driver/reims/suspend.go +++ b/internal/driver/reims/suspend.go @@ -18,7 +18,7 @@ const ( // create suspend.vmstate so incompatible resumes are caught before launch. SuspendMetaFileName = "suspend.json" // SuspendSchemaVersion is the current metadata schema version. - SuspendSchemaVersion = 1 + SuspendSchemaVersion = 2 ) // SuspendInfo describes a VM's saved suspend-to-disk state inside its VM folder. @@ -56,24 +56,46 @@ func SuspendMetaPath(vmDir string) string { // HasSuspendState reports whether vmDir contains a complete suspend snapshot // (both a non-empty suspend.vmstate and its suspend.json metadata). func HasSuspendState(vmDir string) bool { + state, _ := suspendFiles(vmDir) + return state != "" +} + +func suspendFiles(vmDir string) (state, meta string) { if strings.TrimSpace(vmDir) == "" { - return false + return "", "" } - st, err := os.Stat(SuspendStatePath(vmDir)) - if err != nil || st.IsDir() || st.Size() <= 0 { - return false + state, meta = SuspendStatePath(vmDir), SuspendMetaPath(vmDir) + nonEmpty := func(path string) bool { + st, err := os.Stat(path) + return err == nil && st.Mode().IsRegular() && st.Size() > 0 } - mst, err := os.Stat(SuspendMetaPath(vmDir)) - if err != nil || mst.IsDir() || mst.Size() <= 0 { - return false + if nonEmpty(meta) { + if nonEmpty(state) { + return state, meta + } + return "", "" } - return true + // A staged record is written only after the full state file was + // synced. Preserve that pair if either of the publication steps fails. + if nonEmpty(meta + ".tmp") { + if nonEmpty(state) { + return state, meta + ".tmp" + } + if nonEmpty(state + ".tmp") { + return state + ".tmp", meta + ".tmp" + } + } + return "", "" } // ReadSuspendInfo reads suspend.json from vmDir and refreshes VMStateSize from // the actual suspend.vmstate file on disk. func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) { - b, err := os.ReadFile(SuspendMetaPath(vmDir)) + state, meta := suspendFiles(vmDir) + if state == "" { + return nil, os.ErrNotExist + } + b, err := os.ReadFile(meta) if err != nil { return nil, err } @@ -81,33 +103,12 @@ func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) { if err := json.Unmarshal(b, &info); err != nil { return nil, fmt.Errorf("parse %s: %w", SuspendMetaFileName, err) } - if st, err := os.Stat(SuspendStatePath(vmDir)); err == nil && !st.IsDir() { + if st, err := os.Stat(state); err == nil { info.VMStateSize = st.Size() } return &info, nil } -// WriteSuspendInfo atomically writes suspend.json inside vmDir. -func WriteSuspendInfo(vmDir string, info SuspendInfo) error { - if info.SchemaVersion == 0 { - info.SchemaVersion = SuspendSchemaVersion - } - if info.CreatedAt == "" { - info.CreatedAt = time.Now().UTC().Format(time.RFC3339) - } - info.ExtraArgs = StripIncomingDeferArgs(info.ExtraArgs) - b, err := json.MarshalIndent(info, "", " ") - if err != nil { - return err - } - b = append(b, '\n') - tmp := SuspendMetaPath(vmDir) + ".tmp" - if err := os.WriteFile(tmp, b, 0o644); err != nil { - return err - } - return os.Rename(tmp, SuspendMetaPath(vmDir)) -} - // BuildSuspendInfo snapshots a VM's hardware and runtime fingerprint for suspend.json. func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) SuspendInfo { return SuspendInfo{ diff --git a/internal/driver/reims/suspend_lock_other.go b/internal/driver/reims/suspend_lock_other.go new file mode 100644 index 0000000..06f45df --- /dev/null +++ b/internal/driver/reims/suspend_lock_other.go @@ -0,0 +1,26 @@ +//go:build !windows + +package reims + +import ( + "errors" + "fmt" + "os" + "syscall" +) + +func lockVMFile(f *os.File) error { + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if errors.Is(err, syscall.EWOULDBLOCK) { + return ErrVMOperationBusy + } + return err +} + +func mediaFileID(path string, info os.FileInfo) (uint64, uint64, error) { + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0, 0, fmt.Errorf("file identity unavailable for %s", path) + } + return uint64(st.Dev), uint64(st.Ino), nil +} diff --git a/internal/driver/reims/suspend_lock_windows.go b/internal/driver/reims/suspend_lock_windows.go new file mode 100644 index 0000000..251f78a --- /dev/null +++ b/internal/driver/reims/suspend_lock_windows.go @@ -0,0 +1,39 @@ +//go:build windows + +package reims + +import ( + "errors" + "os" + + "golang.org/x/sys/windows" +) + +func lockVMFile(f *os.File) error { + err := windows.LockFileEx(windows.Handle(f.Fd()), + windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, + 0, 1, 0, new(windows.Overlapped)) + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) { + return ErrVMOperationBusy + } + return err +} + +func mediaFileID(path string, _ os.FileInfo) (uint64, uint64, error) { + name, err := windows.UTF16PtrFromString(path) + if err != nil { + return 0, 0, err + } + handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, + windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + return 0, 0, err + } + defer windows.CloseHandle(handle) + var info windows.ByHandleFileInformation + if err := windows.GetFileInformationByHandle(handle, &info); err != nil { + return 0, 0, err + } + return uint64(info.VolumeSerialNumber), uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow), nil +} diff --git a/internal/driver/reims/suspend_test.go b/internal/driver/reims/suspend_test.go index 4401ca6..b285d49 100644 --- a/internal/driver/reims/suspend_test.go +++ b/internal/driver/reims/suspend_test.go @@ -2,6 +2,7 @@ package reims import ( "os" + "path/filepath" "strings" "testing" @@ -17,7 +18,7 @@ func TestSuspendStateLifecycle(t *testing.T) { } // Only vmstate without meta -> incomplete. - if err := os.WriteFile(SuspendStatePath(dir), []byte("vmstate-bytes"), 0o644); err != nil { + if err := os.WriteFile(SuspendStatePath(dir)+".tmp", []byte("vmstate-bytes"), 0o644); err != nil { t.Fatal(err) } if HasSuspendState(dir) { @@ -32,6 +33,7 @@ func TestSuspendStateLifecycle(t *testing.T) { } detail := VMDetail{ Name: "tahoe", + Directory: dir, CPUs: 8, Memory: "8G", Graphics: "reims-vgpu", @@ -42,9 +44,14 @@ func TestSuspendStateLifecycle(t *testing.T) { Network: true, ExtraArgs: "-machine kernel-irqchip=on -incoming defer", } - info := BuildSuspendInfo(detail, active, 13) - if err := WriteSuspendInfo(dir, info); err != nil { - t.Fatalf("WriteSuspendInfo: %v", err) + media := filepath.Join(dir, "disk.qcow2") + for _, path := range []string{media, filepath.Join(dir, "vm.toml")} { + if err := os.WriteFile(path, []byte("state"), 0o600); err != nil { + t.Fatal(err) + } + } + if _, err := SealSuspend(detail, active, []string{media}); err != nil { + t.Fatalf("SealSuspend: %v", err) } if !HasSuspendState(dir) { t.Fatal("expected HasSuspendState=true after writing both files") diff --git a/internal/driver/reims/suspend_transaction.go b/internal/driver/reims/suspend_transaction.go new file mode 100644 index 0000000..63d914a --- /dev/null +++ b/internal/driver/reims/suspend_transaction.go @@ -0,0 +1,185 @@ +package reims + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +var ErrVMOperationBusy = errors.New("another operation holds the VM lock") + +// LockVMOperation serializes GUI and CLI operations on the same VM directory. +// The lock file stays in place so contenders always lock the same inode. +func LockVMOperation(vmDir string) (func(), error) { + if strings.TrimSpace(vmDir) == "" { + return nil, fmt.Errorf("VM directory is required") + } + f, err := os.OpenFile(filepath.Join(vmDir, ".reims-go-vm-operation.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + if err := lockVMFile(f); err != nil { + _ = f.Close() + return nil, err + } + return func() { _ = f.Close() }, nil +} + +type mediaFingerprint struct { + Path string `json:"path"` + Volume uint64 `json:"volume"` + FileID uint64 `json:"file_id"` + Size int64 `json:"size"` + MTime int64 `json:"mtime_ns"` +} + +type suspendRecord struct { + SuspendInfo + ConfigHash string `json:"config_sha256"` + Media []mediaFingerprint `json:"media"` +} + +func fingerprintMedia(path string) (mediaFingerprint, error) { + st, err := os.Stat(path) + if err != nil { + return mediaFingerprint{}, err + } + if !st.Mode().IsRegular() { + return mediaFingerprint{}, fmt.Errorf("attached path is not a regular file: %s", path) + } + volume, id, err := mediaFileID(path, st) + if err != nil { + return mediaFingerprint{}, err + } + return mediaFingerprint{Path: path, Volume: volume, FileID: id, Size: st.Size(), MTime: st.ModTime().UnixNano()}, nil +} + +func suspendConfigHash(vmDir string) (string, error) { + data, err := os.ReadFile(filepath.Join(vmDir, "vm.toml")) + if err != nil { + return "", err + } + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]), nil +} + +// SealSuspend publishes a completed migration as the only usable snapshot. +// Every failure leaves the migration file available and the sender still alive. +func SealSuspend(d VMDetail, active rt.Installed, paths []string) (SuspendInfo, error) { + if len(paths) == 0 { + return SuspendInfo{}, fmt.Errorf("cannot seal a snapshot without attached media") + } + dir := d.Directory + tmp := SuspendStatePath(dir) + ".tmp" + state, err := os.OpenFile(tmp, os.O_RDWR, 0) + if err != nil { + return SuspendInfo{}, err + } + st, err := state.Stat() + if err == nil && (!st.Mode().IsRegular() || st.Size() == 0) { + err = fmt.Errorf("suspend snapshot is empty or is not a regular file") + } + if err == nil { + err = state.Sync() + } + if err := errors.Join(err, state.Close()); err != nil { + return SuspendInfo{}, err + } + configHash, err := suspendConfigHash(dir) + if err != nil { + return SuspendInfo{}, err + } + record := suspendRecord{ + SuspendInfo: BuildSuspendInfo(d, active, st.Size()), + ConfigHash: configHash, + Media: make([]mediaFingerprint, 0, len(paths)), + } + for _, path := range paths { + item, err := fingerprintMedia(path) + if err != nil { + return SuspendInfo{}, fmt.Errorf("fingerprint attached media: %w", err) + } + record.Media = append(record.Media, item) + } + metaTmp := SuspendMetaPath(dir) + ".tmp" + if err := stageSuspendRecord(metaTmp, record); err != nil { + return SuspendInfo{}, err + } + if err := os.Rename(tmp, SuspendStatePath(dir)); err != nil { + return SuspendInfo{}, err + } + if err := os.Rename(metaTmp, SuspendMetaPath(dir)); err != nil { + return SuspendInfo{}, err + } + return record.SuspendInfo, nil +} + +func stageSuspendRecord(path string, record suspendRecord) error { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return err + } + enc := json.NewEncoder(f) + enc.SetIndent("", " ") + err = enc.Encode(record) + if err == nil { + err = f.Sync() + } + return errors.Join(err, f.Close()) +} + +// ValidateSuspendFiles checks contents and identities before starting incoming +// QEMU and returns the expected media paths for validation before load. +func ValidateSuspendFiles(d VMDetail, active rt.Installed) (string, []string, error) { + state, meta := suspendFiles(d.Directory) + if state == "" { + return "", nil, os.ErrNotExist + } + data, err := os.ReadFile(meta) + if err != nil { + return "", nil, err + } + var record suspendRecord + if err := json.Unmarshal(data, &record); err != nil { + return "", nil, err + } + if record.SchemaVersion != SuspendSchemaVersion || record.ConfigHash == "" || len(record.Media) == 0 { + return "", nil, fmt.Errorf("snapshot has no supported VM and media fingerprint") + } + st, err := os.Stat(state) + if err != nil { + return "", nil, err + } + if !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() != record.VMStateSize { + return "", nil, fmt.Errorf("snapshot file size changed") + } + diffs := ValidateSuspendCompatibility(record.SuspendInfo, d, active) + configHash, err := suspendConfigHash(d.Directory) + if err != nil { + return "", nil, err + } + if configHash != record.ConfigHash { + diffs = append(diffs, "VM configuration changed") + } + paths := make([]string, 0, len(record.Media)) + for _, expected := range record.Media { + current, err := fingerprintMedia(expected.Path) + if err != nil || current != expected { + diffs = append(diffs, fmt.Sprintf("attached media changed (%s)", expected.Path)) + } + paths = append(paths, expected.Path) + } + if len(diffs) > 0 { + return "", nil, errors.New(strings.Join(diffs, ", ")) + } + slices.Sort(paths) + return state, paths, nil +} diff --git a/internal/driver/reims/suspend_transaction_test.go b/internal/driver/reims/suspend_transaction_test.go new file mode 100644 index 0000000..7c9a845 --- /dev/null +++ b/internal/driver/reims/suspend_transaction_test.go @@ -0,0 +1,89 @@ +package reims + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func TestVMOperationLockExcludesAnotherHandle(t *testing.T) { + dir := t.TempDir() + release, err := LockVMOperation(dir) + if err != nil { + t.Fatal(err) + } + if _, err = LockVMOperation(dir); !errors.Is(err, ErrVMOperationBusy) { + t.Fatalf("second lock = %v, want busy", err) + } + release() + release, err = LockVMOperation(dir) + if err != nil { + t.Fatal(err) + } + release() +} + +func TestSuspendTransactionRejectsChangedBackingFile(t *testing.T) { + dir := t.TempDir() + top := filepath.Join(dir, "disk.qcow2") + base := filepath.Join(dir, "base.qcow2") + for _, path := range []string{top, base, filepath.Join(dir, "vm.toml"), SuspendStatePath(dir) + ".tmp"} { + if err := os.WriteFile(path, []byte("test data"), 0o600); err != nil { + t.Fatal(err) + } + } + d := VMDetail{Name: "test", Directory: dir, CPUs: 2, Memory: "4G"} + runtime := rt.Installed{Commit: "test"} + if _, err := SealSuspend(d, runtime, []string{top, base}); err != nil { + t.Fatal(err) + } + if _, _, err := ValidateSuspendFiles(d, runtime); err != nil { + t.Fatal(err) + } + st, err := os.Stat(base) + if err != nil { + t.Fatal(err) + } + if err := os.Rename(base, base+".old"); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(base, []byte("test data"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(base, st.ModTime(), st.ModTime()); err != nil { + t.Fatal(err) + } + if _, _, err := ValidateSuspendFiles(d, runtime); err == nil || !strings.Contains(err.Error(), "base.qcow2") { + t.Fatalf("replaced backing file not detected: %v", err) + } +} + +func TestSuspendTransactionKeepsSealedFilesWhenPublicationFails(t *testing.T) { + dir := t.TempDir() + media := filepath.Join(dir, "OVMF_VARS.fd") + stagedState := SuspendStatePath(dir) + ".tmp" + for _, path := range []string{media, filepath.Join(dir, "vm.toml"), stagedState} { + if err := os.WriteFile(path, []byte("test state"), 0o600); err != nil { + t.Fatal(err) + } + } + if err := os.Mkdir(SuspendMetaPath(dir), 0o700); err != nil { + t.Fatal(err) + } + d := VMDetail{Name: "test", Directory: dir} + runtime := rt.Installed{Commit: "test"} + if _, err := SealSuspend(d, runtime, []string{media}); err == nil { + t.Fatal("expected publication to fail") + } + if !HasSuspendState(dir) { + t.Fatal("published state and staged metadata should be recoverable") + } + state, paths, err := ValidateSuspendFiles(d, runtime) + if err != nil || state != SuspendStatePath(dir) || len(paths) != 1 || paths[0] != media { + t.Fatalf("recoverable snapshot = %q, %v, %v", state, paths, err) + } +} diff --git a/internal/qmp/media.go b/internal/qmp/media.go new file mode 100644 index 0000000..0656310 --- /dev/null +++ b/internal/qmp/media.go @@ -0,0 +1,59 @@ +package qmp + +import ( + "encoding/json" + "fmt" + "path/filepath" + "slices" + "strings" +) + +// AttachedFiles lists the inserted image and backing files for each block +// device. QEMU's resolved image names include the real pflash and CD drives. +func (c *Conn) AttachedFiles(vmDir string) ([]string, error) { + raw, err := c.Query("query-block", nil) + if err != nil { + return nil, err + } + type image struct { + Filename string `json:"filename"` + Backing *image `json:"backing-image"` + } + var devices []struct { + Device string `json:"device"` + Inserted *struct { + Image *image `json:"image"` + Backing string `json:"backing_file"` + } `json:"inserted"` + } + if err := json.Unmarshal(raw, &devices); err != nil { + return nil, fmt.Errorf("decode query-block: %w", err) + } + var paths []string + for _, d := range devices { + if d.Inserted == nil { + continue + } + if d.Inserted.Image == nil || (d.Inserted.Backing != "" && d.Inserted.Image.Backing == nil) { + return nil, fmt.Errorf("cannot identify the complete attached disk or backing chain") + } + for img := d.Inserted.Image; img != nil; img = img.Backing { + if img.Filename == "" { + return nil, fmt.Errorf("block device has no filename") + } + name := img.Filename + if strings.HasPrefix(name, "json:") { + return nil, fmt.Errorf("block device %s uses a non-persistent or unresolvable image; eject it before suspending", d.Device) + } + if !filepath.IsAbs(name) { + name = filepath.Join(vmDir, name) + } + paths = append(paths, filepath.Clean(name)) + } + } + if len(paths) == 0 { + return nil, fmt.Errorf("no attached media reported by QEMU") + } + slices.Sort(paths) + return slices.Compact(paths), nil +} diff --git a/internal/qmp/migrate.go b/internal/qmp/migrate.go index effe1d1..0e42803 100644 --- a/internal/qmp/migrate.go +++ b/internal/qmp/migrate.go @@ -53,16 +53,20 @@ type vmStatusReply struct { // If migration fails before reaching completion while the VM is merely paused // (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so // the running VM is not left frozen. -func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { +func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), seal func([]string) error) error { c, err := Dial(ctx, "unix", SocketPath(vmDir)) if err != nil { return err } defer c.Close() - return suspendToFileConn(ctx, c, vmstatePath, onProgress) + paths, err := c.AttachedFiles(vmDir) + if err != nil { + return err + } + return suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) }) } -func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error { +func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress), seal func(*Conn) error) error { if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil { return fmt.Errorf("pause VM before suspend: %w", err) } @@ -92,6 +96,13 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr tryResumePaused(c) return fmt.Errorf("save snapshot: %w", err) } + if seal != nil { + if err := seal(c); err != nil { + // The source still owns the session. Leave it paused and retain + // the completed file if publishing the save failed. + return fmt.Errorf("seal snapshot before exiting QEMU: %w", err) + } + } // Migration completed (RUN_STATE_POSTMIGRATE): never send `cont` here; // exit QEMU cleanly so the disk and WHPX partition close. @@ -109,12 +120,17 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr // completion, and resumes execution with `cont`. // // On any error, vmstatePath is left untouched so the caller can retry. -func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress)) error { +func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), checkMedia func(*Conn) error) error { c, err := dialMigrateConnWithRetry(ctx, "unix", SocketPath(vmDir), 10*time.Second) if err != nil { return err } defer c.Close() + if checkMedia != nil { + if err := checkMedia(c); err != nil { + return err + } + } return resumeFromFileConn(ctx, c, vmstatePath, onProgress) } diff --git a/internal/qmp/migrate_test.go b/internal/qmp/migrate_test.go index 0c863d2..99aa261 100644 --- a/internal/qmp/migrate_test.go +++ b/internal/qmp/migrate_test.go @@ -4,12 +4,87 @@ import ( "bufio" "context" "encoding/json" + "errors" "net" + "path/filepath" + "slices" "strings" "sync" "testing" ) +func TestAttachedFiles(t *testing.T) { + vmDir := t.TempDir() + disk := filepath.Join(vmDir, "disk.qcow2") + parent := filepath.Join(vmDir, "base.qcow2") + addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + if req.Execute != "query-block" { + t.Errorf("unexpected command: %s", req.Execute) + } + return map[string]any{"return": []map[string]any{ + {"device": "disk", "inserted": map[string]any{"image": map[string]any{ + "filename": disk, "backing-image": map[string]any{"filename": parent}, + }}}, + {"device": "empty", "inserted": nil}, + }}, false + }) + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + got, err := c.AttachedFiles(vmDir) + if err != nil || !slices.Equal(got, []string{parent, disk}) { + t.Fatalf("attached files = %v, %v", got, err) + } +} + +func TestAttachedFilesRejectsTemporaryOverlay(t *testing.T) { + addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + return map[string]any{"return": []map[string]any{ + {"device": "installer", "inserted": map[string]any{"image": map[string]any{ + "filename": "json:temporary disk descriptor", + }}}, + }}, false + }) + c, err := Dial(context.Background(), "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.AttachedFiles(t.TempDir()); err == nil || !strings.Contains(err.Error(), "installer uses a non-persistent") { + t.Fatalf("temporary installer overlay = %v", err) + } +} + +func TestSuspendSealFailureDoesNotQuitSource(t *testing.T) { + addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + case "query-migrate": + return map[string]any{"return": map[string]any{"status": "completed"}}, false + case "quit": + t.Error("QEMU would exit with an unsealed snapshot") + } + return map[string]any{"return": map[string]any{}}, false + }) + ctx := context.Background() + c, err := Dial(ctx, "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + sealErr := errors.New("unable to publish state") + if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) { + t.Fatalf("suspend error = %v", err) + } + cmds := recorded() + if len(cmds) == 0 || cmds[len(cmds)-1].Execute != "query-migrate" { + t.Fatalf("unexpected commands: %+v", cmds) + } +} + type mockQMPReq struct { Execute string `json:"execute"` Arguments json.RawMessage `json:"arguments"` @@ -104,7 +179,7 @@ func TestSuspendToFileHappyPath(t *testing.T) { var progress []MigrateProgress if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) { progress = append(progress, p) - }); err != nil { + }, nil); err != nil { t.Fatalf("suspendToFileConn: %v", err) } if len(progress) != 2 || progress[1].Status != "completed" { @@ -141,7 +216,7 @@ func TestSuspendToFileFailureResumesPausedVM(t *testing.T) { } defer c.Close() - err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil) + err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil) if err == nil || !strings.Contains(err.Error(), "disk full") { t.Fatalf("expected disk full error, got %v", err) } diff --git a/internal/vmstart/suspend.go b/internal/vmstart/suspend.go new file mode 100644 index 0000000..958030f --- /dev/null +++ b/internal/vmstart/suspend.go @@ -0,0 +1,198 @@ +package vmstart + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "slices" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/qmp" +) + +// LockVM reads the VM again after locking its directory so that another +// process cannot change the state between inspection and operation. +func LockVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) { + d, err := c.Show(ctx, name) + if err != nil { + return d, nil, err + } + release, err := reims.LockVMOperation(d.Directory) + if errors.Is(err, reims.ErrVMOperationBusy) { + return d, nil, i18n.NewCodedError(c.Locale, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil) + } + if err != nil { + return d, nil, err + } + cur, err := c.Show(ctx, name) + if err == nil && cur.Directory != d.Directory { + err = fmt.Errorf("VM directory changed while waiting to operate on %s", name) + } + if err != nil { + release() + return cur, nil, err + } + return cur, release, nil +} + +func (p *Prep) checkSuspendRuntime(d reims.VMDetail) error { + kind := strings.ToLower(d.Kind) + if !p.Runtime.Manifest.HasCapability("vm-suspend") || strings.Contains(kind, "arm64") || strings.Contains(kind, "aarch64") { + return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil) + } + return nil +} + +// SuspendSnapshot saves and publishes a VM snapshot while the caller holds +// LockVM. The source exits only after the snapshot and metadata are durable. +func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress func(qmp.MigrateProgress)) (reims.SuspendInfo, error) { + var info reims.SuspendInfo + if err := p.checkSuspendRuntime(d); err != nil { + return info, err + } + pid, err := vmPID(ctx, p.Client, d.Name) + if err != nil { + return info, err + } + if pid == 0 { + return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": d.Name}, nil) + } + if memGB, ok := reims.ParseSizeGB(d.Memory); ok { + if avail := host.Inspect(d.Directory).FreeDiskGB; avail > 0 && avail < memGB+1 { + return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{ + "need": fmt.Sprintf("%.1f", memGB+1), "avail": fmt.Sprintf("%.1f", avail), + }, nil) + } + } + state := reims.SuspendStatePath(d.Directory) + tmp := state + ".tmp" + meta := reims.SuspendMetaPath(d.Directory) + for _, path := range []string{state, tmp, meta, meta + ".tmp"} { + if _, err := os.Lstat(path); !os.IsNotExist(err) { + if err != nil { + return info, err + } + return info, fmt.Errorf("previous suspend data still exists: %s", path) + } + } + err = qmp.SuspendToFile(ctx, d.Directory, tmp, progress, func(paths []string) error { + var err error + info, err = reims.SealSuspend(d, p.Runtime, paths) + return err + }) + if err != nil { + return info, err + } + waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) + defer cancel() + if err := host.WaitProcessExit(waitCtx, uint32(pid), "qemu-system-x86_64.exe"); err != nil { + if !errors.Is(err, errors.ErrUnsupported) { + return info, err + } + for { + cur, err := vmPID(waitCtx, p.Client, d.Name) + if err != nil || cur == 0 { + return info, err + } + select { + case <-waitCtx.Done(): + return info, waitCtx.Err() + case <-time.After(100 * time.Millisecond): + } + } + } + return info, nil +} + +// ResumeSnapshot owns the incoming launch and snapshot consumption while +// the caller holds LockVM. The original configuration must be restored +// before guest execution can continue. +func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, rep host.Report, out, stderr io.Writer) error { + if err := p.checkSuspendRuntime(d); err != nil { + return err + } + if d.State == "running" { + return fmt.Errorf("%s", i18n.T(p.Client.Locale, "vm.already_running", d.Name)) + } + if !reims.HasSuspendState(d.Directory) { + return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": d.Name}, nil) + } + state, paths, err := reims.ValidateSuspendFiles(d, p.Runtime) + if err != nil { + return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{"diffs": err.Error()}, err) + } + if err := p.CheckWHPX(rep); err != nil { + return err + } + if err := p.CheckMemory(d.Memory, rep); err != nil { + return err + } + c := p.Client + incoming := reims.MergeIncomingDeferArgs(d.ExtraArgs) + if err := c.Set(ctx, reims.SetOpts{Name: d.Name, ExtraArgs: &incoming}, out, stderr); err != nil { + return err + } + startErr := c.Start(ctx, d.Name, out, stderr) + restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) + restoreErr := c.Set(restoreCtx, reims.SetOpts{Name: d.Name, ExtraArgs: &d.ExtraArgs}, out, stderr) + cancel() + if restoreErr != nil { + restoreErr = fmt.Errorf("restore original VM start arguments: %w", restoreErr) + } + if err := errors.Join(startErr, restoreErr); err != nil { + p.stopFailedIncoming(ctx, d) + return err + } + err = qmp.ResumeFromFile(ctx, d.Directory, state, nil, func(conn *qmp.Conn) error { + attached, err := conn.AttachedFiles(d.Directory) + if err != nil { + return err + } + if !slices.Equal(paths, attached) { + return fmt.Errorf("incoming QEMU opened different media from the saved VM") + } + return nil + }) + if err != nil { + p.stopFailedIncoming(ctx, d) + return err + } + if err := reims.RemoveSuspendState(d.Directory); err != nil { + p.log("Warning: could not remove consumed suspend files: " + err.Error()) + } + return nil +} + +func (p *Prep) stopFailedIncoming(ctx context.Context, d reims.VMDetail) { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) + defer cancel() + if err := qmp.QuitVM(cleanup, d.Directory); err != nil { + _ = p.Client.StopForce(cleanup, d.Name, io.Discard, io.Discard) + } +} + +func DiscardSnapshot(loc i18n.Locale, d reims.VMDetail) error { + if d.State == "running" { + return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": d.Name}, nil) + } + return reims.RemoveSuspendState(d.Directory) +} + +func vmPID(ctx context.Context, c *reims.Client, name string) (int, error) { + vms, err := c.List(ctx) + if err != nil { + return 0, err + } + for _, vm := range vms { + if vm.Name == name && vm.State == "running" && vm.PID != nil { + return *vm.PID, nil + } + } + return 0, nil +} From a32fe323abd9797a269c10f8f851b3ce61ca193d Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:54:22 +0800 Subject: [PATCH 10/23] fix: preserve force stop and recover incomplete VM suspend attempts --- internal/app/app.go | 2 +- internal/app/clone_flow.go | 4 +- internal/app/disk_flow.go | 7 +- internal/app/guesttools_flow.go | 9 ++- internal/app/install_flow.go | 12 ++-- internal/app/snapshot_flow.go | 4 +- internal/app/suspend_flow.go | 19 +++++- internal/cli/cli.go | 8 ++- internal/qmp/client.go | 16 +++-- internal/qmp/migrate.go | 108 ++++++++++++++++++++++++++----- internal/qmp/migrate_test.go | 80 ++++++++++++++++++++++- internal/qmp/watcher.go | 27 +++++++- internal/qmp/watcher_test.go | 17 +++++ internal/vmstart/suspend.go | 35 +++++++++- internal/vmstart/suspend_test.go | 48 ++++++++++++++ 15 files changed, 348 insertions(+), 48 deletions(-) create mode 100644 internal/vmstart/suspend_test.go diff --git a/internal/app/app.go b/internal/app/app.go index 048e2eb..f9a0183 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1512,7 +1512,7 @@ func (a *App) StopVM(name string, force bool) error { if err != nil { return err } - _, release, err := vmstart.LockVM(a.baseCtx(), c, name) + release, err := vmstart.LockVMForStop(a.baseCtx(), c, name, force) if err != nil { return err } diff --git a/internal/app/clone_flow.go b/internal/app/clone_flow.go index 1ab10e6..92b1741 100644 --- a/internal/app/clone_flow.go +++ b/internal/app/clone_flow.go @@ -39,10 +39,12 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error { c := reims.NewClient(&cfgCopy, *active) ctx := a.baseCtx() - src, err := a.GetVMDetail(sourceName) + src, release, err := vmstart.LockVM(ctx, c, sourceName) if err != nil { return err } + defer release() + a.populateVMDetail(&src) if a.isVMRunning(ctx, c, sourceName, src) { return i18n.NewCodedError(loc, "E_VM_CLONE_RUNNING", "err.clone.source_running", i18n.Vars{"name": sourceName}, nil) } diff --git a/internal/app/disk_flow.go b/internal/app/disk_flow.go index fc3e7ed..5f455d4 100644 --- a/internal/app/disk_flow.go +++ b/internal/app/disk_flow.go @@ -7,6 +7,7 @@ import ( "github.com/Nwflower/reims-go/internal/driver/reims" rt "github.com/Nwflower/reims-go/internal/runtime" + "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) @@ -24,10 +25,11 @@ func (a *App) ResizeVMDisk(name, newSize string) (reims.DiskResizeResult, error) c := reims.NewClient(&cfgCopy, *active) ctx := a.baseCtx() - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockVM(ctx, c, name) if err != nil { return reims.DiskResizeResult{}, err } + defer release() if a.isVMRunning(ctx, c, name, d) { return reims.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name) } @@ -73,10 +75,11 @@ func (a *App) CompactVMDisk(name string) (reims.DiskCompactResult, error) { c := reims.NewClient(&cfgCopy, *active) ctx := a.baseCtx() - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockVM(ctx, c, name) if err != nil { return reims.DiskCompactResult{}, err } + defer release() if a.isVMRunning(ctx, c, name, d) { return reims.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name) } diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 6cfe72b..2f3da20 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -225,13 +225,11 @@ func (a *App) AttachGuestTools(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } - if d.Directory == "" { - return fmt.Errorf("VM %s has no directory", name) - } + defer release() srv, port, err := a.ensureGuestToolsBridge() if err != nil { return err @@ -281,10 +279,11 @@ func (a *App) DetachGuestTools(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } + defer release() stripped := reims.StripGuestToolsArgs(d.ExtraArgs) ctx := context.Background() w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) diff --git a/internal/app/install_flow.go b/internal/app/install_flow.go index 10f979a..8f2f678 100644 --- a/internal/app/install_flow.go +++ b/internal/app/install_flow.go @@ -80,10 +80,11 @@ func (a *App) EnterRecovery(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } + defer release() w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) ctx := context.Background() @@ -126,10 +127,11 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) { if err != nil { return "", err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return "", err } + defer release() path := strings.TrimSpace(installerPath) if path == "" { path, err = a.pickCachedRecoveryInstaller() @@ -232,10 +234,11 @@ func (a *App) FinishInstall(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } + defer release() w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) ctx := context.Background() @@ -325,10 +328,11 @@ func (a *App) UpgradeDiskToNVMe(name string) error { if err != nil { return err } - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockMutableVM(a.baseCtx(), c, name) if err != nil { return err } + defer release() if d.HasInstaller { return errors.New("exit recovery mode (eject installer) before switching disk controller") } diff --git a/internal/app/snapshot_flow.go b/internal/app/snapshot_flow.go index 426fc75..0c4b3dd 100644 --- a/internal/app/snapshot_flow.go +++ b/internal/app/snapshot_flow.go @@ -9,6 +9,7 @@ import ( "github.com/Nwflower/reims-go/internal/driver/reims" "github.com/Nwflower/reims-go/internal/i18n" rt "github.com/Nwflower/reims-go/internal/runtime" + "github.com/Nwflower/reims-go/internal/vmstart" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) @@ -78,10 +79,11 @@ func (a *App) runSnapshotOp(name, flag, snapName, verb string) error { c := reims.NewClient(&cfgCopy, *active) ctx := a.baseCtx() - d, err := a.GetVMDetail(name) + d, release, err := vmstart.LockVM(ctx, c, name) if err != nil { return err } + defer release() if a.isVMRunning(ctx, c, name, d) { return i18n.NewCodedError(loc, "E_SNAPSHOT_VM_RUNNING", "err.snapshot.vm_running", i18n.Vars{"name": name}, nil) } diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index 90abdc0..8cfd783 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -2,6 +2,7 @@ package app import ( "fmt" + "os" "time" "github.com/Nwflower/reims-go/internal/driver/reims" @@ -109,10 +110,20 @@ func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error { defer end() a.mu.Lock() - root, mgr := a.cfg.DataRoot, a.pluginMgr + root, tmpDir, mgr := a.cfg.DataRoot, a.cfg.TempDir(), a.pluginMgr a.mu.Unlock() rep := host.Inspect(root) - a.cancelRebootWatcher(name) + var qmpAddr string + if d.State == "stopped" && reims.HasSuspendState(d.Directory) && rep.NeedsColdRebootWorkaround { + sockPath := qmp.RebootSocketPath(d.Directory, tmpDir, name) + if qmp.HasWin10RebootUnixArgs(d.ExtraArgs, sockPath) { + a.cancelRebootWatcher(name) + if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("remove stale reboot socket: %w", err) + } + qmpAddr = "unix:" + sockPath + } + } if prep.Runtime.Manifest.HasCapability("win32-unicode-input") { prep.Client.Env = append(prep.Client.Env, a.inputBridgeEnv(name, d.Directory)...) } @@ -129,8 +140,10 @@ func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error { } if mgr != nil { mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{ - VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, + VMName: name, VMDir: d.Directory, DriverID: builtin.IDDriverReimsMacOS, QMPAddr: qmpAddr, }) + } else if qmpAddr != "" { + a.watchWin10ColdReboot(name, qmpAddr) } a.startVMMonitor(name, d, startAt) a.emitLog(name, fmt.Sprintf("Resumed %s in %.1fs", name, time.Since(startAt).Seconds())) diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 27e6c07..aa74164 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -561,7 +561,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 2 { return fmt.Errorf("usage: reims-go vm stop ") } - _, release, err := vmstart.LockVM(ctx, client, args[1]) + release, err := vmstart.LockVMForStop(ctx, client, args[1], false) if err != nil { return err } @@ -622,10 +622,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 3 { return fmt.Errorf("usage: reims-go vm resize (e.g. 256G or +64G)") } - d, err := client.Show(ctx, args[1]) + d, release, err := vmstart.LockVM(ctx, client, args[1]) if err != nil { return err } + defer release() if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.resize.stop_first", args[1])) } @@ -644,10 +645,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if len(args) < 2 { return fmt.Errorf("usage: reims-go vm compact ") } - d, err := client.Show(ctx, args[1]) + d, release, err := vmstart.LockVM(ctx, client, args[1]) if err != nil { return err } + defer release() if d.State == "running" { return fmt.Errorf("%s", i18n.T(loc, "vm.compact.stop_first", args[1])) } diff --git a/internal/qmp/client.go b/internal/qmp/client.go index bc7ba3b..360e448 100644 --- a/internal/qmp/client.go +++ b/internal/qmp/client.go @@ -45,13 +45,17 @@ func (c *Conn) Close() error { return c.nc.Close() } type qmpReply struct { Return json.RawMessage `json:"return"` - Error *struct { - Class string `json:"class"` - Desc string `json:"desc"` - } `json:"error"` - Event string `json:"event"` + Error *commandError `json:"error"` + Event string `json:"event"` } +type commandError struct { + Class string `json:"class"` + Desc string `json:"desc"` +} + +func (e *commandError) Error() string { return e.Class + ": " + e.Desc } + // Query runs one command with the default 5-second timeout and waits for its // JSON return value, skipping async events. func (c *Conn) Query(command string, args any) (json.RawMessage, error) { @@ -82,7 +86,7 @@ func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration) continue } if r.Error != nil { - return nil, fmt.Errorf("QMP %s: %s: %s", command, r.Error.Class, r.Error.Desc) + return nil, fmt.Errorf("QMP %s: %w", command, r.Error) } if r.Return != nil { return append(json.RawMessage(nil), r.Return...), nil diff --git a/internal/qmp/migrate.go b/internal/qmp/migrate.go index 0e42803..69b2ef8 100644 --- a/internal/qmp/migrate.go +++ b/internal/qmp/migrate.go @@ -46,6 +46,27 @@ type vmStatusReply struct { Status string `json:"status"` } +// ErrIncompleteSuspend marks a save that QEMU rejected, failed, or cancelled. +// The caller may remove its staging file once QEMU no longer writes to it. +var ErrIncompleteSuspend = errors.New("incomplete suspend snapshot") + +type migrationFailure struct { + status string + desc string +} + +func (e *migrationFailure) Error() string { + if e.desc != "" { + return fmt.Sprintf("migration %s: %s", e.status, e.desc) + } + return "migration " + e.status +} + +// A timeout or a dropped connection can hide a completed migration. +type unknownSuspendOutcome struct{ error } + +func (e *unknownSuspendOutcome) Unwrap() error { return e.error } + // SuspendToFile pauses a running Intel VM via QMP, writes a mapped-ram + // multifd file snapshot to vmstatePath, waits for completion, and shuts down // QEMU cleanly via `quit`. @@ -54,7 +75,11 @@ type vmStatusReply struct { // (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so // the running VM is not left frozen. func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), seal func([]string) error) error { - c, err := Dial(ctx, "unix", SocketPath(vmDir)) + if seal == nil { + return errors.New("suspend snapshot requires a seal callback") + } + addr := SocketPath(vmDir) + c, err := Dial(ctx, "unix", addr) if err != nil { return err } @@ -63,7 +88,21 @@ func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress fu if err != nil { return err } - return suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) }) + err = suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) }) + var unknown *unknownSuspendOutcome + if errors.As(err, &unknown) { + _ = c.Close() + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 8*time.Second) + defer cancel() + fresh, dialErr := dialMigrateConnWithRetry(cleanup, "unix", addr, 3*time.Second) + if dialErr == nil { + defer fresh.Close() + if cancelIncompleteSuspend(cleanup, fresh) { + return fmt.Errorf("%w: %w", ErrIncompleteSuspend, err) + } + } + } + return err } func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress), seal func(*Conn) error) error { @@ -88,13 +127,21 @@ func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgr "channels": fileChannels(vmstatePath), } if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil { - tryResumePaused(c) - return fmt.Errorf("start snapshot save: %w", err) + var rejected *commandError + if errors.As(err, &rejected) { + tryResumePaused(c) + return fmt.Errorf("%w: start snapshot save: %w", ErrIncompleteSuspend, err) + } + return &unknownSuspendOutcome{fmt.Errorf("start snapshot save: %w", err)} } if err := waitMigrateDone(ctx, c, onProgress); err != nil { - tryResumePaused(c) - return fmt.Errorf("save snapshot: %w", err) + var failed *migrationFailure + if errors.As(err, &failed) { + tryResumePaused(c) + return fmt.Errorf("%w: save snapshot: %w", ErrIncompleteSuspend, err) + } + return &unknownSuspendOutcome{fmt.Errorf("save snapshot: %w", err)} } if seal != nil { if err := seal(c); err != nil { @@ -223,6 +270,43 @@ func tryResumePaused(c *Conn) { } } +func cancelIncompleteSuspend(ctx context.Context, c *Conn) bool { + cancelSent := false + for ctx.Err() == nil { + info, err := queryMigration(c, 2*time.Second) + if err != nil { + return false + } + switch info.Status { + case "failed", "cancelled": + tryResumePaused(c) + return true + case "completed", "none", "": + return false + } + if !cancelSent { + // Completion can race cancellation. Check the terminal status + // even if QEMU rejects the cancel request. + _ = c.ExecuteWithTimeout("migrate_cancel", nil, 2*time.Second) + cancelSent = true + } + sleep(ctx, migratePollInterval) + } + return false +} + +func queryMigration(c *Conn, timeout time.Duration) (migrateInfo, error) { + var info migrateInfo + raw, err := c.QueryWithTimeout("query-migrate", nil, timeout) + if err != nil { + return info, err + } + if err := json.Unmarshal(raw, &info); err != nil { + return info, fmt.Errorf("parse query-migrate: %w", err) + } + return info, nil +} + func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgress)) error { deadline := time.Now().Add(migrateTotalTimeout) for { @@ -232,14 +316,10 @@ func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgre if time.Now().After(deadline) { return errors.New("timed out waiting for migration to finish") } - raw, err := c.QueryWithTimeout("query-migrate", nil, migrateCmdTimeout) + info, err := queryMigration(c, migrateCmdTimeout) if err != nil { return err } - var info migrateInfo - if err := json.Unmarshal(raw, &info); err != nil { - return fmt.Errorf("parse query-migrate: %w", err) - } prog := MigrateProgress{ Status: info.Status, TotalTimeMs: info.TotalTimeMs, @@ -256,11 +336,7 @@ func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgre case "completed": return nil case "failed", "cancelled": - desc := strings.TrimSpace(info.ErrorDesc) - if desc != "" { - return fmt.Errorf("migration %s: %s", info.Status, desc) - } - return fmt.Errorf("migration %s", info.Status) + return &migrationFailure{status: info.Status, desc: strings.TrimSpace(info.ErrorDesc)} } sleep(ctx, migratePollInterval) } diff --git a/internal/qmp/migrate_test.go b/internal/qmp/migrate_test.go index 99aa261..4a1b8bb 100644 --- a/internal/qmp/migrate_test.go +++ b/internal/qmp/migrate_test.go @@ -11,8 +11,84 @@ import ( "strings" "sync" "testing" + "time" ) +func TestSuspendToFileRequiresSeal(t *testing.T) { + if err := SuspendToFile(context.Background(), t.TempDir(), "state", nil, nil); err == nil || + !strings.Contains(err.Error(), "seal callback") { + t.Fatalf("suspend without a seal callback: %v", err) + } +} + +func TestSuspendMigrationFailedBeforeSeal(t *testing.T) { + addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + reply := map[string]any{} + switch req.Execute { + case "query-status": + reply["status"] = "paused" + reply["running"] = false + case "query-migrate": + reply["status"] = "failed" + reply["error-desc"] = "write failed" + case "quit": + t.Error("QEMU would exit after an incomplete save") + } + return map[string]any{"return": reply}, false + }) + ctx := context.Background() + c, err := Dial(ctx, "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + err = suspendToFileConn(ctx, c, "state.tmp", nil, func(*Conn) error { + t.Error("an incomplete save reached seal") + return nil + }) + if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "write failed") { + t.Fatalf("incomplete save = %v", err) + } +} + +func TestCancelIncompleteSuspendRechecksTerminalStatus(t *testing.T) { + for _, terminal := range []string{"cancelled", "completed"} { + t.Run(terminal, func(t *testing.T) { + cancelled := false + addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) { + switch req.Execute { + case "query-migrate": + status := "active" + if cancelled { + status = terminal + } + return map[string]any{"return": map[string]any{"status": status}}, false + case "migrate_cancel": + cancelled = true + case "query-status": + return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false + } + return map[string]any{"return": map[string]any{}}, false + }) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + c, err := Dial(ctx, "tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + want := terminal == "cancelled" + if got := cancelIncompleteSuspend(ctx, c); got != want { + t.Fatalf("safe discard = %t, want %t", got, want) + } + cmds := recorded() + if sawCont := len(cmds) > 0 && cmds[len(cmds)-1].Execute == "cont"; sawCont != want { + t.Fatalf("unexpected rollback commands: %v", cmds) + } + }) + } +} + func TestAttachedFiles(t *testing.T) { vmDir := t.TempDir() disk := filepath.Join(vmDir, "disk.qcow2") @@ -76,7 +152,7 @@ func TestSuspendSealFailureDoesNotQuitSource(t *testing.T) { } defer c.Close() sealErr := errors.New("unable to publish state") - if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) { + if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) || errors.Is(err, ErrIncompleteSuspend) { t.Fatalf("suspend error = %v", err) } cmds := recorded() @@ -217,7 +293,7 @@ func TestSuspendToFileFailureResumesPausedVM(t *testing.T) { defer c.Close() err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil) - if err == nil || !strings.Contains(err.Error(), "disk full") { + if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "disk full") { t.Fatalf("expected disk full error, got %v", err) } var sawCont bool diff --git a/internal/qmp/watcher.go b/internal/qmp/watcher.go index bd46a2a..6c004b6 100644 --- a/internal/qmp/watcher.go +++ b/internal/qmp/watcher.go @@ -89,9 +89,7 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string { } cleaned = append(cleaned, tok) } - escaped := strings.ReplaceAll(sockPath, ",", ",,") - escaped = strings.ReplaceAll(escaped, `\`, `/`) - qmpVal := fmt.Sprintf("unix:%s,server=on,wait=off", escaped) + qmpVal := win10RebootUnixTarget(sockPath) if strings.ContainsAny(qmpVal, " \t") { qmpVal = `"` + strings.ReplaceAll(qmpVal, `"`, `\"`) + `"` } @@ -99,6 +97,29 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string { return strings.Join(cleaned, " ") } +func win10RebootUnixTarget(sockPath string) string { + escaped := strings.ReplaceAll(sockPath, ",", ",,") + escaped = strings.ReplaceAll(escaped, "\\", "/") + return "unix:" + escaped + ",server=on,wait=off" +} + +// HasWin10RebootUnixArgs checks for the private socket Reims-Go configured, +// without accepting other monitors declared in extra-args. +func HasWin10RebootUnixArgs(extraArgs, sockPath string) bool { + tokens := splitShellTokens(extraArgs) + want := win10RebootUnixTarget(sockPath) + var noReboot, socket bool + for i, token := range tokens { + if token == "-no-reboot" { + noReboot = true + } + if token == "-qmp" && i+1 < len(tokens) && strings.Trim(tokens[i+1], "'\"") == want { + socket = true + } + } + return noReboot && socket +} + func isManagedQMPTarget(arg string) bool { arg = strings.Trim(arg, "'\"") if !strings.HasSuffix(arg, ",server=on,wait=off") { diff --git a/internal/qmp/watcher_test.go b/internal/qmp/watcher_test.go index 5e93da5..8d3d0b2 100644 --- a/internal/qmp/watcher_test.go +++ b/internal/qmp/watcher_test.go @@ -10,6 +10,23 @@ import ( "time" ) +func TestHasWin10RebootUnixArgs(t *testing.T) { + sock := "D:\\VM data\\group,1\\reims-go-reboot.sock" + args := MergeWin10RebootUnixArgs("-machine q35", sock) + if !HasWin10RebootUnixArgs(args, sock) { + t.Fatal("saved socket with escaped comma and quoted path was not recognized") + } + if HasWin10RebootUnixArgs(strings.ReplaceAll(args, "-no-reboot", ""), sock) { + t.Fatal("recognized a monitor without the cold-reboot flag") + } + if HasWin10RebootUnixArgs(args, "D:/other/reims-go-reboot.sock") { + t.Fatal("recognized a different monitor") + } + if HasWin10RebootUnixArgs("-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off", sock) { + t.Fatal("recognized a legacy TCP monitor") + } +} + func TestMergeWin10RebootUnixArgs(t *testing.T) { got := MergeWin10RebootUnixArgs("", `D:\Data\reims-go\vms\m0\reims-go-reboot.sock`) want := "-no-reboot -qmp unix:D:/Data/reims-go/vms/m0/reims-go-reboot.sock,server=on,wait=off" diff --git a/internal/vmstart/suspend.go b/internal/vmstart/suspend.go index 958030f..f1566c1 100644 --- a/internal/vmstart/suspend.go +++ b/internal/vmstart/suspend.go @@ -41,6 +41,30 @@ func LockVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, return cur, release, nil } +// LockMutableVM protects configuration and media updates and rejects updates +// while a published suspend state depends on the current configuration. +func LockMutableVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) { + d, release, err := LockVM(ctx, c, name) + if err != nil { + return d, nil, err + } + if reims.HasSuspendState(d.Directory) { + release() + return d, nil, i18n.NewCodedError(c.Locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) + } + return d, release, nil +} + +// LockVMForStop serializes graceful shutdown. Emergency shutdown is also +// the escape path for a stalled operation that already holds the lock. +func LockVMForStop(ctx context.Context, c *reims.Client, name string, force bool) (func(), error) { + if force { + return func() {}, nil + } + _, release, err := LockVM(ctx, c, name) + return release, err +} + func (p *Prep) checkSuspendRuntime(d reims.VMDetail) error { kind := strings.ToLower(d.Kind) if !p.Runtime.Manifest.HasCapability("vm-suspend") || strings.Contains(kind, "arm64") || strings.Contains(kind, "aarch64") { @@ -87,7 +111,7 @@ func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress f return err }) if err != nil { - return info, err + return info, cleanupSuspendAttempt(tmp, err) } waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second) defer cancel() @@ -110,6 +134,15 @@ func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress f return info, nil } +func cleanupSuspendAttempt(tmp string, err error) error { + if errors.Is(err, qmp.ErrIncompleteSuspend) { + if removeErr := os.Remove(tmp); removeErr != nil && !os.IsNotExist(removeErr) { + return errors.Join(err, fmt.Errorf("remove incomplete snapshot: %w", removeErr)) + } + } + return err +} + // ResumeSnapshot owns the incoming launch and snapshot consumption while // the caller holds LockVM. The original configuration must be restored // before guest execution can continue. diff --git a/internal/vmstart/suspend_test.go b/internal/vmstart/suspend_test.go new file mode 100644 index 0000000..0d28b48 --- /dev/null +++ b/internal/vmstart/suspend_test.go @@ -0,0 +1,48 @@ +package vmstart + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/Nwflower/reims-go/internal/qmp" +) + +func TestForceStopDoesNotWaitForVMInspectionOrLock(t *testing.T) { + // A forced stop must not ask reims-ctl to show the VM before it can + // invoke stop --force. A stalled owner may also be holding its lock. + release, err := LockVMForStop(context.Background(), nil, "stalled", true) + if err != nil { + t.Fatal(err) + } + release() +} + +func TestCleanupSuspendAttempt(t *testing.T) { + for _, tt := range []struct { + name string + err error + keep bool + }{ + {"migration failed", fmt.Errorf("%w: disk full", qmp.ErrIncompleteSuspend), false}, + {"seal failed", errors.New("could not publish suspend metadata"), true}, + {"unknown outcome", errors.New("connection closed"), true}, + } { + t.Run(tt.name, func(t *testing.T) { + tmp := filepath.Join(t.TempDir(), "suspend.vmstate.tmp") + if err := os.WriteFile(tmp, []byte("snapshot data"), 0o600); err != nil { + t.Fatal(err) + } + if err := cleanupSuspendAttempt(tmp, tt.err); !errors.Is(err, tt.err) { + t.Fatalf("cleanup lost the save error: %v", err) + } + _, err := os.Stat(tmp) + if tt.keep && err != nil || !tt.keep && !os.IsNotExist(err) { + t.Fatalf("stat after cleanup = %v, want keep=%t", err, tt.keep) + } + }) + } +} From 5f8d96a40179a522f30e01b6f95411e7bf840a0b Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 09:05:57 +0800 Subject: [PATCH 11/23] fix(ui): align suspend confirmation and single-line toasts --- frontend/src/App.tsx | 4 ++-- frontend/src/styles/app.css | 7 +++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index ceda025..9f9c55c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1314,8 +1314,8 @@ export const App: React.FC = () => { closeLabel={tr('close')} onClose={() => setDiscardSuspendTarget(null)} > -
-

{tr('discardSuspendDesc')}

+
+

{tr('discardSuspendDesc')}

diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index d8c5c50..7e628f1 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -909,6 +909,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; } .dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; } .dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); } +.dialog-body > .dialog-desc:only-child { margin-top: 0; } .dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } .dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); } .dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; } @@ -957,8 +958,10 @@ button.status-issue + .status-metric { margin-left: 6px; } .toast[data-swipe="cancel"] { transform: translateX(0); transition: transform var(--dur) var(--ease-out); } .toast[data-swipe="end"] { animation: toast-swipe-out var(--dur-fast) var(--ease-out) both; } :root[dir="rtl"] .toast[data-swipe="end"] { animation: toast-swipe-out-rtl var(--dur-fast) var(--ease-out) both; } -.toast-main-row { display: flex; align-items: flex-start; gap: var(--sp-3); width: 100%; min-width: 0; } -.toast-main-row > svg { margin-top: 2px; flex-shrink: 0; } +.toast-main-row { display: flex; align-items: center; gap: var(--sp-3); width: 100%; min-width: 0; } +.toast-main-row > svg { flex-shrink: 0; } +.toast-main-row:has(.toast-desc) { align-items: flex-start; } +.toast-main-row:has(.toast-desc) > svg { margin-top: 2px; } .toast.ok .toast-main-row > svg { color: var(--status-running); } .toast.error .toast-main-row > svg { color: var(--status-error); } .toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; } From 003821a28aaccfe708ddd566043121ca69799033 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 09:14:02 +0800 Subject: [PATCH 12/23] fix(ui): refine VM suspend actions and confirmation --- docs/design-guidelines.md | 9 ++-- frontend/src/App.tsx | 41 +++++++---------- frontend/src/components/DeleteDialog.tsx | 42 ++++++----------- frontend/src/components/Sidebar.tsx | 5 ++- frontend/src/components/TitleMenus.tsx | 5 ++- frontend/src/components/VMPage.tsx | 57 +++++++++++++----------- frontend/src/i18n/domains/vm.gen.ts | 4 ++ frontend/src/i18n/keys.gen.ts | 2 + frontend/src/styles/app.css | 1 - frontend/src/ui/dialog.tsx | 32 ++++++++++++- frontend/src/wails.ts | 1 + frontend/wailsjs/go/models.ts | 2 + internal/app/app.go | 7 ++- internal/i18n/catalog_gen.go | 6 ++- internal/tray/tray.go | 24 ++++++---- internal/tray/tray_test.go | 15 +++++++ locales/en-US/native.json | 3 +- locales/en-US/vm.json | 2 + locales/zh-CN/native.json | 3 +- locales/zh-CN/vm.json | 2 + 20 files changed, 161 insertions(+), 102 deletions(-) diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index 1e75b1c..481e3fb 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -20,7 +20,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台 | :--- | :--- | | **声明式配置** | 一台虚拟机对应一份声明式配置,界面只编辑配置项,不让用户直接拼 QEMU 命令行参数。 | | **先校验,后保存** | 保存前在 Go 端完成前置校验(CPU 核数、可用提交内存上限、Vulkan ICD 路径存在性、切换磁盘控制器前是否已弹出安装盘),非法值在提交前拦截。 | -| **随时可编辑,标明生效时机** | 无论虚拟机运行与否,设置面板均可打开编辑;每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 | +| **标明设置的生效时机** | 虚拟机运行中或已停止时可编辑设置。每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 | **写入约束**:凡属于上游 `reims-ctl` 管理的配置项,一律通过 `reims-ctl set` 写入,不直接改写 `vm.toml`,确保上游校验与 OpenCore 重建逻辑照常生效。 @@ -55,11 +55,14 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台 | **正在创建** | 创建流程进行中 | 无(展示分步进度) | 取消创建 | | **已停止** | 上游 `stopped` | **启动** | 设置、恢复点、更多(派生副本、扩容/回收、打开目录、删除) | | **正在启动** | 发起 `start` 至 `running` | 启动中(忙碌态,禁用) | 设置、强制关机 | -| **运行中** | 上游 `running` | **显示 VM 窗口** | 关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) | +| **运行中** | 上游 `running` | **显示 VM 窗口** | 挂起(需支持此功能的内核)、关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) | | **正在停止** | 发起 `stop` 至 `stopped` | 停止中(忙碌态,禁用) | 强制关机 | +| **正在挂起** | 正在保存运行状态 | 挂起中(忙碌态,禁用) | 强制关机 | +| **已挂起** | 运行状态已保存到磁盘 | **恢复**(需支持此功能的内核) | 更多(放弃挂起状态、打开目录) | +| **正在恢复** | 正在从磁盘恢复运行状态 | 恢复中(忙碌态,禁用) | 强制关机 | | **配置损坏** | 上游 `broken` | **查看问题** | 打开目录、删除 | -- 暂不提供暂停或运行中热快照状态(`paused` / `saving` / `restoring`),直到上游验证 `reims-vgpu` 显存与设备状态序列化。 +- 已挂起时,恢复或放弃挂起状态后才可修改配置、管理磁盘和安装或弹出 Guest Tools。切换到不支持挂起的内核时,禁用恢复并提示用户切换内核。放弃挂起状态须经破坏性操作确认框确认。 - 禁用按钮不占据主操作位置;状态变化时直接切换为当前最合适的主操作。 --- diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 9f9c55c..11d5d38 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -20,7 +20,7 @@ import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFo import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats' import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' -import { Modal } from './ui/dialog' +import { ConfirmDialog, Modal } from './ui/dialog' import { Toaster, useToasts } from './ui/toast' import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails' @@ -335,15 +335,7 @@ export const App: React.FC = () => { const effectiveState = selectedVM ? (state?.transitions[selectedVM.name] ?? selectedVM.state) : '' const pending = selectedVM ? (state?.pending_changes[selectedVM.name] ?? []) : [] const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime - const activeManifest = state?.active_runtime?.manifest - const canSuspend = Boolean( - activeManifest?.capabilities?.some((c) => c.toLowerCase() === 'vm-suspend') - || ( - activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('win32-mapped-ram-io')) - && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('intel-whpx-suspend')) - && activeManifest?.patches?.some((p) => p.name.toLowerCase().includes('reims-vgpu-snapshot-replay')) - ), - ) + const canSuspend = state?.can_suspend ?? false onTaskRef.current = (task: Task) => { if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) { @@ -669,6 +661,7 @@ export const App: React.FC = () => { } const onVMActionFor = (name: string, action: VMAction, isRunning: boolean) => { + if (!canSuspend && (action === 'suspend' || action === 'resume')) return const activeBusy = activeVMBusy(name) if ( activeBusy @@ -905,7 +898,11 @@ export const App: React.FC = () => { useEffect(() => { const offSelect = events.onTraySelectVM((name) => { setSelected(name) }) const offNew = events.onTrayNewVM(() => { openWizardRef.current() }) - return () => { offSelect(); offNew() } + const offDiscard = events.onTrayDiscardSuspend((name) => { + setSelected(name) + setDiscardSuspendTarget(name) + }) + return () => { offSelect(); offNew(); offDiscard() } }, []) // Native Wails file drag-and-drop delivery into the selected VM's shared folder. @@ -1309,22 +1306,14 @@ export const App: React.FC = () => { )} {discardSuspendTarget && ( - setDiscardSuspendTarget(null)} - > -
-

{tr('discardSuspendDesc')}

-
-
- - - - - -
-
+ description={tr('discardSuspendDesc')} + cancelLabel={tr('cancel')} + confirmLabel={tr('discardSuspendConfirm')} + onCancel={() => setDiscardSuspendTarget(null)} + onConfirm={confirmDiscardSuspend} + /> )} {cloneSource && ( diff --git a/frontend/src/components/DeleteDialog.tsx b/frontend/src/components/DeleteDialog.tsx index fd2e4b8..50943b1 100644 --- a/frontend/src/components/DeleteDialog.tsx +++ b/frontend/src/components/DeleteDialog.tsx @@ -1,7 +1,7 @@ -import * as Alert from '@radix-ui/react-alert-dialog' import React, { useState } from 'react' import { t } from '../i18n' import { Locale } from '../types' +import { ConfirmDialog } from '../ui/dialog' interface Props { locale: Locale @@ -13,32 +13,18 @@ interface Props { export const DeleteDialog: React.FC = ({ locale, name, onCancel, onConfirm }) => { const [keepFiles, setKeepFiles] = useState(false) return ( - { if (!open) onCancel() }}> - - - -
- {t(locale, 'deleteTitle', { name })} - - {t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')} - - -
-
- - - - - - -
-
-
-
+ onConfirm(keepFiles)} + > + + ) } diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index c6bdd41..850dc2e 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -25,7 +25,7 @@ interface Props { selected: string hostReady: boolean /** Whether the active runtime supports VM suspend/resume. */ - canSuspend?: boolean + canSuspend: boolean onSelect: (id: string) => void /** VM name → display name (its note); empty or missing shows the name. */ displayNames?: Record @@ -164,9 +164,10 @@ export const Sidebar: React.FC = ({ )} {suspended && ( <> - onVMContextAction(vm.name, 'resume')}> + onVMContextAction(vm.name, 'resume')}> {tr('resume')} + {!canSuspend && {tr('resumeUnavailable')}} onVMContextAction(vm.name, 'discardSuspend')}> {tr('discardSuspend')} diff --git a/frontend/src/components/TitleMenus.tsx b/frontend/src/components/TitleMenus.tsx index 4253d95..477d11b 100644 --- a/frontend/src/components/TitleMenus.tsx +++ b/frontend/src/components/TitleMenus.tsx @@ -27,7 +27,7 @@ interface Props { canDark?: boolean onThemeMode: (mode: ThemeMode) => void /** The selected VM and its current state, or null on the system pages. */ - vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend?: boolean } | null + vm: { name: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null onNewVM: () => void onVMAction: (action: VMAction) => void onVMSettings: () => void @@ -220,8 +220,9 @@ export const TitleMenus: React.FC = ({ {running ? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) : suspended - ? item(tr('resume'), () => onVMAction('resume'), { shortcut: 'Ctrl+Enter', disabled: vmBusy }) + ? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend }) : item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })} + {suspended && !vm?.canSuspend && {tr('resumeUnavailable')}} {item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })} {item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })} {item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })} diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index f42998f..cf1adb0 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -41,7 +41,7 @@ import { Upload, UserRound, } from 'lucide-react' -import React, { useEffect, useRef, useState } from 'react' +import React, { useEffect, useId, useRef, useState } from 'react' import { I18nKey, locText, t } from '../i18n' import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, @@ -97,7 +97,7 @@ interface Props { macosMajor: number | null state: string /** Whether the active runtime supports VM suspend/resume. */ - canSuspend?: boolean + canSuspend: boolean /** Whether the native VM-window installation guide is currently active for this boot. */ guideActive: boolean /** Whether the builtin.install-guide plugin is enabled. */ @@ -144,6 +144,9 @@ export const VMPage: React.FC = ({ const busy = busyAction !== undefined const running = state === 'running' const suspended = state === 'suspended' + const guestToolsLocked = suspended || state === 'suspending' || state === 'resuming' + const resumeHintId = useId() + const guestToolsHintId = useId() const installing = !!detail && (detail.has_installer || detail.recovery_mode) const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' // Polled here rather than in App so each tick re-renders only this page. @@ -338,17 +341,19 @@ export const VMPage: React.FC = ({ ) } else if (suspended) { primary = ( - - ) - secondary = ( - - ) } else if (state === 'starting') { primary = } else if (state === 'stopping') { @@ -444,11 +449,6 @@ export const VMPage: React.FC = ({ : <> {tr('enterFullscreen')}} )} - {canSuspend && ( - onAction('suspend')}> - {tr('suspend')} - - )} onAction('restart')}> {tr('restart')} @@ -644,7 +644,7 @@ export const VMPage: React.FC = ({ startLabel={suspended ? tr('resume') : tr('start')} showLabel={tr('showWindow')} shotLabel={tr('copyScreenshot')} - onStart={!busy && (state === 'stopped' || suspended) ? () => onAction(suspended ? 'resume' : 'start') : undefined} + onStart={!busy && (state === 'stopped' || (suspended && canSuspend)) ? () => onAction(suspended ? 'resume' : 'start') : undefined} onShow={running && !busy ? () => onAction('focus') : undefined} onScreenshot={running && !busy ? () => onAction('screenshot') : undefined} /> @@ -738,6 +738,7 @@ export const VMPage: React.FC = ({ ? tr('suspendedNoticeDescWithTime', { time: suspTime, size: suspSize }) : tr('suspendedNoticeDesc', { size: suspSize })}
+ {!canSuspend && {tr('resumeUnavailable')}}
@@ -933,6 +934,10 @@ export const VMPage: React.FC = ({ const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3 // Plugin switched off: show the state and hide controls that would only fail. const gtOff = !!detail.guest_tools_disabled + const gtAttached = detail.guest_tools_attached + const showToolsAction = !gtOff && (gtAttached || !gtConnected || needsUpgrade) + const toolsAction = gtAttached ? 'detachGuestTools' : 'attachGuestTools' + const toolsActionLabel = gtAttached ? 'detachGuestTools' : needsUpgrade ? 'gtUpdate' : 'gtInstall' // One status word per state; how files are shared goes in the tooltip. let gtTone: 'ok' | 'warn' | 'idle' = 'idle' @@ -1045,20 +1050,20 @@ export const VMPage: React.FC = ({
+ {suspended && showToolsAction && ( + {tr('suspendedGuestToolsHint')} + )}
- {gtOff ? null : detail.guest_tools_attached ? ( - - ) : (!gtConnected || needsUpgrade) && ( + {showToolsAction && ( )}
diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 312faa3..1a97e4e 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -119,6 +119,7 @@ export const vmZh: Record = { "pickRecoveryTitle": "选择离线镜像(.img / .dmg)", "restartToApply": "重启以应用", "resume": "恢复", + "resumeUnavailable": "切换到支持挂起的内核后可恢复", "sendText": "发送文本到虚拟机…", "sendTextConfirm": "发送 (Ctrl+Enter)", "sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。", @@ -171,6 +172,7 @@ export const vmZh: Record = { "state_suspended": "已挂起", "state_suspending": "挂起中", "suspend": "挂起", + "suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改", "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", "suspendedNoticeTitle": "已保存运行状态", @@ -333,6 +335,7 @@ export const vmEn: Record = { "pickRecoveryTitle": "Choose an offline image (.img / .dmg)", "restartToApply": "Restart to apply", "resume": "Resume", + "resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM", "sendText": "Send text to VM…", "sendTextConfirm": "Send (Ctrl+Enter)", "sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.", @@ -385,6 +388,7 @@ export const vmEn: Record = { "state_suspended": "Suspended", "state_suspending": "Suspending", "suspend": "Suspend", + "suspendedGuestToolsHint": "Resume or discard saved state to make changes", "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", "suspendedNoticeTitle": "Saved state ready", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index ffd4062..9ee8854 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -625,6 +625,7 @@ export type I18nKey = | "restart" | "restartToApply" | "resume" + | "resumeUnavailable" | "runtimeAlpha" | "runtimeAlphaHint" | "runtimeChannel_alpha" @@ -786,6 +787,7 @@ export type I18nKey = | "summarySSHPort" | "summarySource" | "suspend" + | "suspendedGuestToolsHint" | "suspendedNoticeDesc" | "suspendedNoticeDescWithTime" | "suspendedNoticeTitle" diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 7e628f1..6710013 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -909,7 +909,6 @@ button.status-issue + .status-metric { margin-left: 6px; } .dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); letter-spacing: -0.01em; text-wrap: balance; } .dialog-desc { font-size: var(--fs-13); color: var(--text-2); margin-top: 2px; } .dialog-body { padding: 20px 22px; overflow-y: auto; overscroll-behavior: contain; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); } -.dialog-body > .dialog-desc:only-child { margin-top: 0; } .dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } .dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); } .dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; } diff --git a/frontend/src/ui/dialog.tsx b/frontend/src/ui/dialog.tsx index 7ce95d4..16ddcdc 100644 --- a/frontend/src/ui/dialog.tsx +++ b/frontend/src/ui/dialog.tsx @@ -1,7 +1,37 @@ +import * as Alert from '@radix-ui/react-alert-dialog' import * as RDialog from '@radix-ui/react-dialog' import { X } from 'lucide-react' import React from 'react' -import { IconButton } from './controls' +import { Button, IconButton } from './controls' + +interface ConfirmDialogProps { + title: string + description: string + cancelLabel: string + confirmLabel: string + onCancel: () => void + onConfirm: () => void + children?: React.ReactNode +} + +export const ConfirmDialog: React.FC = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => ( + { if (!open) onCancel() }}> + + + +
+ {title} + {description} + {children} +
+
+ + +
+
+
+
+) interface Props { title: string diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 184007d..182aaa8 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -180,6 +180,7 @@ export const events = { // Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…". onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb), onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb), + onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb), // Renderer health watchdog & crash reporting (internal/app/ui_health.go). onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb), emitUIPong: () => eventsEmit('reims:ui-pong'), diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index bd48390..2423b4e 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -6,6 +6,7 @@ export namespace app { optimizations: host.Optimization[]; runtimes: runtime.Installed[]; active_runtime?: runtime.Installed; + can_suspend: boolean; vms: reims.VMListItem[]; transitions: Record; pending_changes: Record>; @@ -30,6 +31,7 @@ export namespace app { this.optimizations = this.convertValues(source["optimizations"], host.Optimization); this.runtimes = this.convertValues(source["runtimes"], runtime.Installed); this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed); + this.can_suspend = source["can_suspend"]; this.vms = this.convertValues(source["vms"], reims.VMListItem); this.transitions = source["transitions"]; this.pending_changes = this.convertValues(source["pending_changes"], Array, true); diff --git a/internal/app/app.go b/internal/app/app.go index f9a0183..9c035eb 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -43,6 +43,7 @@ type AppState struct { Optimizations []host.Optimization `json:"optimizations"` Runtimes []rt.Installed `json:"runtimes"` ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"` + CanSuspend bool `json:"can_suspend"` VMs []reims.VMListItem `json:"vms"` Transitions map[string]string `json:"transitions"` PendingChanges map[string][]PendingChange `json:"pending_changes"` @@ -658,6 +659,7 @@ func (a *App) GetState() AppState { Optimizations: opts, Runtimes: runtimes, ActiveRuntime: active, + CanSuspend: active != nil && active.Manifest.HasCapability("vm-suspend"), VMs: vms, Transitions: trCopy, PendingChanges: pcCopy, @@ -852,7 +854,10 @@ func (a *App) trayVMAction(name string, act tray.Action) { case tray.ActResume: err, failTitle = a.ResumeVM(name), i18n.M(loc, "tray.notify.resume_fail", vars) case tray.ActDiscardSuspend: - err, failTitle = a.DiscardSuspend(name), i18n.M(loc, "tray.notify.discard_suspend_fail", vars) + a.ShowMainWindow() + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:tray-discard-suspend", name) + } case tray.ActStop: err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars) case tray.ActForceStop: diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index edc8c67..61dcba3 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -440,13 +440,14 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "已保存 SSH 用户名", "toastSaved": "已保存", "toastSavedNextStart": "已保存,下次启动生效", - "tray.menu.discard_suspend": "放弃挂起状态(&X)", + "tray.menu.discard_suspend": "放弃挂起状态…(&X)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.new_vm": "新建虚拟机(&N)…", "tray.menu.open_in_app": "在 Reims-Go 中查看(&V)", "tray.menu.quit": "退出 Reims-Go(&Q)", "tray.menu.restart": "重启(&R)", "tray.menu.resume": "恢复(&U)", + "tray.menu.resume_unavailable": "恢复(当前内核不支持挂起)", "tray.menu.screenshot": "复制屏幕截图(&C)", "tray.menu.shared_folder": "打开共享文件夹(&H)", "tray.menu.show": "显示 Reims-Go(&O)", @@ -973,13 +974,14 @@ var catalog = map[Locale]map[string]string{ "toastSSHUserSaved": "Saved SSH username", "toastSaved": "Saved", "toastSavedNextStart": "Saved — applies on next start", - "tray.menu.discard_suspend": "Discard Saved Stat&e", + "tray.menu.discard_suspend": "Discard Saved Stat&e…", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.new_vm": "&New Virtual Machine…", "tray.menu.open_in_app": "Show in &Reims-Go", "tray.menu.quit": "&Quit Reims-Go", "tray.menu.restart": "&Restart", "tray.menu.resume": "Res&ume", + "tray.menu.resume_unavailable": "Resume (runtime lacks suspend support)", "tray.menu.screenshot": "&Copy Screenshot", "tray.menu.shared_folder": "Open S&hared Folder", "tray.menu.show": "&Show Reims-Go", diff --git a/internal/tray/tray.go b/internal/tray/tray.go index 4523320..41f3cbc 100644 --- a/internal/tray/tray.go +++ b/internal/tray/tray.go @@ -94,15 +94,17 @@ type menuEntry struct { } type texts struct { - show, newVM, quit string - start, stop, forceStop, restart, showWindow, shot string - suspend, resume, discardSuspend string - shared, openInApp string - running, stopped, suspended string - starting, stopping, suspending, resuming string - broken, unknown string + show, newVM, quit string + start, stop, forceStop, restart, showWindow, shot string + suspend, resume, discardSuspend string + shared, openInApp string + running, stopped, suspended string + starting, stopping, suspending, resuming string + broken, unknown string toggleFullscreen string + + resumeUnavailable string } func menuTexts(snap Snapshot) texts { @@ -140,6 +142,8 @@ func menuTexts(snap Snapshot) texts { unknown: i18n.T(loc, "tray.state.unknown"), toggleFullscreen: i18n.T(loc, "tray.menu.toggle_fullscreen"), + + resumeUnavailable: i18n.T(loc, "tray.menu.resume_unavailable"), } } @@ -199,7 +203,11 @@ func buildMenu(snap Snapshot) []menuEntry { case "suspended": dot, state = dotSuspended, t.suspended resume := cmd(ActResume, t.resume) - resume.Default = true + resume.Default = snap.CanSuspend + if !snap.CanSuspend { + resume.Label = t.resumeUnavailable + resume.Disabled = true + } sub = []menuEntry{ resume, cmd(ActDiscardSuspend, t.discardSuspend), sep, cmd(ActSharedFolder, t.shared), sep, diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go index ced0237..b08ff95 100644 --- a/internal/tray/tray_test.go +++ b/internal/tray/tray_test.go @@ -72,6 +72,21 @@ func TestBuildMenuPerState(t *testing.T) { } } +func TestSuspendedVMWithoutCompatibleRuntime(t *testing.T) { + menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{{Name: "macos-sleep", State: "suspended"}}}) + vm := findEntry(menu, "macos-sleep\t已挂起") + if vm == nil { + t.Fatal("suspended VM is missing from the tray menu") + } + resume := vm.Sub[0] + if resume.ID != vmCmd(0, ActResume) || !resume.Disabled || resume.Default || resume.Label != "恢复(当前内核不支持挂起)" { + t.Fatalf("resume should be disabled and explain why: %+v", resume) + } + if discard := vm.Sub[1]; discard.ID != vmCmd(0, ActDiscardSuspend) || discard.Disabled { + t.Fatalf("discard should remain available: %+v", discard) + } +} + func TestDecodeVMCmdRoundTrip(t *testing.T) { for i := 0; i < maxTrayVMs; i++ { for act := ActStart; act <= ActDiscardSuspend; act++ { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 0b80880..0fdcee5 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -409,7 +409,8 @@ "tray.menu.start": "&Start", "tray.menu.suspend": "Sus&pend", "tray.menu.resume": "Res&ume", - "tray.menu.discard_suspend": "Discard Saved Stat&e", + "tray.menu.resume_unavailable": "Resume (runtime lacks suspend support)", + "tray.menu.discard_suspend": "Discard Saved Stat&e…", "tray.menu.stop": "Shut &Down", "tray.menu.force_stop": "&Force Shut Down", "tray.menu.restart": "&Restart", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index f5bfc2c..6f2f87e 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -51,6 +51,7 @@ "state_broken": "Error", "suspend": "Suspend", "resume": "Resume", + "resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM", "discardSuspend": "Discard saved state", "discardSuspendTitle": "Discard saved state for “{name}”?", "discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.", @@ -59,6 +60,7 @@ "suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.", "suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.", "suspendedSettingsHint": "Resume or discard saved state before changing settings", + "suspendedGuestToolsHint": "Resume or discard saved state to make changes", "toastSuspended": "{name} suspended", "toastResumed": "{name} resumed", "toastDiscardSuspend": "Discarded saved state for {name}", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index b36a181..91ce361 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -409,7 +409,8 @@ "tray.menu.start": "启动(&S)", "tray.menu.suspend": "挂起(&P)", "tray.menu.resume": "恢复(&U)", - "tray.menu.discard_suspend": "放弃挂起状态(&X)", + "tray.menu.resume_unavailable": "恢复(当前内核不支持挂起)", + "tray.menu.discard_suspend": "放弃挂起状态…(&X)", "tray.menu.stop": "关机(&D)", "tray.menu.force_stop": "强制关机(&F)", "tray.menu.restart": "重启(&R)", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 3a68042..a8ab8f3 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -51,6 +51,7 @@ "state_broken": "出错", "suspend": "挂起", "resume": "恢复", + "resumeUnavailable": "切换到支持挂起的内核后可恢复", "discardSuspend": "放弃挂起状态", "discardSuspendTitle": "放弃「{name}」的挂起状态?", "discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。", @@ -59,6 +60,7 @@ "suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", "suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。", "suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置", + "suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改", "toastSuspended": "{name} 已挂起", "toastResumed": "{name} 已恢复", "toastDiscardSuspend": "已放弃 {name} 的挂起状态", From 059c1a3b76b97d70411c204fae6978664cf1ae9b Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 10:23:07 +0800 Subject: [PATCH 13/23] fix(guesttools): authenticate macOS Windows drive mounts --- internal/guesttools/drive_mount_test.go | 137 +++++++++++++++++++++ internal/guesttools/drive_share.go | 4 +- internal/guesttools/image.go | 157 ++++++++++++++---------- internal/guesttools/server.go | 4 +- 4 files changed, 234 insertions(+), 68 deletions(-) create mode 100644 internal/guesttools/drive_mount_test.go diff --git a/internal/guesttools/drive_mount_test.go b/internal/guesttools/drive_mount_test.go new file mode 100644 index 0000000..c5e173d --- /dev/null +++ b/internal/guesttools/drive_mount_test.go @@ -0,0 +1,137 @@ +package guesttools + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestGuestAgentDriveMount(t *testing.T) { + shBin, err := exec.LookPath("sh") + if err != nil { + shBin = filepath.Join(os.Getenv("ProgramFiles"), "Git", "bin", "sh.exe") + if _, err := os.Stat(shBin); err != nil { + t.Skip("POSIX shell is unavailable") + } + } + + dir := t.TempDir() + helper := `#!/usr/bin/perl +use strict; +use warnings; +die "Unexpected mount options" unless @ARGV == 9 && "@ARGV[0..5]" eq "-a 3 -S -o rdonly -v"; +my ($drive) = $ARGV[6] =~ /^Windows ([A-Z])$/; +my ($url, $target) = @ARGV[7..8]; +die "Unexpected WebDAV URL" unless $url eq "http://10.0.2.2:19847/dav/mac%20test/drives/$drive/"; +die "Unexpected mount point" unless $target eq "$ENV{DRIVE_MOUNT_ROOT}/$drive"; +open(my $auth, "<&=3") or die "Missing credential descriptor: $!"; +seek($auth, 0, 0) or die "Credential descriptor is not seekable: $!"; +binmode($auth); +local $/; +die "Invalid credential payload" unless <$auth> eq pack("Na5Na64NNN", 5, "reims", 64, "a" x 64, 0, 0, 0); +if ($drive eq "O" && -f $ENV{FAIL_O}) { + print STDERR "Authentication failed\n"; + exit 22; +} +open(my $mounts, ">>", $ENV{MOUNT_STATE}) or die "Could not record mount: $!"; +print $mounts "$url on $target (webdav, read-only)\n"; +` + if err := os.WriteFile(filepath.Join(dir, "mount_webdav"), []byte(helper), 0o755); err != nil { + t.Fatal(err) + } + script := string(GuestAgentScript()) + harness := `set -eu +PATH="$PWD:/usr/bin:/bin:$PATH" +command -v perl >/dev/null 2>&1 || exit 77 +HOME="$PWD/home with spaces" +DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives" +TMP_DIR="$PWD/tmp" +MOUNT_STATE="$PWD/mounts" +FAIL_O="$PWD/fail-O" +export DRIVE_MOUNT_ROOT MOUNT_STATE FAIL_O +REIMS_HOST_URL="http://10.0.2.2:19847/" +REIMS_VM="mac test" +REIMS_TOKEN="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +mkdir -p "$DRIVE_MOUNT_ROOT" "$HOME/Desktop" "$TMP_DIR" +: >"$MOUNT_STATE" +: >"$FAIL_O" +mount() { cat "$MOUNT_STATE"; } +umount() { + [ ! -f "$PWD/busy-${1##*/}" ] || return 1 + awk -v point="$1" 'index($0, " on " point " (webdav") == 0' "$MOUNT_STATE" >"$MOUNT_STATE.next" + mv "$MOUNT_STATE.next" "$MOUNT_STATE" +} +` + scriptSection(t, script, "urlencode() {", "\nhash_file() {") + + scriptSection(t, script, "\ndrive_mount_failures=", "\napply_host_config() {") + ` +sync_drive_mounts '{"shared_drives":["F","O","P"]}' +sync_drive_mounts '{"shared_drives":["F","O","P"]}' +test "$(wc -l <"$MOUNT_STATE")" -eq 2 +test "$(readlink "$HOME/Desktop/Windows F")" = "$DRIVE_MOUNT_ROOT/F" +test ! -L "$HOME/Desktop/Windows O" + +rm "$FAIL_O" +sync_drive_mounts '{"shared_drives":["O","P"]}' +test "$(wc -l <"$MOUNT_STATE")" -eq 2 +test "$(readlink "$HOME/Desktop/Windows O")" = "$DRIVE_MOUNT_ROOT/O" +test ! -e "$DRIVE_MOUNT_ROOT/F" +test ! -L "$HOME/Desktop/Windows F" +test -z "$(ls -A "$TMP_DIR")" + +ln -s "$TMP_DIR" "$DRIVE_MOUNT_ROOT/F" +sync_drive_mounts '{"shared_drives":["F","O","P"]}' +sync_drive_mounts '{"shared_drives":["O","P"]}' +test -L "$DRIVE_MOUNT_ROOT/F" +test "$(wc -l <"$MOUNT_STATE")" -eq 2 + +: >"$PWD/busy-P" +sync_drive_mounts '{"shared_drives":["O"]}' +test -L "$HOME/Desktop/Windows P" +test "$(wc -l <"$MOUNT_STATE")" -eq 2 +rm "$PWD/busy-P" +mkdir "$DRIVE_MOUNT_ROOT/Q" +printf '/dev/disk2 on %s (apfs, local)\n' "$DRIVE_MOUNT_ROOT/Q" >>"$MOUNT_STATE" +sync_drive_mounts '{"shared_drives":["O","Q"]}' +test ! -e "$DRIVE_MOUNT_ROOT/P" +test ! -L "$HOME/Desktop/Windows P" +test ! -e "$HOME/Desktop/Windows Q" +unmount_unused_drives "" +test -d "$DRIVE_MOUNT_ROOT/Q" +test "$(wc -l <"$MOUNT_STATE")" -eq 1 +` + if err := os.WriteFile(filepath.Join(dir, "test.sh"), []byte(harness), 0o644); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, shBin, "test.sh") + cmd.Dir = dir + cmd.Env = append(os.Environ(), "LC_ALL=C", "MSYS=winsymlinks:lnk") + out, err := cmd.CombinedOutput() + if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 77 { + t.Skip("Perl is unavailable for reading the seekable credential descriptor") + } + const wantLog = "Windows drive O: mount failed (exit 22)\nAuthentication failed\n" + + "Windows drive F: mount failed (exit 1)\nMount point is a symbolic link: " + lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") + if err != nil || len(lines) != 4 || !strings.HasPrefix(string(out), wantLog) || + !strings.HasSuffix(lines[3], "/home with spaces/ReimsWindowsDrives/F") { + t.Fatalf("guest drive mount failed: %v\n%s", err, out) + } +} + +func scriptSection(t *testing.T, script, start, end string) string { + t.Helper() + startAt := strings.Index(script, start) + if startAt < 0 { + t.Fatalf("missing script section %q", start) + } + section, _, ok := strings.Cut(script[startAt:], end) + if !ok { + t.Fatalf("missing end of script section %q", start) + } + return section + "\n" +} diff --git a/internal/guesttools/drive_share.go b/internal/guesttools/drive_share.go index e499fd6..a5cbc3a 100644 --- a/internal/guesttools/drive_share.go +++ b/internal/guesttools/drive_share.go @@ -12,8 +12,8 @@ import ( "golang.org/x/net/webdav" ) -// DriveShareAgentVersion is the first macOS agent that applies dynamic drive mounts. -const DriveShareAgentVersion = 4 +// DriveShareAgentVersion is the minimum agent version recommended for drive sharing. +const DriveShareAgentVersion = 7 // NormalizeDriveLetter accepts C, C:, or C:\ and returns the canonical letter C. func NormalizeDriveLetter(raw string) (string, bool) { diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 0a16051..2415203 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -198,64 +198,67 @@ ensure_webdav_mount() { } sleep_active="false" +drive_mount_failures="" +previous_desired_drives="" -is_drive_mounted() { - mount 2>/dev/null | grep -F "on $1 (" >/dev/null 2>&1 -} +` + guestDriveCleanup + ` -update_drive_link() { - letter="$1" - mount_point="$DRIVE_MOUNT_ROOT/$letter" - link="$HOME/Desktop/Windows $letter" - if [ -L "$link" ]; then - [ "$(readlink "$link" 2>/dev/null || true)" = "$mount_point" ] && return 0 - rm -f "$link" 2>/dev/null || true - elif [ -e "$link" ]; then - return 0 +mount_drive_readonly() ( + drive="$1" + target="$2" + if [ -L "$target" ]; then + printf 'Mount point is a symbolic link: %s\n' "$target" >&2 + return 1 fi - ln -s "$mount_point" "$link" 2>/dev/null || true -} + mkdir -p "$target" || return 1 + token_length=${#REIMS_TOKEN} + if [ "$token_length" -eq 0 ] || [ "$token_length" -gt 255 ]; then + printf 'Invalid WebDAV credential length\n' >&2 + return 1 + fi + dav_url="${REIMS_HOST_URL%/}/dav/$(urlencode "$REIMS_VM")/drives/$drive/" -remove_drive_link() { - letter="$1" - mount_point="$DRIVE_MOUNT_ROOT/$letter" - link="$HOME/Desktop/Windows $letter" - if [ -L "$link" ] && [ "$(readlink "$link" 2>/dev/null || true)" = "$mount_point" ]; then - rm -f "$link" 2>/dev/null || true - fi -} - -unmount_drive() { - letter="$1" - mount_point="$DRIVE_MOUNT_ROOT/$letter" - if is_drive_mounted "$mount_point"; then - umount "$mount_point" >/dev/null 2>&1 || true - fi - remove_drive_link "$letter" - if ! is_drive_mounted "$mount_point"; then - rmdir "$mount_point" 2>/dev/null || true - fi -} + # Use the credential descriptor accepted by Apple's WebDAV NetFS helper. + # Each field has a 32-bit big-endian length: user, password, proxy + # user, proxy password, then TLS properties. The descriptor must be seekable. + auth_file=$(mktemp "$TMP_DIR/drive-auth.XXXXXX") || return 1 + trap 'rm -f "$auth_file"' EXIT + { + rm -f "$auth_file" || return 1 + printf '\000\000\000\005reims' >&3 || return 1 + printf '\000\000\000%b%s' "\\0$(printf '%03o' "$token_length")" "$REIMS_TOKEN" >&3 || return 1 + printf '\000\000\000\000\000\000\000\000\000\000\000\000' >&3 || return 1 + exec mount_webdav -a 3 -S -o rdonly -v "Windows $drive" "$dav_url" "$target" + } 3<>"$auth_file" +) mount_drive() { letter="$1" mount_point="$DRIVE_MOUNT_ROOT/$letter" - if is_drive_mounted "$mount_point"; then - update_drive_link "$letter" - return 0 - fi - command -v mount_webdav >/dev/null 2>&1 || return 0 - host_addr=${REIMS_HOST_URL#http://} - host_addr=${host_addr#https://} - host_addr=${host_addr%/} - dav_url="http://reims:${REIMS_TOKEN}@${host_addr}/dav/${REIMS_VM}/drives/${letter}/" - mkdir -p "$mount_point" - # Prefer a client read-only mount where supported; the host remains the authority. - if mount_webdav -o ro -v "Windows $letter" "$dav_url" "$mount_point" >/dev/null 2>&1 || \ - mount_webdav -o ro "$dav_url" "$mount_point" >/dev/null 2>&1 || \ - mount_webdav -v "Windows $letter" "$dav_url" "$mount_point" >/dev/null 2>&1 || \ - mount_webdav "$dav_url" "$mount_point" >/dev/null 2>&1; then - update_drive_link "$letter" + case "$(drive_mount_type "$mount_point")" in + webdav) ;; + "") + mount_output=$(mount_drive_readonly "$letter" "$mount_point" 2>&1) || { + mount_status=$? + case "$drive_mount_failures" in + *"$letter"*) ;; + *) + printf 'Windows drive %s: mount failed (exit %s)\n' "$letter" "$mount_status" >&2 + [ -z "$mount_output" ] || printf '%s\n' "$mount_output" >&2 + drive_mount_failures="$drive_mount_failures$letter" + ;; + esac + return 0 + } + ;; + *) return 0 ;; + esac + case "$drive_mount_failures" in + *"$letter"*) drive_mount_failures=$(printf '%s' "$drive_mount_failures" | tr -d "$letter") ;; + esac + link="$HOME/Desktop/Windows $letter" + if [ ! -L "$link" ] && [ ! -e "$link" ]; then + ln -s "$mount_point" "$link" 2>/dev/null || true fi } @@ -264,14 +267,11 @@ sync_drive_mounts() { desired=$(printf '%s\n' "$cfg_json" | \ sed -n 's/.*"shared_drives"[[:space:]]*:[[:space:]]*\[\([^]]*\)\].*/\1/p' | \ tr ',' '\n' | sed -n 's/^[[:space:]]*"\([A-Z]\)"[[:space:]]*$/\1/p' | tr '\n' ' ') - for mount_point in "$DRIVE_MOUNT_ROOT"/*; do - [ -d "$mount_point" ] || continue - letter=${mount_point##*/} - case " $desired " in - *" $letter "*) ;; - *) unmount_drive "$letter" ;; - esac - done + if [ "$desired" != "$previous_desired_drives" ]; then + previous_desired_drives="$desired" + drive_mount_failures="" + fi + unmount_unused_drives "$desired" for letter in $desired; do mount_drive "$letter" done @@ -638,19 +638,46 @@ DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives" uid=$(id -u) launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true umount "$SHARE_MOUNT" 2>/dev/null || true -for mount_point in "$DRIVE_MOUNT_ROOT"/*; do - [ -d "$mount_point" ] || continue - letter=${mount_point##*/} - umount "$mount_point" 2>/dev/null || true - link="$HOME/Desktop/Windows $letter" - [ -L "$link" ] && rm -f "$link" 2>/dev/null || true -done +` + guestDriveCleanup + ` +unmount_unused_drives "" rm -f "$PLIST" rm -rf "$APP_DIR" echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept." `) } +const guestDriveCleanup = ` +drive_mount_type() { + [ ! -L "$1" ] || return 0 + mount 2>/dev/null | awk -v target=" on $1 (" ' + pos = index($0, target) { + split(substr($0, pos + length(target)), options, /[,)]/) + print options[1] + exit + } + ' +} + +unmount_unused_drives() { + for drive_path in "$DRIVE_MOUNT_ROOT"/*; do + [ -d "$drive_path" ] && [ ! -L "$drive_path" ] || continue + drive_letter=${drive_path##*/} + case "$drive_letter" in [A-Z]) ;; *) continue ;; esac + case " $1 " in *" $drive_letter "*) continue ;; esac + case "$(drive_mount_type "$drive_path")" in + webdav) umount "$drive_path" >/dev/null 2>&1 || continue ;; + "") ;; + *) continue ;; + esac + drive_link="$HOME/Desktop/Windows $drive_letter" + if [ -L "$drive_link" ] && [ "$(readlink "$drive_link")" = "$drive_path" ]; then + rm -f "$drive_link" 2>/dev/null || true + fi + rmdir "$drive_path" 2>/dev/null || true + done +} +` + // GuestPmsetScript offers an optional system-wide pmset configuration command // for users who want persistent no-sleep settings even before login. func GuestPmsetScript() []byte { diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index bb5aacb..910b480 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -37,6 +37,8 @@ const ( ConfigFileName = ".reims-go-tools.json" ) +const bridgeProtocolVersion = 4 + // ErrGuestToolsNotConnected is returned when a guest-assisted operation // requires a live Guest Tools agent inside macOS. var ErrGuestToolsNotConnected = errors.New("guest tools not connected") @@ -692,7 +694,7 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(map[string]any{ "ok": true, "vm": vm.name, - "version": DriveShareAgentVersion, + "version": bridgeProtocolVersion, "capabilities": caps, }) } From fc196316760b55adfb9084aa8028e104b54e9fd9 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 09:47:41 +0800 Subject: [PATCH 14/23] build: source the runtime from the Reims vGPU and QEMU forks --- .github/workflows/build-runtime.yml | 19 +- AGENTS.md | 2 +- docs/portable-runtime-spec.md | 12 +- patches/README.md | 144 +- patches/qemu-intel-whpx-suspend.patch | 906 ---- patches/qemu-whpx-nested-virt-nonfatal.patch | 25 - patches/qemu-whpx-win10-compat.patch | 77 - patches/qemu-whpx-win10-startup-ipis.patch | 104 - .../qemu-win32-coroutine-fiber-commit.patch | 60 - patches/qemu-win32-mapped-ram-io.patch | 727 --- patches/reims-ctl-qcow2-l2-cache.patch | 52 - .../reims-ctl-virtio-discard-iothread.patch | 53 - patches/reims-ctl-win32-random-bytes.patch | 30 - patches/reims-vgpu-display-fixed-mode.patch | 265 - patches/reims-vgpu-snapshot-replay.patch | 4309 ----------------- patches/reims-vgpu-win32-unicode-input.patch | 243 - patches/series.txt | 15 +- scripts/check-runtime-alpha.ps1 | 2 + scripts/pack-runtime.ps1 | 32 +- 19 files changed, 61 insertions(+), 7016 deletions(-) delete mode 100644 patches/qemu-intel-whpx-suspend.patch delete mode 100644 patches/qemu-whpx-nested-virt-nonfatal.patch delete mode 100644 patches/qemu-whpx-win10-compat.patch delete mode 100644 patches/qemu-whpx-win10-startup-ipis.patch delete mode 100644 patches/qemu-win32-coroutine-fiber-commit.patch delete mode 100644 patches/qemu-win32-mapped-ram-io.patch delete mode 100644 patches/reims-ctl-qcow2-l2-cache.patch delete mode 100644 patches/reims-ctl-virtio-discard-iothread.patch delete mode 100644 patches/reims-ctl-win32-random-bytes.patch delete mode 100644 patches/reims-vgpu-display-fixed-mode.patch delete mode 100644 patches/reims-vgpu-snapshot-replay.patch delete mode 100644 patches/reims-vgpu-win32-unicode-input.patch diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 376e939..7721a94 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -1,6 +1,6 @@ name: Build Portable Runtime (Alpha) -# Daily: build the newest steelbrain/reims-vgpu commit with the patch queue +# Daily: build the newest runtime fork commit with the dependency patch queue # (patches/series.txt) and publish it as a GitHub prerelease = the alpha # channel (portable-runtime-spec.md section 6). Never publishes stable: # promotion needs a real-host smoke test and a person (AGENTS.md rule 6). @@ -10,7 +10,7 @@ on: workflow_dispatch: inputs: upstream_commit: - description: "steelbrain/reims-vgpu commit (empty = upstream default branch HEAD)" + description: "Reims vGPU fork commit (empty = runtime branch HEAD)" required: false default: "" publish: @@ -31,7 +31,8 @@ concurrency: cancel-in-progress: false env: - UPSTREAM_URL: https://github.com/steelbrain/reims-vgpu.git + UPSTREAM_URL: https://github.com/yxc0915/reims-vgpu.git + UPSTREAM_BRANCH: codex/intel-vm-suspend KEEP_ALPHAS: "7" # unpromoted alpha prereleases kept; older ones are deleted jobs: @@ -49,8 +50,9 @@ jobs: REBUILD: ${{ inputs.rebuild }} run: | set -euo pipefail - git clone -q --filter=blob:none --no-checkout "$UPSTREAM_URL" up + git clone -q --filter=blob:none --no-checkout --single-branch --branch "$UPSTREAM_BRANCH" "$UPSTREAM_URL" up commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")" + git -C up cat-file -e "$commit:reims-go-runtime.json" echo "commit=$commit" >> "$GITHUB_OUTPUT" # Already published (alpha or stable) under any short-hash length or -pN revision? max_rev=0 @@ -115,7 +117,7 @@ jobs: mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip - - name: Check out upstream and apply the patch queue + - name: Check out the runtime forks and apply dependency patches id: patches shell: pwsh run: | @@ -125,7 +127,7 @@ jobs: # The runner's git defaults to core.autocrlf=true; LF patches need an LF # checkout (upstream also rewrites CRLF files to LF, install-ctl.sh). git config --global core.autocrlf false - git clone -q $env:UPSTREAM_URL $work + git clone -q --single-branch --branch $env:UPSTREAM_BRANCH $env:UPSTREAM_URL $work if ($LASTEXITCODE) { throw 'clone failed' } git -C $work checkout -q '${{ needs.resolve.outputs.commit }}' if ($LASTEXITCODE) { throw 'checkout failed' } @@ -240,7 +242,7 @@ jobs: $ErrorActionPreference = 'Stop' & ./scripts/check-runtime-alpha.ps1 ` -OutDir (Join-Path $env:RUNNER_TEMP 'releases') ` - -Commit $env:RELEASE_ID -RequireSlim ` + -Commit $env:RELEASE_ID -RequireSlim -RequiredCapability vm-suspend ` -Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') ` -AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ }) @@ -263,13 +265,14 @@ jobs: $ErrorActionPreference = 'Stop' $c = $env:RELEASE_ID $short = $env:SHORT_COMMIT + $sourceRepo = $env:UPSTREAM_URL -replace '\.git$', '' $dir = Join-Path $env:RUNNER_TEMP 'releases' $assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$c.tar.zst", 'SHA256SUMS.txt') | ForEach-Object { Join-Path $dir $_ } $applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' } $merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' } $notes = @" - **Alpha** runtime (``$c``), built automatically from upstream [steelbrain/reims-vgpu@$short](https://github.com/steelbrain/reims-vgpu/commit/${{ needs.resolve.outputs.commit }}). + **Alpha** runtime (``$c``), built from [the Reims vGPU fork@$short]($sourceRepo/commit/${{ needs.resolve.outputs.commit }}). Not smoke-tested on a real host. It becomes stable only after ``scripts/smoke-runtime.ps1`` passes on a real Windows host and a person approves (portable-runtime-spec.md section 6). diff --git a/AGENTS.md b/AGENTS.md index 266b695..1047b63 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,7 +50,7 @@ 1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时核对对应上游 commit 与 `文件:行号`;未实测项显式标注「待验证」。 2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:[`.github/workflows/build-runtime.yml`](.github/workflows/build-runtime.yml) 每日从上游构建,通过 `alpha` 准入检查后自动发布为 GitHub 预发布(`alpha` 通道),并自动清理较旧的未升级 `alpha` 预发布。 3. **敏感与专有内容零入库**:严禁提交 SMC OSK、SMBIOS 真实序列号、MAC 地址、任何 Apple IPSW / BaseSystem / 解密固件或闭源二进制。 -4. **对上游的修改只走补丁队列**:不长期维护 fork。补丁放 [`patches/`](patches/),顺序与状态统一在 [`patches/series.txt`](patches/series.txt) 与 [`patches/README.md`](patches/README.md) 维护,目标是清零。补丁打不上就停下报告,不要自动改写补丁。 +4. **运行时源码与依赖补丁**:Reims vGPU 和 QEMU 的源码修改由各自运行时 fork 维护。客户端构建使用 [`patches/series.txt`](patches/series.txt) 应用其余依赖补丁。源码入口、顺序与状态见 [`patches/README.md`](patches/README.md)。补丁打不上就停下报告,不要自动改写补丁。 5. **运行时包如实声明来源**:`manifest.json` 必须写清上游各仓库 commit 与实际应用的全部补丁;带补丁的包不得宣称为纯上游构建。 6. **默认用户只拿 `stable` 通道**:CI 产物先入 `alpha`,经真实宿主冒烟并人工确认后才升为 `stable`(见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。 7. **配置写入只走 `reims-ctl set`**:不直接改写 `vm.toml`,保证上游校验与 OpenCore 重建生效(见 [`docs/design-guidelines.md`](docs/design-guidelines.md))。 diff --git a/docs/portable-runtime-spec.md b/docs/portable-runtime-spec.md index b737c8b..1cd4a3b 100644 --- a/docs/portable-runtime-spec.md +++ b/docs/portable-runtime-spec.md @@ -77,7 +77,7 @@ reims-runtime-/ 运行 `pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出以下发布附件: 1. `reims-runtime-win-x64-.tar.zst`(运行时主体) 2. `reims-runtime-symbols-.tar.zst`(独立调试符号包) -3. `reims-runtime-src-.tar.zst`(上游源码 + 补丁原文 + 重建说明) +3. `reims-runtime-src-.tar.zst`(运行时源码、依赖补丁和重建说明) 4. `reims-runtime-msys2-src-.tar.zst`(MSYS2 copyleft DLL 源码包,由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 生成) 5. `SHA256SUMS.txt`(覆盖上述压缩包的统一校验清单) @@ -85,10 +85,10 @@ reims-runtime-/ ### 3.2 每日 CI 构建 [`.github/workflows/build-runtime.yml`](../.github/workflows/build-runtime.yml) 每日定时(也支持手动指定 commit)在 `windows-latest`(MSYS2 CLANG64)执行: -1. 读取上游默认分支 `HEAD`;若已存在 `runtime-` Release(不论 `alpha` 或 `stable`)则跳过。 -2. 由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按 [`patches/series.txt`](../patches/series.txt) 顺序打补丁:可正常应用的直接应用;已合入上游的自动跳过并开 Issue 提醒退役;遇到冲突则中止构建。 +1. 读取 Reims vGPU fork 的运行时分支,并检出其中固定的 QEMU fork 提交。若该 Reims vGPU 提交已有运行时 Release,则跳过。 +2. 按 [`patches/series.txt`](../patches/series.txt) 顺序为固定的依赖版本应用补丁。已合入上游的补丁会跳过并报告,遇到冲突时中止构建。 3. 执行上游 `scripts/install-ctl.sh --yes` 编译,调用 `scripts/pack-runtime.ps1 -Channel alpha` 打包。 -4. 运行 [`scripts/check-runtime-alpha.ps1`](../scripts/check-runtime-alpha.ps1) 校验 5 个附件、`SHA256SUMS.txt`、`manifest.json` 哈希一致、许可证齐全,以及在不含 MSYS2 的纯净 `PATH` 下验证 vGPU 设备枚举、CLI 版本与 `qcow2` 创建读取。 +4. 运行 [`scripts/check-runtime-alpha.ps1`](../scripts/check-runtime-alpha.ps1) 校验附件哈希、许可证、挂起能力声明,以及在不含 MSYS2 的 `PATH` 下验证 vGPU 设备枚举、CLI 版本和 `qcow2` 创建读取。 5. 通过后发布为 GitHub 预发布(`alpha`),并自动清理超过保留上限(最近 7 个)的旧 `alpha` 预发布;正式版不受影响。 > **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。 @@ -100,11 +100,11 @@ reims-runtime-/ ## 4. 补丁队列 -本仓库不维护长期 fork,所有尚未合入上游的最小兼容性补丁统一维护在 [`patches/`](../patches/)。补丁清单、作用对象、上游化进展与退役检查表见: +Reims vGPU 和 QEMU 的修改由各自的运行时 fork 维护。客户端仓库在 [`patches/`](../patches/) 维护其他运行时依赖的补丁。源码和补丁入口如下。 - 机器清单:[`patches/series.txt`](../patches/series.txt) - 维护文档:[`patches/README.md`](../patches/README.md) -运行时包的 `manifest.json` 必须如实列出所有实际应用的补丁与哈希,带补丁的构建不得标注为纯上游版本。 +运行时包的 `manifest.json` 记录源码仓库、提交、运行时能力及打包时应用的依赖补丁和哈希。 --- diff --git a/patches/README.md b/patches/README.md index cfe32b1..cc09515 100644 --- a/patches/README.md +++ b/patches/README.md @@ -1,140 +1,24 @@ -# 上游临时补丁队列与 PR 跟踪(Upstream Patch Queue) +# 运行时源码与依赖补丁 -本目录存放**尚未被上游合入的最小兼容性补丁**。补丁的应用顺序与作用仓库以 [`series.txt`](series.txt) 为唯一机器清单,CI([`.github/workflows/build-runtime.yml`](../.github/workflows/build-runtime.yml))与本地打包脚本([`scripts/pack-runtime.ps1`](../scripts/pack-runtime.ps1))均只读取该文件。 +Reims-Go 独立构建桌面客户端。便携运行时使用以下源码分支。 -## 维护原则 +| 组件 | 源码 | 维护范围 | +| :--- | :--- | :--- | +| Reims vGPU | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu/tree/codex/intel-vm-suspend) | GPU 挂起重放、窗口和 CLI 兼容性修复 | +| QEMU | [`yxc0915/qemu-reims-vgpu`](https://github.com/yxc0915/qemu-reims-vgpu/tree/codex/intel-vm-suspend) | Windows WHPX、文件迁移和设备状态保存恢复 | -1. **不长期维护 fork**:所有底层修复优先向相应上游仓库提交 PR。目标仓库包括 [`reims-vgpu`](https://github.com/steelbrain/reims-vgpu)、[`qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)、[`reims-util`](https://github.com/steelbrain/reims-util) 和 [`metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。 -2. **人工提 PR,冲突即停**:更新上游基线时由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按顺序执行 `git apply --check`。已合入上游(反向检查通过)的补丁会自动跳过并开 Issue 提醒退役;遇到冲突时立刻中止构建,不自动改写补丁。 -3. **文件格式约束**:所有 `.patch` 文件必须为 **无 BOM、LF 行尾**(由 `.gitattributes` 中的 `*.patch -text` 约束),避免 `git apply` 在 Windows 上失败。 -4. **来源透明与协议兼容**:每个运行时包的 `manifest.json` 与 `patches/` 目录必须如实记录实际应用的全部补丁及哈希;本目录补丁不适用根目录的 Apache-2.0,而是遵循目标上游兼容协议(详见 [`patches/LICENSE`](LICENSE))。 +Reims vGPU 分支通过 `vendor/qemu` 固定 QEMU 提交,并在 `reims-go-runtime.json` 声明运行时能力。更新 QEMU 时先把新提交推到 QEMU fork,再更新 Reims vGPU 的子模块指针。Reims-Go 构建据此记录两个源码仓库及提交号。 -本地构建时,`-UtilRepo` 指向 `reims-ctl` 固定版本的 `reims-util` 工作树,`-Metal2VulkanRepo` 指向 `reims-vgpu/Cargo.toml` 固定版本的 `metal2vulkan` 工作树(并通过 `$CARGO_HOME/config.toml` 的 `[patch."https://github.com/steelbrain/metal2vulkan"]` 覆盖,使 `reims-vgpu/Cargo.lock` 与上游保持逐字节一致)。用相同的 MSYS2 CLANG64 工具链构建后,把同一组工作树传给打包脚本。 +## 构建时应用的依赖补丁 ---- +[`series.txt`](series.txt) 是可执行清单。依赖检出版本由 Reims vGPU 源码固定。补丁冲突会停止构建。 -## 当前补丁清单 +| 补丁 | 依赖 | 作用 | +| :--- | :--- | :--- | +| [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `steelbrain/reims-util` | 有 Apple 分块校验数据时并发下载离线安装包,按顺序验证并写入镜像。 | +| [`metal2vulkan-snapshot-replay.patch`](metal2vulkan-snapshot-replay.patch) | `steelbrain/metal2vulkan` | 读取和恢复缓冲、纹理及事件状态,为 GPU 挂起重放提供依赖。 | -以下顺序与 [`series.txt`](series.txt) 保持一致: - -| 补丁文件 | 目标仓库与路径 | 解决的问题 | 当前状态 | -| :--- | :--- | :--- | :--- | -| [`reims-vgpu-win32-unicode-input.patch`](reims-vgpu-win32-unicode-input.patch) | `reims-vgpu` (`crates/reims-vgpu-window`) | 通过 `SDL_SetWindowsMessageHook` 在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时转发非物理按键的 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`,解决 Windows IME 与中文输入被吞 | 待编入 `alpha` 冒烟验证后提 PR | -| [`reims-vgpu-display-fixed-mode.patch`](reims-vgpu-display-fixed-mode.patch) | `reims-vgpu` (`crates/reims-vgpu-window`, `crates/reims-vgpu`) | 新增 `REIMS_VGPU_WINDOW_FIXED_MODE=1` 将全屏/窗口物理尺寸与客体渲染分辨率解耦,按 `scale * (guest_w / drawable_w)` 推导有效 DPI,并在帧尺寸与目标区域不一致时自动走线性采样 GPU 着色器缩放(支持 4K 全屏 1.5× 超采样 `5120×2880` HiDPI) | `git apply --check` 在 `3731afd9` 通过;待编入 `alpha` 真机验证后提 PR | -| [`reims-ctl-win32-random-bytes.patch`](reims-ctl-win32-random-bytes.patch) | `reims-vgpu` (`crates/reims-ctl/src/vm.rs`) | 修复 Windows 下打不开 `/dev/urandom` 时回退到低熵时间戳种子的缺陷,改用标准库 `RandomState`(底层调用 `ProcessPrng`)生成 MAC/ROM 随机字节 | `git apply --check` 通过;待编入 `alpha` 验证后提 PR | -| [`reims-ctl-virtio-discard-iothread.patch`](reims-ctl-virtio-discard-iothread.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 为 VirtIO 系统盘补齐 `discard=unmap`(与 NVMe 一致透传客体 TRIM)并启用独立 `-object iothread,id=io0`,避免块完成回调与 QEMU 主循环争抢 | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;真机实测与休眠唤醒通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | -| [`reims-ctl-qcow2-l2-cache.patch`](reims-ctl-qcow2-l2-cache.patch) | `reims-vgpu` (`crates/reims-ctl/src/qemu.rs`) | 按 `qcow2` 文件头虚拟容量与簇大小计算全覆盖所需 `l2-cache-size`(上限 32 MiB,仅大于 8 MiB 默认值时追加),避免非 Linux 宿主默认 8 MiB 上限仅覆盖 64 GiB | `git apply --check` 在 `3731afd9` 与上游 `main` 均通过;128 GiB 镜像真机实测通过,暂留 `patches/` 待编入 `alpha` 验证后提 PR | -| [`reims-vgpu-snapshot-replay.patch`](reims-vgpu-snapshot-replay.patch) | `reims-vgpu` (`crates/reims-vgpu*`) | 实现 GPU 静止、实时对象日志与 `RVGSNAP1` 二进制编解码(含统一计数边界校验、因果父对象保留、`whole_library_key` 索引及未附着延迟 SurfaceCache 持久化)、显存与事件保存/重放及严格错误传播 | 单元测试、双进程 RTX A5000 Vulkan 测试及 Intel macOS 26.7.3 同 PID Metal 读回实测通过;待提 PR | -| [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `reims-util` (`src/http.rs`, `src/installer.rs`) | 对有 Apple 分块校验数据的完整离线包并发请求四段,按顺序校验并写入镜像。分段读取失败时用原有单路下载继续 | 待编入 `alpha` 冒烟验证 | -| [`metal2vulkan-snapshot-replay.patch`](metal2vulkan-snapshot-replay.patch) | `metal2vulkan` (`crates/metal2vulkan-runtime/src/`) | 暴露 Private/Shared/Managed 缓冲与纹理(含多层/多 Mip)及事件计数的快照读出与精确地址/内容回写接口 | 随 `reims-vgpu-snapshot-replay.patch` 在干净 checkout 构建并实测通过;待提 PR | -| [`qemu-whpx-win10-compat.patch`](qemu-whpx-win10-compat.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 修复 Windows 10 19045 上两处 WHPX 必现崩溃(探测 TSC deadline 污染主分区、`WHvResetPartition` 未判空) | 已在 Win10 19045 真机验证并随稳定运行时发布;待提 PR | -| [`qemu-whpx-win10-startup-ipis.patch`](qemu-whpx-win10-startup-ipis.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 在 Win10 开启 `kernel-irqchip` 且多核启动时经 `WHvRequestInterrupt` 转发 INIT/SIPI,避免 XNU 从核卡死(依赖上一项) | 8/12 核冷启动通过;客体软重启待验证,待提 PR | -| [`qemu-whpx-nested-virt-nonfatal.patch`](qemu-whpx-nested-virt-nonfatal.patch) | `vendor/qemu` (`target/i386/whpx/whpx-all.c`) | 部分 Win11 宿主设置嵌套虚拟化属性返回 `0x80370302` 时改为警告并清零特性位,保留 `kernel-irqchip=on` 加速(依赖前两项) | 待编入 `alpha` 并在 Win11 真机验证后提 PR | -| [`qemu-win32-coroutine-fiber-commit.patch`](qemu-win32-coroutine-fiber-commit.patch) | `vendor/qemu` (`util/coroutine-windows.c`) | 改用 `CreateFiberEx(64 KiB, 1 MiB, ...)` 将协程初始提交降至 1/16,并判空与检查 `IsThreadAFiber()`,避免高并发 I/O 时 `SwitchToFiber(NULL)` 崩溃 | `git apply --check` 通过;待编入 `alpha` 真机验证后提 PR | -| [`qemu-win32-mapped-ram-io.patch`](qemu-win32-mapped-ram-io.patch) | `vendor/qemu` (`io/channel*.c`, `migration/*.c`) | 为 Win32 `QIOChannelFile` 实现 `preadv`/`pwritev`(合并读写路径、零写保护与文件指针恢复),并解除 `mapped-ram` + `multifd` 文件快照在 Windows 下的 POSIX 限制 | Win11 WHPX 真机跨进程及真实宿主重启恢复实测通过;待提 PR | -| [`qemu-intel-whpx-suspend.patch`](qemu-intel-whpx-suspend.patch) | `vendor/qemu` (`accel/whpx/`, `target/i386/whpx/`, `hw/misc/applesmc.c`, `hw/display/reims-graphics-pci.c`, `migration/`) | 为 Intel x86-64 WHPX 实现停机文件挂起(限制在已暂停 VM 的 `MIG_MODE_NORMAL` + `file:` 迁移入口,保留非 `normal`/在线迁移与 `savevm` 拦截)、完整 LAPIC/x2APIC/TSC/AppleSMC 与 `reims-graphics-pci` VMState 保存恢复 | 7 项 QMP 闸门回归 + Win11 WHPX 真机解锁桌面同 PID Metal 读回及真实宿主重启通过;待提 PR | - ---- - -## 待上游化 PR 证据摘要 - -### 1. `reims-vgpu-win32-unicode-input.patch` -- **目标**:`steelbrain/reims-vgpu`(`crates/reims-vgpu-window`:`native/windows.rs`、`native/sdl_thread/ui.rs`) -- **根因**:SDL3 窗口层未启用文本输入且仅转发 `0x04..=0xE7` 物理扫描码,扫描码为 0 的 `VK_PACKET` 及 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`(宿主机 IME、中文、语音与远程输入)全部被丢弃。 -- **最小修复**:仅在检测到 `REIMS_GO_INPUT_URL`(限定回环地址)时挂接 `SDL_SetWindowsMessageHook` 异步转发非物理字符;对 `WM_CHAR` 按 `lParam` 硬件扫描码(`scan_code == 0`)过滤(不比对 `msg.time`,避免 `TranslateMessage` 写入当前 `GetTickCount()` 导致物理按键被二次转发),对物理键码路径零影响。 - -### 1b. `reims-vgpu-display-fixed-mode.patch` -- **目标**:`steelbrain/reims-vgpu`(`crates/reims-vgpu-window/src/env.rs`、`crates/reims-vgpu/src/graphics.rs`、`crates/reims-vgpu/src/graphics/sink.rs`) -- **根因**:上游 `WindowScreen::mode()` 始终以窗口/全屏物理像素作为唯一客体显示模式,`encode_shown` 对 `BGRA8` 表面默认走 1:1 blit 拷贝不缩放;在 4K 全屏下 macOS 仅提供 1×(3840×2160)和 2× HiDPI(1920×1080),无法渲染 1.5× 超采样(`5120×2880` 2× HiDPI 下采样至 4K,看起来像 `2560×1440`)。 -- **最小修复**:新增可选环境变量 `REIMS_VGPU_WINDOW_FIXED_MODE=1`(默认关闭,对上游默认路径零影响),启用时 `WindowScreen::mode()` 保持上报配置分辨率并按 `host_scale * (guest_w / drawable_w)` 计算 `scale_120ths`;在 `sink.rs` 中当帧尺寸与绘制区域不一致时自动切换至已有的线性采样 `displayPresentFragment` GPU 着色器(含启动/恢复阶段原始 scanout 的暂存纹理缩放)。 -- **实测状态**:已在 `3731afd9` 通过 `git apply --check`,待编入 `alpha` 运行时真机验证。 - -### 2. `reims-ctl-win32-random-bytes.patch` -- **目标**:`steelbrain/reims-vgpu`(`crates/reims-ctl/src/vm.rs:849-864`) -- **根因**:`random_bytes()` 在 `/dev/urandom` 不可用时退回 `纳秒时间 ^ (pid << 64)`。Windows 始终走此分支,导致新 VM 的 MAC 后 3 字节(OpenCore ROM)熵值极低且可预测。 -- **最小修复**:改用标准库 `std::collections::hash_map::RandomState`(Windows 上基于 `ProcessPrng`)派生随机字节,不引入额外依赖。 - -### 3. `qemu-whpx-win10-compat.patch` -- **建议 PR 标题**:`whpx: probe TSC deadline on throwaway partition and guard WHvResetPartition` -- **目标**:`steelbrain/qemu-reims-vgpu`(`target/i386/whpx/whpx-all.c`) -- **影响环境**:Windows 10 22H2(Build 19045)启用 WHPX 的 x86-64 宿主。 -- **根因**: - 1. `whpx_tsc_deadline_refused()`(`whpx-all.c:3211`)在正式分区上临时创建并删除 vCPU 0,导致随后 `whpx_init_vcpu()` 再次创建 vCPU 0 时 `WHvCreateVirtualProcessor` 必现 `E_INVALIDARG (0x80070057)`。 - 2. `whpx_set_registers()`(`whpx-all.c:530`)直接调用 Win11 新增的 `WHvResetPartition` 未判空,Win10 上触发空指针崩溃(`0xc0000005`)。 -- **最小修复**:在独立临时分区中完成 TSC deadline 探测并销毁;调用 `WHvResetPartition` 前判空。 -- **实测证据**:已在 Windows 10 19045 真机通过多轮冷启动与桌面运行验证。 - -### 4. `qemu-whpx-win10-startup-ipis.patch` -- **建议 PR 标题**:`whpx: forward INIT/SIPI via WHvRequestInterrupt on legacy Windows 10 with kernel-irqchip` -- **目标**:`steelbrain/qemu-reims-vgpu`(`target/i386/whpx/whpx-all.c`,依赖补丁 3) -- **影响环境**:Windows 10 19045 开启 `kernel-irqchip=on` 的多核 macOS 客体。 -- **根因**:Win10 内核态 APIC 仿真下,XNU 启动从核发出的第二次 SIPI 可能无法唤醒已 `HLT` 的从核,导致多核启动停住。 -- **最小修复**:仅在 `whpx_is_legacy_os() && whpx_irqchip_in_kernel() && ms->smp.max_cpus > 1` 且宿主支持 `X64ApicInitSipiExitTrap` 时捕获 INIT/SIPI 并经 `WHvRequestInterrupt` 转发(忽略 INIT level deassert)。 -- **实测证据**:Win10 19045 上 8 核与 12 核冷启动均通过 x2APIC、FileVault、SSH 与图形登录;纯补丁下客体软重启仍待进一步验证。 - -### 5. `qemu-whpx-nested-virt-nonfatal.patch` -- **建议 PR 标题**:`whpx: make nested virtualization property failure non-fatal` -- **目标**:`steelbrain/qemu-reims-vgpu`(`target/i386/whpx/whpx-all.c`,依赖补丁 3、4) -- **影响环境**:部分 Windows 11 宿主(如 24H2 / Home 或 Core Ultra 200 系列)。 -- **根因**:`WHvGetCapability` 报告支持嵌套虚拟化,但设置 `WHvPartitionPropertyCodeNestedVirtualization` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)。原代码将其视为致命错误并中止启动,迫使退回 `kernel-irqchip=off`。 -- **最小修复**:改为 `warn_report` 并清零 `Bank1.NestedVirtSupport`,保留 `kernel-irqchip=on` 加速。 -- **实测状态**:宿主探测已复现该错误码;含补丁的运行时待真机编译冒烟验证。 - -### 6. `qemu-win32-coroutine-fiber-commit.patch` -- **建议 PR 标题**:`util/coroutine-windows: reserve 1 MiB stack with 64 KiB initial commit and check fiber creation` -- **目标**:`steelbrain/qemu-reims-vgpu`(`util/coroutine-windows.c`) -- **影响环境**:Windows 10 / 11 高并发磁盘 I/O 与 VA-API 显存提交叠加场景(如登录 Apple ID 触发 iCloud / Spotlight 并发读盘与硬解)。 -- **根因**:`qemu_coroutine_new()`(`coroutine-windows.c:78`)调用 `CreateFiber(1 MiB, ...)` 预提交整块 1 MiB 协程栈,提交内存吃紧时返回 `NULL` 且未判空,进入 `SwitchToFiber(NULL)` 触发 `0xc0000005`(读 `0x10`);`qemu_coroutine_self()` 未检查线程是否已是 Fiber。 -- **最小修复**:改用 `CreateFiberEx(64 * 1024, COROUTINE_STACK_SIZE, 0, ...)` 将初始提交降为 64 KiB;用 `IsThreadAFiber()` 复用已有 Fiber;对 `NULL` 打印 `GetLastError()` 并显式 `abort()`。 -- **实测状态**:已通过 `git apply --check`,待编入 `alpha` 运行时真机验证。 - -### 7. `reims-ctl-virtio-discard-iothread.patch` -- **建议 PR 标题**:`reims-ctl: enable discard=unmap and dedicated iothread on VirtIO system disk` -- **目标**:`steelbrain/reims-vgpu`(`crates/reims-ctl/src/qemu.rs`) -- **影响环境**:使用 VirtIO 系统盘控制器的 macOS 26 虚拟机(Windows WHPX 与 Linux KVM)。 -- **根因**:`q35()` 的 `DiskController::Virtio` 分支未追加 `discard=unmap`(导致客体 TRIM 被丢弃,与 NVMe 分支不一致),且块处理与图形/事件共享 QEMU 主循环。 -- **最小修复**:在 `DiskController::Virtio` 分支追加 `discard=unmap` 与 `-object iothread,id=io0`,并在 `virtio-blk-pci` 上设置 `iothread=io0`,同步更新同文件单元测试。 -- **实测证据**(Windows 10 19045 WHPX + i7-12700K + NVMe SSD + macOS 26.7.3,128 GiB / 54 GiB 已分配,每项 5 轮客体冷缓存 `sudo purge`): - - 消融对照(纯 VirtIO 无 `iothread` vs VirtIO + `iothread`):启用 `iothread` 使 `read-rand` 降 22.3%(297.8 → 231.5 ms)、`create-fullfsync` 降 14.6%(7,723 → 6,597 ms)、`rand-read-large` 降 14.2%(1,222 → 1,049 ms)、`inc-make` 降 11.5%(2,488 → 2,203 ms)。 - - 对比 NVMe 基线:`read-rand` 降 19.3%(286.9 → 231.5 ms)、`rand-read-large` 冷/热分别降 15.5% / 36.5%(1,242 → 1,049 ms / 1,624 → 1,032 ms)、`create-fullfsync` 降 7.5%(7,132 → 6,597 ms);休眠唤醒与校验写入通过。 - -### 8. `reims-ctl-qcow2-l2-cache.patch` -- **建议 PR 标题**:`reims-ctl: size qcow2 l2-cache-size from image header (up to 32 MiB)` -- **目标**:`steelbrain/reims-vgpu`(`crates/reims-ctl/src/qemu.rs`) -- **影响环境**:Windows / macOS 非 Linux 宿主上虚拟容量大于 64 GiB(64 KiB 簇)的 `qcow2` 系统盘。 -- **根因**:QEMU 在非 Linux 宿主将默认 L2 缓存上限设为 8 MiB(Linux 为 32 MiB),128 GiB 镜像全覆盖需 16 MiB,超出 64 GiB 范围的随机访问产生额外 L2 未命中。 -- **最小修复**:仅当磁盘为 `qcow2` 且本地可读有效头时,读取虚拟容量与 `cluster_bits` 计算 `virtual_size / cluster_size * 8` 向上取整至 MiB(上限 32 MiB),大于 8 MiB 时追加 `,l2-cache-size={mib}M`;不存在文件时静默忽略,不影响现有单元测试。 -- **实测证据**(128 GiB 镜像 16 MiB L2 缓存):`rand-read-large`(热缓存)QEMU 块层平均读延迟从 128.5 μs 降至 70.6 μs(-45.1%),端到端耗时从 1,623.6 ms 降至 1,498.7 ms(-7.7%),仅增加 8 MiB 内存占用且无稳定性风险。 - -### 9. `qemu-win32-mapped-ram-io.patch` -- **建议 PR 标题**:`io/channel-file & migration: support Win32 positioned vector I/O for mapped-ram file snapshots` -- **目标**:`steelbrain/qemu-reims-vgpu`(`io/channel-file.c`, `io/channel*.c`, `migration/file.c`, `migration/ram.c`, `migration/qemu-file.c`, `migration/channel-block.c`) -- **影响环境**:Windows 宿主使用 `mapped-ram` + `multifd` 执行停机文件挂起与恢复的场景。 -- **根因**:上游 `QIOChannelFile` 的 `preadv`/`pwritev` 仅在非 Win32 路径实现,`mapped-ram` 与 `multifd` 文件通道在 Windows 上直接受限。 -- **最小修复**:合并 Win32 定位读写公共逻辑(统一偏移校验、溢出安全分块、EOF/短写语义区分、零字节写入返回 `EIO` 防止死循环以及恢复原文件指针),并开放 Win32 `mapped-ram` + `multifd` 文件路径。 - -### 10. `qemu-intel-whpx-suspend.patch` -- **建议 PR 标题**:`whpx & reims-graphics-pci: support paused-VM file suspend and resume on Intel x86-64` -- **目标**:`steelbrain/qemu-reims-vgpu`(`accel/whpx/whpx-common.c`, `include/system/whpx-common.h`, `target/i386/whpx/whpx-all.c`, `target/i386/whpx/whpx-apic.c`, `hw/misc/applesmc.c`, `hw/display/reims-graphics-pci.c`, `migration/migration.c`, `migration/savevm.c`) -- **影响环境**:Intel x86-64 macOS 客体在 Windows WHPX 上的停机挂起至磁盘与跨进程/跨宿主重启恢复。 -- **最小修复**: - 1. 保留非 `MIG_MODE_NORMAL` 模式的 WHPX migration blocker,并在 `qmp_migrate()`、WHPX `MIG_EVENT_SETUP` 回调与 `save_snapshot()` 强制检查:仅放行已暂停 VM 的 `MIG_MODE_NORMAL` + `file:` 路径,拒绝运行中迁移、非 `file:` 传输、postcopy、background-snapshot、COLO 及 `savevm`。 - 2. 补齐 WHPX x86-64 vCPU/LAPIC/x2APIC/TSC 寄存器与 AppleSMC、`reims-graphics-pci` 设备 VMState 保存恢复回调(含损坏快照向 QMP 返回错误并保留挂起文件)。 -- **实测证据**:7 项 QMP 闸门回归全部通过;Windows 11 WHPX + RTX A5000 + Intel macOS 26.7.3 解锁桌面实测跨完整 QEMU 退出及真实 Windows 重启恢复,首帧 1920×1080 SHA-256 完全一致,原应用 PID / Metal 队列 / Private 资源读回 100% 匹配。 - -### 11. `metal2vulkan-snapshot-replay.patch` -- **建议 PR 标题**:`runtime: add snapshot readback and exact-address restore hooks for buffers, textures, and events` -- **目标**:`steelbrain/metal2vulkan`(`crates/metal2vulkan-runtime/src/{block,device,event,floor,lib,memory,places}.rs`) -- **最小修复**:为 `metal2vulkan-runtime` 增加共享/私有池块分配恢复、Private 缓冲/纹理全子资源(含多 mip/slice)内容读回与回写、以及事件值读写接口,使上层 `reims-vgpu` 可在宿主进程重启后原位重建客体可见 GPU 地址与显存内容。 - -### 12. `reims-vgpu-snapshot-replay.patch` -- **建议 PR 标题**:`graphics & pool: add RVGSNAP1 device quiesce, live object log, and strict snapshot replay` -- **目标**:`steelbrain/reims-vgpu`(`crates/reims-vgpu*`) -- **最小修复**: - 1. 统一 `quiesce_device()` 静止流程(排空传输与编译任务、刷写表面缓存并等待 GPU 空闲),由 `reims-vgpu-c` 暴露保存/加载 C ABI 供 `reims-graphics-pci` VMState 调用。 - 2. 新增 `RVGSNAP1` 二进制快照编解码,由 `Dec::checked_count` / `read_vec` 在分配前统一按剩余字节和最小条目大小校验计数并校验尾部无多余字节。 - 3. 完整保存与回放共享/私有内存池、实时对象日志(含 `whole_library_key` 索引与因果父对象保留,避免 ARC 释放 `MTLLibrary` 后导致活跃管线回放失败)、事件计数、Private 缓冲/纹理与未附着延迟 `SurfaceCache`(含 VA-API P010 视频帧),任何关键对象或显存保存/恢复失败均向 QMP 返回错误且不解除静止。 -- **实测证据**:干净上游 checkout 通过 `reims-vgpu-graphics` 与 `reims-vgpu` 快照单元测试及 `reims-vgpu-c` 零警告 release 构建;RTX A5000 双进程 Vulkan 读回与 Intel macOS 26.7.3 解锁桌面跨进程同 PID Metal 读回(Buffer/Texture/Event/SharedEvent + 恢复后原队列继续 Compute 变异)100% 通过。 +构建通过 Cargo 的本地源码覆盖使用已打补丁的 `metal2vulkan`。打包和重建流程见[便携运行时规范](../docs/portable-runtime-spec.md)。 --- diff --git a/patches/qemu-intel-whpx-suspend.patch b/patches/qemu-intel-whpx-suspend.patch deleted file mode 100644 index 8bfda58..0000000 --- a/patches/qemu-intel-whpx-suspend.patch +++ /dev/null @@ -1,906 +0,0 @@ -diff --git a/accel/whpx/whpx-common.c b/accel/whpx/whpx-common.c -index 63e941496d055f1075e8e860b3785a179bb42edf..13bf3e890a93000e32fd0036fc1fde7a75c46eb4 100644 ---- a/accel/whpx/whpx-common.c -+++ b/accel/whpx/whpx-common.c -@@ -50,8 +50,14 @@ struct WHPDispatch whp_dispatch; - void whpx_flush_cpu_state(CPUState *cpu) - { - if (cpu->vcpu_dirty) { -- whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE); -+ WHPXStateLevel level = (cpu->accel && cpu->accel->loadvm_pending) -+ ? WHPX_LEVEL_FULL_STATE -+ : WHPX_LEVEL_RUNTIME_STATE; -+ whpx_set_registers(cpu, level); - cpu->vcpu_dirty = false; -+ if (cpu->accel) { -+ cpu->accel->loadvm_pending = false; -+ } - } - } - -@@ -207,6 +213,19 @@ static void do_whpx_cpu_synchronize_pre_loadvm(CPUState *cpu, - run_on_cpu_data arg) - { - cpu->vcpu_dirty = true; -+ if (cpu->accel) { -+ cpu->accel->loadvm_pending = true; -+ } -+} -+ -+static void do_whpx_cpu_synchronize_post_loadvm(CPUState *cpu, -+ run_on_cpu_data arg) -+{ -+ if (cpu->accel && cpu->accel->loadvm_pending) { -+ whpx_set_registers(cpu, WHPX_LEVEL_FULL_STATE); -+ cpu->vcpu_dirty = false; -+ cpu->accel->loadvm_pending = false; -+ } - } - - /* -@@ -237,7 +256,36 @@ void whpx_cpu_synchronize_pre_loadvm(CPUState *cpu) - - static void whpx_pre_resume_vm(AccelState *as, bool step_pending) - { -+ CPUState *cpu; -+ bool any_loadvm = false; -+ - whpx_global.step_pending = step_pending; -+ -+ CPU_FOREACH(cpu) { -+ if (cpu->accel && cpu->accel->loadvm_pending) { -+ any_loadvm = true; -+ break; -+ } -+ } -+ if (any_loadvm) { -+ uint64_t max_tsc = 0; -+ CPU_FOREACH(cpu) { -+ uint64_t t = cpu_env(cpu)->tsc; -+ if (t > max_tsc) { -+ max_tsc = t; -+ } -+ } -+ if (whp_dispatch.WHvSuspendPartitionTime) { -+ whp_dispatch.WHvSuspendPartitionTime(whpx_global.partition); -+ } -+ CPU_FOREACH(cpu) { -+ if (cpu->accel && cpu->accel->loadvm_pending) { -+ cpu_env(cpu)->tsc = max_tsc; -+ run_on_cpu(cpu, do_whpx_cpu_synchronize_post_loadvm, -+ RUN_ON_CPU_NULL); -+ } -+ } -+ } - } - - /* -@@ -525,7 +573,7 @@ static void whpx_log_sync(MemoryListener *listener, - { - MemoryRegion *mr = section->mr; - -- if (!memory_region_is_ram(mr)) { -+ if (!memory_region_is_ram(mr) || !runstate_is_running()) { - return; - } - -diff --git a/hw/display/reims-graphics-pci.c b/hw/display/reims-graphics-pci.c -index db10858b65dc0447f7d0e660fca6f1acc3bb7473..976b5d4e3bd4d93d2e9a401fd494eeb2d8e6a442 100644 ---- a/hw/display/reims-graphics-pci.c -+++ b/hw/display/reims-graphics-pci.c -@@ -114,7 +114,9 @@ - #endif - #include "qapi/error.h" - #include "qapi/qapi-commands-ui.h" --#include "migration/blocker.h" -+#include "migration/misc.h" -+#include "migration/vmstate.h" -+#include "migration/qemu-file-types.h" - #include "hw/core/qdev-properties.h" - #include "hw/pci/pci_device.h" - #include "hw/pci/msix.h" -@@ -232,6 +234,10 @@ struct ReimsGraphicsPCIState { - bool irqfd_made; /* the notifier is initialised */ - RvgGraphicsDevice *device; - VMChangeStateEntry *vm_state; /* the teardown at QEMU's quit */ -+ NotifierWithReturn mig_notifier; -+ bool mig_notifier_added; -+ bool mig_quiesced; -+ bool region_registered; - /* The displays, display i head i: the first `displays` of them. */ - ReimsGraphicsHead heads[RVG_GRAPHICS_DISPLAYS_MAX]; - ThreadPool *pool; /* where the consoles' reads of the displays run */ -@@ -283,7 +289,6 @@ struct ReimsGraphicsPCIState { - - QEMU_BUILD_BUG_ON(RVG_GRAPHICS_MSIX_VECTORS != 1); - --static Error *reims_graphics_mig_blocker; - - /* ------ Interrupts ------ */ - -@@ -1388,6 +1393,7 @@ static bool reims_graphics_pool_add(ReimsGraphicsPCIState *s, - memory_region_init_ram_ptr(&piece->mr, OBJECT(piece), - "reims-graphics-pci.pool-piece", ask->size, - ask->host); -+ qemu_ram_unset_migratable(piece->mr.ram_block); - /* - * Inside the add's transaction: on its own, set_unmergeable commits - * (and renders every flat view) for a region that is in none yet. -@@ -2111,6 +2117,14 @@ static void reims_graphics_pci_teardown(ReimsGraphicsPCIState *s, bool quit) - ReimsGraphicsHead *head; - uint32_t i; - -+ if (s->mig_notifier_added) { -+ migration_remove_notifier(&s->mig_notifier); -+ s->mig_notifier_added = false; -+ } -+ if (s->region_registered) { -+ vmstate_unregister_ram(&s->region, DEVICE(dev)); -+ s->region_registered = false; -+ } - if (s->vm_state) { - qemu_del_vm_change_state_handler(s->vm_state); - s->vm_state = NULL; -@@ -2477,6 +2491,158 @@ static bool reims_graphics_linux_floor(Error **errp) - return true; - } - -+ -+static int reims_graphics_pci_mig_notify(NotifierWithReturn *notify, -+ MigrationEvent *e, Error **errp) -+{ -+ ReimsGraphicsPCIState *s = -+ container_of(notify, ReimsGraphicsPCIState, mig_notifier); -+ -+ if (!s->device) { -+ return 0; -+ } -+ switch (e->type) { -+ case MIG_EVENT_SETUP: -+ if (!s->mig_quiesced) { -+ RvgStatus status = rvg_graphics_device_quiesce(s->device); -+ if (status != RVG_OK) { -+ error_setg(errp, "%s: rvg_graphics_device_quiesce failed: %s", -+ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); -+ return -1; -+ } -+ reims_graphics_pool_bh(s); -+ s->mig_quiesced = true; -+ } -+ break; -+ case MIG_EVENT_DONE: -+ case MIG_EVENT_FAILED: -+ if (s->mig_quiesced) { -+ rvg_graphics_device_unquiesce(s->device); -+ s->mig_quiesced = false; -+ } -+ break; -+ default: -+ break; -+ } -+ return 0; -+} -+ -+static int reims_graphics_vgpu_snapshot_put(QEMUFile *f, void *pv, size_t size, -+ const VMStateField *field, -+ JSONWriter *vmdesc) -+{ -+ ReimsGraphicsPCIState *s = pv; -+ uint8_t *data = NULL; -+ uintptr_t len = 0; -+ uintptr_t off = 0; -+ RvgStatus status; -+ -+ if (!s->device) { -+ qemu_put_be64(f, 0); -+ return 0; -+ } -+ status = rvg_graphics_device_snapshot_save(s->device, &data, &len); -+ if (status != RVG_OK) { -+ error_report("%s: rvg_graphics_device_snapshot_save failed: %s", -+ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); -+ return -EIO; -+ } -+ qemu_put_be64(f, (uint64_t)len); -+ while (off < len) { -+ size_t chunk = (size_t)MIN(len - off, (uintptr_t)(1 * MiB)); -+ qemu_put_buffer(f, data + off, chunk); -+ off += chunk; -+ } -+ rvg_graphics_snapshot_free(data, len); -+ return qemu_file_get_error(f); -+} -+ -+static int reims_graphics_vgpu_snapshot_get(QEMUFile *f, void *pv, size_t size, -+ const VMStateField *field) -+{ -+ ReimsGraphicsPCIState *s = pv; -+ uint64_t len = qemu_get_be64(f); -+ uint8_t *buf = NULL; -+ uint64_t off = 0; -+ RvgStatus status; -+ -+ if (qemu_file_get_error(f)) { -+ return qemu_file_get_error(f); -+ } -+ if (len == 0) { -+ return 0; -+ } -+ if (len > (uint64_t)8 * GiB || !s->device) { -+ error_report("%s: invalid vgpu snapshot length %" PRIu64, -+ TYPE_REIMS_GRAPHICS_PCI, len); -+ return -EINVAL; -+ } -+ buf = g_try_malloc(len); -+ if (!buf) { -+ return -ENOMEM; -+ } -+ while (off < len) { -+ size_t chunk = (size_t)MIN(len - off, (uint64_t)(1 * MiB)); -+ size_t got = qemu_get_buffer(f, buf + off, chunk); -+ if (got != chunk) { -+ g_free(buf); -+ return -EIO; -+ } -+ off += got; -+ } -+ status = rvg_graphics_device_snapshot_load(s->device, buf, (size_t)len); -+ g_free(buf); -+ if (status != RVG_OK) { -+ error_report("%s: rvg_graphics_device_snapshot_load failed: %s", -+ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status)); -+ return -EIO; -+ } -+ return 0; -+} -+ -+static const VMStateInfo vmstate_info_reims_vgpu_snapshot = { -+ .name = "reims-vgpu-snapshot", -+ .get = reims_graphics_vgpu_snapshot_get, -+ .put = reims_graphics_vgpu_snapshot_put, -+}; -+ -+static int reims_graphics_pci_post_load(void *opaque, int version_id) -+{ -+ ReimsGraphicsPCIState *s = opaque; -+ PCIDevice *dev = PCI_DEVICE(s); -+ -+ /* Synchronously map all restored Shared Pool pieces into guest GPA before cont. */ -+ reims_graphics_pool_bh(s); -+ -+ if (msix_enabled(dev)) { -+ if (s->irqfd_made) { -+ reims_graphics_pci_irqfd_enable(s); -+ } else if (s->msi_direct_made) { -+ reims_graphics_pci_direct_enable(s); -+ } -+ } -+ return 0; -+} -+ -+static const VMStateDescription vmstate_reims_graphics_pci = { -+ .name = TYPE_REIMS_GRAPHICS_PCI, -+ .version_id = 1, -+ .minimum_version_id = 1, -+ .post_load = reims_graphics_pci_post_load, -+ .fields = (const VMStateField[]) { -+ VMSTATE_PCI_DEVICE(parent_obj, ReimsGraphicsPCIState), -+ VMSTATE_MSIX(parent_obj, ReimsGraphicsPCIState), -+ { -+ .name = "reims_vgpu_snapshot", -+ .info = &vmstate_info_reims_vgpu_snapshot, -+ .flags = VMS_SINGLE, -+ .size = sizeof(ReimsGraphicsPCIState), -+ .offset = 0, -+ }, -+ VMSTATE_END_OF_LIST() -+ } -+}; -+ - static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) - { - ReimsGraphicsPCIState *s = REIMS_GRAPHICS_PCI(dev); -@@ -2577,13 +2743,7 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) - } - reims_graphics_pci_check_low_ram(); - -- if (reims_graphics_mig_blocker == NULL) { -- error_setg(&reims_graphics_mig_blocker, -- "Migration state blocked by reims-graphics-pci"); -- if (migrate_add_blocker(&reims_graphics_mig_blocker, errp) < 0) { -- return; -- } -- } -+ - - /* - * The guest's RAM, through which the GPU uses an IOSurface's own pages in -@@ -2707,6 +2867,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) - base = rvg_graphics_device_region(s->device, &size); - memory_region_init_ram_ptr(&s->region, OBJECT(dev), - "reims-graphics-pci.region", size, base); -+ vmstate_register_ram(&s->region, DEVICE(dev)); -+ s->region_registered = true; - pci_register_bar(dev, RVG_GRAPHICS_PCI_BAR_REGION, - PCI_BASE_ADDRESS_SPACE_MEMORY | - PCI_BASE_ADDRESS_MEM_TYPE_64 | -@@ -2728,6 +2890,8 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp) - } - s->vm_state = qemu_add_vm_change_state_handler( - reims_graphics_pci_vm_state_change, s); -+ migration_add_notifier(&s->mig_notifier, reims_graphics_pci_mig_notify); -+ s->mig_notifier_added = true; - return; - - fail: -@@ -2795,6 +2959,7 @@ static void reims_graphics_pci_class_init(ObjectClass *klass, const void *data) - - rc->phases.hold = reims_graphics_pci_reset; - dc->desc = "reims-graphics GPU"; -+ dc->vmsd = &vmstate_reims_graphics_pci; - dc->hotpluggable = false; - set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories); - device_class_set_props(dc, reims_graphics_pci_properties); -diff --git a/hw/misc/applesmc.c b/hw/misc/applesmc.c -index 84bcf4df0abb15ea73fc03ecc2a2c236ae4a7c8c..2dcc20aa0e28104f5d9fa2e2a4a5ffaee4648821 100644 ---- a/hw/misc/applesmc.c -+++ b/hw/misc/applesmc.c -@@ -37,6 +37,7 @@ - #include "qemu/error-report.h" - #include "qemu/module.h" - #include "qemu/timer.h" -+#include "migration/vmstate.h" - #include "qom/object.h" - #include "hw/acpi/acpi_aml_interface.h" - -@@ -108,7 +109,7 @@ struct AppleSMCState { - uint8_t status; - uint8_t status_1e; - uint8_t last_ret; -- char key[4]; -+ uint8_t key[4]; - uint8_t read_pos; - uint8_t data_len; - uint8_t data_pos; -@@ -407,11 +408,30 @@ static void build_applesmc_aml(AcpiDevAmlIf *adev, Aml *scope) - aml_append(scope, dev); - } - -+static const VMStateDescription vmstate_applesmc = { -+ .name = "applesmc", -+ .version_id = 1, -+ .minimum_version_id = 1, -+ .fields = (const VMStateField[]) { -+ VMSTATE_UINT8(cmd, AppleSMCState), -+ VMSTATE_UINT8(status, AppleSMCState), -+ VMSTATE_UINT8(status_1e, AppleSMCState), -+ VMSTATE_UINT8(last_ret, AppleSMCState), -+ VMSTATE_UINT8_ARRAY(key, AppleSMCState, 4), -+ VMSTATE_UINT8(read_pos, AppleSMCState), -+ VMSTATE_UINT8(data_len, AppleSMCState), -+ VMSTATE_UINT8(data_pos, AppleSMCState), -+ VMSTATE_UINT8_ARRAY(data, AppleSMCState, 255), -+ VMSTATE_END_OF_LIST() -+ } -+}; -+ - static void qdev_applesmc_class_init(ObjectClass *klass, const void *data) - { - DeviceClass *dc = DEVICE_CLASS(klass); - AcpiDevAmlIfClass *adevc = ACPI_DEV_AML_IF_CLASS(klass); - -+ dc->vmsd = &vmstate_applesmc; - dc->realize = applesmc_isa_realize; - dc->unrealize = applesmc_unrealize; - device_class_set_legacy_reset(dc, qdev_applesmc_isa_reset); -diff --git a/include/system/whpx-common.h b/include/system/whpx-common.h -index 79710e2fb3c96edda813fadbda5f8ceabcc5afac..a6fcbd2346b8e34a26f868a0ec19250a0fd268a6 100644 ---- a/include/system/whpx-common.h -+++ b/include/system/whpx-common.h -@@ -9,6 +9,7 @@ struct AccelCPUState { - bool ready_for_pic_interrupt; - uint64_t tpr; - bool interruption_pending; -+ bool loadvm_pending; - /* Must be the last field as it may have a tail */ - WHV_RUN_VP_EXIT_CONTEXT exit_ctx; - }; -diff --git a/migration/migration.c b/migration/migration.c -index 5686209ab11b263b20776d79df79baecd26c5970..f105f616d1dbc88daac2c573c9a95cd02305d9ab 100644 ---- a/migration/migration.c -+++ b/migration/migration.c -@@ -63,6 +63,7 @@ - #include "system/dirtylimit.h" - #include "qemu/sockets.h" - #include "system/kvm.h" -+#include "system/whpx.h" - #include "math.h" - - #define NOTIFIER_ELEM_INIT(array, elem) \ -@@ -2174,6 +2175,34 @@ void qmp_migrate(const char *uri, bool has_channels, - return; - } - -+ if (whpx_enabled()) { -+ if (has_resume && resume) { -+ error_setg(errp, "WHPX: migration resume is not supported"); -+ return; -+ } -+ if (migrate_mode() != MIG_MODE_NORMAL) { -+ error_setg(errp, "WHPX: only normal migration mode is supported"); -+ return; -+ } -+ if (runstate_is_running()) { -+ error_setg(errp, -+ "WHPX: live migration is not supported while the VM is running; stop the VM first"); -+ return; -+ } -+ if (main_ch->addr->transport != MIGRATION_ADDRESS_TYPE_FILE) { -+ error_setg(errp, -+ "WHPX: only stopped-VM file suspend (file: URI) is supported"); -+ return; -+ } -+ if (migrate_postcopy() || migrate_background_snapshot() || -+ migrate_colo() || migrate_dirty_bitmaps() || -+ migrate_return_path()) { -+ error_setg(errp, -+ "WHPX: unsupported migration capability for stopped-VM file suspend"); -+ return; -+ } -+ } -+ - if (!migrate_prepare(s, has_resume && resume, errp)) { - /* Error detected, put into errp */ - return; -diff --git a/migration/savevm.c b/migration/savevm.c -index fe94ba96e432c8555bcfc58d97f3830a86eaab60..2a1944010c595995f6d75d3cb4d6ca67525ec1fa 100644 ---- a/migration/savevm.c -+++ b/migration/savevm.c -@@ -64,6 +64,7 @@ - #include "system/runstate.h" - #include "system/system.h" - #include "system/xen.h" -+#include "system/whpx.h" - #include "migration/colo.h" - #include "qemu/bitmap.h" - #include "net/announce.h" -@@ -3317,6 +3318,12 @@ bool save_snapshot(const char *name, bool overwrite, const char *vmstate, - return false; - } - -+ if (whpx_enabled()) { -+ error_setg(errp, -+ "WHPX: internal VM snapshots are not supported; use stopped-VM file migration"); -+ return false; -+ } -+ - if (!replay_can_snapshot()) { - error_setg(errp, "Record/replay does not allow making snapshot " - "right now. Try once more later."); -diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c -index f093b59c0f04e1cdf6a14172d3b059068e61ac00..30b64eb901dcb6d0781c87dfc4241e6b4abe635c 100644 ---- a/target/i386/whpx/whpx-all.c -+++ b/target/i386/whpx/whpx-all.c -@@ -32,6 +32,7 @@ - #include "qapi/qapi-types-common.h" - #include "qapi/qapi-type-infos-common.h" - #include "migration/blocker.h" -+#include "migration/misc.h" - #include "host-cpu.h" - #include "accel/accel-cpu-target.h" - #include -@@ -56,6 +57,24 @@ - #define HV_X64_MSR_VP_ASSIST_PAGE 0x40000073 - #define HV_X64_MSR_GUEST_IDLE 0x400000f0 - -+#define WHPX_MP_STATE_RUNNABLE 0 -+#define WHPX_MP_STATE_UNINITIALIZED 1 -+#define WHPX_MP_STATE_HALTED 3 -+ -+static void whpx_set_reg_optional(CPUState *cpu, WHV_REGISTER_NAME reg, -+ WHV_REGISTER_VALUE val) -+{ -+ whp_dispatch.WHvSetVirtualProcessorRegisters( -+ whpx_global.partition, cpu->cpu_index, ®, 1, &val); -+} -+ -+static bool whpx_get_reg_optional(CPUState *cpu, WHV_REGISTER_NAME reg, -+ WHV_REGISTER_VALUE *val) -+{ -+ return SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorRegisters( -+ whpx_global.partition, cpu->cpu_index, ®, 1, val)); -+} -+ - static bool is_modern_os = true; - static bool whpx_msr_exits_available = true; - static bool whpx_forward_startup_ipis; -@@ -636,18 +655,8 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level) - whpx_set_reg(cpu, WHvX64RegisterCr8, cr8); - } - -- /* 8 Debug Registers - Skipped */ -- -- /* -- * Extended control registers needs to be handled separately depending -- * on whether xsave is supported/enabled or not. -- */ -- whpx_set_xcrs(cpu); -- -- if (whpx_is_xsave_enabled(cpu)) { -- whpx_set_xsave_state(cpu); -- } -- whpx_set_legacy_fp_registers(cpu, level); -+ /* 8 Debug Registers - restored below for FULL_STATE */ -+ /* XCR0/XSAVE/FP restored AFTER CR0/CR4/EFER are committed to WHPX */ - - /* MSRs */ - assert(whpx_register_names[idx] == WHvX64RegisterEfer); -@@ -694,10 +703,77 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level) - hr); - } - -+ if (level > WHPX_LEVEL_FAST_RUNTIME_STATE) { -+ whpx_set_xcrs(cpu); -+ if (!whpx_is_xsave_enabled(cpu) || whpx_set_xsave_state(cpu) != 0) { -+ whpx_set_legacy_fp_registers(cpu, level); -+ } -+ } -+ - if (level >= WHPX_LEVEL_FULL_STATE) { -- WHV_REGISTER_VALUE apic_base = {}; -- apic_base.Reg64 = cpu_get_apic_base(X86_CPU(cpu)->apic_state); -- whpx_set_reg(cpu, WHvX64RegisterApicBase, apic_base); -+ static const WHV_REGISTER_NAME dr_names[6] = { -+ WHvX64RegisterDr0, WHvX64RegisterDr1, WHvX64RegisterDr2, -+ WHvX64RegisterDr3, WHvX64RegisterDr6, WHvX64RegisterDr7, -+ }; -+ WHV_REGISTER_VALUE dr_vals[6] = { -+ { .Reg64 = env->dr[0] }, { .Reg64 = env->dr[1] }, -+ { .Reg64 = env->dr[2] }, { .Reg64 = env->dr[3] }, -+ { .Reg64 = env->dr[6] }, { .Reg64 = env->dr[7] }, -+ }; -+ whp_dispatch.WHvSetVirtualProcessorRegisters( -+ whpx->partition, cpu->cpu_index, dr_names, 6, dr_vals); -+ -+ WHV_REGISTER_VALUE v = {}; -+ v.Reg64 = env->tsc_aux; -+ whpx_set_reg_optional(cpu, WHvX64RegisterTscAux, v); -+ -+ /* Do not write WHvX64RegisterTscAdjust after WHvX64RegisterTsc, -+ * as MSR_IA32_TSC_ADJUST shifts the vCPU TSC offset in Hyper-V. */ -+ if (env->spec_ctrl) { -+ v.Reg64 = env->spec_ctrl; -+ whpx_set_reg_optional(cpu, WHvX64RegisterSpecCtrl, v); -+ } -+ if (env->mtrr_deftype) { -+ v.Reg64 = env->mtrr_deftype; -+ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrDefType, v); -+ for (i = 0; i < MSR_MTRRcap_VCNT; i++) { -+ v.Reg64 = env->mtrr_var[i].base; -+ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysBase0 + i, v); -+ v.Reg64 = env->mtrr_var[i].mask; -+ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysMask0 + i, v); -+ } -+ for (i = 0; i < 11; i++) { -+ v.Reg64 = env->mtrr_fixed[i]; -+ whpx_set_reg_optional(cpu, WHvX64RegisterMsrMtrrFix64k00000 + i, v); -+ } -+ } -+ -+ if (!whpx_irqchip_in_kernel()) { -+ WHV_REGISTER_VALUE apic_base = {}; -+ apic_base.Reg64 = cpu_get_apic_base(X86_CPU(cpu)->apic_state); -+ whpx_set_reg(cpu, WHvX64RegisterApicBase, apic_base); -+ } -+ -+ if (!whpx->tsc_deadline_refused) { -+ WHV_REGISTER_VALUE tsc_deadline = { .Reg64 = env->tsc_deadline }; -+ whpx_set_reg(cpu, WHvX64RegisterTscDeadline, tsc_deadline); -+ } -+ -+ if (whpx_irqchip_in_kernel()) { -+ WHV_REGISTER_VALUE activity = {}; -+ whpx_get_reg_optional(cpu, WHvRegisterInternalActivityState, &activity); -+ activity.InternalActivity.StartupSuspend = -+ (env->mp_state == WHPX_MP_STATE_UNINITIALIZED); -+ activity.InternalActivity.HaltSuspend = 0; -+ whpx_set_reg(cpu, WHvRegisterInternalActivityState, activity); -+ } -+ -+ { -+ WHV_REGISTER_VALUE intr_state = {}; -+ intr_state.InterruptState.InterruptShadow = -+ !!(env->hflags & HF_INHIBIT_IRQ_MASK); -+ whpx_set_reg_optional(cpu, WHvRegisterInterruptState, intr_state); -+ } - } - } - -@@ -940,6 +1016,9 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) - } - - if (!env->tsc_valid) { -+ if (!runstate_is_running() && whp_dispatch.WHvSuspendPartitionTime) { -+ whp_dispatch.WHvSuspendPartitionTime(whpx->partition); -+ } - whpx_get_tsc(cpu); - env->tsc_valid = !runstate_is_running(); - } -@@ -1016,10 +1095,9 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) - */ - whpx_get_xcrs(cpu); - -- if (whpx_is_xsave_enabled(cpu)) { -- whpx_get_xsave_state(cpu); -+ if (!whpx_is_xsave_enabled(cpu) || whpx_get_xsave_state(cpu) != 0) { -+ whpx_get_legacy_fp_registers(cpu, level); - } -- whpx_get_legacy_fp_registers(cpu, level); - - /* MSRs */ - assert(whpx_register_names[idx] == WHvX64RegisterEfer); -@@ -1051,11 +1129,83 @@ void whpx_get_registers(CPUState *cpu, WHPXStateLevel level) - - assert(idx == RTL_NUMBER_OF(whpx_register_names)); - -+ if (level >= WHPX_LEVEL_FULL_STATE) { -+ static const WHV_REGISTER_NAME dr_names[6] = { -+ WHvX64RegisterDr0, WHvX64RegisterDr1, WHvX64RegisterDr2, -+ WHvX64RegisterDr3, WHvX64RegisterDr6, WHvX64RegisterDr7, -+ }; -+ WHV_REGISTER_VALUE dr_vals[6] = {}; -+ if (SUCCEEDED(whp_dispatch.WHvGetVirtualProcessorRegisters( -+ whpx->partition, cpu->cpu_index, dr_names, 6, dr_vals))) { -+ env->dr[0] = dr_vals[0].Reg64; -+ env->dr[1] = dr_vals[1].Reg64; -+ env->dr[2] = dr_vals[2].Reg64; -+ env->dr[3] = dr_vals[3].Reg64; -+ env->dr[6] = dr_vals[4].Reg64; -+ env->dr[7] = dr_vals[5].Reg64; -+ } -+ -+ WHV_REGISTER_VALUE v = {}; -+ if (whpx_get_reg_optional(cpu, WHvX64RegisterTscAux, &v)) { -+ env->tsc_aux = v.Reg64; -+ } -+ if (whpx_get_reg_optional(cpu, WHvX64RegisterTscAdjust, &v)) { -+ env->tsc_adjust = v.Reg64; -+ } -+ if (whpx_get_reg_optional(cpu, WHvX64RegisterSpecCtrl, &v)) { -+ env->spec_ctrl = v.Reg64; -+ } -+ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrDefType, &v)) { -+ env->mtrr_deftype = v.Reg64; -+ for (i = 0; i < MSR_MTRRcap_VCNT; i++) { -+ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysBase0 + i, &v)) { -+ env->mtrr_var[i].base = v.Reg64; -+ } -+ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrPhysMask0 + i, &v)) { -+ env->mtrr_var[i].mask = v.Reg64; -+ } -+ } -+ for (i = 0; i < 11; i++) { -+ if (whpx_get_reg_optional(cpu, WHvX64RegisterMsrMtrrFix64k00000 + i, &v)) { -+ env->mtrr_fixed[i] = v.Reg64; -+ } -+ } -+ } -+ if (!whpx->tsc_deadline_refused && -+ whpx_get_reg_optional(cpu, WHvX64RegisterTscDeadline, &v)) { -+ env->tsc_deadline = v.Reg64; -+ } -+ if (whpx_irqchip_in_kernel() && -+ whpx_get_reg_optional(cpu, WHvRegisterInternalActivityState, &v)) { -+ if (v.InternalActivity.StartupSuspend) { -+ env->mp_state = WHPX_MP_STATE_UNINITIALIZED; -+ } else if (v.InternalActivity.HaltSuspend) { -+ env->mp_state = WHPX_MP_STATE_HALTED; -+ } else { -+ env->mp_state = WHPX_MP_STATE_RUNNABLE; -+ } -+ } -+ if (whpx_get_reg_optional(cpu, WHvRegisterPendingInterruption, &v) && -+ v.PendingInterruption.InterruptionPending) { -+ warn_report("WHPX: vCPU %d saved with PendingInterruption type=%u vec=%u", -+ cpu->cpu_index, -+ (unsigned)v.PendingInterruption.InterruptionType, -+ (unsigned)v.PendingInterruption.InterruptionVector); -+ } -+ } -+ - if (whpx_irqchip_in_kernel()) { - whpx_apic_get(x86_cpu->apic_state); - } - - x86_update_hflags(env); -+ if (level >= WHPX_LEVEL_FULL_STATE) { -+ WHV_REGISTER_VALUE intr_state = {}; -+ if (whpx_get_reg_optional(cpu, WHvRegisterInterruptState, &intr_state) && -+ intr_state.InterruptState.InterruptShadow) { -+ env->hflags |= HF_INHIBIT_IRQ_MASK; -+ } -+ } - } - - static int emulate_instruction(CPUState *cpu, const uint8_t *insn_bytes, size_t insn_len) -@@ -2515,8 +2665,12 @@ int whpx_vcpu_run(CPUState *cpu) - - do { - if (cpu->vcpu_dirty) { -- whpx_set_registers(cpu, WHPX_LEVEL_RUNTIME_STATE); -+ WHPXStateLevel level = vcpu->loadvm_pending -+ ? WHPX_LEVEL_FULL_STATE -+ : WHPX_LEVEL_RUNTIME_STATE; -+ whpx_set_registers(cpu, level); - cpu->vcpu_dirty = false; -+ vcpu->loadvm_pending = false; - } - - if (exclusive_step_mode == WHPX_STEP_NONE) { -@@ -2982,6 +3136,28 @@ int whpx_vcpu_run(CPUState *cpu) - */ - - static Error *whpx_migration_blocker; -+static NotifierWithReturn whpx_migration_notifier; -+static bool whpx_migration_notifier_added; -+ -+static int whpx_migration_setup_notifier(NotifierWithReturn *notify, -+ MigrationEvent *e, Error **errp) -+{ -+ if (e->type != MIG_EVENT_SETUP) { -+ return 0; -+ } -+ if (runstate_is_running()) { -+ error_setg(errp, -+ "WHPX: live migration is not supported while the VM is running; stop the VM first"); -+ return -1; -+ } -+ if (migrate_mode() != MIG_MODE_NORMAL || -+ migrate_postcopy_ram() || migrate_background_snapshot()) { -+ error_setg(errp, -+ "WHPX: only stopped-VM normal file suspend is supported"); -+ return -1; -+ } -+ return 0; -+} - - static void whpx_cpu_update_state(void *opaque, bool running, RunState state) - { -@@ -3006,20 +3182,27 @@ int whpx_init_vcpu(CPUState *cpu) - UINT64 freq = 0; - int ret; - -- /* Add migration blockers for all unsupported features of the -- * Windows Hypervisor Platform -+ /* -+ * WHPX lacks dirty-page tracking, so live migration and non-normal modes -+ * remain blocked. Only stopped-VM normal file suspend (stop -> migrate -> -+ * quit) is permitted and enforced both at migration entry and on setup. - */ -- if (whpx_migration_blocker == NULL) { -+ if (!whpx_migration_blocker) { -+ unsigned non_normal_modes = (BIT(MIG_MODE__MAX) - 1) & -+ ~BIT(MIG_MODE_NORMAL); - error_setg(&whpx_migration_blocker, -- "State blocked due to missing dirty memory tracking support," -- "And some system register/state save-restore "); -- -- if (migrate_add_blocker(&whpx_migration_blocker, &local_error) < 0) { -- error_report_err(local_error); -- ret = -EINVAL; -- goto error; -+ "WHPX: migration mode is not supported (only stopped-VM normal file suspend)"); -+ migrate_add_blocker_modes(&whpx_migration_blocker, non_normal_modes, -+ &local_error); -+ if (local_error) { -+ error_propagate(&error_fatal, local_error); - } - } -+ if (!whpx_migration_notifier_added) { -+ migration_add_notifier(&whpx_migration_notifier, -+ whpx_migration_setup_notifier); -+ whpx_migration_notifier_added = true; -+ } - - vcpu = g_new0(AccelCPUState, 1); - -diff --git a/target/i386/whpx/whpx-apic.c b/target/i386/whpx/whpx-apic.c -index 547b1cd2671bb6b8fb5a826ab5af5ef89b0997be..75ecf48feb48b448cb39d5878d9bb86b0fa5746a 100644 ---- a/target/i386/whpx/whpx-apic.c -+++ b/target/i386/whpx/whpx-apic.c -@@ -35,13 +35,17 @@ static void whpx_put_apic_state(APICCommonState *s, - memset(kapic, 0, sizeof(*kapic)); - if (s->apicbase & MSR_IA32_APICBASE_EXTD) { - kapic->fields[0x2].data = s->initial_apic_id; -+ kapic->fields[0xd].data = -+ ((s->initial_apic_id & ~0xfu) << 12) | -+ (1u << (s->initial_apic_id & 0xfu)); -+ kapic->fields[0xe].data = 0; - } else { - kapic->fields[0x2].data = s->id << 24; -+ kapic->fields[0xd].data = s->log_dest << 24; -+ kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff; - } - kapic->fields[0x3].data = s->version | ((APIC_LVT_NB - 1) << 16); - kapic->fields[0x8].data = s->tpr; -- kapic->fields[0xd].data = s->log_dest << 24; -- kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff; - kapic->fields[0xf].data = s->spurious_vec; - for (i = 0; i < 8; i++) { - kapic->fields[0x10 + i].data = s->isr[i]; -@@ -212,10 +216,18 @@ static void whpx_apic_put(CPUState *cs, run_on_cpu_data data) - &kapic, - sizeof(kapic)); - if (FAILED(hr)) { -+ struct whpx_lapic_state cur = {}; -+ whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( -+ whpx_global.partition, cs->cpu_index, &cur, sizeof(cur), NULL); - fprintf(stderr, -- "WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n", -- hr); -- -+ "WHvSetVirtualProcessorInterruptControllerState2 failed: %08lx cpu=%d apicbase=0x%llx\n", -+ hr, cs->cpu_index, (unsigned long long)s->apicbase); -+ for (int idx = 0; idx < 256; idx++) { -+ if (kapic.fields[idx].data || cur.fields[idx].data) { -+ fprintf(stderr, " lapic[0x%02x]: put=0x%08x cur=0x%08x\n", -+ idx, kapic.fields[idx].data, cur.fields[idx].data); -+ } -+ } - abort(); - } - } -@@ -224,8 +236,17 @@ void whpx_apic_get(APICCommonState *s) - { - CPUState *cpu = CPU(s->cpu); - struct whpx_lapic_state kapic; -+ WHV_REGISTER_NAME base_reg = WHvX64RegisterApicBase; -+ WHV_REGISTER_VALUE base_val = {}; -+ HRESULT hr; -+ -+ hr = whp_dispatch.WHvGetVirtualProcessorRegisters( -+ whpx_global.partition, cpu->cpu_index, &base_reg, 1, &base_val); -+ if (SUCCEEDED(hr)) { -+ s->apicbase = base_val.Reg64; -+ } - -- HRESULT hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( -+ hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2( - whpx_global.partition, - cpu->cpu_index, - &kapic, -@@ -233,7 +254,7 @@ void whpx_apic_get(APICCommonState *s) - NULL); - if (FAILED(hr)) { - fprintf(stderr, -- "WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n", -+ "WHvGetVirtualProcessorInterruptControllerState2 failed: %08lx\n", - hr); - - abort(); -@@ -242,6 +263,17 @@ void whpx_apic_get(APICCommonState *s) - whpx_get_apic_state(s, &kapic); - } - -+static void do_whpx_apic_get(CPUState *cs, run_on_cpu_data data) -+{ -+ APICCommonState *s = data.host_ptr; -+ whpx_apic_get(s); -+} -+ -+static void whpx_apic_pre_save(APICCommonState *s) -+{ -+ run_on_cpu(CPU(s->cpu), do_whpx_apic_get, RUN_ON_CPU_HOST_PTR(s)); -+} -+ - static void whpx_apic_post_load(APICCommonState *s) - { - run_on_cpu(CPU(s->cpu), whpx_apic_put, RUN_ON_CPU_HOST_PTR(s)); -@@ -379,6 +411,7 @@ static void whpx_apic_class_init(ObjectClass *klass, const void *data) - k->set_base = apic_set_base; - k->set_tpr = whpx_apic_set_tpr; - k->get_tpr = whpx_apic_get_tpr; -+ k->pre_save = whpx_apic_pre_save; - k->post_load = whpx_apic_post_load; - k->vapic_base_update = whpx_apic_vapic_base_update; - k->external_nmi = whpx_apic_external_nmi; diff --git a/patches/qemu-whpx-nested-virt-nonfatal.patch b/patches/qemu-whpx-nested-virt-nonfatal.patch deleted file mode 100644 index bda9b24..0000000 --- a/patches/qemu-whpx-nested-virt-nonfatal.patch +++ /dev/null @@ -1,25 +0,0 @@ -diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c ---- a/target/i386/whpx/whpx-all.c -+++ b/target/i386/whpx/whpx-all.c -@@ -3525,17 +3525,16 @@ - whpx_rdtsc_cap = processor_features.Bank0.RdtscpSupport; - whpx_invpcid_cap = processor_features.Bank0.InvpcidSupport; - - if (whpx_irqchip_in_kernel() && processor_features.Bank1.NestedVirtSupport) { - memset(&prop, 0, sizeof(WHV_PARTITION_PROPERTY)); - prop.NestedVirtualization = 1; - hr = whp_dispatch.WHvSetPartitionProperty( - whpx->partition, - WHvPartitionPropertyCodeNestedVirtualization, - &prop, - sizeof(WHV_PARTITION_PROPERTY)); - if (FAILED(hr)) { -- error_report("WHPX: Failed to enable nested virtualization, hr=%08lx", hr); -- ret = -EINVAL; -- goto error; -+ warn_report("WHPX: Failed to enable nested virtualization, hr=%08lx; continuing without nested virt", hr); -+ processor_features.Bank1.NestedVirtSupport = 0; - } - } - - /* diff --git a/patches/qemu-whpx-win10-compat.patch b/patches/qemu-whpx-win10-compat.patch deleted file mode 100644 index 9836d5b..0000000 --- a/patches/qemu-whpx-win10-compat.patch +++ /dev/null @@ -1,77 +0,0 @@ -diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c -index 5aa46bc..4ef32ee 100644 ---- a/target/i386/whpx/whpx-all.c -+++ b/target/i386/whpx/whpx-all.c -@@ -530,7 +530,8 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level) - assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu)); - - /* Assumes that cpu_synchronize_all_post_reset() runs cpu 0 first. */ -- if (level == WHPX_LEVEL_RESET_STATE && cpu->cpu_index == 0) { -+ if (level == WHPX_LEVEL_RESET_STATE && cpu->cpu_index == 0 && -+ whp_dispatch.WHvResetPartition) { - hr = whp_dispatch.WHvResetPartition(whpx->partition); - if (FAILED(hr)) { - error_report("WHPX: Failed to reset partition, hr=%08lx", hr); -@@ -3211,22 +3212,56 @@ static bool whpx_tsc_deadline_refused(void) - { - WHV_REGISTER_NAME name = WHvX64RegisterTscDeadline; - WHV_REGISTER_VALUE value = {}; -+ WHV_PARTITION_HANDLE probe = NULL; -+ WHV_PARTITION_PROPERTY prop = {}; - HRESULT hr; -+ bool refused = false; - -- hr = whp_dispatch.WHvCreateVirtualProcessor(whpx_global.partition, 0, 0); -+ /* -+ * Probe on a throwaway partition: on Windows 10 (e.g. 19045), deleting -+ * vCPU 0 on the real partition causes a subsequent WHvCreateVirtualProcessor -+ * for vCPU 0 in whpx_init_vcpu() to fail with E_INVALIDARG (0x80070057). -+ */ -+ hr = whp_dispatch.WHvCreatePartition(&probe); - if (FAILED(hr)) { - return false; - } -- hr = whp_dispatch.WHvSetVirtualProcessorRegisters(whpx_global.partition, -- 0, &name, 1, &value); -- whp_dispatch.WHvDeleteVirtualProcessor(whpx_global.partition, 0); -+ prop.ProcessorCount = 1; -+ hr = whp_dispatch.WHvSetPartitionProperty( -+ probe, WHvPartitionPropertyCodeProcessorCount, &prop, sizeof(prop)); -+ if (FAILED(hr)) { -+ goto out; -+ } -+ if (whpx_irqchip_in_kernel()) { -+ WHV_X64_LOCAL_APIC_EMULATION_MODE mode = -+ WHvX64LocalApicEmulationModeX2Apic; -+ hr = whp_dispatch.WHvSetPartitionProperty( -+ probe, WHvPartitionPropertyCodeLocalApicEmulationMode, -+ &mode, sizeof(mode)); -+ if (FAILED(hr)) { -+ goto out; -+ } -+ } -+ hr = whp_dispatch.WHvSetupPartition(probe); -+ if (FAILED(hr)) { -+ goto out; -+ } -+ hr = whp_dispatch.WHvCreateVirtualProcessor(probe, 0, 0); -+ if (FAILED(hr)) { -+ goto out; -+ } -+ hr = whp_dispatch.WHvSetVirtualProcessorRegisters(probe, 0, &name, 1, &value); -+ whp_dispatch.WHvDeleteVirtualProcessor(probe, 0); - if (FAILED(hr)) { - warn_report("WHPX: Hyper-V refuses the TSC deadline timer's register," - " hr=%08lx: the guest is offered no TSC deadline timer", - hr); -- return true; -+ refused = true; - } -- return false; -+ -+out: -+ whp_dispatch.WHvDeletePartition(probe); -+ return refused; - } - - int whpx_accel_init(AccelState *as, MachineState *ms) diff --git a/patches/qemu-whpx-win10-startup-ipis.patch b/patches/qemu-whpx-win10-startup-ipis.patch deleted file mode 100644 index dcfbbb8..0000000 --- a/patches/qemu-whpx-win10-startup-ipis.patch +++ /dev/null @@ -1,104 +0,0 @@ -diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c -index 4ef32ee..fe92903 100644 ---- a/target/i386/whpx/whpx-all.c -+++ b/target/i386/whpx/whpx-all.c -@@ -58,6 +58,7 @@ - - static bool is_modern_os = true; - static bool whpx_msr_exits_available = true; -+static bool whpx_forward_startup_ipis; - - static const WHV_REGISTER_NAME whpx_register_names[] = { - -@@ -1681,6 +1682,7 @@ - memset(&prop, 0, sizeof(WHV_PARTITION_PROPERTY)); - prop.ExtendedVmExits.X64MsrExit = 1; - prop.ExtendedVmExits.X64CpuidExit = 1; -+ prop.ExtendedVmExits.X64ApicInitSipiExitTrap = whpx_forward_startup_ipis; - - if (exceptions != 0 || whpx_get_default_exceptions() != 0) { - prop.ExtendedVmExits.ExceptionExit = 1; -@@ -2389,7 +2391,54 @@ - } - } - -+/* On Win10, a guest INIT/SIPI may leave a previously halted AP parked. -+ * Route just these boot-time interrupts through the WHP injection API. */ -+static HRESULT whpx_forward_startup_ipi(CPUState *cpu, uint64_t icr) -+{ -+ unsigned int shorthand = (icr >> APIC_ICR_DEST_SHORT_SHIFT) & 3; -+ WHV_INTERRUPT_CONTROL ipi = { -+ .Type = (icr & APIC_ICR_DELIV_MOD) >> APIC_ICR_DELIV_MOD_SHIFT, -+ .DestinationMode = !!(icr & APIC_ICR_DEST_MOD), -+ .TriggerMode = !!(icr & APIC_ICR_TRIGGER_MOD), -+ .Vector = icr & 0xff, -+ }; -+ HRESULT hr; -+ -+ /* INIT level deassert synchronizes arbitration IDs, without a reset. */ -+ if (ipi.Type == WHvX64InterruptTypeInit && ipi.TriggerMode && -+ !(icr & APIC_ICR_LEVEL)) { -+ return S_OK; -+ } -+ if (!shorthand) { -+ WHV_REGISTER_VALUE base = {}; -+ WHV_REGISTER_NAME name = WHvX64RegisterApicBase; -+ hr = whp_dispatch.WHvGetVirtualProcessorRegisters( -+ whpx_global.partition, cpu->cpu_index, &name, 1, &base); -+ if (FAILED(hr)) { -+ return hr; -+ } -+ ipi.Destination = (base.Reg64 & MSR_IA32_APICBASE_EXTD) -+ ? (icr >> 32) : (icr >> 56); -+ return whp_dispatch.WHvRequestInterrupt(whpx_global.partition, -+ &ipi, sizeof(ipi)); -+ } -+ ipi.DestinationMode = WHvX64InterruptDestinationModePhysical; -+ for (uint32_t i = 0; i <= max_vcpu_index; i++) { -+ if ((shorthand == 1 && i != cpu->cpu_index) || -+ (shorthand == 3 && i == cpu->cpu_index)) { -+ continue; -+ } -+ ipi.Destination = i; -+ hr = whp_dispatch.WHvRequestInterrupt(whpx_global.partition, -+ &ipi, sizeof(ipi)); -+ if (FAILED(hr)) { -+ return hr; -+ } -+ } -+ return S_OK; -+} -+ - int whpx_vcpu_run(CPUState *cpu) - { - HRESULT hr; - struct whpx_state *whpx = &whpx_global; -@@ -2520,7 +2569,15 @@ - vcpu->window_priority = 0; - ret = 0; - break; - -+ case WHvRunVpExitReasonX64ApicInitSipiTrap: -+ hr = whpx_forward_startup_ipi(cpu, vcpu->exit_ctx.ApicInitSipi.ApicIcr); -+ ret = 0; -+ if (FAILED(hr)) { -+ error_report("WHPX: failed to forward startup IPI, hr=%08lx", hr); -+ ret = -1; -+ } -+ break; - case WHvRunVpExitReasonX64ApicEoi: - assert(whpx_irqchip_in_kernel()); - ioapic_eoi_broadcast(vcpu->exit_ctx.ApicEoi.InterruptVector); -@@ -3619,6 +3676,12 @@ - * We do not want to intercept any exceptions from the guest, - * until we actually start debugging with gdb. - */ -+ if (whpx_is_legacy_os() && whpx_irqchip_in_kernel() && ms->smp.max_cpus > 1) { -+ WHV_EXTENDED_VM_EXITS exits = {}; -+ hr = whp_dispatch.WHvGetCapability(WHvCapabilityCodeExtendedVmExits, -+ &exits, sizeof(exits), &whpx_cap_size); -+ whpx_forward_startup_ipis = SUCCEEDED(hr) && exits.X64ApicInitSipiExitTrap; -+ } - whpx->exception_exit_bitmap = -1; - hr = whpx_set_exception_exit_bitmap(0); - diff --git a/patches/qemu-win32-coroutine-fiber-commit.patch b/patches/qemu-win32-coroutine-fiber-commit.patch deleted file mode 100644 index b01ca0a..0000000 --- a/patches/qemu-win32-coroutine-fiber-commit.patch +++ /dev/null @@ -1,60 +0,0 @@ -diff --git a/util/coroutine-windows.c b/util/coroutine-windows.c ---- a/util/coroutine-windows.c -+++ b/util/coroutine-windows.c -@@ -26,6 +26,8 @@ - #include "qemu/coroutine_int.h" - #include "qemu/coroutine-tls.h" - -+#define COROUTINE_INITIAL_COMMIT_SIZE (64 * 1024) -+ - typedef struct - { - Coroutine base; -@@ -71,11 +73,26 @@ - - Coroutine *qemu_coroutine_new(void) - { - const size_t stack_size = COROUTINE_STACK_SIZE; -+ const size_t commit_size = MIN(COROUTINE_INITIAL_COMMIT_SIZE, stack_size); - CoroutineWin32 *co; - - co = g_malloc0(sizeof(*co)); -- co->fiber = CreateFiber(stack_size, coroutine_trampoline, &co->base); -+ /* -+ * CreateFiber(stack_size, ...) commits the full 1 MiB stack up front, -+ * which can exhaust Windows commit charge during burst disk I/O + GPU -+ * workloads and return NULL (later crashing inside SwitchToFiber(NULL) -+ * reading 0x10). Reserve stack_size while committing only 64 KiB upfront. -+ */ -+ co->fiber = CreateFiberEx(commit_size, stack_size, 0, -+ coroutine_trampoline, &co->base); -+ if (!co->fiber) { -+ fprintf(stderr, -+ "qemu_coroutine_new: CreateFiberEx(commit=%zu, reserve=%zu) failed: " -+ "GetLastError()=%lu\n", -+ commit_size, stack_size, (unsigned long)GetLastError()); -+ abort(); -+ } - return &co->base; - } - -@@ -96,7 +113,18 @@ - - current = &leader->base; - set_current(current); -- leader->fiber = ConvertThreadToFiber(NULL); -+ if (IsThreadAFiber()) { -+ leader->fiber = GetCurrentFiber(); -+ } else { -+ leader->fiber = ConvertThreadToFiber(NULL); -+ } -+ if (!leader->fiber) { -+ fprintf(stderr, -+ "qemu_coroutine_self: ConvertThreadToFiber failed: " -+ "GetLastError()=%lu\n", -+ (unsigned long)GetLastError()); -+ abort(); -+ } - } - return current; - } diff --git a/patches/qemu-win32-mapped-ram-io.patch b/patches/qemu-win32-mapped-ram-io.patch deleted file mode 100644 index 61ebe21..0000000 --- a/patches/qemu-win32-mapped-ram-io.patch +++ /dev/null @@ -1,727 +0,0 @@ -diff --git a/include/io/channel.h b/include/io/channel.h -index 834ba7c30986dd48686705da5aa7197eb228cef7..87f751308d6fdd7b87e31be44fca07fe93501aba 100644 ---- a/include/io/channel.h -+++ b/include/io/channel.h -@@ -146,12 +146,12 @@ struct QIOChannelClass { - ssize_t (*io_pwritev)(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp); - ssize_t (*io_preadv)(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp); - int (*io_shutdown)(QIOChannel *ioc, - QIOChannelShutdown how, -@@ -160,8 +160,8 @@ struct QIOChannelClass { - bool enabled); - void (*io_set_delay)(QIOChannel *ioc, - bool enabled); -- off_t (*io_seek)(QIOChannel *ioc, -- off_t offset, -+ int64_t (*io_seek)(QIOChannel *ioc, -+ int64_t offset, - int whence, - Error **errp); - void (*io_set_aio_fd_handler)(QIOChannel *ioc, -@@ -579,7 +579,7 @@ int qio_channel_close(QIOChannel *ioc, - * - */ - ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, -- size_t niov, off_t offset, Error **errp); -+ size_t niov, int64_t offset, Error **errp); - - /** - * qio_channel_pwrite -@@ -595,7 +595,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, - * - */ - ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, -- off_t offset, Error **errp); -+ int64_t offset, Error **errp); - - /** - * qio_channel_pwritev_all: -@@ -614,7 +614,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, - int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp); - - /** -@@ -635,7 +635,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, - int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, - const void *buf, - size_t buflen, -- off_t offset, -+ int64_t offset, - Error **errp); - - /** -@@ -656,7 +656,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, - * - */ - ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, -- size_t niov, off_t offset, Error **errp); -+ size_t niov, int64_t offset, Error **errp); - - /** - * qio_channel_pread -@@ -672,7 +672,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, - * - */ - ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, -- off_t offset, Error **errp); -+ int64_t offset, Error **errp); - - /** - * qio_channel_preadv_all_eof: -@@ -695,7 +695,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, - int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp); - - /** -@@ -717,7 +717,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, - int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp); - - /** -@@ -741,7 +741,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, - int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, - void *buf, - size_t buflen, -- off_t offset, -+ int64_t offset, - Error **errp); - - /** -@@ -763,7 +763,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, - int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc, - void *buf, - size_t buflen, -- off_t offset, -+ int64_t offset, - Error **errp); - - /** -@@ -861,10 +861,10 @@ void qio_channel_set_cork(QIOChannel *ioc, - * Not all implementations will support this facility, - * so may report an error. - * -- * Returns: the new position on success, (off_t)-1 on failure -+ * Returns: the new position on success, (int64_t)-1 on failure - */ --off_t qio_channel_io_seek(QIOChannel *ioc, -- off_t offset, -+int64_t qio_channel_io_seek(QIOChannel *ioc, -+ int64_t offset, - int whence, - Error **errp); - -diff --git a/include/system/ramblock.h b/include/system/ramblock.h -index 24c970d393e9cc3463fa46a9bcace7937e50fde4..981470f59d569181f859718942ecb9a855f33078 100644 ---- a/include/system/ramblock.h -+++ b/include/system/ramblock.h -@@ -68,7 +68,7 @@ struct RAMBlock { - * offset in the file pages belonging to this ramblock are saved, - * used only during migration to a file. - */ -- off_t bitmap_offset; -+ int64_t bitmap_offset; - uint64_t pages_offset; - - /* Bitmap of already received pages. Only used on destination side. */ -diff --git a/io/channel-buffer.c b/io/channel-buffer.c -index 189fa67ac21df8a8dff868a477a8021873bd22c7..873e80faeb8a8496ddb6fb0743a17ad599a60654 100644 ---- a/io/channel-buffer.c -+++ b/io/channel-buffer.c -@@ -124,8 +124,8 @@ static int qio_channel_buffer_set_blocking(QIOChannel *ioc G_GNUC_UNUSED, - } - - --static off_t qio_channel_buffer_seek(QIOChannel *ioc, -- off_t offset, -+static int64_t qio_channel_buffer_seek(QIOChannel *ioc, -+ int64_t offset, - int whence, - Error **errp) - { -diff --git a/io/channel-file.c b/io/channel-file.c -index 2487adaea2ad7108310b94910153a4ffbf6eb094..2fb80f90e1c6251c1b2b493e8ebb6566b6b0b769 100644 ---- a/io/channel-file.c -+++ b/io/channel-file.c -@@ -27,6 +27,9 @@ - #include "qemu/module.h" - #include "qemu/sockets.h" - #include "trace.h" -+#ifdef WIN32 -+#include -+#endif - - QIOChannelFile * - qio_channel_file_new_fd(int fd) -@@ -42,7 +45,7 @@ qio_channel_file_new_fd(int fd) - - ioc->fd = fd; - -- if (lseek(fd, 0, SEEK_CUR) != (off_t)-1) { -+ if (lseek(fd, 0, SEEK_CUR) != (int64_t)-1) { - qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE); - } - -@@ -74,6 +77,9 @@ qio_channel_file_new_path(const char *path, - - ioc = QIO_CHANNEL_FILE(object_new(TYPE_QIO_CHANNEL_FILE)); - -+#ifdef O_BINARY -+ flags |= O_BINARY; -+#endif - if (flags & O_CREAT) { - ioc->fd = qemu_create(path, flags & ~O_CREAT, mode, errp); - } else { -@@ -84,9 +90,18 @@ qio_channel_file_new_path(const char *path, - return NULL; - } - -- if (lseek(ioc->fd, 0, SEEK_CUR) != (off_t)-1) { -+ if (lseek(ioc->fd, 0, SEEK_CUR) != (int64_t)-1) { - qio_channel_set_feature(QIO_CHANNEL(ioc), QIO_CHANNEL_FEATURE_SEEKABLE); - } -+#ifdef WIN32 -+ if (flags & O_CREAT) { -+ HANDLE h = (HANDLE)_get_osfhandle(ioc->fd); -+ if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_DISK) { -+ DWORD br = 0; -+ DeviceIoControl(h, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &br, NULL); -+ } -+ } -+#endif - - trace_qio_channel_file_new_path(ioc, path, flags, mode, ioc->fd); - -@@ -170,7 +185,7 @@ static ssize_t qio_channel_file_writev(QIOChannel *ioc, - static ssize_t qio_channel_file_preadv(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp) - { - QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); -@@ -196,7 +211,7 @@ static ssize_t qio_channel_file_preadv(QIOChannel *ioc, - static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp) - { - QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); -@@ -216,6 +231,125 @@ static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, - } - return ret; - } -+#elif defined(WIN32) -+static ssize_t qio_channel_file_prw_win32(QIOChannel *ioc, -+ const struct iovec *iov, -+ size_t niov, -+ int64_t offset, -+ bool is_write, -+ Error **errp) -+{ -+ static const size_t max_chunk = 16U * 1024U * 1024U; -+ QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); -+ HANDLE h = (HANDLE)_get_osfhandle(fioc->fd); -+ LARGE_INTEGER zero = { .QuadPart = 0 }; -+ LARGE_INTEGER saved = { .QuadPart = 0 }; -+ bool have_saved = false; -+ uint64_t cur; -+ ssize_t total = 0; -+ ssize_t ret = -1; -+ size_t i = 0; -+ -+ if (offset < 0) { -+ error_setg_errno(errp, EINVAL, "Invalid negative offset for %s", -+ is_write ? "pwritev" : "preadv"); -+ return -1; -+ } -+ if (h == INVALID_HANDLE_VALUE) { -+ error_setg_errno(errp, EBADF, "Invalid file handle for %s", -+ is_write ? "pwritev" : "preadv"); -+ return -1; -+ } -+ -+ cur = (uint64_t)offset; -+ have_saved = SetFilePointerEx(h, zero, &saved, FILE_CURRENT); -+ -+ while (i < niov) { -+ uint8_t *base = (uint8_t *)iov[i].iov_base; -+ size_t run = iov[i].iov_len; -+ size_t j = i + 1; -+ -+ while (j < niov && (uint8_t *)iov[j].iov_base == base + run && -+ run < max_chunk && iov[j].iov_len <= max_chunk - run) { -+ run += iov[j].iov_len; -+ j++; -+ } -+ if (run == 0) { -+ i = j; -+ continue; -+ } -+ -+ size_t done = 0; -+ while (done < run) { -+ DWORD chunk = (DWORD)MIN(run - done, max_chunk); -+ DWORD xfer = 0; -+ OVERLAPPED ov; -+ BOOL ok; -+ -+ memset(&ov, 0, sizeof(ov)); -+ ov.Offset = (DWORD)(cur & 0xFFFFFFFFULL); -+ ov.OffsetHigh = (DWORD)(cur >> 32); -+ if (is_write) { -+ ok = WriteFile(h, base + done, chunk, &xfer, &ov); -+ } else { -+ ok = ReadFile(h, base + done, chunk, &xfer, &ov); -+ } -+ if (!ok) { -+ DWORD err = GetLastError(); -+ if (!is_write && err == ERROR_HANDLE_EOF) { -+ ret = total; -+ goto out; -+ } -+ error_setg_win32(errp, err, -+ is_write ? "Unable to pwritev to file" -+ : "Unable to preadv from file"); -+ goto out; -+ } -+ if (xfer == 0) { -+ if (!is_write || total > 0) { -+ ret = total; -+ goto out; -+ } -+ error_setg_errno(errp, EIO, "pwritev made no progress"); -+ goto out; -+ } -+ done += xfer; -+ cur += xfer; -+ total += xfer; -+ if (is_write && xfer < chunk) { -+ /* Preserve short-write semantics for caller retry/error handling. */ -+ ret = total; -+ goto out; -+ } -+ } -+ i = j; -+ } -+ -+ ret = total; -+out: -+ if (have_saved) { -+ SetFilePointerEx(h, saved, NULL, FILE_BEGIN); -+ } -+ return ret; -+} -+ -+static ssize_t qio_channel_file_preadv(QIOChannel *ioc, -+ const struct iovec *iov, -+ size_t niov, -+ int64_t offset, -+ Error **errp) -+{ -+ return qio_channel_file_prw_win32(ioc, iov, niov, offset, false, errp); -+} -+ -+static ssize_t qio_channel_file_pwritev(QIOChannel *ioc, -+ const struct iovec *iov, -+ size_t niov, -+ int64_t offset, -+ Error **errp) -+{ -+ return qio_channel_file_prw_win32(ioc, iov, niov, offset, true, errp); -+} - #endif /* CONFIG_PREADV */ - - static int qio_channel_file_set_blocking(QIOChannel *ioc, -@@ -223,7 +357,11 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc, - Error **errp) - { - #ifdef WIN32 -- /* not implemented */ -+ QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); -+ if (enabled || -+ GetFileType((HANDLE)_get_osfhandle(fioc->fd)) == FILE_TYPE_DISK) { -+ return 0; -+ } - error_setg_errno(errp, errno, "Failed to set FD nonblocking"); - return -1; - #else -@@ -237,16 +375,20 @@ static int qio_channel_file_set_blocking(QIOChannel *ioc, - } - - --static off_t qio_channel_file_seek(QIOChannel *ioc, -- off_t offset, -+static int64_t qio_channel_file_seek(QIOChannel *ioc, -+ int64_t offset, - int whence, - Error **errp) - { - QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc); -- off_t ret; -+ int64_t ret; - -+#ifdef WIN32 -+ ret = (int64_t)_lseeki64(fioc->fd, (int64_t)offset, whence); -+#else - ret = lseek(fioc->fd, offset, whence); -- if (ret == (off_t)-1) { -+#endif -+ if (ret == (int64_t)-1) { - error_setg_errno(errp, errno, - "Unable to seek to offset %lld whence %d in file", - (long long int)offset, whence); -@@ -314,7 +456,7 @@ static void qio_channel_file_class_init(ObjectClass *klass, - ioc_klass->io_writev = qio_channel_file_writev; - ioc_klass->io_readv = qio_channel_file_readv; - ioc_klass->io_set_blocking = qio_channel_file_set_blocking; --#ifdef CONFIG_PREADV -+#if defined(CONFIG_PREADV) || defined(WIN32) - ioc_klass->io_pwritev = qio_channel_file_pwritev; - ioc_klass->io_preadv = qio_channel_file_preadv; - #endif -diff --git a/io/channel-null.c b/io/channel-null.c -index 49f1c80a54e1337aa39010ef39a5ea5de4c5392f..2032d26b3c14a28fc36aedc8a3f0248a4701abb9 100644 ---- a/io/channel-null.c -+++ b/io/channel-null.c -@@ -105,9 +105,9 @@ qio_channel_null_set_blocking(QIOChannel *ioc G_GNUC_UNUSED, - } - - --static off_t -+static int64_t - qio_channel_null_seek(QIOChannel *ioc G_GNUC_UNUSED, -- off_t offset G_GNUC_UNUSED, -+ int64_t offset G_GNUC_UNUSED, - int whence G_GNUC_UNUSED, - Error **errp G_GNUC_UNUSED) - { -diff --git a/io/channel.c b/io/channel.c -index 620256f310dbeb060113e71055246ca29431d13d..03d721ec0d699d7c9bcbf2866881d53d7e6b25c0 100644 ---- a/io/channel.c -+++ b/io/channel.c -@@ -450,7 +450,7 @@ GSource *qio_channel_add_watch_source(QIOChannel *ioc, - - - ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, -- size_t niov, off_t offset, Error **errp) -+ size_t niov, int64_t offset, Error **errp) - { - QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc); - -@@ -468,7 +468,7 @@ ssize_t qio_channel_pwritev(QIOChannel *ioc, const struct iovec *iov, - } - - ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, -- off_t offset, Error **errp) -+ int64_t offset, Error **errp) - { - struct iovec iov = { - .iov_base = buf, -@@ -481,7 +481,7 @@ ssize_t qio_channel_pwrite(QIOChannel *ioc, void *buf, size_t buflen, - int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp) - { - int ret = -1; -@@ -519,7 +519,7 @@ int coroutine_mixed_fn qio_channel_pwritev_all(QIOChannel *ioc, - int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, - const void *buf, - size_t buflen, -- off_t offset, -+ int64_t offset, - Error **errp) - { - struct iovec iov = { .iov_base = (char *)buf, .iov_len = buflen }; -@@ -527,7 +527,7 @@ int coroutine_mixed_fn qio_channel_pwrite_all(QIOChannel *ioc, - } - - ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, -- size_t niov, off_t offset, Error **errp) -+ size_t niov, int64_t offset, Error **errp) - { - QIOChannelClass *klass = QIO_CHANNEL_GET_CLASS(ioc); - -@@ -545,7 +545,7 @@ ssize_t qio_channel_preadv(QIOChannel *ioc, const struct iovec *iov, - } - - ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, -- off_t offset, Error **errp) -+ int64_t offset, Error **errp) - { - struct iovec iov = { - .iov_base = buf, -@@ -558,7 +558,7 @@ ssize_t qio_channel_pread(QIOChannel *ioc, void *buf, size_t buflen, - int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp) - { - int ret = -1; -@@ -609,7 +609,7 @@ int coroutine_mixed_fn qio_channel_preadv_all_eof(QIOChannel *ioc, - int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp) - { - int ret = qio_channel_preadv_all_eof(ioc, iov, niov, offset, errp); -@@ -629,7 +629,7 @@ int coroutine_mixed_fn qio_channel_preadv_all(QIOChannel *ioc, - int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, - void *buf, - size_t buflen, -- off_t offset, -+ int64_t offset, - Error **errp) - { - struct iovec iov = { .iov_base = buf, .iov_len = buflen }; -@@ -639,7 +639,7 @@ int coroutine_mixed_fn qio_channel_pread_all_eof(QIOChannel *ioc, - int coroutine_mixed_fn qio_channel_pread_all(QIOChannel *ioc, - void *buf, - size_t buflen, -- off_t offset, -+ int64_t offset, - Error **errp) - { - struct iovec iov = { .iov_base = buf, .iov_len = buflen }; -@@ -696,8 +696,8 @@ int qio_channel_get_peerpid(QIOChannel *ioc, - return 0; - } - --off_t qio_channel_io_seek(QIOChannel *ioc, -- off_t offset, -+int64_t qio_channel_io_seek(QIOChannel *ioc, -+ int64_t offset, - int whence, - Error **errp) - { -diff --git a/migration/channel-block.c b/migration/channel-block.c -index 9cf383d4b57728b2561dbb45afd44c72df15061b..8a0893fb7e4d4cb9e5e91d1418e99674f4562c23 100644 ---- a/migration/channel-block.c -+++ b/migration/channel-block.c -@@ -101,7 +101,7 @@ static ssize_t - qio_channel_block_preadv(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp) - { - QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc); -@@ -122,7 +122,7 @@ static ssize_t - qio_channel_block_pwritev(QIOChannel *ioc, - const struct iovec *iov, - size_t niov, -- off_t offset, -+ int64_t offset, - Error **errp) - { - QIOChannelBlock *bioc = QIO_CHANNEL_BLOCK(ioc); -@@ -152,9 +152,9 @@ qio_channel_block_set_blocking(QIOChannel *ioc, - } - - --static off_t -+static int64_t - qio_channel_block_seek(QIOChannel *ioc, -- off_t offset, -+ int64_t offset, - int whence, - Error **errp) - { -@@ -169,7 +169,7 @@ qio_channel_block_seek(QIOChannel *ioc, - break; - case SEEK_END: - error_setg(errp, "Size of VMstate region is unknown"); -- return (off_t)-1; -+ return (int64_t)-1; - default: - g_assert_not_reached(); - } -diff --git a/migration/channel-block.h b/migration/channel-block.h -index 31673824e6971398b73f55cfb36a521ca0d91791..b2f6768f6ce5a058dc0a082ccd4d0d9297befd3f 100644 ---- a/migration/channel-block.h -+++ b/migration/channel-block.h -@@ -39,7 +39,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(QIOChannelBlock, QIO_CHANNEL_BLOCK) - struct QIOChannelBlock { - QIOChannel parent; - BlockDriverState *bs; -- off_t offset; -+ int64_t offset; - }; - - -diff --git a/migration/file.c b/migration/file.c -index 8ba1de2006eed5a643b7394b9bc4c83cb8d9b4af..5419455d6d314e7529c20116b274d61ce1e38e99 100644 ---- a/migration/file.c -+++ b/migration/file.c -@@ -108,7 +108,11 @@ QIOChannel *file_connect_outgoing(MigrationState *s, - goto out; - } - -+#ifdef WIN32 -+ if (_chsize_s(fioc->fd, (int64_t)offset) != 0) { -+#else - if (ftruncate(fioc->fd, offset)) { -+#endif - error_setg_errno(errp, errno, - "failed to truncate migration file to offset %" PRIx64, - offset); -diff --git a/migration/multifd.h b/migration/multifd.h -index fbc35702b062fdc3213ce92baed35994f5967c2b..2ce94f07403fe1cbe1655728e13c58eeb53dbbe5 100644 ---- a/migration/multifd.h -+++ b/migration/multifd.h -@@ -133,7 +133,7 @@ struct MultiFDRecvData { - void *opaque; - size_t size; - /* for preadv */ -- off_t file_offset; -+ int64_t file_offset; - }; - - typedef struct { -diff --git a/migration/qemu-file.c b/migration/qemu-file.c -index df3f96fb24005d0fcf397bf8035b460a04eb2490..4aef4856599e83c6bb72012dbea3f163ab838add 100644 ---- a/migration/qemu-file.c -+++ b/migration/qemu-file.c -@@ -532,7 +532,7 @@ void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size) - } - - void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, -- off_t pos) -+ int64_t pos) - { - Error *err = NULL; - -@@ -550,7 +550,7 @@ void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, - } - - --size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, -+size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos, - Error **errp) - { - if (f->last_error) { -@@ -566,10 +566,10 @@ size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, - return buflen; - } - --void qemu_set_offset(QEMUFile *f, off_t off, int whence) -+void qemu_set_offset(QEMUFile *f, int64_t off, int whence) - { - Error *err = NULL; -- off_t ret; -+ int64_t ret; - - if (qemu_file_is_writable(f)) { - qemu_fflush(f); -@@ -580,20 +580,20 @@ void qemu_set_offset(QEMUFile *f, off_t off, int whence) - } - - ret = qio_channel_io_seek(f->ioc, off, whence, &err); -- if (ret == (off_t)-1) { -+ if (ret == (int64_t)-1) { - qemu_file_set_error_obj(f, -EIO, err); - } - } - --off_t qemu_get_offset(QEMUFile *f) -+int64_t qemu_get_offset(QEMUFile *f) - { - Error *err = NULL; -- off_t ret; -+ int64_t ret; - - qemu_fflush(f); - - ret = qio_channel_io_seek(f->ioc, 0, SEEK_CUR, &err); -- if (ret == (off_t)-1) { -+ if (ret == (int64_t)-1) { - qemu_file_set_error_obj(f, -EIO, err); - } - return ret; -diff --git a/migration/qemu-file.h b/migration/qemu-file.h -index 966766788ddfb11e08eb8b059d43c69a66260818..c5d2a984611da615e8561866af954f6e778780bf 100644 ---- a/migration/qemu-file.h -+++ b/migration/qemu-file.h -@@ -72,11 +72,11 @@ QEMUFile *qemu_file_get_return_path(QEMUFile *f); - int qemu_fflush(QEMUFile *f); - bool qemu_file_set_blocking(QEMUFile *f, bool block, Error **errp); - int qemu_file_get_to_fd(QEMUFile *f, int fd, size_t size); --void qemu_set_offset(QEMUFile *f, off_t off, int whence); --off_t qemu_get_offset(QEMUFile *f); -+void qemu_set_offset(QEMUFile *f, int64_t off, int whence); -+int64_t qemu_get_offset(QEMUFile *f); - void qemu_put_buffer_at(QEMUFile *f, const uint8_t *buf, size_t buflen, -- off_t pos); --size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, off_t pos, -+ int64_t pos); -+size_t qemu_get_buffer_at(QEMUFile *f, uint8_t *buf, size_t buflen, int64_t pos, - Error **errp); - - QIOChannel *qemu_file_get_ioc(QEMUFile *file); -diff --git a/migration/ram.c b/migration/ram.c -index e6db3bf523855ee1ea20e79495326979f00d3192..410cfa6a1c2bfe84308d19c36bd8a00157226581 100644 ---- a/migration/ram.c -+++ b/migration/ram.c -@@ -1010,7 +1010,7 @@ static uint64_t physical_memory_sync_dirty_bitmap(RAMBlock *rb, - unsigned long *dest = rb->bmap; - - /* start address and length is aligned at the start of a word? */ -- if (((word * BITS_PER_LONG) << TARGET_PAGE_BITS) == -+ if ((((ram_addr_t)word * BITS_PER_LONG) << TARGET_PAGE_BITS) == - (start + rb->offset) && - !(length & ((BITS_PER_LONG << TARGET_PAGE_BITS) - 1))) { - int k; -@@ -4137,8 +4137,8 @@ static bool handle_zero_mapped_ram(RAMBlock *block, unsigned long from_bit_idx, - return true; - } - -- size = TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx); -- offset = from_bit_idx << TARGET_PAGE_BITS; -+ size = (size_t)TARGET_PAGE_SIZE * (to_bit_idx - from_bit_idx); -+ offset = ((ram_addr_t)from_bit_idx) << TARGET_PAGE_BITS; - host = host_from_ram_block_offset(block, offset); - if (!host) { - error_setg(errp, "zero page outside of ramblock %s range", -@@ -4172,8 +4172,8 @@ static bool read_ramblock_mapped_ram(QEMUFile *f, RAMBlock *block, - /* Non-zero pages */ - clear_bit_idx = find_next_zero_bit(bitmap, num_pages, set_bit_idx + 1); - -- unread = TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx); -- offset = set_bit_idx << TARGET_PAGE_BITS; -+ unread = (size_t)TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx); -+ offset = ((ram_addr_t)set_bit_idx) << TARGET_PAGE_BITS; - - while (unread > 0) { - host = host_from_ram_block_offset(block, offset); diff --git a/patches/reims-ctl-qcow2-l2-cache.patch b/patches/reims-ctl-qcow2-l2-cache.patch deleted file mode 100644 index 9674588..0000000 --- a/patches/reims-ctl-qcow2-l2-cache.patch +++ /dev/null @@ -1,52 +0,0 @@ -diff --git a/crates/reims-ctl/src/qemu.rs b/crates/reims-ctl/src/qemu.rs -index 66c7952..67101dc 100644 ---- a/crates/reims-ctl/src/qemu.rs -+++ b/crates/reims-ctl/src/qemu.rs -@@ -195,6 +195,33 @@ pub fn opt(s: &str) -> String { - s.replace(',', ",,") - } - -+/// Compute the qcow2 L2 cache size in MiB needed to cover the full virtual disk -+/// (`virtual_size / cluster_size * 8` bytes), clamped to `..=32 MiB`, returning `Some(mib)` only -+/// when the image needs more than QEMU's 8 MiB non-Linux default. -+fn qcow2_l2_cache_mib(path: &Path) -> Option { -+ use std::io::Read; -+ let mut hdr = [0u8; 32]; -+ let mut f = std::fs::File::open(path).ok()?; -+ f.read_exact(&mut hdr).ok()?; -+ if &hdr[0..4] != b"QFI\xfb" { -+ return None; -+ } -+ let version = u32::from_be_bytes(hdr[4..8].try_into().ok()?); -+ if version < 2 || version > 3 { -+ return None; -+ } -+ let cluster_bits = u32::from_be_bytes(hdr[20..24].try_into().ok()?); -+ if !(9..=21).contains(&cluster_bits) { -+ return None; -+ } -+ let virtual_size = u64::from_be_bytes(hdr[24..32].try_into().ok()?); -+ let cluster_size = 1u64 << cluster_bits; -+ let clusters = virtual_size.div_ceil(cluster_size); -+ let l2_bytes = clusters.saturating_mul(8); -+ let mib = l2_bytes.div_ceil(1024 * 1024).min(32); -+ (mib > 8).then_some(mib) -+} -+ - fn optp(p: &Path) -> String { - opt(&p.to_string_lossy()) - } -@@ -378,6 +405,13 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec) -> Result<()> { - c.disk_format.as_str(), - optp(&vm.disk()) - ); -+ // QEMU caps default qcow2 L2 cache at 8 MiB on non-Linux hosts (covering only 64 GiB at 64 KiB -+ // clusters). Size l2-cache-size to cover the image's virtual capacity (capped at 32 MiB). -+ if matches!(c.disk_format, crate::vm::ImageFormat::Qcow2) { -+ if let Some(mib) = qcow2_l2_cache_mib(&vm.disk()) { -+ disk.push_str(&format!(",l2-cache-size={mib}M")); -+ } -+ } - // An install's flushes, which the module's doc measures, are dropped while the installer is - // attached. - if q.installer.is_some() { diff --git a/patches/reims-ctl-virtio-discard-iothread.patch b/patches/reims-ctl-virtio-discard-iothread.patch deleted file mode 100644 index 25d17db..0000000 --- a/patches/reims-ctl-virtio-discard-iothread.patch +++ /dev/null @@ -1,53 +0,0 @@ -diff --git a/crates/reims-ctl/src/qemu.rs b/crates/reims-ctl/src/qemu.rs -index 4c80cfb..66c7952 100644 ---- a/crates/reims-ctl/src/qemu.rs -+++ b/crates/reims-ctl/src/qemu.rs -@@ -398,12 +398,15 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec) -> Result<()> { - "-device", - &format!("ide-hd,bus=sata.{},drive=disk,rotation_rate=1", q.disk_port), - ]), -- // SATA's drive options, at the first slot no other device takes. -+ // Pass guest TRIMs (`discard=unmap`) like NVMe and offload block handling to a dedicated -+ // iothread so disk completions do not contend with QEMU's main event loop. - DiskController::Virtio => push(&[ -+ "-object", -+ "iothread,id=io0", - "-drive", -- &disk, -+ &format!("{disk},discard=unmap"), - "-device", -- "virtio-blk-pci,drive=disk,addr=0x6", -+ "virtio-blk-pci,drive=disk,iothread=io0,addr=0x6", - ]), - } - // The installer, on port 4, past OpenCore's, or on 5 past an AHCI disk on 4. -@@ -1754,10 +1757,12 @@ pub(crate) mod tests { - assert!(has( - &a, - &[ -+ "-object", -+ "iothread,id=io0", - "-drive", -- "id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2", -+ "id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,discard=unmap", - "-device", -- "virtio-blk-pci,drive=disk,addr=0x6", -+ "virtio-blk-pci,drive=disk,iothread=io0,addr=0x6", - ] - )); - assert!( -@@ -1782,10 +1787,12 @@ pub(crate) mod tests { - assert!(has( - &a, - &[ -+ "-object", -+ "iothread,id=io0", - "-drive", -- "id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on", -+ "id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on,discard=unmap", - "-device", -- "virtio-blk-pci,drive=disk,addr=0x6", -+ "virtio-blk-pci,drive=disk,iothread=io0,addr=0x6", - ] - )); - } diff --git a/patches/reims-ctl-win32-random-bytes.patch b/patches/reims-ctl-win32-random-bytes.patch deleted file mode 100644 index 0a50d20..0000000 --- a/patches/reims-ctl-win32-random-bytes.patch +++ /dev/null @@ -1,30 +0,0 @@ -diff --git a/crates/reims-ctl/src/vm.rs b/crates/reims-ctl/src/vm.rs -index e8b8e92..f62174f 100644 ---- a/crates/reims-ctl/src/vm.rs -+++ b/crates/reims-ctl/src/vm.rs -@@ -853,12 +853,22 @@ fn random_bytes() -> [u8; N] { - .and_then(|mut f| f.read_exact(&mut b)) - .is_err() - { -+ // Windows has no /dev/urandom. The clock alone is no random source there: it counts -+ // 100 ns, so its low bytes hold some 22 bits, the first of them a multiple of 4, and the -+ // pid, shifted past them, changes none. std's RandomState is keyed from the OS's random -+ // source (ProcessPrng on Windows), so a hash it keys is unpredictable; the clock and the -+ // pid are hashed in too. -+ use std::hash::{BuildHasher, Hasher}; - let t = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default(); -- let seed = t.as_nanos() ^ (std::process::id() as u128) << 64; -- for (i, x) in b.iter_mut().enumerate() { -- *x = (seed >> (i * 8)) as u8; -+ let keys = std::collections::hash_map::RandomState::new(); -+ for (i, chunk) in b.chunks_mut(8).enumerate() { -+ let mut h = keys.build_hasher(); -+ h.write_usize(i); -+ h.write_u128(t.as_nanos()); -+ h.write_u32(std::process::id()); -+ chunk.copy_from_slice(&h.finish().to_le_bytes()[..chunk.len()]); - } - } - b diff --git a/patches/reims-vgpu-display-fixed-mode.patch b/patches/reims-vgpu-display-fixed-mode.patch deleted file mode 100644 index a07ee44..0000000 --- a/patches/reims-vgpu-display-fixed-mode.patch +++ /dev/null @@ -1,265 +0,0 @@ -diff --git a/crates/reims-vgpu-window/src/env.rs b/crates/reims-vgpu-window/src/env.rs -index e73d36f..9e67173 100644 ---- a/crates/reims-vgpu-window/src/env.rs -+++ b/crates/reims-vgpu-window/src/env.rs -@@ -14,6 +14,10 @@ - //! no window ever captures the keyboard or the pointer ([`crate::capture`]). `1`, `true`, - //! `yes` or `on` turns it on. Default: [`CAPTURE_DEFAULT`]. reims-ctl sets it from a VM's - //! settings. -+//! - `REIMS_VGPU_WINDOW_FIXED_MODE`: `1`, `true`, `yes` or `on`, in any case, decouples the -+//! guest's display mode from the window's pixel size so the display keeps offering the -+//! configured resolution (e.g. 5120x2880 HiDPI supersampled into a 4K borderless window) and -+//! scales the frame on the GPU. Default: off. - - use std::sync::OnceLock; - -@@ -25,6 +29,8 @@ pub const SCREENS_VAR: &str = "REIMS_VGPU_WINDOW_SCREENS"; - pub const IMPL_VAR: &str = "REIMS_VGPU_WINDOW_IMPL"; - /// The capture switch's variable. - pub const CAPTURE_VAR: &str = "REIMS_VGPU_WINDOW_CAPTURE"; -+/// The fixed guest mode switch's variable. -+pub const FIXED_MODE_VAR: &str = "REIMS_VGPU_WINDOW_FIXED_MODE"; - - /// Whether a click into the image captures input where the capture switch is unset. - pub const CAPTURE_DEFAULT: bool = true; -@@ -40,6 +46,8 @@ pub struct Settings { - pub window_impl: WindowImpl, - /// Whether a click into the image captures input; off, nothing ever does. - pub capture: bool, -+ /// Keep offering the configured guest resolution instead of following the window's pixels. -+ pub fixed_mode: bool, - } - - impl Default for Settings { -@@ -49,6 +57,7 @@ impl Default for Settings { - screens: Vec::new(), - window_impl: WindowImpl::AppKit, - capture: CAPTURE_DEFAULT, -+ fixed_mode: false, - } - } - } -@@ -116,6 +125,11 @@ fn parse_screens(value: &str) -> Option> { - .collect() - } - -+/// Whether fixed guest mode is on (`1`, `true`, `yes` or `on`, in any case); default off. -+pub fn parse_fixed_mode(value: Option<&str>) -> bool { -+ value.is_some_and(parse_switch) -+} -+ - /// The process's settings, read from its environment the first time they are asked for. A - /// value that is not UTF-8 counts as unset. - pub fn settings() -> &'static Settings { -@@ -126,6 +140,7 @@ pub fn settings() -> &'static Settings { - Settings { - window_impl: parse_impl(var(IMPL_VAR).as_deref()), - capture: parse_capture(var(CAPTURE_VAR).as_deref()), -+ fixed_mode: parse_fixed_mode(var(FIXED_MODE_VAR).as_deref()), - ..parse(borderless.as_deref(), screens.as_deref()) - } - }) -diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs -index 9ce42b2..8cac38c 100644 ---- a/crates/reims-vgpu/src/graphics.rs -+++ b/crates/reims-vgpu/src/graphics.rs -@@ -5321,19 +5321,35 @@ impl Screen for WindowScreen { - /// draw). - 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, - } - } - -diff --git a/crates/reims-vgpu/src/graphics/sink.rs b/crates/reims-vgpu/src/graphics/sink.rs -index 9dd3e90..5e9994b 100644 ---- a/crates/reims-vgpu/src/graphics/sink.rs -+++ b/crates/reims-vgpu/src/graphics/sink.rs -@@ -239,6 +239,8 @@ pub(crate) struct ScanoutDraw { - ramps: Mutex>, - /// The scanout's ramp, made at its first use; `None` inside where the platform refused it. - scanout_ramp: Kept>, -+ /// Staging texture used to GPU-scale a raw scanout whose size differs from the window's image. -+ scanout_stage: Mutex>, - /// 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>, -@@ -568,6 +570,7 @@ impl ScanoutDraw

{ - 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)] -@@ -607,6 +610,7 @@ impl ScanoutDraw

{ - *self.color_table.lock() = None; - self.ramps.lock().clear(); - self.scanout_ramp.forget(); -+ *self.scanout_stage.lock() = None; - *self.cursor.lock() = CursorPass::cursor(); - *self.overlay.lock() = CursorPass::overlay(); - } -@@ -900,7 +904,8 @@ impl ScanoutDraw

{ - if let Some((surface, view, hold)) = self.presented.shown() { - let (from, to) = (surface.pixel_format(), texture.pixel_format()); - self.presented.seen_format(from, to); -- let copied = BGRA8_FORMATS.contains(&from) && BGRA8_FORMATS.contains(&to); -+ let same_size = surface.width() == region.width && surface.height() == region.height; -+ let copied = same_size && BGRA8_FORMATS.contains(&from) && BGRA8_FORMATS.contains(&to); - let drawn = if color.is_none() && copied { - self.encode_surface(&surface, texture, region) - } else { -@@ -1463,6 +1468,15 @@ impl ScanoutDraw

{ - fn encode_scanout(&self, texture: &P::Texture, region: PixelRect) -> Option { - let scanout = (*self.shown.scanout.lock())?; - let (buffer, source_offset) = self.scanout_buffer(&scanout)?; -+ let (sw, sh) = (u64::from(scanout.width), u64::from(scanout.height)); -+ if sw > 0 -+ && sh > 0 -+ && (sw != region.width || sh != region.height) -+ && let Some(cb) = -+ self.encode_scanout_scaled(&scanout, &buffer, source_offset, texture, region) -+ { -+ return Some(cb); -+ } - let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?; - let (texture_width, texture_height) = (texture.width(), texture.height()); - let x = region.x.min(texture_width); -@@ -1569,6 +1583,62 @@ impl ScanoutDraw

{ - }) - } - -+ /// Stages `scanout` into a `BGRA8Unorm` texture and scales it into `texture` at `region` via -+ /// the linear-filtered display present shader (used when guest mode != window pixels, e.g. -+ /// `REIMS_VGPU_WINDOW_FIXED_MODE=1` during boot/Recovery). -+ fn encode_scanout_scaled( -+ &self, -+ scanout: &Scanout, -+ buffer: &P::Buffer, -+ source_offset: u64, -+ texture: &P::Texture, -+ region: PixelRect, -+ ) -> Option { -+ let (sw, sh) = (u64::from(scanout.width), u64::from(scanout.height)); -+ let stage = { -+ let mut slot = self.scanout_stage.lock(); -+ let reuse = slot -+ .as_ref() -+ .is_some_and(|t| t.width() == sw && t.height() == sh); -+ if !reuse { -+ let desc = self.platform.texture_descriptor(&TextureDesc { -+ pixel_format: 80, -+ width: sw, -+ height: sh, -+ usage: RAMP_USAGE, -+ resource_options: Some(PRIVATE), -+ ..TextureDesc::default() -+ }); -+ let made = no_catch(self.device.new_texture(OnFault::Die, &desc))?; -+ *slot = Some(made); -+ } -+ slot.as_ref()?.clone_ref() -+ }; -+ let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?; -+ let blit = Open::new( -+ no_catch(command_buffer.blit_encoder(OnFault::Die))?, -+ end_blit::

, -+ ); -+ let stride = u64::from(scanout.stride); -+ no_catch(blit.get().encode( -+ OnFault::Die, -+ BlitCmd::CopyBufferToTexture { -+ source_buffer: buffer, -+ source_offset, -+ source_bytes_per_row: stride, -+ source_bytes_per_image: stride * sh, -+ source_size: MtlSize::new(sw, sh, 1), -+ destination_texture: &stage, -+ destination_slice: 0, -+ destination_level: 0, -+ destination_origin: MtlOrigin::new(0, 0, 0), -+ }, -+ )); -+ blit.end(); -+ self.encode_converted_into(&command_buffer, &stage, texture, region)?; -+ Some(command_buffer) -+ } -+ - /// A command buffer of the sink's queue with the presented `surface` drawn into `texture` at - /// `region` by the display's present shaders, which convert its format to the drawable's, - /// after a clear of the drawable to black where `region` does not cover it ([`pass_load`]); -@@ -1580,12 +1650,25 @@ impl ScanoutDraw

{ - texture: &P::Texture, - region: PixelRect, - ) -> Option { -+ let command_buffer = self.surface_command_buffer()?; -+ self.encode_converted_into(&command_buffer, surface, texture, region)?; -+ Some(command_buffer) -+ } -+ -+ /// Encodes the linear-filtered display present shader drawing `surface` into `texture` at -+ /// `region` on `command_buffer`. -+ fn encode_converted_into( -+ &self, -+ command_buffer: &P::CommandBuffer, -+ surface: &P::Texture, -+ texture: &P::Texture, -+ region: PixelRect, -+ ) -> Option<()> { - let converter = self.converter()?; - let pipeline = converter.pipelines.pipeline_for(PipelineKey { - format: texture.pixel_format(), - gamma: false, - })?; -- let command_buffer = self.surface_command_buffer()?; - let (texture_width, texture_height) = (texture.width(), texture.height()); - let x = region.x.min(texture_width); - let y = region.y.min(texture_height); -@@ -1657,7 +1740,7 @@ impl ScanoutDraw

{ - } - } - encoder.end(); -- Some(command_buffer) -+ Some(()) - } - - /// Clears all of `texture` to opaque black, in a render pass of `command_buffer` with no diff --git a/patches/reims-vgpu-snapshot-replay.patch b/patches/reims-vgpu-snapshot-replay.patch deleted file mode 100644 index 95593fd..0000000 --- a/patches/reims-vgpu-snapshot-replay.patch +++ /dev/null @@ -1,4309 +0,0 @@ -diff --git a/crates/reims-vgpu-c/src/graphics.rs b/crates/reims-vgpu-c/src/graphics.rs -index 89ab1d0bae44537dcbca5653ac5e6f0690dcdaee..fcb5067c345f9769c216a6756701e9a8fea2429b 100644 ---- a/crates/reims-vgpu-c/src/graphics.rs -+++ b/crates/reims-vgpu-c/src/graphics.rs -@@ -1180,5 +1180,124 @@ 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; -diff --git a/crates/reims-vgpu-graphics/src/device.rs b/crates/reims-vgpu-graphics/src/device.rs -index ae1d87d621a121feff29ac4f427193f7bc129994..e17ccb80c0fba49246ae22fede135c3c8c51fb88 100644 ---- a/crates/reims-vgpu-graphics/src/device.rs -+++ b/crates/reims-vgpu-graphics/src/device.rs -@@ -1104,6 +1104,8 @@ pub(crate) struct Shared { - reset_owed: AtomicBool, - /// Set at the device's end. - ending: AtomicBool, -+ /// Set while quiesced for checkpointing. -+ quiesced: AtomicBool, - /// The control thread's own wake. - wake: Wake, - /// The host's doorbell file for ring 0, once given. -@@ -1874,6 +1876,7 @@ impl Device { - epoch: AtomicU64::new(0), - reset_owed: AtomicBool::new(false), - ending: AtomicBool::new(false), -+ quiesced: AtomicBool::new(false), - wake: Wake::new()?, - doorbell: OnceLock::new(), - submit: Mutex::new(Submit { -@@ -2119,6 +2122,26 @@ impl Device { - pub fn reset(&self) { - self.shared.reset(); - } -+ -+ /// Quiesces the device for stopped-VM checkpointing. -+ pub fn quiesce(&self) { -+ self.shared.quiesce(); -+ } -+ -+ /// Resumes VBLANK ticks and ring consumption after quiesce. -+ pub fn unquiesce(&self) { -+ self.shared.unquiesce(); -+ } -+ -+ /// Exports the quiescent device's BAR0/ring/display/queue/region state. -+ pub fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot { -+ self.shared.export_snapshot() -+ } -+ -+ /// Restores device state on a freshly created device (after QEMU restored BAR2). -+ pub fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> { -+ self.shared.import_snapshot(snap) -+ } - } - - /// The `COMPLETE` a ring-0 command owes, which the host gives from any thread once it has carried -@@ -2577,6 +2600,219 @@ impl Shared { - /// The reset (the module doc). It waits for the message the control thread is taking, and - /// for a take of a queue's ring or a post onto one under way, none of which waits for the - /// host; the host is told on the control thread ([`Self::tell_reset`]). -+ fn quiesce(&self) { -+ self.quiesced.store(true, Ordering::Release); -+ self.wake.wake(); -+ let active_queues: Vec> = { -+ 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> = { -+ 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 = self.pages.iter().map(|p| p.load(Ordering::Acquire)).collect(); -+ let displays: Vec = 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> = -+ self.queues.lock().by_obj.values().cloned().collect(); -+ queue_list.sort_by_key(|q| q.obj_id); -+ let queues: Vec = queue_list -+ .iter() -+ .map(|q| { -+ let s = q.submit.lock(); -+ let c = q.complete.lock(); -+ QueueSnapshot { -+ create_bytes: q.create.as_bytes().to_vec(), -+ flags: q.flags, -+ taken_seqno: q.taken_seqno.load(Ordering::Acquire), -+ taken_buffer_seqno: q.taken_buffer_seqno.load(Ordering::Acquire), -+ submit_count: s.consumer.consumed(), -+ submit_broken: s.broken, -+ complete_count: c.produced(), -+ } -+ }) -+ .collect(); -+ DeviceSnapshot { -+ status, -+ driver_features, -+ control_done, -+ control_submit_count, -+ control_submit_broken, -+ control_completion_count, -+ vt_ring_count, -+ pages, -+ displays, -+ region_blocks, -+ queues, -+ } -+ } -+ -+ fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> { -+ self.quiesced.store(true, Ordering::Release); -+ self.region.import_blocks(&snap.region_blocks); -+ self.driver_features.store(snap.driver_features, Ordering::Release); -+ if snap.driver_features != 0 { -+ self.host.driver_ready(snap.driver_features); -+ } -+ let mut any_page = false; -+ for (dst, &val) in self.pages.iter().zip(snap.pages.iter()) { -+ dst.store(val, Ordering::Release); -+ if val != 0 { -+ any_page = true; -+ } -+ } -+ if any_page { -+ self.pages_bound.store(true, Ordering::Release); -+ } -+ { -+ let mut submit = self.submit.lock(); -+ submit.consumer.set_count(snap.control_submit_count); -+ submit.broken = snap.control_submit_broken; -+ submit.backlog.clear(); -+ } -+ self.control_done.store(snap.control_done, Ordering::Release); -+ self.completion.lock().set_count(snap.control_completion_count); -+ self.vt_ring.lock().set_count(snap.vt_ring_count); -+ self.reset_owed.store(false, Ordering::Release); -+ for (display, ds) in self.displays.iter().zip(snap.displays.iter()) { -+ { -+ let mut st = display.state.lock(); -+ st.scanout = ds.scanout; -+ st.vblank = ds.vblank; -+ st.asleep = ds.asleep; -+ st.refreshes = ds.refreshes; -+ st.told = ds.told; -+ st.changed = ds.changed; -+ st.cursor_image = ds.cursor_image.clone(); -+ } -+ display.screen.scanout(ds.scanout); -+ display.screen.cursor_image(ds.cursor_image.clone()); -+ display.screen.power(!ds.asleep); -+ } -+ self.status.store(snap.status, Ordering::Release); -+ let epoch = self.epoch.load(Ordering::Acquire); -+ for qs in &snap.queues { -+ let Ok(q) = RgfxQueueCreate::read_from_bytes(&qs.create_bytes) else { -+ return Err("malformed RgfxQueueCreate in snapshot"); -+ }; -+ let Some((submit_at, complete_at)) = self.validate_rings(&q) else { -+ return Err("queue rings invalid against restored BAR2 block ledger"); -+ }; -+ let Some(me) = self.weak_self.get().and_then(Weak::upgrade) else { -+ return Err("device weak_self missing"); -+ }; -+ let Some(wake) = Wake::new() else { -+ return Err("queue wake allocation failed"); -+ }; -+ let bell = if self.driver_took(RGFX_FEATURE_DOORBELL_ASKS) { -+ wake::bell() -+ } else { -+ None -+ }; -+ let mut consumer = Consumer::new(submit_at); -+ consumer.set_count(qs.submit_count); -+ let mut producer = Producer::new(complete_at); -+ producer.set_count(qs.complete_count); -+ let queue = Arc::new(QueueShared { -+ obj_id: q.obj_id, -+ context: (q.obj_id >> RGFX_CONTEXT_OBJ_ID_SHIFT) as u32, -+ create: q, -+ flags: qs.flags, -+ epoch, -+ ring_id: q.submit_offset, -+ vector: q.vector, -+ submit: Mutex::new(Submit { -+ consumer, -+ broken: qs.submit_broken, -+ backlog: Backlog::default(), -+ asleep: false, -+ }), -+ taken_seqno: AtomicU64::new(qs.taken_seqno), -+ taken_buffer_seqno: AtomicU64::new(qs.taken_buffer_seqno), -+ consuming: Mutex::new(None), -+ complete: Mutex::new(producer), -+ room: Room::default(), -+ full: AtomicBool::new(false), -+ untold: Mutex::new(Untold::default()), -+ handed: Mutex::new(Handed::default()), -+ handing: AtomicBool::new(false), -+ wake, -+ bell, -+ route: AtomicU64::new(0), -+ route_page: AtomicU32::new(u32::MAX), -+ ending: AtomicBool::new(false), -+ trip: trip::Queue::default(), -+ }); -+ { -+ let mut queues = self.queues.lock(); -+ queues.by_obj.insert(q.obj_id, Arc::clone(&queue)); -+ queues.by_ring.insert(q.submit_offset, Arc::clone(&queue)); -+ } -+ let service = Arc::clone(&queue); -+ std::thread::Builder::new() -+ .name(format!("reims-vgpu.graphics-queue-{:#x}", q.obj_id)) -+ .spawn(move || me.queue_service_restored(&service)) -+ .map_err(|_| "failed to spawn restored queue thread")?; -+ self.route(&queue); -+ self.host.queue_made(&self.queue_poster(&queue)); -+ } -+ Ok(()) -+ } -+ - fn reset(&self) { - self.status.store(RGFX_STATUS_RESET, Ordering::Release); - self.driver_features.store(0, Ordering::Release); -@@ -3254,6 +3490,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); -@@ -4438,6 +4678,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) { -+ 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::() as u32, -+ seqno: 0, -+ }, -+ obj_id: queue.obj_id, -+ }; -+ self.host.stage3_message(&poster, destroy.as_bytes()); -+ } -+ } -+ - fn queue_service(&self, queue: &Arc) { - let poster = self.queue_poster(queue); - // The host makes the queue's handle first, so a command buffer on it can name it. -@@ -4464,6 +4721,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, 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) { -@@ -5074,6 +5335,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; - }; -diff --git a/crates/reims-vgpu-graphics/src/device/lanes.rs b/crates/reims-vgpu-graphics/src/device/lanes.rs -index 110cbb6a4cbaf7e2450fa7040d365c3de73d9026..12b201509a9f574c8ed20f831e04d4961e66e541 100644 ---- a/crates/reims-vgpu-graphics/src/device/lanes.rs -+++ b/crates/reims-vgpu-graphics/src/device/lanes.rs -@@ -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) { -diff --git a/crates/reims-vgpu-graphics/src/lib.rs b/crates/reims-vgpu-graphics/src/lib.rs -index ae8a328435c264e712b4d34e5153cdfcce1ca55b..40214d647726016d9aabbcc21122b3931e18493f 100644 ---- a/crates/reims-vgpu-graphics/src/lib.rs -+++ b/crates/reims-vgpu-graphics/src/lib.rs -@@ -31,6 +31,7 @@ pub mod keep; - pub mod managed; - pub mod ops; - pub mod region; -+pub mod snapshot; - mod ring; - // The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header. - /// cbindgen:ignore -diff --git a/crates/reims-vgpu-graphics/src/region.rs b/crates/reims-vgpu-graphics/src/region.rs -index c6032c91cb349f4a9c5e22931f46908de2eef86b..e986d707926a9d0ac524abc9499ae013bfca1442 100644 ---- a/crates/reims-vgpu-graphics/src/region.rs -+++ b/crates/reims-vgpu-graphics/src/region.rs -@@ -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, -+ /// 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 { -+ 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(); - } -diff --git a/crates/reims-vgpu-graphics/src/ring.rs b/crates/reims-vgpu-graphics/src/ring.rs -index 36585f35100fa121406d92c019f8172755a5cb18..12f3f11703ab5175cd90f0e6a919bb8fda017a97 100644 ---- a/crates/reims-vgpu-graphics/src/ring.rs -+++ b/crates/reims-vgpu-graphics/src/ring.rs -@@ -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); -diff --git a/crates/reims-vgpu-graphics/src/snapshot.rs b/crates/reims-vgpu-graphics/src/snapshot.rs -new file mode 100644 -index 0000000000000000000000000000000000000000..00ddc52e940a6cd246a777ee74073007e91ad006 ---- /dev/null -+++ b/crates/reims-vgpu-graphics/src/snapshot.rs -@@ -0,0 +1,293 @@ -+//! 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, -+ /// 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, -+ /// Whether a `DISPLAY_CHANGED` event is owed. -+ pub changed: bool, -+ /// Current guest cursor image, if any. -+ pub cursor_image: Option, -+} -+ -+/// Serializable per-command-queue ring state. -+#[derive(Clone, Debug, PartialEq, Eq)] -+pub struct QueueSnapshot { -+ /// Raw `RgfxQueueCreate` wire message bytes. -+ pub create_bytes: Vec, -+ /// Accepted `RGFX_QUEUE_*` flags. -+ pub flags: u32, -+ /// Highest message seqno taken off the queue's submission ring. -+ pub taken_seqno: u64, -+ /// Highest command-buffer seqno taken off the queue's submission ring. -+ pub taken_buffer_seqno: u64, -+ /// Host consumer byte count on the queue's submission ring. -+ pub submit_count: u64, -+ /// Whether the queue's submission ring was marked broken. -+ pub submit_broken: bool, -+ /// Host producer byte count on the queue's completion ring. -+ pub complete_count: u64, -+} -+ -+/// Complete serializable snapshot of `reims_vgpu_graphics::Device` (BAR0/rings/displays/queues). -+#[derive(Clone, Debug, PartialEq, Eq)] -+pub struct DeviceSnapshot { -+ /// `STATUS` register value. -+ pub status: u32, -+ /// Negotiated `DRIVER_FEATURES` bitmask. -+ pub driver_features: u64, -+ /// Control submission ring `control_done` count. -+ pub control_done: u64, -+ /// Control submission ring consumer byte count. -+ pub control_submit_count: u64, -+ /// Whether control submission ring is broken. -+ pub control_submit_broken: bool, -+ /// Control completion ring producer byte count. -+ pub control_completion_count: u64, -+ /// VideoToolbox ring producer byte count. -+ pub vt_ring_count: u64, -+ /// Doorbell page context bindings (`RGFX_REG_DOORBELL_PAGE_BIND`). -+ pub pages: Vec, -+ /// Per-display state. -+ pub displays: Vec, -+ /// Active BAR2 granted/shared blocks. -+ pub region_blocks: Vec, -+ /// Active per-queue rings. -+ pub queues: Vec, -+} -+ -+fn put_u8(o: &mut Vec, v: u8) { o.push(v); } -+fn put_u32(o: &mut Vec, v: u32) { o.extend_from_slice(&v.to_le_bytes()); } -+fn put_u64(o: &mut Vec, v: u64) { o.extend_from_slice(&v.to_le_bytes()); } -+fn put_bytes(o: &mut Vec, b: &[u8]) { -+ put_u64(o, b.len() as u64); -+ o.extend_from_slice(b); -+} -+ -+fn get_u8(i: &mut &[u8]) -> Option { -+ let (&b, rest) = i.split_first()?; -+ *i = rest; -+ Some(b) -+} -+fn get_u32(i: &mut &[u8]) -> Option { -+ 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 { -+ 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> { -+ 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 { -+ 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( -+ i: &mut &[u8], -+ min_item_bytes: usize, -+ mut f: impl FnMut(&mut &[u8]) -> Option, -+) -> Option> { -+ 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) { -+ put_u32(o, 1); -+ put_u32(o, self.status); -+ put_u64(o, self.driver_features); -+ put_u64(o, self.control_done); -+ put_u64(o, self.control_submit_count); -+ put_u8(o, u8::from(self.control_submit_broken)); -+ put_u64(o, self.control_completion_count); -+ put_u64(o, self.vt_ring_count); -+ -+ put_u32(o, self.pages.len() as u32); -+ for &p in &self.pages { put_u32(o, p); } -+ -+ put_u32(o, self.displays.len() as u32); -+ for d in &self.displays { -+ match d.scanout { -+ Some(s) => { -+ put_u8(o, 1); -+ put_u32(o, s.width); put_u32(o, s.height); -+ put_u32(o, s.stride); put_u64(o, s.offset); -+ } -+ None => put_u8(o, 0), -+ } -+ put_u8(o, u8::from(d.vblank)); -+ put_u8(o, u8::from(d.asleep)); -+ put_u64(o, d.refreshes); -+ match d.told { -+ Some(m) => { -+ put_u8(o, 1); -+ put_u32(o, m.width); put_u32(o, m.height); -+ put_u32(o, m.refresh_mhz); put_u32(o, m.scale_120ths); -+ } -+ None => put_u8(o, 0), -+ } -+ put_u8(o, u8::from(d.changed)); -+ match &d.cursor_image { -+ Some(c) => { -+ put_u8(o, 1); -+ put_u32(o, c.width); put_u32(o, c.height); -+ put_u32(o, c.hot_spot.0); put_u32(o, c.hot_spot.1); -+ put_bytes(o, &c.rgba); -+ } -+ None => put_u8(o, 0), -+ } -+ } -+ -+ put_u32(o, self.region_blocks.len() as u32); -+ for b in &self.region_blocks { -+ put_u64(o, b.offset); put_u64(o, b.size); -+ put_u8(o, u8::from(b.shared)); -+ put_u32(o, b.holders.len() as u32); -+ for &h in &b.holders { put_u32(o, h); } -+ } -+ -+ put_u32(o, self.queues.len() as u32); -+ for q in &self.queues { -+ put_bytes(o, &q.create_bytes); -+ put_u32(o, q.flags); -+ put_u64(o, q.taken_seqno); -+ put_u64(o, q.taken_buffer_seqno); -+ put_u64(o, q.submit_count); -+ put_u8(o, u8::from(q.submit_broken)); -+ put_u64(o, q.complete_count); -+ } -+ } -+ -+ /// Decodes a device snapshot from `i`. -+ pub fn decode(i: &mut &[u8]) -> Option { -+ if get_u32(i)? != 1 { return None; } -+ let status = get_u32(i)?; -+ let driver_features = get_u64(i)?; -+ let control_done = get_u64(i)?; -+ let control_submit_count = get_u64(i)?; -+ let control_submit_broken = get_u8(i)? != 0; -+ let control_completion_count = get_u64(i)?; -+ let vt_ring_count = get_u64(i)?; -+ -+ let pages = read_vec(i, 4, get_u32)?; -+ let displays = read_vec(i, 14, |i| { -+ let scanout = if get_u8(i)? != 0 { -+ Some(Scanout { -+ width: get_u32(i)?, height: get_u32(i)?, -+ stride: get_u32(i)?, offset: get_u64(i)?, -+ }) -+ } else { None }; -+ let vblank = get_u8(i)? != 0; -+ let asleep = get_u8(i)? != 0; -+ let refreshes = get_u64(i)?; -+ let told = if get_u8(i)? != 0 { -+ Some(Mode { -+ width: get_u32(i)?, height: get_u32(i)?, -+ refresh_mhz: get_u32(i)?, scale_120ths: get_u32(i)?, -+ }) -+ } else { None }; -+ let changed = get_u8(i)? != 0; -+ let cursor_image = if get_u8(i)? != 0 { -+ Some(CursorImage { -+ width: get_u32(i)?, height: get_u32(i)?, -+ hot_spot: (get_u32(i)?, get_u32(i)?), -+ rgba: get_bytes(i)?, -+ }) -+ } else { None }; -+ Some(DisplaySnapshot { scanout, vblank, asleep, refreshes, told, changed, cursor_image }) -+ })?; -+ let region_blocks = read_vec(i, 21, |i| { -+ let offset = get_u64(i)?; -+ let size = get_u64(i)?; -+ let shared = get_u8(i)? != 0; -+ let holders = read_vec(i, 4, get_u32)?; -+ Some(RegionBlockSnapshot { offset, size, holders, shared }) -+ })?; -+ let queues = read_vec(i, 45, |i| { -+ Some(QueueSnapshot { -+ create_bytes: get_bytes(i)?, -+ flags: get_u32(i)?, -+ taken_seqno: get_u64(i)?, -+ taken_buffer_seqno: get_u64(i)?, -+ submit_count: get_u64(i)?, -+ submit_broken: get_u8(i)? != 0, -+ complete_count: get_u64(i)?, -+ }) -+ })?; -+ -+ Some(DeviceSnapshot { -+ status, driver_features, control_done, -+ control_submit_count, control_submit_broken, -+ control_completion_count, vt_ring_count, -+ pages, displays, region_blocks, queues, -+ }) -+ } -+} -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ -+ #[test] -+ fn decode_rejects_oversized_counts_without_allocating() { -+ // Minimal valid header (version=1 + fixed scalar fields = 49 bytes). -+ let mut base = Vec::new(); -+ let empty = DeviceSnapshot { -+ status: 1, -+ driver_features: 2, -+ control_done: 3, -+ control_submit_count: 4, -+ control_submit_broken: false, -+ control_completion_count: 5, -+ vt_ring_count: 6, -+ pages: vec![], -+ displays: vec![], -+ region_blocks: vec![], -+ queues: vec![], -+ }; -+ empty.encode(&mut base); -+ let mut s = base.as_slice(); -+ assert_eq!(DeviceSnapshot::decode(&mut s), Some(empty)); -+ assert!(s.is_empty()); -+ -+ // Overwrite each of the 4 top-level collection counts with u32::MAX. -+ // Header length before pages count: 4 + 4 + 8 + 8 + 8 + 1 + 8 + 8 = 49. -+ for offset in [49usize, 53, 57, 61] { -+ let mut bad = base.clone(); -+ bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes()); -+ let mut sl = bad.as_slice(); -+ assert!(DeviceSnapshot::decode(&mut sl).is_none(), "offset {offset} must fail"); -+ } -+ } -+} -diff --git a/crates/reims-vgpu-vulkan/src/core/platform/device.rs b/crates/reims-vgpu-vulkan/src/core/platform/device.rs -index 50b24be4d3d3cfb3a3305694ef8e948d7c41b72d..e737f7260b9407aa886eec0370af670b1519c806 100644 ---- a/crates/reims-vgpu-vulkan/src/core/platform/device.rs -+++ b/crates/reims-vgpu-vulkan/src/core/platform/device.rs -@@ -564,4 +564,44 @@ pub trait GpuDevice: Handle { - &self, - desc: &FullComputePipelineDesc<'_, P>, - ) -> Result, 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>, &'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>, &'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 -+ } - } -diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/device.rs b/crates/reims-vgpu-vulkan/src/rt_platform/device.rs -index 2a87bbc65e5c2093e3d1c06b1abbd297abbcc7da..4df542484ffe702a5837a5dd7f765bbb50e07531 100644 ---- a/crates/reims-vgpu-vulkan/src/rt_platform/device.rs -+++ b/crates/reims-vgpu-vulkan/src/rt_platform/device.rs -@@ -2625,6 +2625,327 @@ impl GpuDevice for RtObj { - 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: &::Event) -> u64 { -+ event.signaled_value() -+ } -+ -+ fn event_restore_signaled_value( -+ &self, -+ event: &::Event, -+ value: u64, -+ ) -> bool { -+ if value > 0 { -+ event.restore_signaled_value(value).is_ok() -+ } else { -+ true -+ } -+ } -+ -+ fn read_standalone_buffer( -+ &self, -+ buffer: &::Buffer, -+ ) -> Result>, &'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, &'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: &::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: &::Texture, -+ ) -> Result>, &'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, &'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: &::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, 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 -diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs -index 8cac38c823e4bbd3d76eafa0ac3bc2f3461bd5f4..a4715175ae46687face600f1ed683c4c628570c0 100644 ---- a/crates/reims-vgpu/src/graphics.rs -+++ b/crates/reims-vgpu/src/graphics.rs -@@ -93,7 +93,8 @@ use reims_vgpu_graphics::wire::{ - RGFX_FEATURE_TEXTURE_DID_MODIFY_DATA, RGFX_FEATURE_UNCHANGING_PAGES, - RGFX_FEATURE_UNSHARED_QUEUES, RGFX_FEATURE_UPLOADS_WRITTEN, RGFX_FEATURE_VT_MESSAGES, - RGFX_RESOURCE_ID_CHUNK, RGFX_RESOURCE_ID_CHUNKS, RGFX_STATUS_INVALID_ARGUMENT, -- RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED, RGFX_VIDEO_CAPS_CODECS, -+ RGFX_STATUS_CACHE, 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, -@@ -190,6 +191,7 @@ mod present; - mod read; - mod rt_window; - mod sink; -+mod snapshot; - mod slow_answers; - mod summary; - mod trip; -@@ -1035,6 +1037,7 @@ impl GraphicsDevice

{ - 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> = (0..count) - .map(|display| { -@@ -1350,6 +1353,242 @@ impl GraphicsDevice

{ - (self.cursors.get(display as usize)).map_or((0, 0), |cursor| cursor.position()) - }) - } -+ -+ fn quiesce_device(&self) -> Option>> { -+ self.device.quiesce(); -+ if let Some(pool) = &self.pool { -+ pool.quiesce(); -+ } -+ let control = self.ending.upgrade()?; -+ control.pool.wait_idle(); -+ control.icb_worker.flush(); -+ let decoder = control.decoder(); -+ decoder.flush_workers(); -+ decoder.flush_all_surface_caches(&control.device); -+ control.device.wait_idle(); -+ Some(control) -+ } -+ -+ /// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings, -+ /// drains pending compiles and workers, flushes dirty device-cached IOSurfaces back to Guest -+ /// RAM, and waits for GPU idle. -+ pub fn quiesce(&self) -> Result<(), Error> { -+ entry::run(|_| { -+ let _ = self.quiesce_device(); -+ Ok(()) -+ }) -+ } -+ -+ /// Resumes VBLANK and ring service threads after a snapshot completes or aborts. -+ pub fn unquiesce(&self) { -+ entry::run(|_| { -+ self.device.unquiesce(); -+ }); -+ } -+ -+ /// Serializes the full graphics device state (device rings/displays/queues, Shared Pool, -+ /// Private Blocks + VRAM, live Metal/Vulkan objects, timeline events, and standalone GPU -+ /// buffers/textures) into a portable byte blob for suspend-to-disk. -+ pub fn snapshot_save(&self) -> Result, Error> { -+ entry::run(|_| { -+ let t0 = std::time::Instant::now(); -+ let control = self.quiesce_device().ok_or(Error::HostResources)?; -+ let decoder = control.decoder(); -+ -+ let mut device_snapshot = Vec::new(); -+ self.device.export_snapshot().encode(&mut device_snapshot); -+ let shared_pool = self.pool.as_ref().map(|p| p.export_snapshot()).transpose()?; -+ let private_blocks = control.private_blocks.export_snapshot()?; -+ let id_chunks = decoder.export_id_chunks(); -+ let (live_records, surface_pages, standalone_tex_set, presented_surfaces) = -+ control.live_log.export(); -+ -+ let mut known_ranges: Vec<(u64, u64)> = Vec::new(); -+ if let Some(sp) = &shared_pool { -+ for piece in &sp.pieces { -+ if piece.gpu_address != 0 { -+ known_ranges.push((piece.gpu_address, piece.len)); -+ } -+ } -+ } -+ for pb in &private_blocks.blocks { -+ if pb.gpu_address != 0 { -+ known_ranges.push((pb.gpu_address, pb.len)); -+ } -+ } -+ let live_values = decoder -+ .export_live_values(&control.device, &known_ranges, &standalone_tex_set) -+ .map_err(|_| Error::HostResources)?; -+ let mut standalone_textures: Vec = standalone_tex_set.into_iter().collect(); -+ standalone_textures.sort_unstable(); -+ -+ let snap = snapshot::VgpuSnapshot { -+ device_snapshot, -+ shared_pool, -+ private_blocks, -+ id_chunks, -+ surface_pages, -+ live_records, -+ standalone_textures, -+ presented_surfaces, -+ live_values, -+ }; -+ let t_exp = t0.elapsed(); -+ let n_tex = snap.live_values.textures.len(); -+ let tex_bytes: usize = snap.live_values.textures.iter().map(|(_, b)| b.len()).sum(); -+ let n_caches = snap.live_values.surface_caches.len(); -+ let cache_bytes: usize = snap -+ .live_values -+ .surface_caches -+ .iter() -+ .map(|(_, b)| b.len()) -+ .sum(); -+ let encoded = snap.encode(); -+ log::info!( -+ target: "reims_vgpu::graphics", -+ "snapshot_save done in {:.2}s (export={:.2}s): total={} B, textures={} ({:.1} MiB), unattached_caches={} ({:.1} MiB)", -+ t0.elapsed().as_secs_f64(), -+ t_exp.as_secs_f64(), -+ encoded.len(), -+ n_tex, -+ tex_bytes as f64 / (1024.0 * 1024.0), -+ n_caches, -+ cache_bytes as f64 / (1024.0 * 1024.0), -+ ); -+ Ok(encoded) -+ }) -+ } -+ -+ /// Restores the full graphics device state from a snapshot produced by [`Self::snapshot_save`] -+ /// in a fresh host process. -+ pub fn snapshot_load(&self, data: &[u8]) -> Result<(), Error> { -+ entry::run(|_| { -+ let snap = snapshot::VgpuSnapshot::decode(data).ok_or(Error::InvalidArgument)?; -+ let mut dev_slice: &[u8] = &snap.device_snapshot; -+ let dev_snap = reims_vgpu_graphics::snapshot::DeviceSnapshot::decode(&mut dev_slice) -+ .ok_or(Error::InvalidArgument)?; -+ if !dev_slice.is_empty() { -+ return Err(Error::InvalidArgument); -+ } -+ let control = self.ending.upgrade().ok_or(Error::HostResources)?; -+ -+ // Keep device rings and VBLANK paused until full object table replay finishes. -+ // Any error below returns without unquiescing so partial restores never report success. -+ self.device.quiesce(); -+ -+ match (&self.pool, &snap.shared_pool) { -+ (Some(pool), Some(ps)) => pool.import_snapshot(ps)?, -+ (None, Some(ps)) if !ps.pieces.is_empty() => return Err(Error::HostResources), -+ _ => {} -+ } -+ control.private_blocks.import_snapshot(&snap.private_blocks)?; -+ -+ self.device.import_snapshot(&dev_snap).map_err(|_| Error::InvalidArgument)?; -+ control -+ .decoder() -+ .set_managed_at_copy(dev_snap.driver_features & RGFX_FEATURE_MANAGED_AT_COPY != 0); -+ -+ { -+ let decoder = control.decoder(); -+ decoder.import_id_chunks(&snap.id_chunks); -+ for sp in &snap.surface_pages { -+ decoder -+ .replay_surface_pages( -+ &control.device, -+ &sp.pages, -+ &sp.runs, -+ sp.flags, -+ sp.layout, -+ ) -+ .map_err(|_| Error::HostResources)?; -+ } -+ } -+ -+ let mut records = snap.live_records; -+ records.sort_by_key(|r| r.seq); -+ for rec in &records { -+ control.replay_record(rec)?; -+ } -+ -+ let n_surface_pages = snap.surface_pages.len(); -+ let n_records = records.len(); -+ let standalone_set: std::collections::HashSet = -+ 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 Drop for GraphicsDevice

{ -@@ -1543,6 +1782,7 @@ struct GraphicsControl { - /// 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 -@@ -2196,6 +2436,7 @@ impl GraphicsControl

{ - 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() -@@ -2286,6 +2527,7 @@ impl GraphicsControl

{ - } - // 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 { -@@ -2348,6 +2590,7 @@ impl GraphicsControl

{ - 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); -@@ -2648,6 +2891,10 @@ impl GraphicsControl

{ - let _carried = me.reset_gate.read_recursive(); - let status = (me.decoder()) - .carry_out_surface_pages(&me.device, &pages, &runs, flags, layout, &settle); -+ if matches!(status, Some(RGFX_STATUS_OK | RGFX_STATUS_CACHE)) { -+ me.live_log -+ .record_surface_pages(pages, runs.clone(), flags, layout); -+ } - // Where the guest took IMPORT_ADDRESSES_LATER, answered now, with no address, - // before the view is made and given one below. - let answer = match status { -@@ -2746,6 +2993,197 @@ impl GraphicsControl

{ - /// ([`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 = 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::

(&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::

(&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, - poster: &CompletionPoster, -@@ -2753,6 +3191,7 @@ impl GraphicsControl

{ - claim: Option<&mut QueueClaim<'_>>, - ) { - let message: &[u8] = &bytes; -+ self.live_log.record_stage3(sender_context(poster, message), message); - let r#type = RgfxMsgHeader::read_from_prefix(message).map_or(0, |(h, _)| h.r#type); - // A queue's command buffer taken from its ring: the presents' late-show lines keep when - // the host first saw it (`present`). -@@ -3632,6 +4071,10 @@ impl GraphicsControl

{ - "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()); - } -@@ -4141,7 +4584,15 @@ impl GraphicsControl

{ - .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); -@@ -4214,6 +4665,7 @@ impl GraphicsControl

{ - 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); -@@ -4245,6 +4697,7 @@ impl GraphicsControl

{ - 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); -@@ -4788,6 +5241,7 @@ fn vt_decoders(caps: &RgfxVideoCaps) -> Vec { - /// 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(f: impl FnOnce() -> T) -> T { - let Some(_step) = reims_vgpu_vulkan::exit_gate::step() else { - reims_vgpu_vulkan::exit_gate::stay() -diff --git a/crates/reims-vgpu/src/graphics/compile.rs b/crates/reims-vgpu/src/graphics/compile.rs -index 1c5bb492f943fe8ba303b6ac5c0af130efb41243..8813dc8627b78e865730c9d084765c6a83006d42 100644 ---- a/crates/reims-vgpu/src/graphics/compile.rs -+++ b/crates/reims-vgpu/src/graphics/compile.rs -@@ -582,6 +582,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::() > 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; -@@ -672,10 +683,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)); - } - -diff --git a/crates/reims-vgpu/src/graphics/decode/library.rs b/crates/reims-vgpu/src/graphics/decode/library.rs -index 8c626c80aefb48b6f36e828a2d911021213a4bc4..f426f5365fdd5f996cff52d90b168d94c6719139 100644 ---- a/crates/reims-vgpu/src/graphics/decode/library.rs -+++ b/crates/reims-vgpu/src/graphics/decode/library.rs -@@ -402,9 +402,9 @@ pub(crate) struct LibraryJob { - pub(crate) obj_id: u64, - /// The create's seqno, which its `COMPLETE` carries. - pub(crate) seqno: u64, -- bytes: Vec, -+ pub(crate) bytes: Vec, - /// The key the guest sent with the bytes. -- guest_key: Option, -+ pub(crate) guest_key: Option, - slot: Arc>, - /// The device's resets when it was prepared. - resets: u64, -@@ -697,6 +697,29 @@ impl GraphicsDecoder

{ - }) - } - -+ /// Prepares a [`LibraryJob`] directly from snapshotted library bytes for silent replay. -+ pub(crate) fn prepare_library_bytes( -+ &self, -+ obj_id: u64, -+ bytes: Vec, -+ guest_key: Option, -+ ) -> LibraryJob

{ -+ 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 -diff --git a/crates/reims-vgpu/src/graphics/decode/mod.rs b/crates/reims-vgpu/src/graphics/decode/mod.rs -index b39feceac6e4360b1a678c40d5468e5a893fc44a..8929bacedd1a1dc3f248c7a11c3816e8044e973e 100644 ---- a/crates/reims-vgpu/src/graphics/decode/mod.rs -+++ b/crates/reims-vgpu/src/graphics/decode/mod.rs -@@ -220,6 +220,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; -@@ -264,6 +265,7 @@ pub(crate) use library::verified_key as test_key; - #[cfg(test)] - pub(crate) use library::whole_key as test_whole_key; - use library::{Libraries, LibraryRef}; -+pub(crate) use library::LibraryKey; - pub(crate) use library::{LibraryJob, LibraryStart, MadeLibrary, complete, make_library}; - use managed::{STORAGE_MODE_MANAGED, storage_mode}; - pub(crate) use pipeline_key::PipelineKey; -@@ -608,6 +610,16 @@ fn new_sampler( - /// 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)>, -+ pub(crate) textures: Vec<(u64, Vec)>, -+ pub(crate) surface_caches: Vec<(u64, Vec)>, -+} -+ - enum ObjHandle { - Event(P::Event), - Fence(P::Fence), -@@ -3538,6 +3550,285 @@ impl GraphicsDecoder

{ - } - - /// 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 { -+ 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, -+ ) -> 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, -+ ) -> Result { -+ let mut values = LiveValues::default(); -+ let mut first_err: Option<&'static str> = None; -+ let mut contexts: Vec>> = -+ 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>> = -@@ -6539,6 +6830,11 @@ impl CompiledPipeline

{ - } - } - -+ /// 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

, reflection: RgfxPipelineReflection) -> Self { - CompiledPipeline { -diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs -index 27e49048da96c560f0cdafe794a526fec2186f08..e57b0ce603eb3b4ad28803102c92a09793ba252f 100644 ---- a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs -+++ b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs -@@ -3589,6 +3589,18 @@ impl SurfaceCaches

{ - .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) { -+ 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 -@@ -8337,6 +8349,171 @@ impl Caches

{ - /// `trace`: `done` once the pages hold the cache, or `failed` where the platform raised at - /// the copy. - #[allow(clippy::too_many_arguments)] // the download's, and its trace -+ /// Returns all currently tracked surface cache block offsets for pre-snapshot flushing. -+ pub(crate) fn attached_live_blocks(&self) -> Vec { -+ 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)>, &'static str> { -+ let need_mem: Vec = { -+ let state = self.lock(); -+ state -+ .by_block -+ .values() -+ .filter(|c| { -+ c.pages.is_none() -+ && !c.device.memory_made() -+ && c.shapes.iter().any(|s| s.dirty) -+ }) -+ .map(|c| c.device.clone_ref()) -+ .collect() -+ }; -+ self.make_memory(need_mem, MemoryFor::WriteBack); -+ -+ let mut flushed_any = false; -+ { -+ let mut state = self.lock(); -+ let dirty_blocks: Vec = state -+ .by_block -+ .iter() -+ .filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty)) -+ .map(|(&b, _)| b) -+ .collect(); -+ if !dirty_blocks.is_empty() { -+ if !state -+ .make_transfer(device) -+ .map_err(|_| "snapshot_save: surface cache transfer init failed")? -+ { -+ return Err("snapshot_save: surface cache transfer queue unavailable"); -+ } -+ for block in dirty_blocks { -+ let cb_opt = { -+ let transfer = state -+ .transfer -+ .as_mut() -+ .ok_or("snapshot_save: surface cache transfer missing")?; -+ transfer -+ .queue -+ .command_buffer(ON) -+ .map_err(|_| "snapshot_save: surface cache command buffer failed")? -+ }; -+ let Some(cb) = cb_opt else { -+ return Err("snapshot_save: surface cache command buffer unavailable"); -+ }; -+ let Some(cache) = state.by_block.get_mut(&block) else { -+ continue; -+ }; -+ if !cache.copy_through(MemoryFor::WriteBack) { -+ return Err("snapshot_save: deferred surface cache allocation failed"); -+ } -+ let back = shapes::write_back::

(&cb, &cache.device, &cache.shapes, |s| { -+ s.dirty -+ }) -+ .map_err(|_| "snapshot_save: surface cache shape write_back failed")?; -+ cache.wrote_shapes(&back); -+ state.owed_commits.push(cb); -+ flushed_any = true; -+ } -+ } -+ } -+ if flushed_any { -+ device.wait_idle(); -+ } -+ -+ let mut to_read: Vec<(u64, P::Buffer)> = { -+ let state = self.lock(); -+ state -+ .by_block -+ .iter() -+ .filter(|(_, c)| c.pages.is_none() && c.device.memory_made()) -+ .map(|(&block, c)| (block, c.device.clone_ref())) -+ .collect() -+ }; -+ to_read.sort_by_key(|(block, _)| *block); -+ -+ let mut out = Vec::with_capacity(to_read.len()); -+ for (block, buf) in to_read { -+ match device.read_standalone_buffer(&buf)? { -+ Some(bytes) => out.push((block, bytes)), -+ None => return Err("snapshot_save: unattached surface cache buffer unreadable"), -+ } -+ } -+ Ok(out) -+ } -+ -+ /// Restores GPU buffer contents for deferred unattached IOSurface device caches. -+ pub(crate) fn import_unattached( -+ &self, -+ device: &P::Device, -+ entries: &[(u64, Vec)], -+ ) -> 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 = targets -+ .iter() -+ .filter(|(_, b)| !b.memory_made()) -+ .map(|(_, b)| b.clone_ref()) -+ .collect(); -+ self.make_memory(need_mem, MemoryFor::Fill); -+ -+ for ((block, buf), (_, bytes)) in targets.iter().zip(entries.iter()) { -+ if !buf.memory_made() { -+ log::error!( -+ target: "reims_vgpu::graphics", -+ "snapshot_load: failed to allocate memory for unattached surface cache {block:#x}" -+ ); -+ return Err("snapshot_load: surface cache memory allocation failed"); -+ } -+ if !device.write_standalone_buffer(buf, bytes) { -+ log::error!( -+ target: "reims_vgpu::graphics", -+ "snapshot_load: failed to upload unattached surface cache {block:#x} ({} bytes)", -+ bytes.len() -+ ); -+ return Err("snapshot_load: surface cache upload failed"); -+ } -+ } -+ -+ let mut state = self.lock(); -+ for (block, _) in entries { -+ if let Some(cache) = state.by_block.get_mut(block) { -+ let _ = cache.copy_through(MemoryFor::Fill); -+ cache.written = true; -+ cache.first_fill = None; -+ cache.zeros = false; -+ cache.lacks = false; -+ cache.changed = Changed::All; -+ cache.shapes.mark_owed_all(); -+ } -+ } -+ Ok(()) -+ } -+ - pub(crate) fn download( - &self, - device: &P::Device, -diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs -index eef3c5ef0e1297204a7344bc10eea333182b5ac1..f98695af9b83e699b9f7e87219baf9eb2246b3a6 100644 ---- a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs -+++ b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs -@@ -914,6 +914,23 @@ impl ShapeTable { - shape.map(|s| s.dirty = true).is_some() - } - -+ /// Marks a shape whose pixels were directly uploaded during snapshot restore as valid & dirty. -+ pub(crate) fn mark_restored(&mut self, id: u64) { -+ if let Some(s) = self.shapes.iter_mut().find(|s| s.id() == id) { -+ s.owed = false; -+ s.dirty = true; -+ s.cleared = false; -+ } -+ } -+ -+ pub(crate) fn mark_owed_all(&mut self) { -+ for s in &mut self.shapes { -+ s.owed = true; -+ s.cleared = false; -+ s.clean(); -+ } -+ } -+ - /// A video command buffer wrote the buffer, its decodes' pictures, not the images: every - /// shape owes a fill from it, its own write before the buffer's lost (the decode writes its - /// planes whole, and a write it does not cover was copied into the buffer before it ran); -diff --git a/crates/reims-vgpu/src/graphics/decode/surface_order.rs b/crates/reims-vgpu/src/graphics/decode/surface_order.rs -index ad08151f5256e959c46bf08f79cff98b0140b70e..c315b96ed11d9116e1c54e118f33d417a419795b 100644 ---- a/crates/reims-vgpu/src/graphics/decode/surface_order.rs -+++ b/crates/reims-vgpu/src/graphics/decode/surface_order.rs -@@ -292,6 +292,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. -@@ -862,6 +873,19 @@ impl SurfaceOrder

{ - q.buffers = Some(buffers); - } - -+ /// Restores a queue's commit/surface-order watermarks and timeline event value after snapshot load. -+ pub(crate) fn restore_queue_watermark(&mut self, queue: u64, seqno: u64) { -+ if seqno == 0 { -+ return; -+ } -+ if let Some(q) = self.queues.get(&queue) { -+ q.marks.restore_watermark(seqno); -+ if let Some(ev) = &q.event { -+ let _ = ev.set_signaled_value(seqno); -+ } -+ } -+ } -+ - /// What a removal from context `context`'s table waits for before its entry is let go of - /// ([`super::tables`], "After the buffers posted before it"): each queue of the context the - /// decoder made and that has not ended, whose ring published a command buffer its commit mark -diff --git a/crates/reims-vgpu/src/graphics/present.rs b/crates/reims-vgpu/src/graphics/present.rs -index a1fc887bd509b6c90d82b7a134be162bfc7a6ccc..20e3f7496d65d713e518ebe0d1e3e43748770766 100644 ---- a/crates/reims-vgpu/src/graphics/present.rs -+++ b/crates/reims-vgpu/src/graphics/present.rs -@@ -272,6 +272,16 @@ impl PresentQueue

{ - 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 -diff --git a/crates/reims-vgpu/src/graphics/snapshot.rs b/crates/reims-vgpu/src/graphics/snapshot.rs -new file mode 100644 -index 0000000000000000000000000000000000000000..70a3cec742ef2a3c75d074749593fe6f58f37067 ---- /dev/null -+++ b/crates/reims-vgpu/src/graphics/snapshot.rs -@@ -0,0 +1,1151 @@ -+//! Full GPU device snapshot (`LiveLog` + `RVGSNAP1` binary codec) for suspend-to-disk & resume. -+ -+use std::collections::{BTreeMap, HashMap, HashSet}; -+ -+use reims_vgpu_graphics::wire::{ -+ RGFX_CMD_BUFFER_AT_OFFSET, RGFX_CMD_BUFFER_CREATE, RGFX_CMD_BUFFER_ESCAPED, -+ RGFX_CMD_BUFFER_MANAGED_AT_OFFSET, RGFX_CMD_BUFFER_OVER_HOST_MEMORY, -+ RGFX_CMD_BUFFER_OVER_PAGES, RGFX_CMD_BUFFER_OVER_SURFACE_PAGES, -+ RGFX_CMD_COMPUTE_PIPELINE_CREATE, RGFX_CMD_DEPTH_STENCIL_CREATE, -+ RGFX_CMD_DYNAMIC_LIBRARY_CREATE, RGFX_CMD_EVENT_CREATE, RGFX_CMD_FENCE_CREATE, -+ RGFX_CMD_FUNCTION_HANDLE_CREATE, RGFX_CMD_FUNCTION_TABLE_CREATE, -+ RGFX_CMD_FUNCTION_TABLE_SET, RGFX_CMD_HEAP_CREATE, RGFX_CMD_HEAP_OVER_HOST_MEMORY, -+ RGFX_CMD_HEAP_OVER_PAGES, RGFX_CMD_HEAP_OVER_POOL, RGFX_CMD_ICB_CREATE, -+ RGFX_CMD_ICB_SLOTS, RGFX_CMD_ICB_SLOTS_IN_PAGES, RGFX_CMD_ICB_WRITE, -+ RGFX_CMD_LIBRARY_LOOKUP, RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER, RGFX_CMD_MANAGED_BUFFER_CREATE, -+ RGFX_CMD_MANAGED_TEXTURE_CREATE, RGFX_CMD_MESH_RENDER_PIPELINE_CREATE, -+ RGFX_CMD_OBJECT_DESTROY, RGFX_CMD_QUEUE_CREATE, RGFX_CMD_RATE_MAP_CREATE, -+ RGFX_CMD_RATE_MAP_RESET, RGFX_CMD_RENDER_PIPELINE_CREATE, RGFX_CMD_SAMPLER_CREATE, -+ RGFX_CMD_SHARED_EVENT_CREATE, RGFX_CMD_SHARED_EVENT_IMPORT, RGFX_CMD_SHARED_EVENT_NAME, -+ RGFX_CMD_SHARED_EVENT_UNNAME, RGFX_CMD_TEXTURE_CREATE, RGFX_CMD_TEXTURE_FROM_BUFFER, -+ RGFX_CMD_TEXTURE_FROM_IOSURFACE, RGFX_CMD_TEXTURE_VIEW, RGFX_SURFACE_PAGES_ATTACH, -+ RgfxComputePipelineCreate, RgfxDynamicLibraryCreate, RgfxFunctionHandleCreate, -+ RgfxFunctionTableSet, RgfxLibraryLookup, RgfxLinearTextureFromBuffer, RgfxLinkedFunction, -+ RgfxMeshRenderPipelineCreate, RgfxMsgHeader, RgfxObjectDestroy, RgfxPageRun, -+ RgfxPipelineLibrary, RgfxRenderPipelineCreate, RgfxSharedEventImport, RgfxSharedEventName, -+ RgfxSharedEventUnname, RgfxSurfacePages, RgfxSurfacePagesLayout, RgfxTextureCreate, -+ RgfxTextureFromBuffer, RgfxTextureView, -+}; -+use reims_vgpu_vulkan::core::sync::Mutex; -+use zerocopy::{FromBytes, IntoBytes}; -+ -+use crate::pool::{ -+ BlockCapture, MemoryClass, PoolCarveSnapshot, PoolPieceSnapshot, PoolSnapshot, -+ PrivateBlockSnapshot, PrivateBlocksSnapshot, -+}; -+ -+use super::decode::{LibraryKey, LiveValues}; -+ -+pub(crate) const SNAPSHOT_MAGIC: &[u8; 8] = b"RVGSNAP1"; -+pub(crate) const SNAPSHOT_VERSION: u32 = 1; -+ -+/// Synthetic tag stored in [`LogRecord::msg_type`] for assembled libraries (covers both inline -+/// `LIBRARY_CREATE` and chunked `LIBRARY_FROM_REGION`). -+pub(crate) const LOG_TAG_ASSEMBLED_LIBRARY: u32 = 0xFFFF_0001; -+ -+/// A recorded live object creation or persistent state mutation. -+#[derive(Clone, Debug)] -+pub(crate) struct LogRecord { -+ pub(crate) seq: u64, -+ pub(crate) context: u32, -+ pub(crate) obj_id: u64, -+ pub(crate) msg_type: u32, -+ /// Raw wire message bytes (or for `LOG_TAG_ASSEMBLED_LIBRARY`, optional 32-byte key if present). -+ pub(crate) bytes: Vec, -+ /// Assembled library bytes (for `LOG_TAG_ASSEMBLED_LIBRARY`), empty otherwise. -+ pub(crate) inline_bytes: Vec, -+} -+ -+/// Recorded `SURFACE_PAGES` registration for an active shared guest-RAM block. -+#[derive(Clone, Debug)] -+pub(crate) struct SurfacePagesRecord { -+ pub(crate) pages: RgfxSurfacePages, -+ pub(crate) runs: Vec, -+ pub(crate) flags: u32, -+ pub(crate) layout: Option, -+} -+ -+#[derive(Default)] -+struct LiveLogState { -+ next_seq: u64, -+ records: Vec, -+ surface_pages: BTreeMap>, -+ standalone_textures: HashSet, -+ presented_surfaces: Vec, -+ library_bytes_by_key: HashMap>, -+} -+ -+/// Records live guest GPU object creations & persistent mutations so a fresh host process can -+/// reconstruct the exact Metal/Vulkan object table without re-executing past draws or dispatches. -+pub(crate) struct LiveLog { -+ state: Mutex, -+} -+ -+impl LiveLog { -+ pub(crate) fn new(displays: usize) -> Self { -+ Self { -+ state: Mutex::new(LiveLogState { -+ presented_surfaces: vec![0; displays], -+ ..LiveLogState::default() -+ }), -+ } -+ } -+ -+ pub(crate) fn record_stage3(&self, context: u32, message: &[u8]) { -+ let Ok((hdr, _)) = RgfxMsgHeader::read_from_prefix(message) else { -+ return; -+ }; -+ match hdr.r#type { -+ RGFX_CMD_OBJECT_DESTROY => { -+ if let Ok((m, _)) = RgfxObjectDestroy::read_from_prefix(message) { -+ let mut st = self.state.lock(); -+ st.standalone_textures.remove(&m.obj_id); -+ let prev_destroy = st -+ .records -+ .iter() -+ .rposition(|r| { -+ r.obj_id == m.obj_id && r.msg_type == RGFX_CMD_OBJECT_DESTROY -+ }); -+ let search_from = prev_destroy.map_or(0, |i| i + 1); -+ let Some(inc_rel) = st.records[search_from..] -+ .iter() -+ .position(|r| r.obj_id == m.obj_id) -+ else { -+ return; -+ }; -+ let inc_start = search_from + inc_rel; -+ let inc_seq = st.records[inc_start].seq; -+ let mut named_events: Vec = Vec::new(); -+ for r in &st.records[inc_start..] { -+ if r.obj_id == m.obj_id && r.msg_type == RGFX_CMD_SHARED_EVENT_NAME { -+ if let Ok((n, _)) = RgfxSharedEventName::read_from_prefix(&r.bytes) { -+ named_events.push(n.name); -+ } -+ } -+ } -+ let referenced = st.records[inc_start + 1..].iter().any(|r| { -+ if r.obj_id == m.obj_id { -+ return false; -+ } -+ if record_parent_ids(r).contains(&m.obj_id) { -+ return true; -+ } -+ if !named_events.is_empty() && r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT { -+ if let Ok((imp, _)) = RgfxSharedEventImport::read_from_prefix(&r.bytes) -+ { -+ return named_events.contains(&imp.name); -+ } -+ } -+ false -+ }); -+ if referenced { -+ let seq = st.next_seq; -+ st.next_seq = st.next_seq.wrapping_add(1); -+ st.records.push(LogRecord { -+ seq, -+ context, -+ obj_id: m.obj_id, -+ msg_type: RGFX_CMD_OBJECT_DESTROY, -+ bytes: message.to_vec(), -+ inline_bytes: Vec::new(), -+ }); -+ } else { -+ st.records -+ .retain(|r| !(r.obj_id == m.obj_id && r.seq >= inc_seq)); -+ } -+ } -+ } -+ RGFX_CMD_SHARED_EVENT_UNNAME => { -+ if let Ok((m, _)) = RgfxSharedEventUnname::read_from_prefix(message) { -+ let mut st = self.state.lock(); -+ let name_pos = st.records.iter().rposition(|r| { -+ r.msg_type == RGFX_CMD_SHARED_EVENT_NAME -+ && RgfxSharedEventName::read_from_prefix(&r.bytes) -+ .is_ok_and(|(n, _)| n.name == m.name) -+ }); -+ let Some(pos) = name_pos else { -+ return; -+ }; -+ let imported = st.records[pos + 1..].iter().any(|r| { -+ r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT -+ && RgfxSharedEventImport::read_from_prefix(&r.bytes) -+ .is_ok_and(|(imp, _)| imp.name == m.name) -+ }); -+ if imported { -+ let seq = st.next_seq; -+ st.next_seq = st.next_seq.wrapping_add(1); -+ st.records.push(LogRecord { -+ seq, -+ context, -+ obj_id: 0, -+ msg_type: RGFX_CMD_SHARED_EVENT_UNNAME, -+ bytes: message.to_vec(), -+ inline_bytes: Vec::new(), -+ }); -+ } else { -+ st.records.remove(pos); -+ } -+ } -+ } -+ ty if is_persistent_stage3(ty) => { -+ let obj_id = message -+ .get(16..24) -+ .and_then(|b| b.try_into().ok()) -+ .map(u64::from_le_bytes) -+ .unwrap_or(0); -+ let mut st = self.state.lock(); -+ if matches!( -+ ty, -+ RGFX_CMD_TEXTURE_CREATE -+ | RGFX_CMD_MANAGED_TEXTURE_CREATE -+ | RGFX_CMD_TEXTURE_FROM_BUFFER -+ | RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER -+ ) && obj_id != 0 -+ { -+ st.standalone_textures.insert(obj_id); -+ } -+ let seq = st.next_seq; -+ st.next_seq = st.next_seq.wrapping_add(1); -+ st.records.push(LogRecord { -+ seq, -+ context, -+ obj_id, -+ msg_type: ty, -+ bytes: message.to_vec(), -+ inline_bytes: Vec::new(), -+ }); -+ } -+ _ => {} -+ } -+ } -+ -+ pub(crate) fn record_library( -+ &self, -+ context: u32, -+ obj_id: u64, -+ bytes: Vec, -+ guest_key: Option, -+ ) { -+ let mut st = self.state.lock(); -+ if let Some(k) = guest_key { -+ st.library_bytes_by_key.insert(k, bytes.clone()); -+ if let Some(wk) = super::decode::whole_library_key(&bytes) -+ && wk != k -+ { -+ st.library_bytes_by_key.insert(wk, bytes.clone()); -+ } -+ } -+ let seq = st.next_seq; -+ st.next_seq = st.next_seq.wrapping_add(1); -+ st.records.push(LogRecord { -+ seq, -+ context, -+ obj_id, -+ msg_type: LOG_TAG_ASSEMBLED_LIBRARY, -+ bytes: guest_key.map(|k| k.to_vec()).unwrap_or_default(), -+ inline_bytes: bytes, -+ }); -+ } -+ -+ pub(crate) fn record_library_lookup(&self, context: u32, message: &[u8]) { -+ let Ok((m, _)) = RgfxLibraryLookup::read_from_prefix(message) else { -+ return; -+ }; -+ let mut st = self.state.lock(); -+ let seq = st.next_seq; -+ st.next_seq = st.next_seq.wrapping_add(1); -+ if let Some(inline_bytes) = st.library_bytes_by_key.get(&m.key).cloned() { -+ st.records.push(LogRecord { -+ seq, -+ context, -+ obj_id: m.obj_id, -+ msg_type: LOG_TAG_ASSEMBLED_LIBRARY, -+ bytes: m.key.to_vec(), -+ inline_bytes, -+ }); -+ } else { -+ st.records.push(LogRecord { -+ seq, -+ context, -+ obj_id: m.obj_id, -+ msg_type: RGFX_CMD_LIBRARY_LOOKUP, -+ bytes: message.to_vec(), -+ inline_bytes: Vec::new(), -+ }); -+ } -+ } -+ -+ pub(crate) fn record_surface_pages( -+ &self, -+ pages: RgfxSurfacePages, -+ runs: Vec, -+ flags: u32, -+ layout: Option, -+ ) { -+ let rec = SurfacePagesRecord { -+ pages, -+ runs, -+ flags, -+ layout, -+ }; -+ let mut st = self.state.lock(); -+ if flags & RGFX_SURFACE_PAGES_ATTACH != 0 { -+ st.surface_pages.entry(pages.block_offset).or_default().push(rec); -+ } else { -+ st.surface_pages.insert(pages.block_offset, vec![rec]); -+ } -+ } -+ -+ pub(crate) fn forget_surface_pages(&self, block_offset: u64) { -+ self.state.lock().surface_pages.remove(&block_offset); -+ } -+ -+ pub(crate) fn record_present(&self, display: usize, iosurface_id: u32) { -+ let mut st = self.state.lock(); -+ if let Some(slot) = st.presented_surfaces.get_mut(display) { -+ *slot = iosurface_id; -+ } -+ } -+ -+ pub(crate) fn close_context(&self, context: u32) { -+ let mut st = self.state.lock(); -+ let removed: HashSet = st -+ .records -+ .iter() -+ .filter(|r| r.context == context) -+ .map(|r| r.obj_id) -+ .collect(); -+ st.records.retain(|r| r.context != context); -+ st.standalone_textures.retain(|id| !removed.contains(id)); -+ st.surface_pages.retain(|_, v| { -+ v.retain(|sp| sp.pages.context != context); -+ !v.is_empty() -+ }); -+ } -+ -+ pub(crate) fn reset(&self) { -+ let mut st = self.state.lock(); -+ st.records.clear(); -+ st.surface_pages.clear(); -+ st.standalone_textures.clear(); -+ for slot in &mut st.presented_surfaces { -+ *slot = 0; -+ } -+ } -+ -+ pub(crate) fn export( -+ &self, -+ ) -> ( -+ Vec, -+ Vec, -+ HashSet, -+ Vec, -+ ) { -+ let st = self.state.lock(); -+ ( -+ compact_records(&st.records), -+ st.surface_pages.values().flatten().cloned().collect(), -+ st.standalone_textures.clone(), -+ st.presented_surfaces.clone(), -+ ) -+ } -+ -+ pub(crate) fn restore( -+ &self, -+ records: Vec, -+ surface_pages: Vec, -+ standalone_textures: HashSet, -+ presented_surfaces: Vec, -+ ) { -+ let mut st = self.state.lock(); -+ let max_seq = records.iter().map(|r| r.seq).max().unwrap_or(0); -+ st.next_seq = max_seq.wrapping_add(1); -+ st.library_bytes_by_key.clear(); -+ for r in &records { -+ if r.msg_type == LOG_TAG_ASSEMBLED_LIBRARY -+ && r.bytes.len() == 32 -+ && !r.inline_bytes.is_empty() -+ && let Ok(k) = <[u8; 32]>::try_from(r.bytes.as_slice()) -+ { -+ st.library_bytes_by_key.insert(k, r.inline_bytes.clone()); -+ if let Some(wk) = super::decode::whole_library_key(&r.inline_bytes) -+ && wk != k -+ { -+ st.library_bytes_by_key.insert(wk, r.inline_bytes.clone()); -+ } -+ } -+ } -+ st.records = records; -+ st.surface_pages.clear(); -+ for sp in surface_pages { -+ st.surface_pages.entry(sp.pages.block_offset).or_default().push(sp); -+ } -+ st.standalone_textures = standalone_textures; -+ let n = st.presented_surfaces.len().min(presented_surfaces.len()); -+ st.presented_surfaces[..n].copy_from_slice(&presented_surfaces[..n]); -+ } -+} -+ -+fn is_persistent_stage3(ty: u32) -> bool { -+ matches!( -+ ty, -+ RGFX_CMD_EVENT_CREATE -+ | RGFX_CMD_FENCE_CREATE -+ | RGFX_CMD_SHARED_EVENT_CREATE -+ | RGFX_CMD_SHARED_EVENT_IMPORT -+ | RGFX_CMD_SHARED_EVENT_NAME -+ | RGFX_CMD_QUEUE_CREATE -+ | RGFX_CMD_DYNAMIC_LIBRARY_CREATE -+ | RGFX_CMD_SAMPLER_CREATE -+ | RGFX_CMD_DEPTH_STENCIL_CREATE -+ | RGFX_CMD_BUFFER_CREATE -+ | RGFX_CMD_BUFFER_OVER_HOST_MEMORY -+ | RGFX_CMD_BUFFER_OVER_SURFACE_PAGES -+ | RGFX_CMD_BUFFER_OVER_PAGES -+ | RGFX_CMD_BUFFER_MANAGED_AT_OFFSET -+ | RGFX_CMD_MANAGED_BUFFER_CREATE -+ | RGFX_CMD_BUFFER_AT_OFFSET -+ | RGFX_CMD_BUFFER_ESCAPED -+ | RGFX_CMD_HEAP_CREATE -+ | RGFX_CMD_HEAP_OVER_HOST_MEMORY -+ | RGFX_CMD_HEAP_OVER_POOL -+ | RGFX_CMD_HEAP_OVER_PAGES -+ | RGFX_CMD_TEXTURE_CREATE -+ | RGFX_CMD_MANAGED_TEXTURE_CREATE -+ | RGFX_CMD_TEXTURE_VIEW -+ | RGFX_CMD_TEXTURE_FROM_BUFFER -+ | RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER -+ | RGFX_CMD_TEXTURE_FROM_IOSURFACE -+ | RGFX_CMD_RENDER_PIPELINE_CREATE -+ | RGFX_CMD_MESH_RENDER_PIPELINE_CREATE -+ | RGFX_CMD_COMPUTE_PIPELINE_CREATE -+ | RGFX_CMD_ICB_CREATE -+ | RGFX_CMD_ICB_WRITE -+ | RGFX_CMD_ICB_SLOTS -+ | RGFX_CMD_ICB_SLOTS_IN_PAGES -+ | RGFX_CMD_RATE_MAP_CREATE -+ | RGFX_CMD_RATE_MAP_RESET -+ | RGFX_CMD_FUNCTION_HANDLE_CREATE -+ | RGFX_CMD_FUNCTION_TABLE_CREATE -+ | RGFX_CMD_FUNCTION_TABLE_SET -+ ) -+} -+ -+fn push_linked_libraries(out: &mut Vec, bytes: &[u8], offset: u32, count: u32) { -+ let Ok(start) = usize::try_from(offset) else { -+ return; -+ }; -+ let Ok(n) = usize::try_from(count) else { -+ return; -+ }; -+ let elem = std::mem::size_of::(); -+ for i in 0..n { -+ let Some(at) = i.checked_mul(elem).and_then(|d| start.checked_add(d)) else { -+ break; -+ }; -+ let Some(slice) = bytes.get(at..) else { -+ break; -+ }; -+ let Ok((lf, _)) = RgfxLinkedFunction::read_from_prefix(slice) else { -+ break; -+ }; -+ if lf.library_obj_id != 0 { -+ out.push(lf.library_obj_id); -+ } -+ } -+} -+ -+fn push_pipeline_libraries(out: &mut Vec, bytes: &[u8], end_of_fixed: usize, count: u32) { -+ let Ok(n) = usize::try_from(count) else { -+ return; -+ }; -+ let elem = std::mem::size_of::(); -+ let Some(total) = n.checked_mul(elem) else { -+ return; -+ }; -+ let Some(start) = bytes.len().checked_sub(total) else { -+ return; -+ }; -+ if start < end_of_fixed { -+ return; -+ } -+ for i in 0..n { -+ let Some(slice) = bytes.get(start + i * elem..) else { -+ break; -+ }; -+ let Ok((pl, _)) = RgfxPipelineLibrary::read_from_prefix(slice) else { -+ break; -+ }; -+ if pl.obj_id != 0 { -+ out.push(pl.obj_id); -+ } -+ } -+} -+ -+/// Returns all parent object IDs referenced when replaying `rec`. -+fn record_parent_ids(rec: &LogRecord) -> Vec { -+ let mut out = Vec::new(); -+ let b = &rec.bytes; -+ match rec.msg_type { -+ RGFX_CMD_RENDER_PIPELINE_CREATE => { -+ if let Ok((m, _)) = RgfxRenderPipelineCreate::read_from_prefix(b) { -+ if m.vertex_library_obj_id != 0 { -+ out.push(m.vertex_library_obj_id); -+ } -+ if m.fragment_library_obj_id != 0 { -+ out.push(m.fragment_library_obj_id); -+ } -+ push_linked_libraries(&mut out, b, m.vertex_linked_offset, m.vertex_linked_count); -+ push_linked_libraries( -+ &mut out, -+ b, -+ m.fragment_linked_offset, -+ m.fragment_linked_count, -+ ); -+ } -+ } -+ RGFX_CMD_MESH_RENDER_PIPELINE_CREATE => { -+ if let Ok((m, _)) = RgfxMeshRenderPipelineCreate::read_from_prefix(b) { -+ if m.object_library_obj_id != 0 { -+ out.push(m.object_library_obj_id); -+ } -+ if m.mesh_library_obj_id != 0 { -+ out.push(m.mesh_library_obj_id); -+ } -+ if m.fragment_library_obj_id != 0 { -+ out.push(m.fragment_library_obj_id); -+ } -+ push_linked_libraries(&mut out, b, m.object_linked_offset, m.object_linked_count); -+ push_linked_libraries(&mut out, b, m.mesh_linked_offset, m.mesh_linked_count); -+ push_linked_libraries( -+ &mut out, -+ b, -+ m.fragment_linked_offset, -+ m.fragment_linked_count, -+ ); -+ } -+ } -+ RGFX_CMD_COMPUTE_PIPELINE_CREATE => { -+ if let Ok((m, _)) = RgfxComputePipelineCreate::read_from_prefix(b) { -+ if m.function_library_obj_id != 0 { -+ out.push(m.function_library_obj_id); -+ } -+ push_linked_libraries(&mut out, b, m.linked_offset, m.linked_count); -+ push_pipeline_libraries( -+ &mut out, -+ b, -+ std::mem::size_of::(), -+ m.library_count, -+ ); -+ } -+ } -+ RGFX_CMD_DYNAMIC_LIBRARY_CREATE => { -+ if let Ok((m, _)) = RgfxDynamicLibraryCreate::read_from_prefix(b) -+ && m.library_obj_id != 0 -+ { -+ out.push(m.library_obj_id); -+ } -+ } -+ RGFX_CMD_FUNCTION_HANDLE_CREATE => { -+ if let Ok((m, _)) = RgfxFunctionHandleCreate::read_from_prefix(b) { -+ if m.pipeline_obj_id != 0 { -+ out.push(m.pipeline_obj_id); -+ } -+ if m.function.library_obj_id != 0 { -+ out.push(m.function.library_obj_id); -+ } -+ } -+ } -+ RGFX_CMD_FUNCTION_TABLE_SET => { -+ if let Ok((m, rest)) = RgfxFunctionTableSet::read_from_prefix(b) { -+ let count = m.count as usize; -+ for chunk in rest.chunks_exact(8).take(count) { -+ if let Ok(arr) = <[u8; 8]>::try_from(chunk) { -+ let id = u64::from_le_bytes(arr); -+ if id != 0 { -+ out.push(id); -+ } -+ } -+ } -+ } -+ } -+ RGFX_CMD_TEXTURE_VIEW => { -+ if let Ok((m, _)) = RgfxTextureView::read_from_prefix(b) -+ && m.parent_obj_id != 0 -+ { -+ out.push(m.parent_obj_id); -+ } -+ } -+ RGFX_CMD_TEXTURE_CREATE => { -+ if let Ok((m, _)) = RgfxTextureCreate::read_from_prefix(b) -+ && m.heap_obj_id != 0 -+ { -+ out.push(m.heap_obj_id); -+ } -+ } -+ RGFX_CMD_TEXTURE_FROM_BUFFER => { -+ if let Ok((m, _)) = RgfxTextureFromBuffer::read_from_prefix(b) -+ && m.buffer_obj_id != 0 -+ { -+ out.push(m.buffer_obj_id); -+ } -+ } -+ RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER => { -+ if let Ok((m, _)) = RgfxLinearTextureFromBuffer::read_from_prefix(b) -+ && m.buffer_obj_id != 0 -+ { -+ out.push(m.buffer_obj_id); -+ } -+ } -+ RGFX_CMD_SHARED_EVENT_NAME => { -+ if let Ok((m, _)) = RgfxSharedEventName::read_from_prefix(b) -+ && m.listen_queue_obj_id != 0 -+ { -+ out.push(m.listen_queue_obj_id); -+ } -+ } -+ RGFX_CMD_SHARED_EVENT_IMPORT => { -+ if let Ok((m, _)) = RgfxSharedEventImport::read_from_prefix(b) -+ && m.listen_queue_obj_id != 0 -+ { -+ out.push(m.listen_queue_obj_id); -+ } -+ } -+ _ => {} -+ } -+ out -+} -+ -+/// Drops destroyed incarnations that are no longer transitively referenced by any live object. -+fn compact_records(records: &[LogRecord]) -> Vec { -+ let mut active_inc: HashMap = HashMap::new(); -+ let mut active_name_inc: HashMap = HashMap::new(); -+ let mut destroyed: Vec = Vec::new(); -+ let mut deps: Vec> = Vec::new(); -+ let mut rec_inc: Vec> = Vec::with_capacity(records.len()); -+ -+ for r in records { -+ match r.msg_type { -+ RGFX_CMD_OBJECT_DESTROY => { -+ if let Some(inc) = active_inc.remove(&r.obj_id) { -+ destroyed[inc] = true; -+ rec_inc.push(Some(inc)); -+ } else { -+ rec_inc.push(None); -+ } -+ } -+ RGFX_CMD_SHARED_EVENT_UNNAME => { -+ let inc = RgfxSharedEventUnname::read_from_prefix(&r.bytes) -+ .ok() -+ .and_then(|(m, _)| active_name_inc.remove(&m.name)); -+ rec_inc.push(inc); -+ } -+ _ => { -+ let inc = if r.obj_id != 0 { -+ *active_inc.entry(r.obj_id).or_insert_with(|| { -+ let id = destroyed.len(); -+ destroyed.push(false); -+ deps.push(Vec::new()); -+ id -+ }) -+ } else { -+ let id = destroyed.len(); -+ destroyed.push(false); -+ deps.push(Vec::new()); -+ id -+ }; -+ for pid in record_parent_ids(r) { -+ if let Some(&pinc) = active_inc.get(&pid) -+ && pinc != inc -+ { -+ deps[inc].push(pinc); -+ } -+ } -+ if r.msg_type == RGFX_CMD_SHARED_EVENT_NAME { -+ if let Ok((m, _)) = RgfxSharedEventName::read_from_prefix(&r.bytes) { -+ active_name_inc.insert(m.name, inc); -+ } -+ } else if r.msg_type == RGFX_CMD_SHARED_EVENT_IMPORT { -+ if let Ok((m, _)) = RgfxSharedEventImport::read_from_prefix(&r.bytes) -+ && let Some(&ninc) = active_name_inc.get(&m.name) -+ && ninc != inc -+ { -+ deps[inc].push(ninc); -+ } -+ } -+ rec_inc.push(Some(inc)); -+ } -+ } -+ } -+ -+ let mut keep = vec![false; destroyed.len()]; -+ let mut stack: Vec = Vec::new(); -+ for (inc, &is_dead) in destroyed.iter().enumerate() { -+ if !is_dead { -+ keep[inc] = true; -+ stack.push(inc); -+ } -+ } -+ while let Some(inc) = stack.pop() { -+ for &pinc in &deps[inc] { -+ if !keep[pinc] { -+ keep[pinc] = true; -+ stack.push(pinc); -+ } -+ } -+ } -+ -+ records -+ .iter() -+ .zip(rec_inc) -+ .filter_map(|(r, inc)| inc.filter(|&i| keep[i]).map(|_| r.clone())) -+ .collect() -+} -+ -+/// Complete serialized snapshot of a [`super::GraphicsDevice`]. -+pub(crate) struct VgpuSnapshot { -+ pub(crate) device_snapshot: Vec, -+ pub(crate) shared_pool: Option, -+ pub(crate) private_blocks: PrivateBlocksSnapshot, -+ pub(crate) id_chunks: Vec, -+ pub(crate) surface_pages: Vec, -+ pub(crate) live_records: Vec, -+ pub(crate) standalone_textures: Vec, -+ pub(crate) presented_surfaces: Vec, -+ pub(crate) live_values: LiveValues, -+} -+ -+struct Enc(Vec); -+ -+impl Enc { -+ fn u8(&mut self, v: u8) { -+ self.0.push(v); -+ } -+ fn u32(&mut self, v: u32) { -+ self.0.extend_from_slice(&v.to_le_bytes()); -+ } -+ fn u64(&mut self, v: u64) { -+ self.0.extend_from_slice(&v.to_le_bytes()); -+ } -+ fn bytes(&mut self, b: &[u8]) { -+ self.u64(b.len() as u64); -+ self.0.extend_from_slice(b); -+ } -+ fn capture(&mut self, c: Option) { -+ match c { -+ None => self.u8(0), -+ Some(c) => { -+ self.u8(1); -+ self.u8(match c.class { -+ MemoryClass::Shared => 0, -+ MemoryClass::Private => 1, -+ }); -+ self.u64(c.alloc_len); -+ self.u64(c.offset); -+ self.u64(c.len); -+ self.u64(c.gpu_address); -+ self.u64(c.opaque_buffer_address); -+ self.u64(c.opaque_memory_address); -+ } -+ } -+ } -+} -+ -+struct Dec<'a> { -+ buf: &'a [u8], -+ pos: usize, -+} -+ -+impl<'a> Dec<'a> { -+ fn remaining(&self) -> usize { -+ self.buf.len().saturating_sub(self.pos) -+ } -+ fn take(&mut self, n: usize) -> Option<&'a [u8]> { -+ let end = self.pos.checked_add(n)?; -+ let s = self.buf.get(self.pos..end)?; -+ self.pos = end; -+ Some(s) -+ } -+ fn checked_count(&mut self, min_item_bytes: usize) -> Option { -+ let count = usize::try_from(self.u32()?).ok()?; -+ let min_bytes = min_item_bytes.max(1); -+ if count > self.remaining() / min_bytes { -+ return None; -+ } -+ Some(count) -+ } -+ fn read_vec( -+ &mut self, -+ min_item_bytes: usize, -+ mut f: impl FnMut(&mut Self) -> Option, -+ ) -> Option> { -+ let count = self.checked_count(min_item_bytes)?; -+ let mut out = Vec::with_capacity(count); -+ for _ in 0..count { -+ out.push(f(self)?); -+ } -+ Some(out) -+ } -+ fn u8(&mut self) -> Option { -+ Some(self.take(1)?[0]) -+ } -+ fn u32(&mut self) -> Option { -+ Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) -+ } -+ fn u64(&mut self) -> Option { -+ Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?)) -+ } -+ fn bytes(&mut self) -> Option> { -+ let n = usize::try_from(self.u64()?).ok()?; -+ Some(self.take(n)?.to_vec()) -+ } -+ fn capture(&mut self) -> Option> { -+ match self.u8()? { -+ 0 => Some(None), -+ 1 => { -+ let class = match self.u8()? { -+ 0 => MemoryClass::Shared, -+ 1 => MemoryClass::Private, -+ _ => return None, -+ }; -+ Some(Some(BlockCapture { -+ class, -+ alloc_len: self.u64()?, -+ offset: self.u64()?, -+ len: self.u64()?, -+ gpu_address: self.u64()?, -+ opaque_buffer_address: self.u64()?, -+ opaque_memory_address: self.u64()?, -+ })) -+ } -+ _ => None, -+ } -+ } -+} -+ -+impl VgpuSnapshot { -+ pub(crate) fn encode(&self) -> Vec { -+ let mut e = Enc(Vec::with_capacity(64 * 1024)); -+ e.0.extend_from_slice(SNAPSHOT_MAGIC); -+ e.u32(SNAPSHOT_VERSION); -+ e.bytes(&self.device_snapshot); -+ -+ match &self.shared_pool { -+ None => e.u8(0), -+ Some(pool) => { -+ e.u8(1); -+ e.u64(pool.serial); -+ e.u32(pool.pieces.len() as u32); -+ for p in &pool.pieces { -+ e.u64(p.gpa); -+ e.u64(p.len); -+ e.u64(p.gpu_address); -+ e.capture(p.capture); -+ e.bytes(&p.bytes); -+ } -+ e.u32(pool.carves.len() as u32); -+ for c in &pool.carves { -+ e.u64(c.gpa); -+ e.u32(c.context); -+ e.u64(c.len); -+ e.u64(c.serial); -+ e.u64(c.gpu_address); -+ e.u8(u8::from(c.picked_address)); -+ } -+ } -+ } -+ -+ e.u64(self.private_blocks.serial); -+ e.u32(self.private_blocks.blocks.len() as u32); -+ for b in &self.private_blocks.blocks { -+ e.u64(b.gpu_address); -+ e.u32(b.context); -+ e.u64(b.len); -+ e.u64(b.serial); -+ e.capture(b.capture); -+ e.bytes(&b.bytes); -+ } -+ -+ e.u32(self.id_chunks.len() as u32); -+ for &c in &self.id_chunks { -+ e.u32(c); -+ } -+ -+ e.u32(self.surface_pages.len() as u32); -+ for sp in &self.surface_pages { -+ e.bytes(sp.pages.as_bytes()); -+ e.u32(sp.runs.len() as u32); -+ for r in &sp.runs { -+ e.bytes(r.as_bytes()); -+ } -+ e.u32(sp.flags); -+ match &sp.layout { -+ None => e.u8(0), -+ Some(l) => { -+ e.u8(1); -+ e.bytes(l.as_bytes()); -+ } -+ } -+ } -+ -+ e.u32(self.live_records.len() as u32); -+ for r in &self.live_records { -+ e.u64(r.seq); -+ e.u32(r.context); -+ e.u64(r.obj_id); -+ e.u32(r.msg_type); -+ e.bytes(&r.bytes); -+ e.bytes(&r.inline_bytes); -+ } -+ -+ e.u32(self.standalone_textures.len() as u32); -+ for &id in &self.standalone_textures { -+ e.u64(id); -+ } -+ -+ e.u32(self.presented_surfaces.len() as u32); -+ for &id in &self.presented_surfaces { -+ e.u32(id); -+ } -+ -+ e.u32(self.live_values.events.len() as u32); -+ for &(id, val) in &self.live_values.events { -+ e.u64(id); -+ e.u64(val); -+ } -+ e.u32(self.live_values.shared_events.len() as u32); -+ for &(id, val) in &self.live_values.shared_events { -+ e.u64(id); -+ e.u64(val); -+ } -+ e.u32(self.live_values.buffers.len() as u32); -+ for (id, bytes) in &self.live_values.buffers { -+ e.u64(*id); -+ e.bytes(bytes); -+ } -+ e.u32(self.live_values.textures.len() as u32); -+ for (id, bytes) in &self.live_values.textures { -+ e.u64(*id); -+ e.bytes(bytes); -+ } -+ e.u32(self.live_values.surface_caches.len() as u32); -+ for (block, bytes) in &self.live_values.surface_caches { -+ e.u64(*block); -+ e.bytes(bytes); -+ } -+ e.0 -+ } -+ -+ pub(crate) fn decode(data: &[u8]) -> Option { -+ let mut d = Dec { buf: data, pos: 0 }; -+ if d.take(8)? != SNAPSHOT_MAGIC { -+ return None; -+ } -+ if d.u32()? != SNAPSHOT_VERSION { -+ return None; -+ } -+ let device_snapshot = d.bytes()?; -+ -+ let shared_pool = match d.u8()? { -+ 0 => None, -+ 1 => { -+ let serial = d.u64()?; -+ let pieces = d.read_vec(33, |d| { -+ Some(PoolPieceSnapshot { -+ gpa: d.u64()?, -+ len: d.u64()?, -+ gpu_address: d.u64()?, -+ capture: d.capture()?, -+ bytes: d.bytes()?, -+ }) -+ })?; -+ let carves = d.read_vec(37, |d| { -+ Some(PoolCarveSnapshot { -+ gpa: d.u64()?, -+ context: d.u32()?, -+ len: d.u64()?, -+ serial: d.u64()?, -+ gpu_address: d.u64()?, -+ picked_address: d.u8()? != 0, -+ }) -+ })?; -+ Some(PoolSnapshot { -+ serial, -+ pieces, -+ carves, -+ }) -+ } -+ _ => return None, -+ }; -+ -+ let pb_serial = d.u64()?; -+ let blocks = d.read_vec(37, |d| { -+ Some(PrivateBlockSnapshot { -+ gpu_address: d.u64()?, -+ context: d.u32()?, -+ len: d.u64()?, -+ serial: d.u64()?, -+ capture: d.capture()?, -+ bytes: d.bytes()?, -+ }) -+ })?; -+ let private_blocks = PrivateBlocksSnapshot { -+ serial: pb_serial, -+ blocks, -+ }; -+ -+ let id_chunks = d.read_vec(4, Dec::u32)?; -+ -+ let surface_pages = d.read_vec(17, |d| { -+ let pages_b = d.bytes()?; -+ let (pages, _) = RgfxSurfacePages::read_from_prefix(&pages_b).ok()?; -+ let runs = d.read_vec(8 + std::mem::size_of::(), |d| { -+ let rb = d.bytes()?; -+ let (r, _) = RgfxPageRun::read_from_prefix(&rb).ok()?; -+ Some(r) -+ })?; -+ let flags = d.u32()?; -+ let layout = match d.u8()? { -+ 0 => None, -+ 1 => { -+ let lb = d.bytes()?; -+ let (l, _) = RgfxSurfacePagesLayout::read_from_prefix(&lb).ok()?; -+ Some(l) -+ } -+ _ => return None, -+ }; -+ Some(SurfacePagesRecord { -+ pages, -+ runs, -+ flags, -+ layout, -+ }) -+ })?; -+ -+ let live_records = d.read_vec(40, |d| { -+ Some(LogRecord { -+ seq: d.u64()?, -+ context: d.u32()?, -+ obj_id: d.u64()?, -+ msg_type: d.u32()?, -+ bytes: d.bytes()?, -+ inline_bytes: d.bytes()?, -+ }) -+ })?; -+ -+ let standalone_textures = d.read_vec(8, Dec::u64)?; -+ let presented_surfaces = d.read_vec(4, Dec::u32)?; -+ -+ let live_values = LiveValues { -+ events: d.read_vec(16, |d| Some((d.u64()?, d.u64()?)))?, -+ shared_events: d.read_vec(16, |d| Some((d.u64()?, d.u64()?)))?, -+ buffers: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, -+ textures: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, -+ surface_caches: d.read_vec(16, |d| Some((d.u64()?, d.bytes()?)))?, -+ }; -+ if d.remaining() != 0 { -+ return None; -+ } -+ -+ Some(VgpuSnapshot { -+ device_snapshot, -+ shared_pool, -+ private_blocks, -+ id_chunks, -+ surface_pages, -+ live_records, -+ standalone_textures, -+ presented_surfaces, -+ live_values, -+ }) -+ } -+} -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ -+ fn empty_snapshot() -> VgpuSnapshot { -+ VgpuSnapshot { -+ device_snapshot: Vec::new(), -+ shared_pool: Some(PoolSnapshot { -+ serial: 1, -+ pieces: Vec::new(), -+ carves: Vec::new(), -+ }), -+ private_blocks: PrivateBlocksSnapshot { -+ serial: 2, -+ blocks: Vec::new(), -+ }, -+ id_chunks: Vec::new(), -+ surface_pages: Vec::new(), -+ live_records: Vec::new(), -+ standalone_textures: Vec::new(), -+ presented_surfaces: Vec::new(), -+ live_values: LiveValues::default(), -+ } -+ } -+ -+ #[test] -+ fn decode_rejects_oversized_counts_and_trailing_bytes() { -+ let encoded = empty_snapshot().encode(); -+ assert!(VgpuSnapshot::decode(&encoded).is_some()); -+ -+ let mut with_tail = encoded.clone(); -+ with_tail.push(0xAA); -+ assert!(VgpuSnapshot::decode(&with_tail).is_none()); -+ -+ assert_eq!(encoded.len(), 89); -+ for offset in [29usize, 33, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85] { -+ let mut bad = encoded.clone(); -+ bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes()); -+ assert!( -+ VgpuSnapshot::decode(&bad).is_none(), -+ "oversized count at offset {offset} must fail cleanly" -+ ); -+ } -+ } -+ -+ #[test] -+ fn live_log_retains_destroyed_parent_library_for_live_pipeline() { -+ let log = LiveLog::new(1); -+ let ctx = 7u32; -+ -+ // Create two libraries: obj 10 (needed by pipeline 20) and obj 11 (unused). -+ let lib_bytes = b"MTLB_DUMMY_PAYLOAD".to_vec(); -+ log.record_library(ctx, 10, lib_bytes.clone(), Some([0x11; 32])); -+ log.record_library(ctx, 11, lib_bytes, Some([0x22; 32])); -+ -+ // Create a compute pipeline (obj 20) referencing library 10. -+ let mut pipe = zerocopy::FromZeros::new_zeroed(); -+ let pipe_ref: &mut RgfxComputePipelineCreate = &mut pipe; -+ pipe_ref.header.r#type = RGFX_CMD_COMPUTE_PIPELINE_CREATE; -+ pipe_ref.header.size = std::mem::size_of::() as u32; -+ pipe_ref.obj_id = 20; -+ pipe_ref.function_library_obj_id = 10; -+ log.record_stage3(ctx, pipe_ref.as_bytes()); -+ -+ // Destroy both libraries (e.g. ARC releasing MTLLibrary after compiling pipeline). -+ for dead in [10u64, 11u64] { -+ let mut d = zerocopy::FromZeros::new_zeroed(); -+ let d_ref: &mut RgfxObjectDestroy = &mut d; -+ d_ref.header.r#type = RGFX_CMD_OBJECT_DESTROY; -+ d_ref.header.size = std::mem::size_of::() as u32; -+ d_ref.obj_id = dead; -+ log.record_stage3(ctx, d_ref.as_bytes()); -+ } -+ -+ let (records, _, _, _) = log.export(); -+ let summary: Vec<(u64, u32)> = records.iter().map(|r| (r.obj_id, r.msg_type)).collect(); -+ // Library 10 and its trailing destroy must be kept so pipeline 20 can replay; -+ // unused library 11 and its destroy must be compacted away. -+ assert_eq!( -+ summary, -+ vec![ -+ (10, LOG_TAG_ASSEMBLED_LIBRARY), -+ (20, RGFX_CMD_COMPUTE_PIPELINE_CREATE), -+ (10, RGFX_CMD_OBJECT_DESTROY), -+ ] -+ ); -+ } -+} -diff --git a/crates/reims-vgpu/src/pool.rs b/crates/reims-vgpu/src/pool.rs -index e915869056a8c7ac9f81f2a5b7d18b90290c542c..58deecf094f39ab8f8d3aaf6b988ed3c43a3937c 100644 ---- a/crates/reims-vgpu/src/pool.rs -+++ b/crates/reims-vgpu/src/pool.rs -@@ -85,6 +85,7 @@ - mod addresses; - mod host_blocks; - mod private_blocks; -+pub(crate) use private_blocks::{PrivateBlockSnapshot, PrivateBlocksSnapshot}; - mod rt_blocks; - mod takes; - -@@ -309,6 +310,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, -+ pub bytes: Vec, -+} -+ -+/// 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, -+ pub carves: Vec, -+} -+ - pub trait BlockSource: Send + Sync { - /// A block of `class` at least `len` long ([`BlockInfo::len`]). Waits only when no block is - /// ready. -@@ -317,6 +359,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 { -+ None -+ } -+ -+ /// Replays a previously captured block at its exact Vulkan device address. -+ fn take_block_replayed(&self, _cap: BlockCapture) -> Result { -+ 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>, 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. -@@ -1087,6 +1150,146 @@ impl Pool { - dead_code, - reason = "the guest's side of the pool (its ring messages) calls it once it lands" - )] -+ /// Waits until in-flight pool take workers and zeroer are idle. -+ pub(crate) fn quiesce(&self) { -+ let deadline = std::time::Instant::now() + Duration::from_secs(5); -+ loop { -+ let busy = { -+ let st = self.shared.state.lock(); -+ st.workers > 0 || st.zeroer || st.serving > 0 || !st.asks.is_empty() -+ }; -+ if !busy || std::time::Instant::now() >= deadline { -+ break; -+ } -+ std::thread::sleep(Duration::from_millis(2)); -+ } -+ } -+ -+ /// Exports all live Shared Pool pieces (with raw bytes & BDA capture metadata) and carves. -+ pub(crate) fn export_snapshot(&self) -> Result { -+ self.quiesce(); -+ let st = self.shared.state.lock(); -+ let source = st.source.clone(); -+ let mut pieces = Vec::new(); -+ for (&gpa, p) in &st.pieces { -+ if !matches!(p.mapped, Mapped::Live | Mapped::Adding) { -+ continue; -+ } -+ let cap = source.as_ref().and_then(|s| s.capture_block(p.block.id)); -+ let ptr = p.block.contents.ok_or(Error::HostResources)?; -+ let bytes = unsafe { -+ std::slice::from_raw_parts(ptr.as_ptr(), p.block.len as usize).to_vec() -+ }; -+ pieces.push(PoolPieceSnapshot { -+ gpa, -+ len: p.block.len, -+ gpu_address: p.block.gpu_address, -+ capture: cap, -+ bytes, -+ }); -+ } -+ let carves = takes::export_carves(&st.carves); -+ Ok(PoolSnapshot { -+ serial: st.serial, -+ pieces, -+ carves, -+ }) -+ } -+ -+ /// Restores Shared Pool pieces at their exact GPAs and Vulkan BDAs, and asks host to map them. -+ pub(crate) fn import_snapshot(&self, snap: &PoolSnapshot) -> Result<(), Error> { -+ self.quiesce(); -+ let source = { -+ let st = self.shared.state.lock(); -+ st.source.clone() -+ }; -+ let Some(source) = source else { -+ return if snap.pieces.is_empty() { -+ Ok(()) -+ } else { -+ Err(Error::HostResources) -+ }; -+ }; -+ // First release any pre-existing empty pieces if any (fresh device has none). -+ let mut restored_pieces: Vec<(u64, BlockInfo)> = Vec::with_capacity(snap.pieces.len()); -+ for ps in &snap.pieces { -+ let blk = if let Some(cap) = ps.capture { -+ source -+ .take_block_replayed(cap) -+ .map_err(|_| Error::HostResources)? -+ } else { -+ source -+ .take_block(MemoryClass::Shared, ps.len) -+ .map_err(|_| Error::HostResources)? -+ }; -+ let ptr = blk.contents.ok_or(Error::HostResources)?; -+ if ps.bytes.len() as u64 != blk.len { -+ return Err(Error::InvalidArgument); -+ } -+ unsafe { -+ std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len()); -+ } -+ restored_pieces.push((ps.gpa, blk)); -+ } -+ { -+ let mut st = self.shared.state.lock(); -+ st.serial = st.serial.max(snap.serial); -+ for (gpa, blk) in &restored_pieces { -+ let piece_carves = snap -+ .carves -+ .iter() -+ .filter(|c| c.gpa >= *gpa && c.gpa < *gpa + blk.len) -+ .count() as u64; -+ st.by_block.insert(blk.id, *gpa); -+ st.pieces.insert( -+ *gpa, -+ Piece { -+ block: *blk, -+ mapped: Mapped::Adding, -+ empty_since: if piece_carves == 0 { -+ Some((self.shared.now)()) -+ } else { -+ None -+ }, -+ holds: 0, -+ kept: Arc::new(()), -+ carves: piece_carves, -+ zeros: takes::Ranges::new(), -+ zero_pending: false, -+ going: None, -+ }, -+ ); -+ } -+ let state = &mut *st; -+ takes::import_carves(&mut state.carves, &mut state.addresses, &snap.carves); -+ } -+ for (gpa, blk) in &restored_pieces { -+ if let Some(ptr) = blk.contents { -+ (self.shared.host.add)(*gpa, ptr.as_ptr(), blk.len); -+ } -+ } -+ self.shared.wake(); -+ Ok(()) -+ } -+ -+ /// Re-copies snapshotted Shared Pool piece bytes after LiveLog replay (so any `new_buffer` -+ /// zero-initialization during replay cannot clobber saved guest/GPU contents). -+ pub(crate) fn restore_bytes(&self, snap: &PoolSnapshot) -> Result<(), Error> { -+ let st = self.shared.state.lock(); -+ for ps in &snap.pieces { -+ let piece = st.pieces.get(&ps.gpa).ok_or(Error::HostResources)?; -+ let ptr = piece.block.contents.ok_or(Error::HostResources)?; -+ if ps.bytes.len() as u64 != piece.block.len { -+ return Err(Error::InvalidArgument); -+ } -+ unsafe { -+ std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len()); -+ } -+ } -+ Ok(()) -+ } -+ -+ #[cfg(any(test, feature = "testkit"))] - pub fn live(&self) -> Vec<(u64, u64)> { - let st = self.shared.state.lock(); - (st.pieces.iter()) -diff --git a/crates/reims-vgpu/src/pool/private_blocks.rs b/crates/reims-vgpu/src/pool/private_blocks.rs -index ebe6e77b899a55b102dc0d9fc07b9d57a315c44e..5a42f97cb40d4b3d067b9283d1e2232a7eecc6a5 100644 ---- a/crates/reims-vgpu/src/pool/private_blocks.rs -+++ b/crates/reims-vgpu/src/pool/private_blocks.rs -@@ -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, -+ pub(crate) bytes: Vec, -+} -+ -+/// Complete snapshot of all contexts' Private blocks. -+#[derive(Clone, Debug, Default)] -+pub(crate) struct PrivateBlocksSnapshot { -+ pub(crate) serial: u64, -+ pub(crate) blocks: Vec, -+} -+ - #[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 { -+ let deadline = std::time::Instant::now() + Duration::from_secs(5); -+ loop { -+ let busy = { -+ let st = self.inner.state.lock(); -+ st.takers.values().any(|t| t.busy || !t.jobs.is_empty()) -+ }; -+ if !busy { -+ break; -+ } -+ if std::time::Instant::now() >= deadline { -+ return Err(super::Error::HostResources); -+ } -+ std::thread::sleep(Duration::from_millis(2)); -+ } -+ let entries: Vec<(u64, u32, u64, u64, Option)> = { -+ 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(); -diff --git a/crates/reims-vgpu/src/pool/rt_blocks.rs b/crates/reims-vgpu/src/pool/rt_blocks.rs -index ea0ae46f22cbaaeca83f3b205d5bd34ab02fb10d..91676ea8ef346cc4f35dea1c79c6c9e51a33d943 100644 ---- a/crates/reims-vgpu/src/pool/rt_blocks.rs -+++ b/crates/reims-vgpu/src/pool/rt_blocks.rs -@@ -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 { -+ 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 { -+ 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>, 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, 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 { -diff --git a/crates/reims-vgpu/src/pool/takes.rs b/crates/reims-vgpu/src/pool/takes.rs -index d724a3413c17940834fae97b41cb025089b6e164..1c9ea6db4f9d47e151454c128caf41ea5254c383 100644 ---- a/crates/reims-vgpu/src/pool/takes.rs -+++ b/crates/reims-vgpu/src/pool/takes.rs -@@ -191,6 +191,47 @@ enum GpuAddress { - Picked(u64), - } - -+pub(super) fn export_carves(carves: &BTreeMap) -> Vec { -+ 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, -+ _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 { diff --git a/patches/reims-vgpu-win32-unicode-input.patch b/patches/reims-vgpu-win32-unicode-input.patch deleted file mode 100644 index 1b24ff1..0000000 --- a/patches/reims-vgpu-win32-unicode-input.patch +++ /dev/null @@ -1,243 +0,0 @@ -diff --git a/crates/reims-vgpu-window/src/native/sdl_thread/ui.rs b/crates/reims-vgpu-window/src/native/sdl_thread/ui.rs -index 6f70e07..074917c 100644 ---- a/crates/reims-vgpu-window/src/native/sdl_thread/ui.rs -+++ b/crates/reims-vgpu-window/src/native/sdl_thread/ui.rs -@@ -183,6 +183,8 @@ fn start_video() -> bool { - ); - return false; - } -+ #[cfg(target_os = "windows")] -+ super::super::windows::install_unicode_input_hook(); - // SAFETY: SDL's video runs. - let kind = unsafe { SDL_RegisterEvents(1) }; - WAKE.store(kind, Ordering::Release); -diff --git a/crates/reims-vgpu-window/src/native/windows.rs b/crates/reims-vgpu-window/src/native/windows.rs -index cc456c5..4ce46a6 100644 ---- a/crates/reims-vgpu-window/src/native/windows.rs -+++ b/crates/reims-vgpu-window/src/native/windows.rs -@@ -42,12 +42,19 @@ - //! taskbar then goes to the bottom of the z-order while the window is active, and that taking - //! the mark away leaves the window to the shell's own detection. - -+use std::cell::Cell; - use std::ffi::c_void; -+use std::io::Write; -+use std::net::{SocketAddr, TcpStream}; - use std::ptr::{NonNull, null, null_mut}; -+use std::sync::OnceLock; -+use std::sync::mpsc::{self, RecvTimeoutError, SyncSender}; -+use std::time::Duration; - - use sdl3_sys::everything::{ -- SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties, -- SDL_PROP_WINDOW_WIN32_HWND_POINTER, SDL_WINDOW_FULLSCREEN, SDL_Window, -+ MSG as SDL_MSG, SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties, -+ SDL_PROP_WINDOW_WIN32_HWND_POINTER, SDL_SetWindowsMessageHook, SDL_WINDOW_FULLSCREEN, -+ SDL_Window, - }; - use windows_sys::Win32::Foundation::{FALSE, HWND, RPC_E_CHANGED_MODE, S_FALSE, S_OK, TRUE}; - use windows_sys::Win32::System::Com::{ -@@ -62,6 +69,203 @@ use crate::capture::HostOs; - /// The OS whose names the title gives the release chord's keys: Ctrl+Alt+Win (the module doc). - pub(super) const HOST_OS: HostOs = HostOs::Windows; - -+/// Win32 MSG layout matching winuser.h for SDL_SetWindowsMessageHook. -+#[repr(C)] -+struct Win32Msg { -+ /// Target window handle. -+ _hwnd: HWND, -+ /// Message identifier (WM_*). -+ message: u32, -+ /// WPARAM. -+ w_param: usize, -+ /// LPARAM. -+ l_param: isize, -+ /// Message timestamp (GetMessageTime). -+ _time: u32, -+ /// Cursor position (POINT). -+ _pt: [i32; 2], -+} -+ -+/// WM_KEYDOWN. -+const WM_KEYDOWN: u32 = 0x0100; -+/// WM_CHAR. -+const WM_CHAR: u32 = 0x0102; -+/// WM_SYSKEYDOWN. -+const WM_SYSKEYDOWN: u32 = 0x0104; -+/// WM_UNICHAR. -+const WM_UNICHAR: u32 = 0x0109; -+/// WM_IME_CHAR. -+const WM_IME_CHAR: u32 = 0x0286; -+/// UNICODE_NOCHAR. -+const UNICODE_NOCHAR: usize = 0xFFFF; -+/// VK_PROCESSKEY (host IME intercepted key). -+const VK_PROCESSKEY: u16 = 0x00E5; -+/// VK_PACKET (SendInput with KEYEVENTF_UNICODE). -+const VK_PACKET: u16 = 0x00E7; -+ -+/// Non-blocking channel carrying UTF-16 code units from the SDL UI thread to the HTTP forwarder. -+static UNICODE_TX: OnceLock> = OnceLock::new(); -+ -+thread_local! { -+ /// Whether the most recent WM_KEYDOWN was unmapped (VK_PACKET or VK_PROCESSKEY). -+ static LAST_KEY_UNMAPPED: Cell = const { Cell::new(false) }; -+} -+ -+/// Parses a loopback http://127.0.0.1: endpoint from REIMS_GO_INPUT_URL. -+fn parse_loopback_input_url(raw: &str) -> Option<(SocketAddr, String)> { -+ let rest = raw.trim().strip_prefix("http://127.0.0.1:")?; -+ let (port_str, path) = match rest.find('/') { -+ Some(idx) => (&rest[..idx], &rest[idx..]), -+ None => (rest, "/v1/host-text"), -+ }; -+ let port: u16 = port_str.parse().ok()?; -+ if port == 0 || path.contains(['\r', '\n', ' ']) { -+ return None; -+ } -+ let addr = SocketAddr::from(([127, 0, 0, 1], port)); -+ Some((addr, path.to_owned())) -+} -+ -+/// Installs a Win32 message hook on SDL's UI thread when REIMS_GO_INPUT_URL and -+/// REIMS_GO_INPUT_TOKEN are set, forwarding non-keyboard WM_CHAR / WM_UNICHAR / -+/// WM_IME_CHAR text (remote IMEs, dictation, host IME commits) to the local host bridge. -+pub(super) fn install_unicode_input_hook() { -+ let Ok(url) = std::env::var("REIMS_GO_INPUT_URL") else { -+ return; -+ }; -+ let Ok(token) = std::env::var("REIMS_GO_INPUT_TOKEN") else { -+ return; -+ }; -+ if token.is_empty() || token.contains(['\r', '\n']) { -+ return; -+ } -+ let Some((addr, path)) = parse_loopback_input_url(&url) else { -+ log::warn!(target: "reims_vgpu_window", "ignoring non-loopback REIMS_GO_INPUT_URL"); -+ return; -+ }; -+ let (tx, rx) = mpsc::sync_channel::(512); -+ if UNICODE_TX.set(tx).is_err() { -+ return; -+ } -+ let _ = std::thread::Builder::new() -+ .name("reims-vgpu.ime".into()) -+ .spawn(move || forward_unicode_loop(rx, addr, path, token)); -+ // SAFETY: called on SDL's UI thread right after SDL_Init(SDL_INIT_VIDEO). -+ unsafe { SDL_SetWindowsMessageHook(Some(unicode_message_hook), null_mut()) }; -+} -+ -+/// Enqueues a UTF-16 code unit without blocking the Win32 message loop. -+fn enqueue_utf16(unit: u16) { -+ if unit != 0 -+ && let Some(tx) = UNICODE_TX.get() -+ { -+ let _ = tx.try_send(unit); -+ } -+} -+ -+/// SDL Win32 message hook: forwards non-physical WM_CHAR / WM_UNICHAR / WM_IME_CHAR -+/// events to the local input bridge while leaving all physical keyboard events untouched. -+unsafe extern "C" fn unicode_message_hook(_userdata: *mut c_void, raw_msg: *mut SDL_MSG) -> bool { -+ if raw_msg.is_null() { -+ return true; -+ } -+ // SAFETY: SDL passes a valid pointer to Win32 MSG for the duration of the callback. -+ let msg = unsafe { &*raw_msg.cast::() }; -+ match msg.message { -+ WM_KEYDOWN | WM_SYSKEYDOWN => { -+ let vk = (msg.w_param & 0xFFFF) as u16; -+ LAST_KEY_UNMAPPED.set(vk == VK_PACKET || vk == VK_PROCESSKEY); -+ true -+ } -+ WM_CHAR => { -+ let unit = (msg.w_param & 0xFFFF) as u16; -+ let scan_code = (msg.l_param.cast_unsigned() >> 16) & 0xFF; -+ // Any WM_CHAR carrying a hardware scan code came from TranslateMessage on -+ // a physical WM_KEYDOWN that SDL already forwarded as a USB HID key. -+ // Never compare msg.time against WM_KEYDOWN.time: TranslateMessage stamps -+ // WM_CHAR with the current GetTickCount(), not the keydown's time. -+ let non_physical = scan_code == 0 -+ && (LAST_KEY_UNMAPPED.get() || unit >= 0x80 || msg.l_param == 0); -+ if non_physical && (unit >= 0x20 || unit == 0x0D || unit == 0x09) { -+ enqueue_utf16(unit); -+ return false; -+ } -+ true -+ } -+ WM_IME_CHAR => { -+ let unit = (msg.w_param & 0xFFFF) as u16; -+ if unit >= 0x20 || unit == 0x0D || unit == 0x09 { -+ enqueue_utf16(unit); -+ return false; -+ } -+ true -+ } -+ WM_UNICHAR => { -+ if msg.w_param != UNICODE_NOCHAR -+ && let Ok(code) = u32::try_from(msg.w_param) -+ && let Some(ch) = char::from_u32(code) -+ && (ch >= ' ' || ch == '\r' || ch == '\t') -+ { -+ let mut pair = [0u16; 2]; -+ for &mut u in ch.encode_utf16(&mut pair) { -+ enqueue_utf16(u); -+ } -+ return false; -+ } -+ true -+ } -+ _ => true, -+ } -+} -+ -+/// Decodes UTF-16 code units, coalesces bursts, and POSTs UTF-8 text to the loopback bridge. -+fn forward_unicode_loop(rx: mpsc::Receiver, addr: SocketAddr, path: String, token: String) { -+ let mut units: Vec = 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 diff --git a/patches/series.txt b/patches/series.txt index 0b43011..5946bfe 100644 --- a/patches/series.txt +++ b/patches/series.txt @@ -1,19 +1,8 @@ # Patch queue, in the order the patches are applied (see patches/README.md). # One patch per line: . -# Targets are "reims-vgpu", "vendor/qemu", "reims-util", and "metal2vulkan". +# The runtime forks contain the Reims vGPU and QEMU changes. +# This queue applies additional patches to their pinned dependencies. # CI (build-runtime.yml via scripts/apply-patch-series.ps1) and # scripts/pack-runtime.ps1 both read this file; add or retire patches here. -reims-vgpu reims-vgpu-win32-unicode-input.patch -reims-vgpu reims-vgpu-display-fixed-mode.patch -reims-vgpu reims-ctl-win32-random-bytes.patch -reims-vgpu reims-ctl-virtio-discard-iothread.patch -reims-vgpu reims-ctl-qcow2-l2-cache.patch -reims-vgpu reims-vgpu-snapshot-replay.patch reims-util reims-util-parallel-offline-download.patch metal2vulkan metal2vulkan-snapshot-replay.patch -vendor/qemu qemu-whpx-win10-compat.patch -vendor/qemu qemu-whpx-win10-startup-ipis.patch -vendor/qemu qemu-whpx-nested-virt-nonfatal.patch -vendor/qemu qemu-win32-coroutine-fiber-commit.patch -vendor/qemu qemu-win32-mapped-ram-io.patch -vendor/qemu qemu-intel-whpx-suspend.patch diff --git a/scripts/check-runtime-alpha.ps1 b/scripts/check-runtime-alpha.ps1 index 9900001..fcf5ab6 100644 --- a/scripts/check-runtime-alpha.ps1 +++ b/scripts/check-runtime-alpha.ps1 @@ -26,6 +26,7 @@ param( [Parameter(Mandatory = $true)] [string]$Zstd, [string[]]$AppliedPatches = @(), + [string]$RequiredCapability = '', [switch]$RequireSlim, # Only for checking packages built before the 2026-11-28 rename ("candidate"). [string]$ExpectChannel = 'alpha', @@ -84,6 +85,7 @@ try { if ($m.commit -ne $Commit) { throw "manifest commit is $($m.commit), expected $Commit" } if ($m.channel -ne $ExpectChannel) { throw "manifest channel is $($m.channel), expected $ExpectChannel" } if ($m.source_package -ne $names.source) { throw "manifest source_package is $($m.source_package), expected $($names.source)" } + if ($RequiredCapability -and $RequiredCapability -notin $m.capabilities) { throw "manifest lacks capability $RequiredCapability" } $files = @(Get-ChildItem -LiteralPath $root -Recurse -File) if ($m.file_count -ne $files.Count) { throw "manifest file_count is $($m.file_count), actual $($files.Count)" } $rawBytes = [int64](($files | Measure-Object Length -Sum).Sum) diff --git a/scripts/pack-runtime.ps1 b/scripts/pack-runtime.ps1 index 1294bb7..9d22d18 100644 --- a/scripts/pack-runtime.ps1 +++ b/scripts/pack-runtime.ps1 @@ -29,7 +29,7 @@ .EXAMPLE pwsh -File scripts/pack-runtime.ps1 -Channel alpha - pwsh -File scripts/pack-runtime.ps1 -Patches reims-vgpu-snapshot-replay.patch,metal2vulkan-snapshot-replay.patch,qemu-whpx-win10-compat.patch + pwsh -File scripts/pack-runtime.ps1 -Patches reims-util-parallel-offline-download.patch,metal2vulkan-snapshot-replay.patch #> [CmdletBinding(PositionalBinding = $false)] param( @@ -111,6 +111,13 @@ function New-TarZst([string]$parent, [string]$name, [string]$archive) { } # ── 1. Inputs and provenance ───────────────────────────────── +function Get-GitHubSource([string]$Url, [string]$Fallback) { + if ($Url -match '^(?:https://(?:[^/@]+@)?github\.com/|git@github\.com:)([\w.-]+/[\w.-]+?)(?:\.git)?/?$') { + return "https://github.com/$($Matches[1])" + } + return "https://github.com/$Fallback" +} + $ctlExe = Join-Path $CargoBin 'reims-ctl.exe' $utilExe = Join-Path $CargoBin 'reims-util.exe' $qemuExe = Join-Path $QemuDir 'bin\qemu-system-x86_64.exe' @@ -123,6 +130,15 @@ $fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim() $id = if ($ReleaseId -and $ReleaseId.Trim()) { $ReleaseId.Trim() } else { $commit } $qemuRepo = Join-Path $ReimsRepo 'vendor\qemu' $qemuCommit = (git -C $qemuRepo rev-parse HEAD).Trim() +$reimsOrigin = git -C $ReimsRepo config --get remote.origin.url 2>$null +$qemuOrigin = git -C $ReimsRepo config --file .gitmodules --get submodule.vendor/qemu.url +$reimsSource = Get-GitHubSource $reimsOrigin 'steelbrain/reims-vgpu' +$qemuSource = Get-GitHubSource $qemuOrigin 'steelbrain/qemu-reims-vgpu' +$capabilities = @() +$runtimeFeatures = Join-Path $ReimsRepo 'reims-go-runtime.json' +if (Test-Path -LiteralPath $runtimeFeatures) { + $capabilities = @((Get-Content -Raw -LiteralPath $runtimeFeatures | ConvertFrom-Json).capabilities) +} # reims-util's pinned commit is a constant in reims-ctl (crates/reims-ctl/src/reims_util.rs, REV). $utilSrc = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'crates\reims-ctl\src\reims_util.rs') @@ -480,15 +496,15 @@ Write-Utf8 "$srcDir\README.md" @" Corresponding source for the binaries in ``$bundleName.tar.zst``. -| Directory | Upstream | Commit | +| Directory | Source repository | Commit | | :-- | :-- | :-- | -| ``reims-vgpu-$commit/`` | https://github.com/steelbrain/reims-vgpu | ``$fullCommit`` | -| ``reims-vgpu-$commit/vendor/qemu/`` | https://github.com/steelbrain/qemu-reims-vgpu | ``$qemuCommit`` | +| ``reims-vgpu-$commit/`` | $reimsSource | ``$fullCommit`` | +| ``reims-vgpu-$commit/vendor/qemu/`` | $qemuSource | ``$qemuCommit`` | | ``reims-util-$($utilCommit.Substring(0, 7))/`` | https://github.com/steelbrain/reims-util | ``$utilCommit`` | | ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | https://github.com/steelbrain/metal2vulkan | ``$m2vCommit`` | -The trees are pristine upstream. The binaries were built after applying the -patches in ``patches/``: +The archive exports the commits above. Apply the patches in ``patches/`` +before compiling: cd reims-vgpu-$commit $((($patchSpecs | Where-Object { $_.Target -eq 'reims-vgpu' } | ForEach-Object { " git apply ../patches/$($_.Name)" }) -join "`n")) @@ -513,13 +529,15 @@ $manifest = [ordered]@{ schema_version = 2 name = $bundleName platform = 'windows-x86_64' - upstream_repo = 'https://github.com/steelbrain/reims-vgpu' + upstream_repo = $reimsSource commit = $id full_commit = $fullCommit + vendor_qemu_repo = $qemuSource vendor_qemu_commit = $qemuCommit util_commit = $utilCommit metal2vulkan_commit = $m2vCommit patches = $patchEntries + capabilities = $capabilities channel = $Channel source_package = "$srcName.tar.zst" symbols_package = "$symbolsName.tar.zst" From 4a2bffd5d2320d61a879d1eeeae801b101c492d3 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 10:55:06 +0800 Subject: [PATCH 15/23] ci: publish runtime previews from the runtime fork --- .github/workflows/build-runtime.yml | 98 +++++++---------------------- AGENTS.md | 2 +- docs/portable-runtime-spec.md | 8 +-- internal/runtime/remote.go | 70 ++++++++++++++------- internal/runtime/remote_test.go | 53 ++++++++++++++++ patches/README.md | 4 +- 6 files changed, 132 insertions(+), 103 deletions(-) diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 7721a94..f15d08c 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -1,12 +1,19 @@ name: Build Portable Runtime (Alpha) -# Daily: build the newest runtime fork commit with the dependency patch queue -# (patches/series.txt) and publish it as a GitHub prerelease = the alpha -# channel (portable-runtime-spec.md section 6). Never publishes stable: -# promotion needs a real-host smoke test and a person (AGENTS.md rule 6). +# The runtime fork calls this workflow to build and publish previews. +# A manual run in Reims-Go builds artifacts for verification. on: - schedule: - - cron: "23 3 * * *" # 03:23 UTC daily; skipped when upstream has not moved + workflow_call: + inputs: + upstream_commit: + type: string + default: "" + publish: + type: boolean + default: false + rebuild: + type: boolean + default: false workflow_dispatch: inputs: upstream_commit: @@ -14,17 +21,16 @@ on: required: false default: "" publish: - description: "Publish as an alpha prerelease (never stable)" + description: "Publish a preview when run in the runtime fork" type: boolean - default: true + default: false rebuild: description: "Build a new patch revision (runtime--pN) even if this upstream commit is already released" type: boolean default: false permissions: - contents: write - issues: write + contents: read concurrency: group: build-runtime @@ -33,7 +39,6 @@ concurrency: env: UPSTREAM_URL: https://github.com/yxc0915/reims-vgpu.git UPSTREAM_BRANCH: codex/intel-vm-suspend - KEEP_ALPHAS: "7" # unpromoted alpha prereleases kept; older ones are deleted jobs: resolve: @@ -92,14 +97,14 @@ jobs: if: needs.resolve.outputs.skip != 'true' runs-on: windows-latest timeout-minutes: 150 - outputs: - short: ${{ steps.patches.outputs.short }} - release_id: ${{ steps.patches.outputs.release_id }} - applied: ${{ steps.patches.outputs.applied }} - merged: ${{ steps.patches.outputs.merged }} - conflict: ${{ steps.patches.outputs.conflict }} + permissions: + contents: write steps: - uses: actions/checkout@v4 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + persist-credentials: false - name: Setup MSYS2 CLANG64 id: msys2 @@ -161,8 +166,6 @@ jobs: if ($LASTEXITCODE) { throw 'metal2vulkan checkout failed' } $short = (git -C $work rev-parse --short=7 HEAD).Trim() $releaseId = "$short${{ needs.resolve.outputs.suffix }}" - "short=$short" >> $env:GITHUB_OUTPUT - "release_id=$releaseId" >> $env:GITHUB_OUTPUT # Applies what applies, skips what upstream already has, stops on a # conflict without touching the patch (AGENTS.md rule 4). @@ -173,9 +176,7 @@ jobs: } finally { if (Test-Path $resultFile) { $r = Get-Content -Raw $resultFile | ConvertFrom-Json - "applied=$(@($r.applied) -join ',')" >> $env:GITHUB_OUTPUT "merged=$(@($r.merged) -join ',')" >> $env:GITHUB_OUTPUT - "conflict=$($r.conflict)" >> $env:GITHUB_OUTPUT "APPLIED_PATCHES=$(@($r.applied) -join ',')" >> $env:GITHUB_ENV } } @@ -256,7 +257,7 @@ jobs: retention-days: 14 - name: Publish alpha prerelease (never stable) - if: github.event_name == 'schedule' || inputs.publish + if: github.repository == 'yxc0915/reims-vgpu' && inputs.publish env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} MERGED: ${{ steps.patches.outputs.merged }} @@ -283,56 +284,5 @@ jobs: Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID "@ - gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes + gh release create "runtime-$c" @assets --repo $env:GITHUB_REPOSITORY --target '${{ needs.resolve.outputs.commit }}' --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" } - - - name: Prune old alpha prereleases - if: github.event_name == 'schedule' || inputs.publish - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - shell: pwsh - run: | - # Only unpromoted runtime prereleases; stable releases are never touched. - $alphas = gh release list -R $env:GITHUB_REPOSITORY --limit 1000 --json tagName,isPrerelease,isDraft,createdAt | ConvertFrom-Json | - Where-Object { $_.tagName -like 'runtime-*' -and $_.isPrerelease -and -not $_.isDraft } | - Sort-Object createdAt -Descending - $alphas | Select-Object -Skip ([int]$env:KEEP_ALPHAS) | ForEach-Object { - Write-Host "Deleting old alpha $($_.tagName)" - gh release delete $_.tagName -R $env:GITHUB_REPOSITORY --yes --cleanup-tag - } - - report: - needs: [resolve, build] - if: always() && needs.resolve.outputs.skip != 'true' && (failure() || needs.build.outputs.merged != '') - runs-on: ubuntu-latest - steps: - - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - RESULT: ${{ needs.build.result }} - COMMIT: ${{ needs.resolve.outputs.commit }} - CONFLICT: ${{ needs.build.outputs.conflict }} - MERGED: ${{ needs.build.outputs.merged }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: | - set -euo pipefail - # One open issue per kind; later runs add a comment instead of a new issue. - file_issue() { - local title="$1" body="$2" n - n="$(gh issue list -R "$GITHUB_REPOSITORY" --state open --search "in:title \"$title\"" --json number,title -q ".[] | select(.title == \"$title\") | .number" | head -n1)" - if [ -n "$n" ]; then - gh issue comment "$n" -R "$GITHUB_REPOSITORY" --body "$body" - else - gh issue create -R "$GITHUB_REPOSITORY" --title "$title" --body "$body" - fi - } - if [ "$RESULT" != "success" ]; then - if [ -n "$CONFLICT" ]; then - why="Patch \`$CONFLICT\` neither applies to upstream \`$COMMIT\` nor is already there. Per AGENTS.md rule 4 the patch was not edited; a person decides how to rebase or retire it." - else - why="The build, packaging or alpha gate failed for upstream \`$COMMIT\`; see the log." - fi - file_issue "Runtime alpha build failed" "$why"$'\n\n'"Run: $RUN_URL"$'\n\n'"No alpha was published." - fi - if [ -n "$MERGED" ]; then - file_issue "Patch queue: patches already upstream" "Upstream \`$COMMIT\` already contains: \`$MERGED\`. They were skipped. Record the merge commit in portable-runtime-spec.md section 5, then remove them from patches/ and patches/series.txt."$'\n\n'"Run: $RUN_URL" - fi diff --git a/AGENTS.md b/AGENTS.md index 1047b63..5a2953c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,7 @@ ## 事实核验与安全规则 1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时核对对应上游 commit 与 `文件:行号`;未实测项显式标注「待验证」。 -2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:[`.github/workflows/build-runtime.yml`](.github/workflows/build-runtime.yml) 每日从上游构建,通过 `alpha` 准入检查后自动发布为 GitHub 预发布(`alpha` 通道),并自动清理较旧的未升级 `alpha` 预发布。 +2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:Reims vGPU fork 的 Preview 工作流每天构建,通过 `alpha` 准入检查后在运行时仓库发布 GitHub 预发布。 3. **敏感与专有内容零入库**:严禁提交 SMC OSK、SMBIOS 真实序列号、MAC 地址、任何 Apple IPSW / BaseSystem / 解密固件或闭源二进制。 4. **运行时源码与依赖补丁**:Reims vGPU 和 QEMU 的源码修改由各自运行时 fork 维护。客户端构建使用 [`patches/series.txt`](patches/series.txt) 应用其余依赖补丁。源码入口、顺序与状态见 [`patches/README.md`](patches/README.md)。补丁打不上就停下报告,不要自动改写补丁。 5. **运行时包如实声明来源**:`manifest.json` 必须写清上游各仓库 commit 与实际应用的全部补丁;带补丁的包不得宣称为纯上游构建。 diff --git a/docs/portable-runtime-spec.md b/docs/portable-runtime-spec.md index 1cd4a3b..ed3e8cc 100644 --- a/docs/portable-runtime-spec.md +++ b/docs/portable-runtime-spec.md @@ -84,17 +84,17 @@ reims-runtime-/ 打包前脚本会核对构建目录的 `git diff` 是否与声明的补丁逐字节一致;存在未声明修改或补丁不匹配时立即停止。 ### 3.2 每日 CI 构建 -[`.github/workflows/build-runtime.yml`](../.github/workflows/build-runtime.yml) 每日定时(也支持手动指定 commit)在 `windows-latest`(MSYS2 CLANG64)执行: +Reims vGPU fork 的 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 每日调用 [Reims-Go 的运行时构建工作流](../.github/workflows/build-runtime.yml),也支持手动指定提交。在 `windows-latest`(MSYS2 CLANG64)执行以下步骤。 1. 读取 Reims vGPU fork 的运行时分支,并检出其中固定的 QEMU fork 提交。若该 Reims vGPU 提交已有运行时 Release,则跳过。 2. 按 [`patches/series.txt`](../patches/series.txt) 顺序为固定的依赖版本应用补丁。已合入上游的补丁会跳过并报告,遇到冲突时中止构建。 3. 执行上游 `scripts/install-ctl.sh --yes` 编译,调用 `scripts/pack-runtime.ps1 -Channel alpha` 打包。 4. 运行 [`scripts/check-runtime-alpha.ps1`](../scripts/check-runtime-alpha.ps1) 校验附件哈希、许可证、挂起能力声明,以及在不含 MSYS2 的 `PATH` 下验证 vGPU 设备枚举、CLI 版本和 `qcow2` 创建读取。 -5. 通过后发布为 GitHub 预发布(`alpha`),并自动清理超过保留上限(最近 7 个)的旧 `alpha` 预发布;正式版不受影响。 +5. 通过后在 Reims vGPU fork 的 Releases 发布 Preview,标记为 GitHub 预发布(`alpha`)。从 Reims-Go 仓库发起的手动构建提供 CI 产物供验证。 > **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。 ### 3.3 客户端下载与安装 -`internal/runtime` 默认从 GitHub Releases(tag `runtime-`)拉取,沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。 +`internal/runtime` 从 GitHub Releases 查找 `runtime-`。正式运行时来自 `Nwflower/Reims-Go`,开启内核 Alpha 后同时列出 `yxc0915/reims-vgpu` 的 Preview。下载沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。 --- @@ -118,7 +118,7 @@ Reims vGPU 和 QEMU 的修改由各自的运行时 fork 维护。客户端仓库 | **`stable`** | 正式发布(Release) | 从 `alpha` 晋升:在真实 Windows 10/11 宿主运行 [`scripts/smoke-runtime.ps1`](../scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 | - 客户端默认仅获取 `stable` 通道;`alpha` 需用户在界面开启「接收 Alpha 版」或在 CLI 传入 `--alpha`。 -- 晋升 `stable` 不重新打包,仅将既有 GitHub 预发布转为正式发布,确保用户下载的二进制与冒烟验证的资产完全一致(因此包内 `manifest.json` 的构建通道字段保持 `alpha`,客户端以 Release 状态区分通道)。 +- 晋升 `stable` 时,在 `Nwflower/Reims-Go` 正式 Release 分发已通过冒烟的原始资产及同一份校验清单。客户端以 Release 状态区分通道,包内 `manifest.json` 保留构建时的 `alpha` 标记。 --- diff --git a/internal/runtime/remote.go b/internal/runtime/remote.go index 144004e..964add3 100644 --- a/internal/runtime/remote.go +++ b/internal/runtime/remote.go @@ -1,8 +1,7 @@ package runtime -// Online install: runtime packages are GitHub Release assets of the reims-go -// repository (decided 2026-11-28, AGENTS.md). A runtime release is tagged -// "runtime-" and carries: +// Online install lists stable packages from Reims-Go and alpha packages from +// the Reims vGPU fork. A runtime release is tagged "runtime-" and carries: // // reims-runtime-win-x64-.tar.zst // reims-runtime-src-.tar.zst (matching sources, spec §7) @@ -34,11 +33,12 @@ import ( ) const ( - DefaultReleasesRepo = "Nwflower/reims-go" - DefaultAPIBase = "https://api.github.com" - DefaultWebBase = "https://github.com" - runtimeTagPrefix = "runtime-" - sumsAsset = fetch.SumsAsset + DefaultReleasesRepo = "Nwflower/reims-go" + DefaultAlphaReleasesRepo = "yxc0915/reims-vgpu" + DefaultAPIBase = "https://api.github.com" + DefaultWebBase = "https://github.com" + runtimeTagPrefix = "runtime-" + sumsAsset = fetch.SumsAsset ) var errRateLimited = errors.New("GitHub API rate limit reached") @@ -67,27 +67,31 @@ func NormalizeChannel(s string) string { // app releases and (until pruned) daily alpha runtimes. const maxReleasePages = 10 -// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO overrides -// the repository (for forks and testing). +// Source lists runtime releases. If AlphaRepo is set, it supplies the previews +// and Repo supplies the stable releases. REIMS_GO_RELEASES_REPO uses one repo +// for both channels (for forks and testing). type Source struct { - APIBase string - WebBase string - Repo string - Client *http.Client + APIBase string + WebBase string + Repo string + AlphaRepo string + Client *http.Client } // DefaultSource returns the default GitHub runtime source. func DefaultSource() Source { - repo := os.Getenv("REIMS_GO_RELEASES_REPO") - if repo == "" { - repo = DefaultReleasesRepo + s := Source{ + APIBase: DefaultAPIBase, + WebBase: DefaultWebBase, + Repo: DefaultReleasesRepo, + AlphaRepo: DefaultAlphaReleasesRepo, + Client: netproxy.NewClient(), } - return Source{ - APIBase: DefaultAPIBase, - WebBase: DefaultWebBase, - Repo: repo, - Client: netproxy.NewClient(), + if repo := os.Getenv("REIMS_GO_RELEASES_REPO"); repo != "" { + s.Repo = repo + s.AlphaRepo = "" } + return s } // Remote is a runtime package published as a release. @@ -156,6 +160,28 @@ func (s Source) webBase() string { // ListRemote lists published runtime packages, newest first. Alpha runtimes // are included only when includeAlpha is set. func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) { + if !includeAlpha || s.AlphaRepo == "" { + return s.listRemote(ctx, includeAlpha) + } + stable, err := s.listRemote(ctx, false) + if err != nil { + return nil, err + } + s.Repo = s.AlphaRepo + previews, err := s.listRemote(ctx, true) + if err != nil { + return nil, err + } + for _, r := range previews { + if r.Channel == ChannelAlpha { + stable = append(stable, r) + } + } + sortRemotesNewestFirst(stable) + return stable, nil +} + +func (s Source) listRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) { base := strings.TrimRight(s.APIBase, "/") url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", base, s.Repo) var rels []ghRelease diff --git a/internal/runtime/remote_test.go b/internal/runtime/remote_test.go index 922fd74..69fe7ff 100644 --- a/internal/runtime/remote_test.go +++ b/internal/runtime/remote_test.go @@ -5,12 +5,14 @@ import ( "context" "crypto/sha256" "encoding/hex" + "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "strings" + "sync/atomic" "testing" "time" ) @@ -93,6 +95,57 @@ func TestListRemoteFiltersChannelsAndIncompleteReleases(t *testing.T) { } } +func TestDefaultSourceListsPreviewsFromRuntimeFork(t *testing.T) { + t.Setenv("REIMS_GO_RELEASES_REPO", "") + release := func(commit, date string, alpha bool) ghRelease { + return ghRelease{ + TagName: "runtime-" + commit, PublishedAt: date, Prerelease: alpha, + Assets: []ghAsset{ + {Name: "reims-runtime-win-x64-" + commit + ".tar.zst", URL: "archive"}, + {Name: "reims-runtime-src-" + commit + ".tar.zst", URL: "source"}, + {Name: sumsAsset, URL: "sums"}, + }, + } + } + var previewRequests atomic.Int32 + mux := http.NewServeMux() + mux.HandleFunc("/repos/"+DefaultReleasesRepo+"/releases", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode([]ghRelease{ + release("official-stable", "2026-11-30T00:00:00Z", false), + release("old-alpha", "2026-11-30T12:00:00Z", true), + }) + }) + mux.HandleFunc("/repos/"+DefaultAlphaReleasesRepo+"/releases", func(w http.ResponseWriter, _ *http.Request) { + previewRequests.Add(1) + _ = json.NewEncoder(w).Encode([]ghRelease{ + release("fork-preview", "2026-12-01T00:00:00Z", true), + release("fork-stable", "2026-12-01T01:00:00Z", false), + }) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + src := DefaultSource() + src.APIBase, src.Client = srv.URL, srv.Client() + + stable, err := src.ListRemote(context.Background(), false) + if err != nil || len(stable) != 1 || stable[0].Commit != "official-stable" || previewRequests.Load() != 0 { + t.Fatalf("stable list = %+v, %v, preview requests = %d", stable, err, previewRequests.Load()) + } + all, err := src.ListRemote(context.Background(), true) + if err != nil || len(all) != 2 || all[0].Commit != "fork-preview" || all[0].Channel != ChannelAlpha || + all[1].Commit != "official-stable" || previewRequests.Load() != 1 { + t.Fatalf("alpha list = %+v, %v, preview requests = %d", all, err, previewRequests.Load()) + } + + t.Setenv("REIMS_GO_RELEASES_REPO", DefaultReleasesRepo) + override := DefaultSource() + override.APIBase, override.Client = srv.URL, srv.Client() + all, err = override.ListRemote(context.Background(), true) + if err != nil || len(all) != 2 || all[0].Commit != "old-alpha" || previewRequests.Load() != 1 { + t.Fatalf("override list = %+v, %v, preview requests = %d", all, err, previewRequests.Load()) + } +} + func TestDownloadResumesAndVerifies(t *testing.T) { g := newFakeGitHub(t) src := g.source() diff --git a/patches/README.md b/patches/README.md index cc09515..c6710fa 100644 --- a/patches/README.md +++ b/patches/README.md @@ -40,8 +40,8 @@ Reims vGPU 分支通过 `vendor/qemu` 固定 QEMU 提交,并在 `reims-go-runt ## 补丁退役检查表 -当上游合入等价修复(每日构建会自动跳过该补丁并开 Issue 提醒)后,按以下步骤清理: +每日构建会跳过已合入的等价补丁,并在日志中报告。确认后按以下步骤清理。 1. 删除 `patches/` 下对应的 `.patch` 文件,并同步更新 [`series.txt`](series.txt) 与本文件。 -2. 等待次日定时构建或手动触发 [`.github/workflows/build-runtime.yml`](../.github/workflows/build-runtime.yml) 产出新的 `alpha` 运行时。 +2. 等待下一次定时构建,或在 Reims vGPU fork 手动触发 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml)。 3. 在真实宿主运行 [`scripts/smoke-runtime.ps1`](../scripts/smoke-runtime.ps1) 完成冒烟并人工确认后,将对应 Release 升级为 `stable`。 From 43d793ec3683c6e89e01cdeb444cf9167a477ec0 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 10:57:38 +0800 Subject: [PATCH 16/23] runtime: show promoted previews only once --- internal/runtime/remote.go | 6 +++++- internal/runtime/remote_test.go | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/internal/runtime/remote.go b/internal/runtime/remote.go index 964add3..1d90486 100644 --- a/internal/runtime/remote.go +++ b/internal/runtime/remote.go @@ -172,8 +172,12 @@ func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, er if err != nil { return nil, err } + stableCommits := make(map[string]bool, len(stable)) + for _, r := range stable { + stableCommits[r.Commit] = true + } for _, r := range previews { - if r.Channel == ChannelAlpha { + if r.Channel == ChannelAlpha && !stableCommits[r.Commit] { stable = append(stable, r) } } diff --git a/internal/runtime/remote_test.go b/internal/runtime/remote_test.go index 69fe7ff..4e06e27 100644 --- a/internal/runtime/remote_test.go +++ b/internal/runtime/remote_test.go @@ -120,6 +120,7 @@ func TestDefaultSourceListsPreviewsFromRuntimeFork(t *testing.T) { _ = json.NewEncoder(w).Encode([]ghRelease{ release("fork-preview", "2026-12-01T00:00:00Z", true), release("fork-stable", "2026-12-01T01:00:00Z", false), + release("official-stable", "2026-12-01T02:00:00Z", true), }) }) srv := httptest.NewServer(mux) From 5f96f4ab089f653bbb72db3fdadf639fb964d4f5 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 11:05:44 +0800 Subject: [PATCH 17/23] runtime: use the fork catalog for stable and preview releases --- docs/portable-runtime-spec.md | 4 +- internal/runtime/remote.go | 74 ++++++++++----------------------- internal/runtime/remote_test.go | 65 +++++------------------------ 3 files changed, 35 insertions(+), 108 deletions(-) diff --git a/docs/portable-runtime-spec.md b/docs/portable-runtime-spec.md index ed3e8cc..e0fa2bc 100644 --- a/docs/portable-runtime-spec.md +++ b/docs/portable-runtime-spec.md @@ -94,7 +94,7 @@ Reims vGPU fork 的 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/bl > **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。 ### 3.3 客户端下载与安装 -`internal/runtime` 从 GitHub Releases 查找 `runtime-`。正式运行时来自 `Nwflower/Reims-Go`,开启内核 Alpha 后同时列出 `yxc0915/reims-vgpu` 的 Preview。下载沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。 +`internal/runtime` 从 `yxc0915/reims-vgpu` 的 GitHub Releases 查找 `runtime-`。默认列出正式运行时,开启内核 Alpha 后同时列出 Preview。下载沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。 --- @@ -118,7 +118,7 @@ Reims vGPU 和 QEMU 的修改由各自的运行时 fork 维护。客户端仓库 | **`stable`** | 正式发布(Release) | 从 `alpha` 晋升:在真实 Windows 10/11 宿主运行 [`scripts/smoke-runtime.ps1`](../scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 | - 客户端默认仅获取 `stable` 通道;`alpha` 需用户在界面开启「接收 Alpha 版」或在 CLI 传入 `--alpha`。 -- 晋升 `stable` 时,在 `Nwflower/Reims-Go` 正式 Release 分发已通过冒烟的原始资产及同一份校验清单。客户端以 Release 状态区分通道,包内 `manifest.json` 保留构建时的 `alpha` 标记。 +- 晋升 `stable` 时,在运行时仓库将已通过冒烟的 Preview 改为正式 Release,并移除标题中的 Alpha 标记。保留原资产、校验清单和 `manifest.json` 的构建通道。 --- diff --git a/internal/runtime/remote.go b/internal/runtime/remote.go index 1d90486..271cded 100644 --- a/internal/runtime/remote.go +++ b/internal/runtime/remote.go @@ -1,7 +1,8 @@ package runtime -// Online install lists stable packages from Reims-Go and alpha packages from -// the Reims vGPU fork. A runtime release is tagged "runtime-" and carries: +// Online install reads runtime packages from the Reims vGPU fork's GitHub +// Releases. A runtime release is tagged +// "runtime-" and carries: // // reims-runtime-win-x64-.tar.zst // reims-runtime-src-.tar.zst (matching sources, spec §7) @@ -33,12 +34,11 @@ import ( ) const ( - DefaultReleasesRepo = "Nwflower/reims-go" - DefaultAlphaReleasesRepo = "yxc0915/reims-vgpu" - DefaultAPIBase = "https://api.github.com" - DefaultWebBase = "https://github.com" - runtimeTagPrefix = "runtime-" - sumsAsset = fetch.SumsAsset + DefaultReleasesRepo = "yxc0915/reims-vgpu" + DefaultAPIBase = "https://api.github.com" + DefaultWebBase = "https://github.com" + runtimeTagPrefix = "runtime-" + sumsAsset = fetch.SumsAsset ) var errRateLimited = errors.New("GitHub API rate limit reached") @@ -67,31 +67,27 @@ func NormalizeChannel(s string) string { // app releases and (until pruned) daily alpha runtimes. const maxReleasePages = 10 -// Source lists runtime releases. If AlphaRepo is set, it supplies the previews -// and Repo supplies the stable releases. REIMS_GO_RELEASES_REPO uses one repo -// for both channels (for forks and testing). +// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO overrides +// the repository (for forks and testing). type Source struct { - APIBase string - WebBase string - Repo string - AlphaRepo string - Client *http.Client + APIBase string + WebBase string + Repo string + Client *http.Client } // DefaultSource returns the default GitHub runtime source. func DefaultSource() Source { - s := Source{ - APIBase: DefaultAPIBase, - WebBase: DefaultWebBase, - Repo: DefaultReleasesRepo, - AlphaRepo: DefaultAlphaReleasesRepo, - Client: netproxy.NewClient(), + repo := os.Getenv("REIMS_GO_RELEASES_REPO") + if repo == "" { + repo = DefaultReleasesRepo } - if repo := os.Getenv("REIMS_GO_RELEASES_REPO"); repo != "" { - s.Repo = repo - s.AlphaRepo = "" + return Source{ + APIBase: DefaultAPIBase, + WebBase: DefaultWebBase, + Repo: repo, + Client: netproxy.NewClient(), } - return s } // Remote is a runtime package published as a release. @@ -160,32 +156,6 @@ func (s Source) webBase() string { // ListRemote lists published runtime packages, newest first. Alpha runtimes // are included only when includeAlpha is set. func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) { - if !includeAlpha || s.AlphaRepo == "" { - return s.listRemote(ctx, includeAlpha) - } - stable, err := s.listRemote(ctx, false) - if err != nil { - return nil, err - } - s.Repo = s.AlphaRepo - previews, err := s.listRemote(ctx, true) - if err != nil { - return nil, err - } - stableCommits := make(map[string]bool, len(stable)) - for _, r := range stable { - stableCommits[r.Commit] = true - } - for _, r := range previews { - if r.Channel == ChannelAlpha && !stableCommits[r.Commit] { - stable = append(stable, r) - } - } - sortRemotesNewestFirst(stable) - return stable, nil -} - -func (s Source) listRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) { base := strings.TrimRight(s.APIBase, "/") url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", base, s.Repo) var rels []ghRelease diff --git a/internal/runtime/remote_test.go b/internal/runtime/remote_test.go index 4e06e27..f6f621d 100644 --- a/internal/runtime/remote_test.go +++ b/internal/runtime/remote_test.go @@ -5,14 +5,12 @@ import ( "context" "crypto/sha256" "encoding/hex" - "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "strings" - "sync/atomic" "testing" "time" ) @@ -68,6 +66,17 @@ func (g *fakeGitHub) source() Source { return Source{APIBase: g.srv.URL, Repo: "o/r", Client: g.srv.Client()} } +func TestDefaultSourceUsesRuntimeFork(t *testing.T) { + t.Setenv("REIMS_GO_RELEASES_REPO", "") + if got := DefaultSource().Repo; got != "yxc0915/reims-vgpu" { + t.Fatalf("default runtime repository = %q", got) + } + t.Setenv("REIMS_GO_RELEASES_REPO", "example/runtime") + if got := DefaultSource().Repo; got != "example/runtime" { + t.Fatalf("overridden runtime repository = %q", got) + } +} + func TestListRemoteFiltersChannelsAndIncompleteReleases(t *testing.T) { g := newFakeGitHub(t) stable, err := g.source().ListRemote(context.Background(), false) @@ -95,58 +104,6 @@ func TestListRemoteFiltersChannelsAndIncompleteReleases(t *testing.T) { } } -func TestDefaultSourceListsPreviewsFromRuntimeFork(t *testing.T) { - t.Setenv("REIMS_GO_RELEASES_REPO", "") - release := func(commit, date string, alpha bool) ghRelease { - return ghRelease{ - TagName: "runtime-" + commit, PublishedAt: date, Prerelease: alpha, - Assets: []ghAsset{ - {Name: "reims-runtime-win-x64-" + commit + ".tar.zst", URL: "archive"}, - {Name: "reims-runtime-src-" + commit + ".tar.zst", URL: "source"}, - {Name: sumsAsset, URL: "sums"}, - }, - } - } - var previewRequests atomic.Int32 - mux := http.NewServeMux() - mux.HandleFunc("/repos/"+DefaultReleasesRepo+"/releases", func(w http.ResponseWriter, _ *http.Request) { - _ = json.NewEncoder(w).Encode([]ghRelease{ - release("official-stable", "2026-11-30T00:00:00Z", false), - release("old-alpha", "2026-11-30T12:00:00Z", true), - }) - }) - mux.HandleFunc("/repos/"+DefaultAlphaReleasesRepo+"/releases", func(w http.ResponseWriter, _ *http.Request) { - previewRequests.Add(1) - _ = json.NewEncoder(w).Encode([]ghRelease{ - release("fork-preview", "2026-12-01T00:00:00Z", true), - release("fork-stable", "2026-12-01T01:00:00Z", false), - release("official-stable", "2026-12-01T02:00:00Z", true), - }) - }) - srv := httptest.NewServer(mux) - defer srv.Close() - src := DefaultSource() - src.APIBase, src.Client = srv.URL, srv.Client() - - stable, err := src.ListRemote(context.Background(), false) - if err != nil || len(stable) != 1 || stable[0].Commit != "official-stable" || previewRequests.Load() != 0 { - t.Fatalf("stable list = %+v, %v, preview requests = %d", stable, err, previewRequests.Load()) - } - all, err := src.ListRemote(context.Background(), true) - if err != nil || len(all) != 2 || all[0].Commit != "fork-preview" || all[0].Channel != ChannelAlpha || - all[1].Commit != "official-stable" || previewRequests.Load() != 1 { - t.Fatalf("alpha list = %+v, %v, preview requests = %d", all, err, previewRequests.Load()) - } - - t.Setenv("REIMS_GO_RELEASES_REPO", DefaultReleasesRepo) - override := DefaultSource() - override.APIBase, override.Client = srv.URL, srv.Client() - all, err = override.ListRemote(context.Background(), true) - if err != nil || len(all) != 2 || all[0].Commit != "old-alpha" || previewRequests.Load() != 1 { - t.Fatalf("override list = %+v, %v, preview requests = %d", all, err, previewRequests.Load()) - } -} - func TestDownloadResumesAndVerifies(t *testing.T) { g := newFakeGitHub(t) src := g.source() From e6c8388c37fd20728e5aa4dc08827239a126634c Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 11:19:50 +0800 Subject: [PATCH 18/23] build: keep portable runtime tooling in the runtime repository --- .github/workflows/build-runtime.yml | 288 --------- AGENTS.md | 8 +- NOTICE.md | 5 +- docs/architecture.md | 1 - docs/plugin-architecture.md | 4 +- docs/portable-runtime-spec.md | 30 +- docs/roadmap.md | 4 +- patches/LICENSE | 11 - patches/README.md | 47 -- patches/metal2vulkan-snapshot-replay.patch | 525 ---------------- ...reims-util-parallel-offline-download.patch | 524 ---------------- patches/series.txt | 8 - scripts/apply-patch-series.ps1 | 102 --- scripts/check-runtime-alpha.ps1 | 152 ----- scripts/debug/work-store.mjs | 2 +- scripts/debug/work-template.md | 2 +- scripts/pack-msys2-sources.ps1 | 171 ------ scripts/pack-runtime.ps1 | 580 ------------------ scripts/smoke-runtime.ps1 | 191 ------ scripts/stage-runtime-binaries.ps1 | 42 -- 20 files changed, 27 insertions(+), 2670 deletions(-) delete mode 100644 .github/workflows/build-runtime.yml delete mode 100644 patches/LICENSE delete mode 100644 patches/README.md delete mode 100644 patches/metal2vulkan-snapshot-replay.patch delete mode 100644 patches/reims-util-parallel-offline-download.patch delete mode 100644 patches/series.txt delete mode 100644 scripts/apply-patch-series.ps1 delete mode 100644 scripts/check-runtime-alpha.ps1 delete mode 100644 scripts/pack-msys2-sources.ps1 delete mode 100644 scripts/pack-runtime.ps1 delete mode 100644 scripts/smoke-runtime.ps1 delete mode 100644 scripts/stage-runtime-binaries.ps1 diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml deleted file mode 100644 index f15d08c..0000000 --- a/.github/workflows/build-runtime.yml +++ /dev/null @@ -1,288 +0,0 @@ -name: Build Portable Runtime (Alpha) - -# The runtime fork calls this workflow to build and publish previews. -# A manual run in Reims-Go builds artifacts for verification. -on: - workflow_call: - inputs: - upstream_commit: - type: string - default: "" - publish: - type: boolean - default: false - rebuild: - type: boolean - default: false - workflow_dispatch: - inputs: - upstream_commit: - description: "Reims vGPU fork commit (empty = runtime branch HEAD)" - required: false - default: "" - publish: - description: "Publish a preview when run in the runtime fork" - type: boolean - default: false - rebuild: - description: "Build a new patch revision (runtime--pN) even if this upstream commit is already released" - type: boolean - default: false - -permissions: - contents: read - -concurrency: - group: build-runtime - cancel-in-progress: false - -env: - UPSTREAM_URL: https://github.com/yxc0915/reims-vgpu.git - UPSTREAM_BRANCH: codex/intel-vm-suspend - -jobs: - resolve: - runs-on: ubuntu-latest - outputs: - commit: ${{ steps.r.outputs.commit }} - skip: ${{ steps.r.outputs.skip }} - suffix: ${{ steps.r.outputs.suffix }} - steps: - - id: r - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - WANT: ${{ inputs.upstream_commit }} - REBUILD: ${{ inputs.rebuild }} - run: | - set -euo pipefail - git clone -q --filter=blob:none --no-checkout --single-branch --branch "$UPSTREAM_BRANCH" "$UPSTREAM_URL" up - commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")" - git -C up cat-file -e "$commit:reims-go-runtime.json" - echo "commit=$commit" >> "$GITHUB_OUTPUT" - # Already published (alpha or stable) under any short-hash length or -pN revision? - max_rev=0 - for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do - rest="${tag#runtime-}" - base="${rest%%-p*}" - case "$commit" in - "$base"*) - rev=1 - if [ "$rest" != "$base" ]; then - num="${rest#"$base"-p}" - case "$num" in - ''|*[!0-9]*) ;; - *) rev="$num" ;; - esac - fi - if [ "$rev" -gt "$max_rev" ]; then max_rev="$rev"; fi - echo "Upstream $commit is already released as $tag (rev $rev)" - ;; - esac - done - skip=false - suffix="" - if [ "$max_rev" -gt 0 ]; then - if [ "$REBUILD" = "true" ]; then - suffix="-p$((max_rev + 1))" - echo "Rebuild requested: will publish with suffix $suffix" - else - skip=true - fi - fi - echo "skip=$skip" >> "$GITHUB_OUTPUT" - echo "suffix=$suffix" >> "$GITHUB_OUTPUT" - - build: - needs: resolve - if: needs.resolve.outputs.skip != 'true' - runs-on: windows-latest - timeout-minutes: 150 - permissions: - contents: write - steps: - - uses: actions/checkout@v4 - with: - repository: ${{ job.workflow_repository }} - ref: ${{ job.workflow_sha }} - persist-credentials: false - - - name: Setup MSYS2 CLANG64 - id: msys2 - uses: msys2/setup-msys2@v2 - with: - msystem: CLANG64 - update: true - install: >- - git zstd tar mingw-w64-clang-x86_64-toolchain - mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-meson - mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf - mingw-w64-clang-x86_64-glib2 mingw-w64-clang-x86_64-pixman - mingw-w64-clang-x86_64-gtk3 mingw-w64-clang-x86_64-libslirp - mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-libva - mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader - mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip - - - name: Check out the runtime forks and apply dependency patches - id: patches - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $work = Join-Path $env:RUNNER_TEMP 'reims-vgpu' - foreach ($d in 'cargo', 'xdg-data', 'xdg-cache') { New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP $d) | Out-Null } - # The runner's git defaults to core.autocrlf=true; LF patches need an LF - # checkout (upstream also rewrites CRLF files to LF, install-ctl.sh). - git config --global core.autocrlf false - git clone -q --single-branch --branch $env:UPSTREAM_BRANCH $env:UPSTREAM_URL $work - if ($LASTEXITCODE) { throw 'clone failed' } - git -C $work checkout -q '${{ needs.resolve.outputs.commit }}' - if ($LASTEXITCODE) { throw 'checkout failed' } - git -C $work submodule update --init --depth 1 vendor/qemu - if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu } - if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' } - $utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util' - $utilPin = Get-Content -Raw -LiteralPath (Join-Path $work 'crates/reims-ctl/src/reims_util.rs') - if ($utilPin -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found' } - $utilRev = $Matches[1] - git init -q $utilRepo - if ($LASTEXITCODE) { throw 'reims-util init failed' } - git -C $utilRepo fetch -q --depth 1 https://github.com/steelbrain/reims-util.git $utilRev - if ($LASTEXITCODE) { throw 'reims-util fetch failed' } - git -C $utilRepo checkout -q --detach FETCH_HEAD - if ($LASTEXITCODE) { throw 'reims-util checkout failed' } - $m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan' - $cargoToml = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.toml') - if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') { - $m2vRev = $Matches[1] - } else { - $lockTxt = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.lock') - if ($lockTxt -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' } - $m2vRev = $Matches[1] - } - git init -q $m2vRepo - if ($LASTEXITCODE) { throw 'metal2vulkan init failed' } - git -C $m2vRepo fetch -q --depth 1 https://github.com/steelbrain/metal2vulkan.git $m2vRev - if ($LASTEXITCODE) { throw 'metal2vulkan fetch failed' } - git -C $m2vRepo checkout -q --detach FETCH_HEAD - if ($LASTEXITCODE) { throw 'metal2vulkan checkout failed' } - $short = (git -C $work rev-parse --short=7 HEAD).Trim() - $releaseId = "$short${{ needs.resolve.outputs.suffix }}" - - # Applies what applies, skips what upstream already has, stops on a - # conflict without touching the patch (AGENTS.md rule 4). - $resultFile = Join-Path $env:RUNNER_TEMP 'patches.json' - try { - pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -Metal2VulkanRepo $m2vRepo -ResultFile $resultFile - $ok = $LASTEXITCODE -eq 0 - } finally { - if (Test-Path $resultFile) { - $r = Get-Content -Raw $resultFile | ConvertFrom-Json - "merged=$(@($r.merged) -join ',')" >> $env:GITHUB_OUTPUT - "APPLIED_PATCHES=$(@($r.applied) -join ',')" >> $env:GITHUB_ENV - } - } - if (-not $ok) { throw 'patch queue does not apply' } - $cargoHome = Join-Path $env:RUNNER_TEMP 'cargo' - $m2vFwd = $m2vRepo.Replace('\', '/') - $cargoCfg = @" - [patch."https://github.com/steelbrain/metal2vulkan"] - metal2vulkan = { path = "$m2vFwd/crates/metal2vulkan" } - metal2vulkan-runtime = { path = "$m2vFwd/crates/metal2vulkan-runtime" } - "@ -replace '(?m)^ ', '' - [IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false)) - "UPSTREAM_DIR=$work" >> $env:GITHUB_ENV - "REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV - "METAL2VULKAN_DIR=$m2vRepo" >> $env:GITHUB_ENV - "SHORT_COMMIT=$short" >> $env:GITHUB_ENV - "RELEASE_ID=$releaseId" >> $env:GITHUB_ENV - "CARGO_HOME=$cargoHome" >> $env:GITHUB_ENV - "XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV - "XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV - - - name: Build upstream runtime in MSYS2 CLANG64 - shell: msys2 {0} - env: - REIMS_INSTALL_SKIP_HOST_CHECKS: "1" - run: | - set -euo pipefail - cd "$(cygpath -u "$UPSTREAM_DIR")" - # Upstream's own non-interactive CLANG64 build script. - bash scripts/install-ctl.sh --yes - util_repo="$(cygpath -u "$REIMS_UTIL_DIR")" - if [[ -n "$(git -C "$util_repo" status --porcelain)" ]]; then - toolchain="$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)" - export PATH="$(cygpath -u "$CARGO_HOME")/bin:$PATH" - CC=clang CXX=clang++ AR=llvm-ar cargo +"$toolchain-x86_64-pc-windows-gnullvm" install \ - --locked --force --root "$CARGO_HOME" --path "$REIMS_UTIL_DIR" - fi - - - name: Package alpha runtime and source archives - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $outDir = Join-Path $env:RUNNER_TEMP 'releases' - New-Item -ItemType Directory -Force -Path $outDir | Out-Null - # In-process call, so an empty list (every patch already upstream) binds - # as an empty array rather than being dropped as an empty argument. - $applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ }) - & ./scripts/pack-runtime.ps1 ` - -ReimsRepo $env:UPSTREAM_DIR ` - -UtilRepo $env:REIMS_UTIL_DIR ` - -Metal2VulkanRepo $env:METAL2VULKAN_DIR ` - -CargoHome $env:CARGO_HOME ` - -QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') ` - -Msys2 '${{ steps.msys2.outputs.msys2-location }}' ` - -OutDir $outDir ` - -TempRoot $env:RUNNER_TEMP ` - -Channel alpha ` - -ReleaseId $env:RELEASE_ID ` - -Patches $applied - - - name: Alpha entry gate - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - & ./scripts/check-runtime-alpha.ps1 ` - -OutDir (Join-Path $env:RUNNER_TEMP 'releases') ` - -Commit $env:RELEASE_ID -RequireSlim -RequiredCapability vm-suspend ` - -Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') ` - -AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ }) - - - name: Upload alpha artifacts - uses: actions/upload-artifact@v4 - with: - name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha - path: | - ${{ runner.temp }}/releases/reims-runtime-*.tar.zst - ${{ runner.temp }}/releases/SHA256SUMS.txt - retention-days: 14 - - - name: Publish alpha prerelease (never stable) - if: github.repository == 'yxc0915/reims-vgpu' && inputs.publish - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - MERGED: ${{ steps.patches.outputs.merged }} - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $c = $env:RELEASE_ID - $short = $env:SHORT_COMMIT - $sourceRepo = $env:UPSTREAM_URL -replace '\.git$', '' - $dir = Join-Path $env:RUNNER_TEMP 'releases' - $assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$c.tar.zst", 'SHA256SUMS.txt') | - ForEach-Object { Join-Path $dir $_ } - $applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' } - $merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' } - $notes = @" - **Alpha** runtime (``$c``), built from [the Reims vGPU fork@$short]($sourceRepo/commit/${{ needs.resolve.outputs.commit }}). - - Not smoke-tested on a real host. It becomes stable only after ``scripts/smoke-runtime.ps1`` passes on a real Windows host and a person approves (portable-runtime-spec.md section 6). - - Local patches applied (sources and patches are in the attached source packages): - $applied$merged - - The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis. - - Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID - "@ - gh release create "runtime-$c" @assets --repo $env:GITHUB_REPOSITORY --target '${{ needs.resolve.outputs.commit }}' --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes - if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" } diff --git a/AGENTS.md b/AGENTS.md index 5a2953c..ad9c2c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ 与上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的分工: - **`reims-vgpu`**:底层引擎(QEMU 分支、`reims-graphics-pci`、`metal2vulkan`、`reims-ctl`、`reims-util`)。 -- **`reims-go`(本仓库)**:桌面应用、命令行包装与便携运行时打包/分发流水线,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。 +- **`reims-go`(本仓库)**:桌面应用、命令行包装与运行时下载管理,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。 ## 存储与产物边界 @@ -32,7 +32,7 @@ - 用户显式要求工单,或任务需要跨会话恢复、多人/多 Agent 交接、持续积累验收证据时,再通过 `work.mjs` 建立或复用工单。 - 一次性产物用 `node scripts/debug/tmp.mjs new

+ {t(locale, 'vmCloseTitle', { name })} + + {t(locale, canSuspend ? 'vmCloseDesc' : 'vmCloseDescNoSuspend')} + +
+
+ + + +
+ + + +) diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 1a97e4e..d03f387 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -214,6 +214,9 @@ export const vmZh: Record = { "typeIntoVM": "在虚拟机里键入", "typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本", "upgradeToNVMe": "升级到 NVMe", + "vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。", + "vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。", + "vmCloseTitle": "关闭「{name}」?", } export const vmEn: Record = { @@ -430,4 +433,7 @@ export const vmEn: Record = { "typeIntoVM": "Type into the VM", "typeUntypeable": "Only US-keyboard ASCII characters work without Guest Tools; connect Guest Tools for Chinese and Unicode text", "upgradeToNVMe": "Upgrade to NVMe", + "vmCloseDesc": "Shut down asks macOS to shut down. Suspend saves the session.", + "vmCloseDescNoSuspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", + "vmCloseTitle": "Close “{name}”?", } diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 9ee8854..68e7e96 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -888,6 +888,9 @@ export type I18nKey = | "validationPassed" | "vcpus" | "viewLogs" + | "vmCloseDesc" + | "vmCloseDescNoSuspend" + | "vmCloseTitle" | "vmDir" | "vmName" | "welcomeCheckHost" diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 182aaa8..d279a68 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -181,6 +181,7 @@ export const events = { onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb), onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb), onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb), + onVMCloseRequest: (cb: (name: string) => void) => eventsOn('reims:vm-close-request', cb), // Renderer health watchdog & crash reporting (internal/app/ui_health.go). onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb), emitUIPong: () => eventsEmit('reims:ui-pong'), diff --git a/internal/app/app.go b/internal/app/app.go index 9c035eb..07227eb 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1474,6 +1474,9 @@ func (a *App) StartVM(name string) error { host.ShouldUseFixedGuestMode(curDetail.Borderless, curDetail.Resolution, rep.PrimaryDisplay) { c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") } + if prep.Runtime.Manifest.HasCapability("client-window-close") { + c.Env = append(c.Env, vmCloseRequestEnv(name)...) + } a.mu.Lock() a.transitions[name] = "starting" diff --git a/internal/app/suspend_flow.go b/internal/app/suspend_flow.go index ea960b6..35350cd 100644 --- a/internal/app/suspend_flow.go +++ b/internal/app/suspend_flow.go @@ -130,6 +130,9 @@ func (a *App) resumeLocked(prep *vmstart.Prep, d reims.VMDetail) error { host.ShouldUseFixedGuestMode(d.Borderless, d.Resolution, rep.PrimaryDisplay) { prep.Client.Env = append(prep.Client.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1") } + if prep.Runtime.Manifest.HasCapability("client-window-close") { + prep.Client.Env = append(prep.Client.Env, vmCloseRequestEnv(name)...) + } startAt := time.Now() out := vmstart.LineWriter(func(line string) { a.emitLog(name, line) }) diff --git a/internal/app/window_launch.go b/internal/app/window_launch.go index 8f02579..b3c42db 100644 --- a/internal/app/window_launch.go +++ b/internal/app/window_launch.go @@ -6,11 +6,13 @@ package app import ( "fmt" + "os" "path/filepath" "strings" "github.com/Nwflower/reims-go/internal/cli" "github.com/wailsapp/wails/v2/pkg/options" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // afterStartup runs the launch request once the window's context exists. A @@ -41,6 +43,15 @@ func (a *App) onSecondInstance(data options.SecondInstanceData) { // (double-click while running in the tray) brings the window forward. A // `vm start` handed over from the command line leaves the window as it is. func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { + if w.CloseVM != "" { + if a.ctx != nil { + go func() { + a.ShowMainWindow() + wailsRuntime.EventsEmit(a.ctx, "reims:vm-close-request", w.CloseVM) + }() + } + return + } if w.StartVM == "" { if secondLaunch && !w.Background { a.ShowMainWindow() @@ -70,6 +81,17 @@ func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { }() } +func vmCloseRequestEnv(name string) []string { + executable, err := os.Executable() + if err != nil { + return nil + } + return []string{ + "REIMS_GO_VM_CLOSE_EXE=" + executable, + "REIMS_GO_VM_CLOSE_NAME=" + name, + } +} + // logCapture keeps the last few log lines one source emits while it is // registered, for reporting a failed start back to the command line. type logCapture struct{ lines []string } diff --git a/internal/cli/handoff_other.go b/internal/cli/handoff_other.go index e5c0b49..22c4aaf 100644 --- a/internal/cli/handoff_other.go +++ b/internal/cli/handoff_other.go @@ -9,6 +9,6 @@ const windowHandoffWorks = false func findWindow() uintptr { return 0 } -func sendToWindow(uintptr, []string) error { return errors.ErrUnsupported } +func sendToWindow(uintptr, []string, uint32) error { return errors.ErrUnsupported } func spawnWindow([]string) error { return errors.ErrUnsupported } diff --git a/internal/cli/handoff_windows.go b/internal/cli/handoff_windows.go index f62ce91..c3c76da 100644 --- a/internal/cli/handoff_windows.go +++ b/internal/cli/handoff_windows.go @@ -23,15 +23,17 @@ import ( const ( wmCopyData = 0x004A wailsCopyDataID = 1542 + smtoAbortIfHung = 0x0002 hwndMessage = ^uintptr(2) // HWND_MESSAGE, (HWND)-3 detachedProcess = 0x00000008 windowHandoffWorks = true ) var ( - user32 = syscall.NewLazyDLL("user32.dll") - procFindWindowExW = user32.NewProc("FindWindowExW") - procSendMessageW = user32.NewProc("SendMessageW") + user32 = syscall.NewLazyDLL("user32.dll") + procFindWindowExW = user32.NewProc("FindWindowExW") + procSendMessageW = user32.NewProc("SendMessageW") + procSendMessageTimeoutW = user32.NewProc("SendMessageTimeoutW") ) type copyDataStruct struct { @@ -57,7 +59,7 @@ func findWindow() uintptr { // sendToWindow delivers args to the running window as if a second // `reims-go.exe ` had been launched. -func sendToWindow(hwnd uintptr, args []string) error { +func sendToWindow(hwnd uintptr, args []string, timeoutMS uint32) error { wd, _ := os.Getwd() payload, err := json.Marshal(options.SecondInstanceData{Args: args, WorkingDirectory: wd}) if err != nil { @@ -72,6 +74,16 @@ func sendToWindow(hwnd uintptr, args []string) error { cbData: uint32(len(buf) * 2), lpData: uintptr(unsafe.Pointer(&buf[0])), } + if timeoutMS != 0 { + var result uintptr + sent, _, _ := procSendMessageTimeoutW.Call(hwnd, wmCopyData, 0, + uintptr(unsafe.Pointer(&cds)), smtoAbortIfHung, uintptr(timeoutMS), uintptr(unsafe.Pointer(&result))) + runtime.KeepAlive(buf) + if sent == 0 { + return errors.New("desktop window did not respond") + } + return nil + } procSendMessageW.Call(hwnd, wmCopyData, 0, uintptr(unsafe.Pointer(&cds))) runtime.KeepAlive(buf) return nil diff --git a/internal/cli/start.go b/internal/cli/start.go index 3cbf862..a090314 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -97,7 +97,7 @@ func startInWindow(ctx context.Context, cfg *config.Config, name string) error { w := WindowArgs{StartVM: name, StartResult: result} if hwnd := findWindow(); hwnd != 0 { fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name})) - if err := sendToWindow(hwnd, w.Args()); err != nil { + if err := sendToWindow(hwnd, w.Args(), 0); err != nil { return err } } else { diff --git a/internal/cli/window_args.go b/internal/cli/window_args.go index 48c15be..690f3df 100644 --- a/internal/cli/window_args.go +++ b/internal/cli/window_args.go @@ -14,6 +14,7 @@ const ( flagSafeMode = "--safe-mode" flagStartVM = "--start-vm=" flagStartResult = "--start-result=" + flagCloseVM = "--close-vm=" flagWaitPID = "--wait-pid=" ) @@ -30,6 +31,8 @@ type WindowArgs struct { // StartResult is a file the window writes a StartResult to once StartVM // has returned, so the command that asked can report it. StartResult string + // CloseVM requests a close confirmation in the running desktop window. + CloseVM string // WaitPID is a Reims-Go process that is quitting after installing an // update: the new window waits for it to exit before taking the // single-instance lock, which it would otherwise hand straight back to it. @@ -50,6 +53,11 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) { w.StartVM = strings.TrimPrefix(a, flagStartVM) case strings.HasPrefix(a, flagStartResult): w.StartResult = strings.TrimPrefix(a, flagStartResult) + case strings.HasPrefix(a, flagCloseVM): + w.CloseVM = strings.TrimPrefix(a, flagCloseVM) + if w.CloseVM == "" { + return WindowArgs{}, false + } case strings.HasPrefix(a, flagWaitPID): pid, err := strconv.ParseUint(strings.TrimPrefix(a, flagWaitPID), 10, 32) if err != nil || pid == 0 { @@ -78,12 +86,22 @@ func (w WindowArgs) Args() []string { if w.StartResult != "" { out = append(out, flagStartResult+w.StartResult) } + if w.CloseVM != "" { + out = append(out, flagCloseVM+w.CloseVM) + } if w.WaitPID != 0 { out = append(out, flagWaitPID+strconv.FormatUint(uint64(w.WaitPID), 10)) } return out } +// ForwardVMClose asks an existing desktop instance to show a confirmation. +func ForwardVMClose(name string) bool { + const timeoutMS = 500 + hwnd := findWindow() + return hwnd != 0 && sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), timeoutMS) == nil +} + // StartResult is the JSON the window writes to WindowArgs.StartResult. type StartResult struct { OK bool `json:"ok"` diff --git a/internal/cli/window_args_test.go b/internal/cli/window_args_test.go index 84d34f0..9949fc1 100644 --- a/internal/cli/window_args_test.go +++ b/internal/cli/window_args_test.go @@ -24,6 +24,8 @@ func TestParseWindowArgs(t *testing.T) { {[]string{"--background", "vm", "list"}, WindowArgs{}, false}, {[]string{"--help"}, WindowArgs{}, false}, {[]string{"--start-vm", "m0"}, WindowArgs{}, false}, // value must be joined with = + {[]string{"--close-vm=mac os"}, WindowArgs{CloseVM: "mac os"}, true}, + {[]string{"--close-vm="}, WindowArgs{}, false}, {[]string{"--wait-pid=4242"}, WindowArgs{WaitPID: 4242}, true}, {[]string{"--background", "--wait-pid=7"}, WindowArgs{Background: true, WaitPID: 7}, true}, {[]string{"--wait-pid=0"}, WindowArgs{}, false}, @@ -40,6 +42,13 @@ func TestParseWindowArgs(t *testing.T) { } } +func TestCloseWindowArgsRoundTrip(t *testing.T) { + want := WindowArgs{CloseVM: "macOS Test"} + if got, ok := ParseWindowArgs(want.Args()); !ok || got != want { + t.Fatalf("close request round trip = %+v, %v", got, ok) + } +} + func TestWindowArgsRoundTrip(t *testing.T) { w := WindowArgs{Background: true, StartVM: "mac os", StartResult: `D:\Data\tmp\cli-start-9.json`, WaitPID: 31337} got, ok := ParseWindowArgs(w.Args()) diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index 6f2f87e..bc05abf 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -50,6 +50,9 @@ "state_resuming": "Resuming", "state_broken": "Error", "suspend": "Suspend", + "vmCloseTitle": "Close “{name}”?", + "vmCloseDesc": "Shut down asks macOS to shut down. Suspend saves the session.", + "vmCloseDescNoSuspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", "resume": "Resume", "resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM", "discardSuspend": "Discard saved state", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index a8ab8f3..7f73d4a 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -50,6 +50,9 @@ "state_resuming": "恢复中", "state_broken": "出错", "suspend": "挂起", + "vmCloseTitle": "关闭「{name}」?", + "vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。", + "vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。", "resume": "恢复", "resumeUnavailable": "切换到支持挂起的内核后可恢复", "discardSuspend": "放弃挂起状态", diff --git a/main.go b/main.go index dba7dff..9fb98c7 100644 --- a/main.go +++ b/main.go @@ -35,6 +35,12 @@ func main() { os.Exit(cli.Main(args)) } launch, _ := cli.ParseWindowArgs(args) + if launch.CloseVM != "" { + if !cli.ForwardVMClose(launch.CloseVM) { + os.Exit(1) + } + return + } if launch.WaitPID != 0 { // Relaunched by an in-app update: let the old window exit first, or the // single-instance lock below hands this launch back to it. From 30db99fc719b465b1459485c912401e6c8b556b8 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 17:45:29 +0800 Subject: [PATCH 22/23] fix(ui): anchor close confirmation to the VM window --- frontend/src/App.tsx | 31 +--- frontend/src/components/VMCloseDialog.tsx | 36 ----- frontend/src/i18n/domains/vm.gen.ts | 6 - frontend/src/i18n/keys.gen.ts | 3 - frontend/src/wails.ts | 1 - internal/app/app.go | 1 + internal/app/vm_close_other.go | 5 + internal/app/vm_close_windows.go | 55 ++++++++ internal/app/window_launch.go | 8 +- internal/cli/handoff_other.go | 2 + internal/cli/handoff_windows.go | 16 +++ internal/cli/window_args.go | 9 +- internal/host/fullscreen_windows.go | 7 +- internal/i18n/catalog_gen.go | 9 ++ internal/installguide/appearance_windows.go | 31 +++- internal/installguide/close_vm_windows.go | 124 ++++++++++++++++ .../installguide/close_vm_windows_test.go | 133 ++++++++++++++++++ internal/installguide/dialog_windows.go | 11 +- internal/installguide/guide.go | 32 +++-- locales/en-US/native.json | 4 + locales/en-US/vm.json | 3 - locales/zh-CN/native.json | 4 + locales/zh-CN/vm.json | 3 - 23 files changed, 416 insertions(+), 118 deletions(-) delete mode 100644 frontend/src/components/VMCloseDialog.tsx create mode 100644 internal/app/vm_close_other.go create mode 100644 internal/app/vm_close_windows.go create mode 100644 internal/installguide/close_vm_windows.go create mode 100644 internal/installguide/close_vm_windows_test.go diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 38e2665..b3e9a8a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,7 +2,6 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react' import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react' import type { WizardDraft } from './components/CreateWizard' import { DeleteDialog } from './components/DeleteDialog' -import { VMCloseDialog } from './components/VMCloseDialog' import { CloneDialog } from './components/CloneDialog' import { OnlineRecoveryDialog } from './components/OnlineRecoveryDialog' import { SendTextDialog } from './components/SendTextDialog' @@ -90,7 +89,6 @@ export const App: React.FC = () => { const [affinityVersion, setAffinityVersion] = useState(0) const [deleteTarget, setDeleteTarget] = useState(null) const [discardSuspendTarget, setDiscardSuspendTarget] = useState(null) - const [vmCloseRequests, setVMCloseRequests] = useState([]) const [cloneSource, setCloneSource] = useState(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) @@ -878,19 +876,9 @@ export const App: React.FC = () => { const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) const appDialogOpen = showSetup || showWizard || showSettings || affinityTarget || deleteTarget || discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate - const vmCloseTarget = appDialogOpen ? undefined : vmCloseRequests[0] - const finishVMWindowClose = (name: string, action?: 'stop' | 'suspend') => { - setVMCloseRequests((requests) => requests.filter((target) => target !== name)) - if (action) { - setSelected(name) - onVMActionFor(name, action, true) - } else if (vmCloseRequests.length === 1) { - api.FocusVMWindow(name).catch(() => {}) - } - } shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return - if (appDialogOpen || vmCloseTarget) return + if (appDialogOpen) return if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return const k = e.key.toLowerCase() if (k === 'n') { e.preventDefault(); openWizard() } @@ -916,10 +904,7 @@ export const App: React.FC = () => { setSelected(name) setDiscardSuspendTarget(name) }) - const offClose = events.onVMCloseRequest((name) => { - setVMCloseRequests((requests) => requests.includes(name) ? requests : [...requests, name]) - }) - return () => { offSelect(); offNew(); offDiscard(); offClose() } + return () => { offSelect(); offNew(); offDiscard() } }, []) // Native Wails file drag-and-drop delivery into the selected VM's shared folder. @@ -1322,18 +1307,6 @@ export const App: React.FC = () => { setDeleteTarget(null)} onConfirm={confirmDelete} /> )} - {vmCloseTarget && ( - finishVMWindowClose(vmCloseTarget, 'stop')} - onSuspend={() => finishVMWindowClose(vmCloseTarget, 'suspend')} - onCancel={() => finishVMWindowClose(vmCloseTarget)} - /> - )} - {discardSuspendTarget && ( void - onSuspend: () => void - onCancel: () => void -} - -export const VMCloseDialog: React.FC = ({ locale, name, canSuspend, busy, onStop, onSuspend, onCancel }) => ( - { if (!open) onCancel() }}> - - - -
- {t(locale, 'vmCloseTitle', { name })} - - {t(locale, canSuspend ? 'vmCloseDesc' : 'vmCloseDescNoSuspend')} - -
-
- - - -
-
-
-
-) diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index d03f387..1a97e4e 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -214,9 +214,6 @@ export const vmZh: Record = { "typeIntoVM": "在虚拟机里键入", "typeUntypeable": "未连接 Guest Tools 时仅支持美式键盘 ASCII 字符;安装并连接 Guest Tools 后即可输入中文与任意 Unicode 文本", "upgradeToNVMe": "升级到 NVMe", - "vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。", - "vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。", - "vmCloseTitle": "关闭「{name}」?", } export const vmEn: Record = { @@ -433,7 +430,4 @@ export const vmEn: Record = { "typeIntoVM": "Type into the VM", "typeUntypeable": "Only US-keyboard ASCII characters work without Guest Tools; connect Guest Tools for Chinese and Unicode text", "upgradeToNVMe": "Upgrade to NVMe", - "vmCloseDesc": "Shut down asks macOS to shut down. Suspend saves the session.", - "vmCloseDescNoSuspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", - "vmCloseTitle": "Close “{name}”?", } diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 68e7e96..9ee8854 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -888,9 +888,6 @@ export type I18nKey = | "validationPassed" | "vcpus" | "viewLogs" - | "vmCloseDesc" - | "vmCloseDescNoSuspend" - | "vmCloseTitle" | "vmDir" | "vmName" | "welcomeCheckHost" diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index d279a68..182aaa8 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -181,7 +181,6 @@ export const events = { onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb), onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb), onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb), - onVMCloseRequest: (cb: (name: string) => void) => eventsOn('reims:vm-close-request', cb), // Renderer health watchdog & crash reporting (internal/app/ui_health.go). onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb), emitUIPong: () => eventsEmit('reims:ui-pong'), diff --git a/internal/app/app.go b/internal/app/app.go index 07227eb..1983b2a 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -94,6 +94,7 @@ type App struct { runtimeKinds *rt.KindRegistry uiHealth uiHealthState themeMode installguide.Theme + vmClosePrompts sync.Map } // Lifecycle exposes Wails lifecycle callbacks without exporting them as diff --git a/internal/app/vm_close_other.go b/internal/app/vm_close_other.go new file mode 100644 index 0000000..b24d7d1 --- /dev/null +++ b/internal/app/vm_close_other.go @@ -0,0 +1,5 @@ +//go:build !windows + +package app + +func (*App) confirmVMWindowClose(string) {} diff --git a/internal/app/vm_close_windows.go b/internal/app/vm_close_windows.go new file mode 100644 index 0000000..a5d3055 --- /dev/null +++ b/internal/app/vm_close_windows.go @@ -0,0 +1,55 @@ +package app + +import ( + "strings" + + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/installguide" + "github.com/Nwflower/reims-go/internal/tray" +) + +func (a *App) confirmVMWindowClose(name string) { + if _, pending := a.vmClosePrompts.LoadOrStore(name, struct{}{}); pending { + return + } + defer a.vmClosePrompts.Delete(name) + ctx := a.baseCtx() + pid := a.cachedVMPID(name) + owner := host.ProcessDisplayWindow(uint32(pid)) + if owner == 0 { + pid = a.findRunningVMPID(ctx, name) + owner = host.ProcessDisplayWindow(uint32(pid)) + } + if owner == 0 { + a.emitLog(name, "Could not locate the VM display window for close confirmation") + return + } + loc, theme := a.guidePreferences() + label := strings.TrimSpace(a.GetVMNote(name)) + if label == "" { + label = name + } + prep, err := a.prep(name) + canSuspend := err == nil && prep.Runtime.Manifest.HasCapability("vm-suspend") + choice, err := installguide.ConfirmVMClose(ctx, owner, label, loc, theme, canSuspend) + if err != nil { + a.emitLog(name, err.Error()) + return + } + if choice == installguide.VMCloseCancel { + return + } + vms, err := a.listVMsInternal(ctx) + if err != nil { + a.emitLog(name, err.Error()) + return + } + if current, running := findRunningVMPID(vms, name); !running || current != uint32(pid) { + return + } + if choice == installguide.VMCloseSuspend { + a.trayVMAction(name, tray.ActSuspend) + } else { + a.trayVMAction(name, tray.ActStop) + } +} diff --git a/internal/app/window_launch.go b/internal/app/window_launch.go index b3c42db..e4bc918 100644 --- a/internal/app/window_launch.go +++ b/internal/app/window_launch.go @@ -12,7 +12,6 @@ import ( "github.com/Nwflower/reims-go/internal/cli" "github.com/wailsapp/wails/v2/pkg/options" - wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // afterStartup runs the launch request once the window's context exists. A @@ -44,12 +43,7 @@ func (a *App) onSecondInstance(data options.SecondInstanceData) { // `vm start` handed over from the command line leaves the window as it is. func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) { if w.CloseVM != "" { - if a.ctx != nil { - go func() { - a.ShowMainWindow() - wailsRuntime.EventsEmit(a.ctx, "reims:vm-close-request", w.CloseVM) - }() - } + go a.confirmVMWindowClose(w.CloseVM) return } if w.StartVM == "" { diff --git a/internal/cli/handoff_other.go b/internal/cli/handoff_other.go index 22c4aaf..0ddda69 100644 --- a/internal/cli/handoff_other.go +++ b/internal/cli/handoff_other.go @@ -9,6 +9,8 @@ const windowHandoffWorks = false func findWindow() uintptr { return 0 } +func ForwardVMClose(string) bool { return false } + func sendToWindow(uintptr, []string, uint32) error { return errors.ErrUnsupported } func spawnWindow([]string) error { return errors.ErrUnsupported } diff --git a/internal/cli/handoff_windows.go b/internal/cli/handoff_windows.go index c3c76da..50726ee 100644 --- a/internal/cli/handoff_windows.go +++ b/internal/cli/handoff_windows.go @@ -34,6 +34,8 @@ var ( procFindWindowExW = user32.NewProc("FindWindowExW") procSendMessageW = user32.NewProc("SendMessageW") procSendMessageTimeoutW = user32.NewProc("SendMessageTimeoutW") + procGetWindowPID = user32.NewProc("GetWindowThreadProcessId") + procAllowSetForeground = user32.NewProc("AllowSetForegroundWindow") ) type copyDataStruct struct { @@ -57,6 +59,20 @@ func findWindow() uintptr { return h } +// ForwardVMClose delegates both the request and the foreground permission +// inherited from the VM window that launched this helper. +func ForwardVMClose(name string) bool { + hwnd := findWindow() + if hwnd == 0 { + return false + } + var pid uint32 + if tid, _, _ := procGetWindowPID.Call(hwnd, uintptr(unsafe.Pointer(&pid))); tid != 0 { + procAllowSetForeground.Call(uintptr(pid)) + } + return sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), 500) == nil +} + // sendToWindow delivers args to the running window as if a second // `reims-go.exe ` had been launched. func sendToWindow(hwnd uintptr, args []string, timeoutMS uint32) error { diff --git a/internal/cli/window_args.go b/internal/cli/window_args.go index 690f3df..ae9bf05 100644 --- a/internal/cli/window_args.go +++ b/internal/cli/window_args.go @@ -31,7 +31,7 @@ type WindowArgs struct { // StartResult is a file the window writes a StartResult to once StartVM // has returned, so the command that asked can report it. StartResult string - // CloseVM requests a close confirmation in the running desktop window. + // CloseVM asks the running client to show a confirmation over the VM display. CloseVM string // WaitPID is a Reims-Go process that is quitting after installing an // update: the new window waits for it to exit before taking the @@ -95,13 +95,6 @@ func (w WindowArgs) Args() []string { return out } -// ForwardVMClose asks an existing desktop instance to show a confirmation. -func ForwardVMClose(name string) bool { - const timeoutMS = 500 - hwnd := findWindow() - return hwnd != 0 && sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), timeoutMS) == nil -} - // StartResult is the JSON the window writes to WindowArgs.StartResult. type StartResult struct { OK bool `json:"ok"` diff --git a/internal/host/fullscreen_windows.go b/internal/host/fullscreen_windows.go index c722cb2..486e8f7 100644 --- a/internal/host/fullscreen_windows.go +++ b/internal/host/fullscreen_windows.go @@ -118,7 +118,8 @@ func hasDisplayClientArea(hwnd uintptr) bool { (placement.Normal.Bottom-placement.Normal.Top)-(client.Bottom-client.Top) >= 300 } -func findDisplayWindow(pid uint32) uintptr { +// ProcessDisplayWindow finds the VM's display window, preferring the foreground display. +func ProcessDisplayWindow(pid uint32) uintptr { if pid == 0 { return 0 } @@ -149,7 +150,7 @@ func liveWindowPID(hwnd uintptr) uint32 { // IsProcessWindowFullscreen reports whether the selected display window fills its monitor without a frame. func IsProcessWindowFullscreen(pid uint32) bool { fullscreenState.prune(liveWindowPID) - hwnd := findDisplayWindow(pid) + hwnd := ProcessDisplayWindow(pid) if hwnd == 0 { return false } @@ -176,7 +177,7 @@ func IsProcessWindowFullscreen(pid uint32) bool { // borderless fullscreen and windowed mode. func ToggleProcessWindowFullscreen(pid uint32) (bool, error) { fullscreenState.prune(liveWindowPID) - hwnd := findDisplayWindow(pid) + hwnd := ProcessDisplayWindow(pid) if hwnd == 0 { return false, fmt.Errorf("%w for pid %d", ErrDisplayWindowNotFound, pid) } diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 61dcba3..0be7dcb 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -536,6 +536,10 @@ var catalog = map[Locale]map[string]string{ "vmstart.pin.non_lpe": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)", "vmstart.pin.pcores": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)", "vmstart.pin.skipped": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿", + "window.close.description": "关机将请求系统关闭。挂起会保存当前会话。", + "window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。", + "window.close.suspend": "挂起", + "window.close.title": "关闭「{name}」?", }, EnUS: { "affinity.applied.all": "[CPU] Set QEMU (PID {pid}) affinity to all CPUs ({count} logical CPUs, mask {mask}{eco})", @@ -1070,6 +1074,10 @@ var catalog = map[Locale]map[string]string{ "vmstart.pin.non_lpe": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)", "vmstart.pin.pcores": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)", "vmstart.pin.skipped": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall", + "window.close.description": "Shut down asks macOS to shut down. Suspend saves the session.", + "window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", + "window.close.suspend": "Suspend", + "window.close.title": "Close “{name}”?", }, } @@ -1233,4 +1241,5 @@ var paramOrder = map[string][]string{ "vmstart.pin.non_lpe": {"vcpus", "pthreads", "pid", "cores", "threads", "mask", "lpe"}, "vmstart.pin.pcores": {"pid", "cores", "threads", "mask", "excluded"}, "vmstart.pin.skipped": {"vcpus", "pthreads"}, + "window.close.title": {"name"}, } diff --git a/internal/installguide/appearance_windows.go b/internal/installguide/appearance_windows.go index 3caa9f9..a112b3c 100644 --- a/internal/installguide/appearance_windows.go +++ b/internal/installguide/appearance_windows.go @@ -572,7 +572,7 @@ func stylePanel(hwnd, flags uintptr) { roundPanel(hwnd) } - for _, id := range []uintptr{idFold, idLeft, idRight, idExtra, idJump} { + for _, id := range []uintptr{idFold, idLeft, idRight, idExtra, idJump, idCancel} { if ctrl, _, _ := getDlgItem.Call(hwnd, id); ctrl != 0 { setWindowSubclass.Call(ctrl, btnSubclassProc, id, 0) } @@ -785,6 +785,7 @@ func layoutPanel(hwnd uintptr) { leftCtrl, _, _ := getDlgItem.Call(hwnd, idLeft) extraCtrl, _, _ := getDlgItem.Call(hwnd, idExtra) rightCtrl, _, _ := getDlgItem.Call(hwnd, idRight) + cancelCtrl, _, _ := getDlgItem.Call(hwnd, idCancel) jumpCtrl, _, _ := getDlgItem.Call(hwnd, idJump) // Adaptively widen cardW up to maxCardW when single-line controls (footer strip, @@ -911,6 +912,27 @@ func layoutPanel(hwnd uintptr) { if extraCtrl != 0 { needInline += extraW + gap } + if cancelCtrl != 0 { + setCtrlFont(cancelCtrl, fonts.btn) + cancelW := min(innerW, max(dp(dpi, 60), measureLineWidth(dc, fonts.btn, controlText(cancelCtrl))+btnPadX*2)) + y += dp(dpi, 16) + if leftW+rightW+cancelW+gap*2 <= innerW { + x := cardW - padX - cancelW + moveControl(cancelCtrl, x, y, cancelW, btnH) + x -= gap + rightW + moveControl(rightCtrl, x, y, rightW, btnH) + moveControl(leftCtrl, x-gap-leftW, y, leftW, btnH) + y += btnH + } else { + for _, ctrl := range []uintptr{leftCtrl, rightCtrl, cancelCtrl} { + moveControl(ctrl, padX, y, innerW, btnH) + y += btnH + gap + } + y -= gap + } + setWindowPos.Call(hwnd, 0, 0, 0, uintptr(cardW), uintptr(y+dp(dpi, 16)), 0x16) + return + } if extraCtrl != 0 && needInline > innerW { st.extraStacked = true setCtrlFont(extraCtrl, fonts.smallMed) @@ -1187,6 +1209,11 @@ func paintItem(it *drawItem) { flags = 0x8824 case idRight: selectGDI.Call(dc, fonts.btnBold) + if it.state&0x0004 != 0 { // ODS_DISABLED + paintRoundedBox(dc, r, btnR, pal.surface, pal.btnFill, pal.btnBorder, true, rgb{}, false) + fg = pal.text3 + break + } fill := pal.accent if pressed { fill = pal.accentPress @@ -1195,7 +1222,7 @@ func paintItem(it *drawItem) { } paintRoundedBox(dc, r, btnR, pal.surface, fill, rgb{}, false, pal.accentHighlight, !pressed) fg = rgb{255, 255, 255} - case idLeft: + case idLeft, idCancel: selectGDI.Call(dc, fonts.btn) fill := pal.btnFill if pressed { diff --git a/internal/installguide/close_vm_windows.go b/internal/installguide/close_vm_windows.go new file mode 100644 index 0000000..9943241 --- /dev/null +++ b/internal/installguide/close_vm_windows.go @@ -0,0 +1,124 @@ +package installguide + +import ( + "context" + "fmt" + "runtime" + "unsafe" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +type VMCloseChoice uint8 + +const ( + VMCloseCancel VMCloseChoice = iota + VMCloseShutdown + VMCloseSuspend +) + +var setDialogFocus = user32.NewProc("SetFocus") + +// ConfirmVMClose uses the same native card as the installation guide, owned by +// the display window. Keep the foreign window enabled so it remains usable if +// Reims-Go exits while the confirmation is open. +func ConfirmVMClose(ctx context.Context, owner uintptr, name string, loc i18n.Locale, theme Theme, canSuspend bool) (VMCloseChoice, error) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + desc := "window.close.description" + if !canSuspend { + desc = "window.close.description_no_suspend" + } + c := content{ + title: i18n.M(loc, "window.close.title", i18n.Vars{"name": name}), + body: i18n.T(loc, desc), + left: i18n.T(loc, "stop"), + right: i18n.T(loc, "window.close.suspend"), + cancel: i18n.T(loc, "cancel"), + disableRight: !canSuspend, + } + template := dialogTemplate(confirm, c, loc) + flags := uintptr(scriptForLocale(loc)) << dialogScriptShift + if resolveDark(theme) { + flags |= dialogDark + } + hwnd, _, err := createDialog.Call(0, uintptr(unsafe.Pointer(&template[0])), owner, dialogProc, flags) + if hwnd == 0 { + return VMCloseCancel, fmt.Errorf("create VM close confirmation: %w", err) + } + defer destroyWindow.Call(hwnd) + + timer, _, err := setTimer.Call(0, 0, 200, 0) + if timer == 0 { + return VMCloseCancel, fmt.Errorf("track VM window: %w", err) + } + defer killTimer.Call(0, timer) + + centerVMCloseDialog(hwnd, owner) + sendMessage.Call(hwnd, 0x0401, idCancel, 0) // DM_SETDEFID + showWindow.Call(hwnd, 4) // SW_SHOWNOACTIVATE + revealPanel(hwnd) + if foreground, _, _ := getForeground.Call(); foreground == owner { + if active, _, _ := setForeground.Call(hwnd); active != 0 { + cancel, _, _ := getDlgItem.Call(hwnd, idCancel) + setDialogFocus.Call(cancel) + } + } + + for ctx.Err() == nil { + var msg message + ret, _, err := getMessage.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(ret) == -1 { + return VMCloseCancel, err + } + if ret == 0 { + break + } + if currentOwner, _, _ := getWindow.Call(hwnd, 4); currentOwner != owner { // GW_OWNER + break + } + if msg.id == 0x0113 && msg.hwnd == 0 { // WM_TIMER + centerVMCloseDialog(hwnd, owner) + continue + } + if msg.id == wmAction && msg.hwnd == hwnd { + switch msg.wp { + case idLeft: + return VMCloseShutdown, nil + case idRight: + if canSuspend { + return VMCloseSuspend, nil + } + case idCancel: + return VMCloseCancel, nil + } + } + if handled, _, _ := isDialogMessage.Call(hwnd, uintptr(unsafe.Pointer(&msg))); handled == 0 { + translateMessage.Call(uintptr(unsafe.Pointer(&msg))) + dispatchMessage.Call(uintptr(unsafe.Pointer(&msg))) + } + } + return VMCloseCancel, nil +} + +func centerVMCloseDialog(hwnd, owner uintptr) { + if iconic, _, _ := isIconic.Call(owner); iconic != 0 { + return + } + var client, bounds rect + var origin point + if ok, _, _ := getClientRect.Call(owner, uintptr(unsafe.Pointer(&client))); ok == 0 { + return + } + if ok, _, _ := clientToScreen.Call(owner, uintptr(unsafe.Pointer(&origin))); ok == 0 { + return + } + getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&bounds))) + x := origin.x + (client.right-(bounds.right-bounds.left))/2 + y := origin.y + (client.bottom-(bounds.bottom-bounds.top))/2 + if x != bounds.left || y != bounds.top { + // SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER + setWindowPos.Call(hwnd, 0, uintptr(x), uintptr(y), 0, 0, 0x0215) + } +} diff --git a/internal/installguide/close_vm_windows_test.go b/internal/installguide/close_vm_windows_test.go new file mode 100644 index 0000000..946ef15 --- /dev/null +++ b/internal/installguide/close_vm_windows_test.go @@ -0,0 +1,133 @@ +package installguide + +import ( + "bufio" + "context" + "fmt" + "os" + "os/exec" + "runtime" + "syscall" + "testing" + "time" + "unsafe" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +func TestVMCloseConfirmation(t *testing.T) { + const ownerEnv = "REIMS_GO_TEST_CLOSE_DIALOG_OWNER" + if os.Getenv(ownerEnv) != "" { + runCloseDialogOwner(t) + return + } + ownerCtx, stopOwner := context.WithTimeout(context.Background(), 25*time.Second) + defer stopOwner() + proc := exec.CommandContext(ownerCtx, os.Args[0], "-test.run=^TestVMCloseConfirmation$") + proc.Env = append(os.Environ(), ownerEnv+"=1") + proc.Stderr = os.Stderr + stdout, err := proc.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := proc.Start(); err != nil { + t.Fatal(err) + } + defer func() { + stopOwner() + _ = proc.Wait() + }() + var owner uintptr + if _, err := fmt.Fscan(bufio.NewReader(stdout), &owner); err != nil || owner == 0 { + t.Fatalf("read test display HWND: %v", err) + } + + for _, tc := range []struct { + name string + canSuspend bool + button uintptr + want VMCloseChoice + }{ + {"shutdown", true, idLeft, VMCloseShutdown}, + {"suspend", true, idRight, VMCloseSuspend}, + {"escape", true, idCancel, VMCloseCancel}, + {"unsupported", false, idCancel, VMCloseCancel}, + } { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + result := make(chan error, 1) + go func() { + result <- exerciseVMCloseDialog(ctx, owner, tc.name, tc.button, tc.canSuspend) + }() + choice, err := ConfirmVMClose(ctx, owner, tc.name, i18n.ZhCN, ThemeDark, tc.canSuspend) + deadline := ctx.Err() + cancel() + if probeErr := <-result; probeErr != nil || err != nil || choice != tc.want || deadline != nil { + t.Fatalf("%s: choice %v, want %v, dialog error %v, probe error %v, deadline %v", tc.name, choice, tc.want, err, probeErr, deadline) + } + } +} + +func runCloseDialogOwner(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + class, _ := syscall.UTF16PtrFromString("STATIC") + offscreen := int32(-16000) + owner, _, err := user32.NewProc("CreateWindowExW").Call(0x80, uintptr(unsafe.Pointer(class)), 0, 0x80000000, + uintptr(offscreen), uintptr(offscreen), 1280, 720, 0, 0, 0, 0) + if owner == 0 { + t.Fatal(err) + } + defer destroyWindow.Call(owner) + fmt.Fprintln(os.Stdout, owner) + for { + var msg message + ret, _, _ := getMessage.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0) + if int32(ret) <= 0 { + return + } + dispatchMessage.Call(uintptr(unsafe.Pointer(&msg))) + } +} + +func exerciseVMCloseDialog(ctx context.Context, owner uintptr, name string, button uintptr, canSuspend bool) error { + findWindowW := user32.NewProc("FindWindowW") + title, _ := syscall.UTF16PtrFromString("关闭「" + name + "」?") + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for ctx.Err() == nil { + hwnd, _, _ := findWindowW.Call(0, uintptr(unsafe.Pointer(title))) + if visible, _, _ := user32.NewProc("IsWindowVisible").Call(hwnd); visible != 0 { + actualOwner, _, _ := getWindow.Call(hwnd, 4) // GW_OWNER + if actualOwner != owner { + return fmt.Errorf("dialog owner %#x, want %#x", actualOwner, owner) + } + var guest, dialog rect + getWindowRect.Call(owner, uintptr(unsafe.Pointer(&guest))) + getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&dialog))) + dx := guest.left + guest.right - dialog.left - dialog.right + dy := guest.top + guest.bottom - dialog.top - dialog.bottom + if dx > 1 || dx < -1 || dy > 1 || dy < -1 { + return fmt.Errorf("dialog %+v is not centered over %+v", dialog, guest) + } + suspend, _, _ := getDlgItem.Call(hwnd, idRight) + if enabled, _, _ := isWindowEnabled.Call(suspend); suspend == 0 || (enabled != 0) != canSuspend { + return fmt.Errorf("suspend button availability differs from %t", canSuspend) + } + control, _, _ := getDlgItem.Call(hwnd, button) + if control == 0 { + return fmt.Errorf("missing button %d", button) + } + if button == idCancel { + postMessage.Call(control, 0x0100, 0x1b, 0) // WM_KEYDOWN, VK_ESCAPE + } else { + postMessage.Call(control, 0x00f5, 0, 0) // BM_CLICK + } + return nil + } + select { + case <-ctx.Done(): + case <-ticker.C: + } + } + return fmt.Errorf("waiting for confirmation window: %w", ctx.Err()) +} diff --git a/internal/installguide/dialog_windows.go b/internal/installguide/dialog_windows.go index 06222f9..4513354 100644 --- a/internal/installguide/dialog_windows.go +++ b/internal/installguide/dialog_windows.go @@ -19,6 +19,7 @@ const ( idRight = 112 idExtra = 113 idJump = 114 + idCancel = 2 // IDCANCEL, including Escape in the dialog message loop. wmAction = 0x8001 ) @@ -50,6 +51,9 @@ func dialogTemplate(p page, c content, locale i18n.Locale) []uint16 { if class == button { style |= 1 // WS_TABSTOP controlStyle = 0x0b // BS_OWNERDRAW + if id == idRight && c.disableRight { + style |= 0x0800 // WS_DISABLED + } } else { controlStyle = 0x0d // SS_OWNERDRAW } @@ -89,6 +93,9 @@ func dialogTemplate(p page, c content, locale i18n.Locale) []uint16 { if c.right != "" { item(button, idRight, c.right) } + if c.cancel != "" { + item(button, idCancel, c.cancel) + } if c.jump != "" { item(button, idJump, c.jump) } @@ -127,12 +134,12 @@ var dialogProc = syscall.NewCallback(func(hwnd, msg, wp, lp uintptr) uintptr { } case 0x0111: // WM_COMMAND id := wp & 0xffff - if wp>>16 == 0 && (id == idFold || id == idLeft || id == idRight || id == idExtra || id == idJump || id == 2) { + if wp>>16 == 0 && (id == idFold || id == idLeft || id == idRight || id == idExtra || id == idJump || id == idCancel) { postMessage.Call(hwnd, wmAction, id, 0) return 1 } case 0x0010: // WM_CLOSE: leave a way to reopen the guide. - postMessage.Call(hwnd, wmAction, 2, 0) + postMessage.Call(hwnd, wmAction, idCancel, 0) return 1 case 0x0082: // WM_NCDESTROY cleanupPanelState(hwnd) diff --git a/internal/installguide/guide.go b/internal/installguide/guide.go index 5f02cd4..7a2d3e6 100644 --- a/internal/installguide/guide.go +++ b/internal/installguide/guide.go @@ -94,21 +94,23 @@ const ( ) type content struct { - stage string - stageTone tone - title string - body string - code string - left string - right string - extra string - jump string - fold string - inputHint string - prev page - next page - alt page - isConfirm bool + stage string + stageTone tone + title string + body string + code string + left string + right string + extra string + jump string + fold string + inputHint string + prev page + next page + alt page + isConfirm bool + cancel string + disableRight bool } func (g Guide) preferences() (i18n.Locale, Theme) { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 0fdcee5..bc43cb6 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -1,4 +1,8 @@ { + "window.close.title": "Close “{name}”?", + "window.close.description": "Shut down asks macOS to shut down. Suspend saves the session.", + "window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", + "window.close.suspend": "Suspend", "doctor.title": "Reims-Go Host Environment Check", "doctor.os": "Operating System", "doctor.cpu": "CPU & Core Topology", diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index bc05abf..6f2f87e 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -50,9 +50,6 @@ "state_resuming": "Resuming", "state_broken": "Error", "suspend": "Suspend", - "vmCloseTitle": "Close “{name}”?", - "vmCloseDesc": "Shut down asks macOS to shut down. Suspend saves the session.", - "vmCloseDescNoSuspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.", "resume": "Resume", "resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM", "discardSuspend": "Discard saved state", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 91ce361..784d0e3 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -1,4 +1,8 @@ { + "window.close.title": "关闭「{name}」?", + "window.close.description": "关机将请求系统关闭。挂起会保存当前会话。", + "window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。", + "window.close.suspend": "挂起", "doctor.title": "Reims-Go 宿主机环境体检", "doctor.os": "操作系统", "doctor.cpu": "处理器与核心拓扑", diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index 7f73d4a..a8ab8f3 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -50,9 +50,6 @@ "state_resuming": "恢复中", "state_broken": "出错", "suspend": "挂起", - "vmCloseTitle": "关闭「{name}」?", - "vmCloseDesc": "关机将请求系统关闭。挂起会保存当前会话。", - "vmCloseDescNoSuspend": "当前运行时不支持挂起。关机将请求系统关闭。", "resume": "恢复", "resumeUnavailable": "切换到支持挂起的内核后可恢复", "discardSuspend": "放弃挂起状态", From f8943ea78c93cc55faae2f683cacd51e8f2f9e6e Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 18:06:40 +0800 Subject: [PATCH 23/23] docs: define PR ownership and client boundaries --- AGENTS.md | 1 + docs/pr-review-guidelines.md | 53 ++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 docs/pr-review-guidelines.md diff --git a/AGENTS.md b/AGENTS.md index ad9c2c8..a7fd824 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,7 @@ - [`docs/roadmap.md`](docs/roadmap.md) — 公开路线图与近期重点 - [`docs/architecture.md`](docs/architecture.md) — 系统架构、模块职责与安全边界 - [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案) +- [`docs/pr-review-guidelines.md`](docs/pr-review-guidelines.md) — PR 变更归属、跨仓交付与客户端独立性审查 - [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范 - [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范 - [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) — 运行时源码入口与依赖补丁 diff --git a/docs/pr-review-guidelines.md b/docs/pr-review-guidelines.md new file mode 100644 index 0000000..43ba194 --- /dev/null +++ b/docs/pr-review-guidelines.md @@ -0,0 +1,53 @@ +# PR 变更归属审查 + +> 以产生行为的实现为准。先定位改动发生在哪个组件,再决定提交仓库和验证范围。桌面或 CLI 是否有入口,只决定客户端是否也需要改动。 + +## 1. 确认归属 + +以 PR 实际目标分支与提交的差异为准。使用 GitHub 的「Files changed」或本地 `git diff ...`,同时检查生成文件对应的源文件、补丁目标、依赖锁定和 CI 变更。先从用户入口沿调用链找到行为的实现,再按下表归属。 + +| 类别 | 行为或改动 | 实现归属 | +| :--- | :--- | :--- | +| 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 | +| 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 | +| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 | +| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 | +| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 | +| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 | +| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 | +| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时规范](portable-runtime-spec.md)。 | + +同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。 + +## 2. 审查客户端独立性 + +- **构建与发布**:客户端 CI 仅从 `Reims-Go` 源码检出完成前端构建、Go 检查和应用产物构建。运行时源码、编译工具链和运行时发布产物由运行时仓库管理。客户端自行发布应用,并在虚拟机运行前下载、校验或导入兼容的独立运行时。 +- **接口边界**:客户端通过约定的子进程接口和协议调用运行时。配置写入沿用 [`reims-ctl set`](design-guidelines.md#2-配置原语)。需要新增命令、参数、字段或能力时,在负责组件实现,并在客户端附上对应接口证据。 +- **运行时兼容**:客户端 PR 写明验证使用的运行时与最低要求。若依赖新能力,优先使用运行时明确声明的能力或版本,在旧版、缺失运行时和不支持该能力的场景下明确禁用、提示或保留既有流程。客户端合入与运行时发布各自按其流程验收,用户默认仍走受支持的 `stable` 通道。 +- **跨仓交付**:按归属拆分 PR。客户端 PR 链接底层 PR、提交或运行时版本,列出合并顺序和兼容路径。临时依赖补丁由运行时仓库记录,注明目标仓库、适用提交和退役条件。跨仓定位以源码、依赖锁定和产物清单为证据。 + +## 3. PR 描述与合并检查 + +提交者在 PR 描述中附上以下信息。纯文档或纯客户端改动可将无关字段写为「不适用」。 + +```markdown +## 变更归属 + +- 用户可见行为 +- 变更位置与责任仓库 +- 上游证据(仓库、commit、文件及行号) +- 跨仓依赖(关联 PR、合并顺序、运行时要求) +- 旧版或缺失运行时的表现 + +## 验证 + +- 已通过的检查及运行时版本 +- 待验证场景及其影响 +``` + +审查者在合并前核对以下各项。 + +- [ ] 差异中的客户端、内核、独立依赖和分发变更均已注明归属。跨仓实现已拆分并可追溯。 +- [ ] 客户端能独立通过其 CI。行为变更已按影响验证 GUI、CLI 或两者的正常入口。 +- [ ] 底层或打包改动有负责仓库的验证证据。涉及运行时发布时,核对 `manifest.json` 中的来源提交、补丁与能力声明,以及相应的 [`alpha` 准入与 `stable` 冒烟要求](portable-runtime-spec.md#5-发布通道alpha--stable)。 +- [ ] 上游行为已定位到对应提交和源码行号。真机或兼容性覆盖不足的场景标明「待验证」,合并前明确其对客户端发布和能力开放的影响。