From fc196316760b55adfb9084aa8028e104b54e9fd9 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 09:47:41 +0800 Subject: [PATCH] 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"