Compare commits

...
Author SHA1 Message Date
YXC0915 4aeac5d646 feat(runtime): package a separate QEMU Stambha ARM preview 2026-12-04 18:37:37 +08:00
YXC0915 4f7c54c458 🆕 Package runtimes from the organization dependency pins [skip ci]
Read the source URLs and revisions directly from the selected runtime. Retire the six patches now in the organization forks and record the resolved URLs in the manifest and source package.
2026-12-03 02:54:20 +08:00
YXC0915 28457772f4 🐛 Isolate Places allocations from buffer address replay
Keep texture blocks in non-replay Vulkan allocations while preserving exact-address replay for captured buffers.
2026-12-03 01:02:03 +08:00
YXC0915 116ef68ae8 🐛 Resolve a working zstd for Windows runtime archives 2026-12-03 01:02:03 +08:00
Xiaochi You 1bc441947c Merge pull request #5 from yxc0915/steelbrain/static-attachment-feedback
🐛 Use static Vulkan attachment feedback for Windows
2026-12-03 00:41:50 +08:00
YXC0915 c0b03faa85 🐛 Use static Vulkan attachment feedback for Windows
Fix the dark desktop after FileVault unlock on RTX A5000 by setting the color attachment feedback flag at pipeline creation. Retain the existing feature gate and the shadow-copy fallback.
2026-12-03 00:40:40 +08:00
YXC0915 57024d3ab1 Handle retired maintenance refs during Alpha publication [ci skip]
A branch rename can remove the ref while a runtime build is running. Keep the verified artifact and skip automatic publication when Git succeeds with no match. Preserve the checks for a failed query or a superseded commit.
2026-12-02 19:41:01 +08:00
YXC0915 e8083c97ea 🐛 Update maintenance branch references [ci skip]
Keep automation and documentation aligned with the renamed branch.
The source pins and build steps stay the same.
2026-12-02 19:27:53 +08:00
YXC0915 3bbf37b149 Build Windows runtimes with the AMD Vulkan startup fixes
Apply the GPU address carry and dynamic attachment feedback backports after the snapshot replay patch. The runtime source archive records both patches alongside their pinned upstream base.
2026-12-02 18:59:10 +08:00
YXC0915 98f1677b5f 🆕 Select Alpha versions by suspend compatibility [ci skip]
Publish the version planner and compatibility manifest contract.
Wait for a new runtime baseline before building the next Alpha.
2026-12-02 03:22:02 +08:00
YXC0915 9a6ace7a3a 📝 Define Alpha suspend compatibility versions [ci skip]
Document patch revisions, compatibility boundaries, and the client
validation required to restore older saved state.
2026-12-02 02:47:03 +08:00
YXC0915 add539cd0f 🐛 Replace unfinished Alpha builds on push
Cancel older builds only for new automatic updates. Resolve stale
dispatches before taking the build lock and check published versions
inside it so queued runs skip work that already finished.
2026-12-02 02:05:31 +08:00
YXC0915 3cb5384b33 🆕 Build and publish Alpha on runtime changes
Build a new Alpha when packaging inputs change and queue an Alpha for
each upstream merge into the runtime maintenance branch.
2026-12-02 01:57:47 +08:00
23 changed files with 2152 additions and 1184 deletions

No files matched your search

+22 -1
View File
@@ -17,12 +17,15 @@ jobs:
if: github.repository == 'reims-go/reims-vgpu'
runs-on: ubuntu-latest
timeout-minutes: 20
outputs:
runtime_commit: ${{ steps.merge.outputs.runtime_commit }}
steps:
- name: Merge upstream into the maintenance branch
id: merge
shell: bash
env:
GH_TOKEN: ${{ github.token }}
TARGET_BRANCH: codex/intel-vm-suspend
TARGET_BRANCH: intel-vm-suspend
UPSTREAM_REPO: steelbrain/reims-vgpu
UPSTREAM_BRANCH: master
GIT_AUTHOR_NAME: YXC0915
@@ -88,4 +91,22 @@ jobs:
echo "::add-mask::$auth"
git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $auth" \
push origin "$merged:refs/heads/$TARGET_BRANCH"
printf 'runtime_commit=%s\n' "$merged" >> "$GITHUB_OUTPUT"
summary "Merged upstream commit $source into $TARGET_BRANCH at $merged."
alpha:
# Pushes made by GITHUB_TOKEN do not start push-triggered workflows.
needs: sync
if: needs.sync.outputs.runtime_commit != ''
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Queue Alpha for the merged commit
env:
GH_TOKEN: ${{ github.token }}
RUNTIME_COMMIT: ${{ needs.sync.outputs.runtime_commit }}
run: |
gh workflow run runtime-preview.yml --repo "$GITHUB_REPOSITORY" --ref master \
-f upstream_commit="$RUNTIME_COMMIT" -f publish=true -f supersede=true
+99 -80
View File
@@ -1,6 +1,10 @@
name: Publish Runtime Preview
on:
push:
branches: [master]
paths:
- "packaging/windows-runtime/**"
schedule:
- cron: "23 3 * * *"
workflow_dispatch:
@@ -13,21 +17,21 @@ on:
description: "Publish the verified preview as a GitHub prerelease"
type: boolean
default: true
supersede:
description: "Replace older builds for an automatic maintenance-branch push"
type: boolean
default: false
rebuild:
description: "Build a new patch revision (runtime-<commit>-pN) even if this upstream commit is already released"
description: "Plan a rebuild of an already published runtime using verified compatibility"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: build-runtime
cancel-in-progress: false
env:
UPSTREAM_URL: ${{ github.server_url }}/${{ github.repository }}.git
UPSTREAM_BRANCH: codex/intel-vm-suspend
UPSTREAM_BRANCH: intel-vm-suspend
jobs:
resolve:
@@ -35,55 +39,28 @@ jobs:
outputs:
commit: ${{ steps.r.outputs.commit }}
skip: ${{ steps.r.outputs.skip }}
suffix: ${{ steps.r.outputs.suffix }}
steps:
- id: r
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
WANT: ${{ inputs.upstream_commit }}
REBUILD: ${{ inputs.rebuild }}
CURRENT_ONLY: ${{ inputs.supersede }}
run: |
set -euo pipefail
git clone -q --filter=blob:none --no-checkout --single-branch --branch "$UPSTREAM_BRANCH" "$UPSTREAM_URL" up
commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")"
git -C up cat-file -e "$commit:reims-go-runtime.json"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
# Already published (alpha or stable) under any short-hash length or -pN revision?
max_rev=0
for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do
rest="${tag#runtime-}"
base="${rest%%-p*}"
case "$commit" in
"$base"*)
rev=1
if [ "$rest" != "$base" ]; then
num="${rest#"$base"-p}"
case "$num" in
''|*[!0-9]*) ;;
*) rev="$num" ;;
esac
fi
if [ "$rev" -gt "$max_rev" ]; then max_rev="$rev"; fi
echo "Upstream $commit is already released as $tag (rev $rev)"
;;
esac
done
skip=false
suffix=""
if [ "$max_rev" -gt 0 ]; then
if [ "$REBUILD" = "true" ]; then
suffix="-p$((max_rev + 1))"
echo "Rebuild requested: will publish with suffix $suffix"
else
skip=true
fi
if [[ "$CURRENT_ONLY" == true && "$commit" != "$(git -C up rev-parse HEAD)" ]]; then
echo "Skipping superseded runtime commit $commit"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
echo "skip=$skip" >> "$GITHUB_OUTPUT"
echo "suffix=$suffix" >> "$GITHUB_OUTPUT"
build:
needs: resolve
if: needs.resolve.outputs.skip != 'true'
concurrency:
group: build-runtime
cancel-in-progress: ${{ github.event_name == 'push' || inputs.supersede }}
runs-on: windows-latest
timeout-minutes: 150
permissions:
@@ -93,7 +70,36 @@ jobs:
with:
persist-credentials: false
# Select the version inside the build lock, including queued runs.
- name: Plan Alpha release
id: plan
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RUNTIME_COMMIT: ${{ needs.resolve.outputs.commit }}
REBUILD: ${{ github.event_name == 'push' || inputs.rebuild }}
PACKAGING_PUSH: ${{ github.event_name == 'push' }}
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
git config --global core.autocrlf false
git clone -q --filter=blob:none --no-checkout --single-branch --branch $env:UPSTREAM_BRANCH $env:UPSTREAM_URL $work
if ($LASTEXITCODE) { throw 'runtime clone failed' }
$plan = & ./packaging/windows-runtime/scripts/plan-runtime-release.ps1 `
-RuntimeRepo $work -RuntimeCommit $env:RUNTIME_COMMIT `
-PackagingRepo $env:GITHUB_WORKSPACE -PackagingCommit $env:GITHUB_SHA `
-Repository $env:GITHUB_REPOSITORY -Rebuild:($env:REBUILD -eq 'true') `
-PackagingPush:($env:PACKAGING_PUSH -eq 'true')
"skip=$($plan.Skip.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT
if ($plan.Skip) { return }
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"RELEASE_ID=$($plan.ReleaseId)" >> $env:GITHUB_ENV
"SUSPEND_COMPAT_ID=$($plan.SuspendCompatID)" >> $env:GITHUB_ENV
"SUSPEND_VERIFICATION=$($plan.Evidence)" >> $env:GITHUB_ENV
"SUSPEND_PREDECESSOR=$($plan.Predecessor)" >> $env:GITHUB_ENV
- name: Setup MSYS2 CLANG64
if: steps.plan.outputs.skip != 'true'
id: msys2
uses: msys2/setup-msys2@v2
with:
@@ -110,49 +116,35 @@ jobs:
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
- name: Check out the runtime forks and apply dependency patches
if: steps.plan.outputs.skip != 'true'
id: patches
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
$work = $env:UPSTREAM_DIR
foreach ($d in 'cargo', 'xdg-data', 'xdg-cache') { New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP $d) | Out-Null }
# The runner's git defaults to core.autocrlf=true; LF patches need an LF
# checkout (upstream also rewrites CRLF files to LF, install-ctl.sh).
git config --global core.autocrlf false
git clone -q --single-branch --branch $env:UPSTREAM_BRANCH $env:UPSTREAM_URL $work
if ($LASTEXITCODE) { throw 'clone failed' }
git -C $work checkout -q '${{ needs.resolve.outputs.commit }}'
if ($LASTEXITCODE) { throw 'checkout failed' }
git -C $work submodule update --init --depth 1 vendor/qemu
if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu }
if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' }
$utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util'
$utilPin = Get-Content -Raw -LiteralPath (Join-Path $work 'crates/reims-ctl/src/reims_util.rs')
if ($utilPin -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found' }
$utilRev = $Matches[1]
git init -q $utilRepo
if ($LASTEXITCODE) { throw 'reims-util init failed' }
git -C $utilRepo fetch -q --depth 1 https://github.com/steelbrain/reims-util.git $utilRev
if ($LASTEXITCODE) { throw 'reims-util fetch failed' }
git -C $utilRepo checkout -q --detach FETCH_HEAD
if ($LASTEXITCODE) { throw 'reims-util checkout failed' }
$m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan'
$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.toml')
if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') {
$m2vRev = $Matches[1]
} else {
$lockTxt = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.lock')
if ($lockTxt -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' }
$m2vRev = $Matches[1]
$pins = & ./packaging/windows-runtime/scripts/read-runtime-dependencies.ps1 -RuntimeRepo $work
function Get-DependencyCheckout($pin, [string]$path) {
git init -q $path
if ($LASTEXITCODE) { throw "Could not initialize $path" }
git -C $path remote add origin $pin.Url
if ($LASTEXITCODE) { throw "Could not add origin for $path" }
git -C $path fetch -q --depth 1 origin $pin.Rev
if ($LASTEXITCODE) { throw "Could not fetch $($pin.Url)@$($pin.Rev)" }
git -C $path checkout -q --detach $pin.Rev
if ($LASTEXITCODE) { throw "Could not check out $($pin.Url)@$($pin.Rev)" }
Write-Host "Using $($pin.Url)@$($pin.Rev)"
}
git init -q $m2vRepo
if ($LASTEXITCODE) { throw 'metal2vulkan init failed' }
git -C $m2vRepo fetch -q --depth 1 https://github.com/steelbrain/metal2vulkan.git $m2vRev
if ($LASTEXITCODE) { throw 'metal2vulkan fetch failed' }
git -C $m2vRepo checkout -q --detach FETCH_HEAD
if ($LASTEXITCODE) { throw 'metal2vulkan checkout failed' }
$utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util'
$m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan'
Get-DependencyCheckout $pins.Util $utilRepo
Get-DependencyCheckout $pins.Metal $m2vRepo
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
$releaseId = "$short${{ needs.resolve.outputs.suffix }}"
# Applies what applies, skips what upstream already has, stops on a
# conflict without touching the patch (AGENTS.md rule 4).
@@ -169,23 +161,26 @@ jobs:
}
if (-not $ok) { throw 'patch queue does not apply' }
$cargoHome = Join-Path $env:RUNNER_TEMP 'cargo'
$m2vFwd = $m2vRepo.Replace('\', '/')
$cargoCfg = @"
[patch."https://github.com/steelbrain/metal2vulkan"]
$m2vChanges = git -C $m2vRepo status --porcelain
if ($LASTEXITCODE) { throw 'Could not read metal2vulkan checkout status' }
if ($m2vChanges) {
$m2vFwd = $m2vRepo.Replace('\', '/')
$cargoCfg = @"
[patch."$($pins.Metal.Url)"]
metal2vulkan = { path = "$m2vFwd/crates/metal2vulkan" }
metal2vulkan-runtime = { path = "$m2vFwd/crates/metal2vulkan-runtime" }
"@ -replace '(?m)^ ', ''
[IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false))
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"@
[IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false))
}
"REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV
"METAL2VULKAN_DIR=$m2vRepo" >> $env:GITHUB_ENV
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
"RELEASE_ID=$releaseId" >> $env:GITHUB_ENV
"CARGO_HOME=$cargoHome" >> $env:GITHUB_ENV
"XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV
"XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV
- name: Build upstream runtime in MSYS2 CLANG64
if: steps.plan.outputs.skip != 'true'
shell: msys2 {0}
env:
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
@@ -203,6 +198,7 @@ jobs:
fi
- name: Package alpha runtime and source archives
if: steps.plan.outputs.skip != 'true'
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
@@ -222,19 +218,24 @@ jobs:
-TempRoot $env:RUNNER_TEMP `
-Channel alpha `
-ReleaseId $env:RELEASE_ID `
-SuspendCompatID $env:SUSPEND_COMPAT_ID `
-PackagingCommit $env:GITHUB_SHA `
-Patches $applied
- name: Alpha entry gate
if: steps.plan.outputs.skip != 'true'
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
& ./packaging/windows-runtime/scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:RELEASE_ID -RequireSlim -RequiredCapability vm-suspend `
-RequiredSuspendCompatID $env:SUSPEND_COMPAT_ID -RequiredPackagingCommit $env:GITHUB_SHA `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
- name: Upload alpha artifacts
if: steps.plan.outputs.skip != 'true'
uses: actions/upload-artifact@v4
with:
name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha
@@ -244,13 +245,27 @@ jobs:
retention-days: 14
- name: Publish alpha prerelease (never stable)
if: github.event_name == 'schedule' || inputs.publish
if: steps.plan.outputs.skip != 'true' && (github.event_name == 'push' || github.event_name == 'schedule' || inputs.publish)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CURRENT_ONLY: ${{ github.event_name == 'push' || inputs.supersede }}
MERGED: ${{ steps.patches.outputs.merged }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if ($env:CURRENT_ONLY -eq 'true') {
$ref = "refs/heads/$env:UPSTREAM_BRANCH"
$remote = git ls-remote $env:UPSTREAM_URL $ref
if ($LASTEXITCODE -ne 0) { throw "Could not query the runtime maintenance ref $ref" }
if (!$remote) {
Write-Warning "Skipping Alpha publication because $ref no longer exists. The verified archives are available in the workflow artifact."
return
}
if (($remote -split '\s+')[0] -ne '${{ needs.resolve.outputs.commit }}') {
Write-Host 'Skipping Alpha publication for a superseded runtime commit.'
return
}
}
$c = $env:RELEASE_ID
$short = $env:SHORT_COMMIT
$sourceRepo = $env:UPSTREAM_URL -replace '\.git$', ''
@@ -259,6 +274,7 @@ jobs:
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 { '' }
$compatibility = if ($env:SUSPEND_PREDECESSOR) { "`nVerified against $env:SUSPEND_PREDECESSOR. $env:SUSPEND_VERIFICATION" } else { '' }
$notes = @"
**Alpha** runtime (``$c``), built from [the Reims vGPU fork@$short]($sourceRepo/commit/${{ needs.resolve.outputs.commit }}).
@@ -269,7 +285,10 @@ jobs:
The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis.
Packaging commit: ``$env:GITHUB_SHA``
Suspend compatibility ID: ``$env:SUSPEND_COMPAT_ID``$compatibility
Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID
"@
gh release create "runtime-$c" @assets --repo $env:GITHUB_REPOSITORY --target '${{ needs.resolve.outputs.commit }}' --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
gh release create "runtime-$c" @assets --repo $env:GITHUB_REPOSITORY --target '${{ needs.resolve.outputs.commit }}' --prerelease --latest=false --title "Portable Runtime runtime-$c (alpha)" --notes $notes
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
+1
View File
@@ -1 +1,2 @@
patches/*.patch -text
patches/stambha-qemu/*.patch -text whitespace=-blank-at-eol,-blank-at-eof
+9 -12
View File
@@ -4,21 +4,18 @@
| 组件 | 源码 | 维护范围 |
| :--- | :--- | :--- |
| 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、文件迁移和设备状态保存恢复 |
| Reims vGPU | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu/tree/intel-vm-suspend) | GPU 挂起重放、窗口和 CLI 兼容性修复 |
| QEMU | [`reims-go/qemu-reims-vgpu`](https://github.com/reims-go/qemu-reims-vgpu/tree/intel-vm-suspend) | Windows WHPX、文件迁移和设备状态保存恢复 |
| metal2vulkan | [`reims-go/metal2vulkan`](https://github.com/reims-go/metal2vulkan/tree/development) | Vulkan 渲染、附件反馈和 GPU 地址重放 |
| reims-util | [`reims-go/reims-util`](https://github.com/reims-go/reims-util/tree/development) | OpenCore 和 macOS 安装介质,包括并发离线下载 |
Reims vGPU 分支通过 `vendor/qemu` 固定 QEMU 提交,并在 `reims-go-runtime.json` 声明运行时能力。更新 QEMU 时先把新提交推到 QEMU fork,再更新 Reims vGPU 的子模块指针。Reims-Go 构建据此记录两个源码仓库及提交号。
Reims vGPU 用 `vendor/qemu` 固定 QEMU 提交,用 `Cargo.toml` 和 `Cargo.lock` 固定 metal2vulkan,用 `crates/reims-ctl/src/reims_util.rs` 固定 reims-util。CI 根据这些固定值检出依赖,在运行时清单和对应源码包中记录四个组件的仓库及实际提交。
Alpha 编号与挂起兼容判定见 [Alpha 运行时编号与挂起兼容性规范](../versioning.md)。
## 构建时应用的依赖补丁
[`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 挂起重放提供依赖。 |
构建通过 Cargo 的本地源码覆盖使用已打补丁的 `metal2vulkan`。客户端的运行时包格式见[便携运行时规范](https://github.com/Nwflower/Reims-Go/blob/main/docs/portable-runtime-spec.md)。
[`series.txt`](series.txt) 目前为空。临时补丁按清单顺序应用,冲突会停止构建。客户端的运行时包格式见[便携运行时规范](https://github.com/Nwflower/Reims-Go/blob/main/docs/portable-runtime-spec.md)。
---
@@ -43,5 +40,5 @@ Reims vGPU 分支通过 `vendor/qemu` 固定 QEMU 提交,并在 `reims-go-runt
每日构建会跳过已合入的等价补丁,并在日志中报告。确认后按以下步骤清理。
1. 删除 `patches/` 下对应的 `.patch` 文件,并同步更新 [`series.txt`](series.txt) 与本文件。
2. 等待下一次定时构建,或在 Reims vGPU fork 手动触发 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml)。
2. 等待下一次定时构建,或在 Reims vGPU fork 手动触发 [Preview 工作流](https://github.com/reims-go/reims-vgpu/actions/workflows/runtime-preview.yml)。
3. 在真实宿主运行 [`smoke-runtime.ps1`](../scripts/smoke-runtime.ps1) 完成冒烟并人工确认后,将对应 Release 升级为 `stable`。
@@ -1,525 +0,0 @@
diff --git a/crates/metal2vulkan-runtime/src/block.rs b/crates/metal2vulkan-runtime/src/block.rs
index 0ac77ecac0f3abb9e9b76fb82d17c3536e22f4f5..426d025513a2f04e97f31efa66d1632635f7254d 100644
--- a/crates/metal2vulkan-runtime/src/block.rs
+++ b/crates/metal2vulkan-runtime/src/block.rs
@@ -54,6 +54,12 @@ impl Block {
Block { claim }
}
+ /// Returns capture/replay address metadata for this block (if supported).
+ pub fn capture_info(&self) -> Option<memory::BlockCaptureInfo> {
+ let (core, block) = self.held().ok()?;
+ core.pool.capture_info(&block.memory)
+ }
+
/// Whether the block is of `core`'s device.
pub(crate) fn is_of(&self, core: &Arc<Core>) -> bool {
Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core)
diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs
index 8edf1f27202f9a19b19cc4a4484d1e31341b8ab1..68f79440cc7727f2fae6063756380fe7a85ce7f9 100644
--- a/crates/metal2vulkan-runtime/src/device.rs
+++ b/crates/metal2vulkan-runtime/src/device.rs
@@ -273,6 +273,7 @@ pub(crate) struct Core {
/// every render pipeline takes its colour flag, and a draw reads an attachment of its pass
/// with the image in the feedback layout.
pub(crate) feedback_loop: bool,
+ pub(crate) capture_replay: bool,
/// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists
/// it): a lost device's fault report, read once, at its first loss (`crate::fault`).
pub(crate) fault: Option<ash::ext::device_fault::Device>,
@@ -860,6 +861,7 @@ impl Device {
ticks,
calibrated,
feedback_loop: capabilities.feedback_loop,
+ capture_replay: capabilities.buffer_device_address_capture_replay,
fault,
indirect,
attachment_reads: capabilities.attachment_reads,
@@ -1140,6 +1142,41 @@ impl Device {
/// allocation past the device's count; [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped)
/// where the consumer did not map the allocation the take made; [`Error::Vulkan`] where the
/// device is out of memory or lost; [`Error::Quiesced`].
+ /// Whether Vulkan `bufferDeviceAddressCaptureReplay` is enabled on this device.
+ pub fn buffer_device_address_capture_replay(&self) -> bool {
+ self.shared.core.capture_replay
+ }
+
+ /// Waits non-destructively until all in-flight GPU work has completed and retired.
+ pub fn wait_idle(&self) -> Result<(), Error> {
+ let core = &self.shared.core;
+ if core.closed() {
+ return Err(Error::Quiesced);
+ }
+ // Wait for submitted command buffers to retire on the completion thread.
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while core.pool.in_flight() > 0 && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ // SAFETY: `device` is live and wait_idle synchronizes all host queues.
+ let _q = lock(&core.queues.runtime);
+ unsafe { core.device.device_wait_idle() }.map_err(Error::vulkan("vkDeviceWaitIdle"))?;
+ Ok(())
+ }
+
+ /// Replays a previously captured block at its exact Vulkan device address.
+ pub fn take_block_replayed(&self, capture: memory::BlockCaptureInfo) -> Result<Block, Error> {
+ let core = &self.shared.core;
+ if core.closed() {
+ return Err(Error::Quiesced);
+ }
+ let memory = core.pool.take_replayed(core, capture, crate::counters::Site::take(capture.class))?;
+ let info = memory.info();
+ let block = memory::Block::new(memory, Arc::clone(core));
+ Ok(Block::claim(core, info, block))
+ }
+
+ /// Allocates a new GPU memory block of `class` and `len` bytes.
pub fn take_block(&self, class: MemoryClass, len: u64) -> Result<Block, Error> {
let core = &self.shared.core;
if core.closed() {
diff --git a/crates/metal2vulkan-runtime/src/event.rs b/crates/metal2vulkan-runtime/src/event.rs
index fe95046625fb1d1c81e2925458c22c4dd3641197..8b47e5604f50dec0549733c515ce80e02dbe348e 100644
--- a/crates/metal2vulkan-runtime/src/event.rs
+++ b/crates/metal2vulkan-runtime/src/event.rs
@@ -140,6 +140,35 @@ impl Event {
}
}
+impl Event {
+ /// Reads the current signaled value of this timeline event (for checkpointing).
+ pub fn signaled_value(&self) -> u64 {
+ let inner = &self.inner;
+ let state = lock(&inner.state);
+ let floor = state.observed.max(state.floor);
+ inner.reached(None).map_or(floor, |reached| reached.max(floor))
+ }
+
+ /// Restores the timeline semaphore and CPU floor to `value` on a freshly created event.
+ pub fn restore_signaled_value(&self, value: u64) -> Result<(), Error> {
+ if value == 0 {
+ return Ok(());
+ }
+ let inner = &self.inner;
+ let info = vk::SemaphoreSignalInfo::default()
+ .semaphore(inner.semaphore)
+ .value(value);
+ // SAFETY: `semaphore` is a live timeline semaphore on `inner.core.device`.
+ unsafe { inner.core.device.signal_semaphore(&info) }
+ .map_err(Error::vulkan("vkSignalSemaphore"))?;
+ let mut state = lock(&inner.state);
+ state.floor = state.floor.max(value);
+ state.observed = state.observed.max(value);
+ inner.changed.notify_all();
+ Ok(())
+ }
+}
+
impl SharedEvent {
/// `signaledValue`: the higher of the semaphore's value and the host's floor, the semaphore's
/// value being one a host wait confirmed: a counter read finds it, and a wait with a timeout
diff --git a/crates/metal2vulkan-runtime/src/floor.rs b/crates/metal2vulkan-runtime/src/floor.rs
index 0e165934f4b7534d0a093b1a22bcd763a47db8d7..90c7f9e354af205aa5a6b2fbeb506e58fbba1ab8 100644
--- a/crates/metal2vulkan-runtime/src/floor.rs
+++ b/crates/metal2vulkan-runtime/src/floor.rs
@@ -1079,6 +1079,8 @@ pub struct Capabilities {
/// [`ATTACHMENT_READ_EXTENSIONS`]: a draw reads an attachment through the attachment feedback
/// loop, the feedback layout its image moves to and the flag every render pipeline takes.
pub feedback_loop: bool,
+ /// Whether `bufferDeviceAddressCaptureReplay` is enabled for checkpoint/restore.
+ pub buffer_device_address_capture_replay: bool,
/// The features device creation enables: every one the floor requires, each of the optional,
/// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment
/// and fault-report ones the device reports, the attachment-read ones where
@@ -1425,6 +1427,10 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else {
return Err(BelowFloor { missing });
};
+ let capture_replay = reported.vulkan12.buffer_device_address_capture_replay == vk::TRUE;
+ if capture_replay {
+ features.vulkan12.buffer_device_address_capture_replay = vk::TRUE;
+ }
for feature in (OPTIONAL.iter().chain(STEP_RATES))
.chain(MIN_LOD_CLAMPS)
.chain(FILL_MODES)
@@ -1491,6 +1497,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE,
attachment_reads,
feedback_loop,
+ buffer_device_address_capture_replay: capture_replay,
features,
extensions: DEVICE_EXTENSIONS
.iter()
diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs
index a2d59cc6f31eb64307c1a886fe7cf75f401511b1..557a1a4b213773df976895f703cd4c037ad2602b 100644
--- a/crates/metal2vulkan-runtime/src/lib.rs
+++ b/crates/metal2vulkan-runtime/src/lib.rs
@@ -100,7 +100,7 @@ pub use host_bytes::HostBytes;
pub use import::ImportHandle;
pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType};
pub use instance::{Instance, PhysicalDevice};
-pub use memory::{AllocationId, AllocationInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
+pub use memory::{AllocationId, AllocationInfo, BlockCaptureInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
/// `MTLLibrary`: the translator's, read from AIR or a metallib.
/// `MTLSamplerDescriptor`: the translator's.
pub use metal2vulkan::bind::SamplerDescriptor;
diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs
index 173e0858f2e6d07660cafd5f7893aee280f2dcdc..2864f4ba6b48a4892e6d9651548c75a4babcf395 100644
--- a/crates/metal2vulkan-runtime/src/memory.rs
+++ b/crates/metal2vulkan-runtime/src/memory.rs
@@ -235,8 +235,28 @@ impl AllocationId {
/// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer
/// usage and a device address, spans it; an imported or exported block is the whole of an
/// allocation of its own. Only an exported block is exportable.
+/// Capture/replay address metadata for restoring a block at its exact Vulkan device address.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct BlockCaptureInfo {
+ /// Storage mode (`Shared` or `Private`).
+ pub class: MemoryClass,
+ /// Full parent Vulkan allocation length in bytes.
+ pub alloc_len: u64,
+ /// Offset of this block inside its parent allocation.
+ pub offset: u64,
+ /// Block length in bytes.
+ pub len: u64,
+ /// Guest-visible `VkDeviceAddress` of this block's first byte.
+ pub gpu_address: u64,
+ /// Opaque capture address of the parent `VkBuffer`.
+ pub opaque_buffer_address: u64,
+ /// Opaque capture address of the parent `VkDeviceMemory`.
+ pub opaque_memory_address: u64,
+}
+
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
+/// Metadata describing an allocated GPU memory block.
pub struct BlockInfo {
/// The block's number.
pub id: BlockId,
@@ -611,6 +631,10 @@ struct Allocation {
buffer: vk::Buffer,
/// The device address of its first byte.
address: u64,
+ /// Opaque capture address of `buffer` (0 if capture-replay unsupported).
+ opaque_buffer_address: u64,
+ /// Opaque capture address of `memory` (0 if capture-replay unsupported).
+ opaque_memory_address: u64,
len: u64,
mapping: Option<Mapping>,
device_local: bool,
@@ -823,6 +847,8 @@ struct State {
/// The internal the block-maker thread took up and is making ([`run`]).
making: Option<Internal>,
stop: bool,
+ replaying: bool,
+ making_ahead: bool,
next_id: u32,
next_allocation: u32,
/// The allocations [`BlockMappings::map`] accepted whose unmap has not run.
@@ -952,6 +978,8 @@ impl Pool {
asked: [true; INTERNALS],
making: None,
stop: false,
+ replaying: false,
+ making_ahead: false,
next_id: 1,
next_allocation: 1,
mapped: HashSet::new(),
@@ -1368,6 +1396,158 @@ impl Pool {
}
}
+ /// Returns capture/replay info for a pool block, if capture-replay is enabled.
+ pub(crate) fn capture_info(&self, memory: &Memory) -> Option<BlockCaptureInfo> {
+ if memory.own.is_some() {
+ return None;
+ }
+ let state = self.lock();
+ let alloc = state.allocations[memory.class.index()]
+ .iter()
+ .find(|a| a.memory == memory.memory)?;
+
+ Some(BlockCaptureInfo {
+ class: memory.class,
+ alloc_len: alloc.len,
+ offset: memory.base,
+ len: memory.len,
+ gpu_address: memory.address,
+ opaque_buffer_address: alloc.opaque_buffer_address,
+ opaque_memory_address: alloc.opaque_memory_address,
+ })
+ }
+
+ /// Replays a previously captured pool block at its exact Vulkan device address.
+ pub(crate) fn take_replayed(
+ &self,
+ core: &Core,
+ cap: BlockCaptureInfo,
+ site: Site,
+ ) -> Result<Memory, Error> {
+ let index = cap.class.index();
+ // 1. Check if the parent allocation is already present (e.g. another sub-block restored it,
+ // or a pre-stocked idle reserve landed at the exact same address!).
+ {
+ let mut state = self.lock();
+ if state.stop {
+ return Err(Error::Quiesced);
+ }
+ let id = number(&mut state)?;
+ let want_base = cap.gpu_address.saturating_sub(cap.offset);
+ if let Some(alloc) = state.allocations[index].iter_mut().find(|a| {
+ a.address == want_base
+ && a.opaque_buffer_address == cap.opaque_buffer_address
+ && a.opaque_memory_address == cap.opaque_memory_address
+ && a.len == cap.alloc_len
+ }) {
+ if alloc.free.take_at(cap.offset, cap.len) {
+ let carve = alloc.carve(cap.offset);
+ alloc.live += 1;
+ alloc.placed += cap.len;
+ alloc.ahead = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ return Ok(carve.block(id, cap.class, cap.len));
+ }
+ }
+ }
+ // 2. Pause block-maker ahead allocations, wait for any in-flight ahead make,
+ // and purge idle reserve slabs so none collide with the target opaque VA!
+ let idle_allocs: Vec<Allocation> = {
+ let mut state = self.lock();
+ state.replaying = true;
+ while state.making_ahead {
+ state = self.wait(state);
+ }
+ // Re-check if an ahead allocation that just finished landed at the exact target VA!
+ let want_base = cap.gpu_address.saturating_sub(cap.offset);
+ let hit = state.allocations[index].iter_mut().find_map(|a| {
+ if a.address == want_base
+ && a.opaque_buffer_address == cap.opaque_buffer_address
+ && a.opaque_memory_address == cap.opaque_memory_address
+ && a.len == cap.alloc_len
+ && a.free.take_at(cap.offset, cap.len)
+ {
+ let carve = a.carve(cap.offset);
+ a.live += 1;
+ a.placed += cap.len;
+ a.ahead = false;
+ Some(carve)
+ } else {
+ None
+ }
+ });
+ if let Some(carve) = hit {
+ let id = number(&mut state)?;
+ state.replaying = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ return Ok(carve.block(id, cap.class, cap.len));
+ }
+ let mut drained = Vec::new();
+ for c in MemoryClass::ALL {
+ let ci = c.index();
+ let mut kept = Vec::new();
+ for a in state.allocations[ci].drain(..) {
+ if a.live == 0 {
+ drained.push(a);
+ } else {
+ kept.push(a);
+ }
+ }
+ state.allocations[ci] = kept;
+ self.settle(&mut state, c);
+ }
+ drained
+ };
+ for a in idle_allocs {
+ free_idle(core, a);
+ }
+ // 3. Allocate at the exact captured opaque buffer + memory addresses.
+ let alloc_res = make_allocation_ex(
+ core,
+ cap.class,
+ cap.alloc_len,
+ Some(site),
+ Some((cap.opaque_buffer_address, cap.opaque_memory_address)),
+ );
+ let mut allocation = match alloc_res {
+ Ok(a) => a,
+ Err(e) => {
+ let mut state = self.lock();
+ state.replaying = false;
+ self.changed.notify_all();
+ return Err(e);
+ }
+ };
+ let mapped = self.map(&allocation, cap.class, true);
+ if !mapped {
+ free_allocation(core, allocation);
+ let mut state = self.lock();
+ state.replaying = false;
+ self.changed.notify_all();
+ return Err(Error::Limit(Limit::AllocationNotMapped {
+ class: cap.class,
+ len: cap.alloc_len,
+ }));
+ }
+ let ok = allocation.free.take_at(cap.offset, cap.len);
+ debug_assert!(ok, "fresh allocation must contain captured block range");
+ let mut state = self.lock();
+ let id = number(&mut state)?;
+ let memory = allocation.carve(cap.offset).block(id, cap.class, cap.len);
+ allocation.live = 1;
+ allocation.placed = cap.len;
+ state.allocations[index].push(allocation);
+ state.replaying = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ Ok(memory)
+ }
+
/// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its
/// allocation at once.
pub(crate) fn give_back(&self, memory: Memory) {
@@ -1788,12 +1968,16 @@ pub(crate) fn run(core: Arc<Core>) {
state = pool.lock();
continue;
}
- let wanted = (MemoryClass::ALL.into_iter())
- .find(|&class| !state.failed[class.index()] && !state.whole(class));
+ let wanted = (!state.replaying).then(|| {
+ (MemoryClass::ALL.into_iter())
+ .find(|&class| !state.failed[class.index()] && !state.whole(class))
+ }).flatten();
if let Some(class) = wanted {
+ state.making_ahead = true;
drop(state);
let made = ahead(&core, class);
state = pool.lock();
+ state.making_ahead = false;
match made {
// Idle from now: the reserve, which the idle rule does not weigh.
Some(mut allocation) => {
@@ -2022,6 +2206,16 @@ fn make_allocation(
class: MemoryClass,
len: u64,
site: Option<Site>,
+) -> Result<Allocation, Error> {
+ make_allocation_ex(core, class, len, site, None)
+}
+
+fn make_allocation_ex(
+ core: &Core,
+ class: MemoryClass,
+ len: u64,
+ site: Option<Site>,
+ replay: Option<(u64, u64)>,
) -> Result<Allocation, Error> {
let device = &core.device;
let (id, freed_at) = {
@@ -2031,22 +2225,38 @@ fn make_allocation(
state.freed_at[class.index()],
)
};
- let info = vk::BufferCreateInfo::default()
+ let mut buf_opaque = vk::BufferOpaqueCaptureAddressCreateInfo::default()
+ .opaque_capture_address(replay.map_or(0, |(b, _)| b));
+ let mut info = vk::BufferCreateInfo::default()
.size(len)
.usage(floor::BUFFER_USAGE)
.sharing_mode(vk::SharingMode::EXCLUSIVE);
+ if core.capture_replay {
+ info = info.flags(vk::BufferCreateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY);
+ if replay.is_some_and(|(b, _)| b != 0) {
+ info = info.push_next(&mut buf_opaque);
+ }
+ }
// SAFETY: the device is live, and the create info valid: `len` is at most its
// `maxBufferSize`.
let buffer =
unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?;
// SAFETY: the buffer is the device's.
let requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
- let mut flags =
- vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS);
- let allocate_info = vk::MemoryAllocateInfo::default()
+ let mut mem_flags = vk::MemoryAllocateFlags::DEVICE_ADDRESS;
+ if core.capture_replay {
+ mem_flags |= vk::MemoryAllocateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY;
+ }
+ let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(mem_flags);
+ let mut mem_opaque = vk::MemoryOpaqueCaptureAddressAllocateInfo::default()
+ .opaque_capture_address(replay.map_or(0, |(_, m)| m));
+ let mut allocate_info = vk::MemoryAllocateInfo::default()
.allocation_size(requirements.size.max(len))
.memory_type_index(core.memory_type(class))
.push_next(&mut flags);
+ if core.capture_replay && replay.is_some_and(|(_, m)| m != 0) {
+ allocate_info = allocate_info.push_next(&mut mem_opaque);
+ }
let bits = requirements.memory_type_bits;
// SAFETY: the floor chose the memory type for buffers of this usage on this device, and
// `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow.
@@ -2065,6 +2275,8 @@ fn make_allocation(
memory,
buffer,
address: 0,
+ opaque_buffer_address: 0,
+ opaque_memory_address: 0,
len,
mapping: None,
device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0,
@@ -2101,6 +2313,13 @@ fn make_allocation(
let of = vk::BufferDeviceAddressInfo::default().buffer(buffer);
// SAFETY: the buffer has device-address usage and is bound.
allocation.address = unsafe { device.get_buffer_device_address(&of) };
+ if core.capture_replay {
+ allocation.opaque_buffer_address =
+ unsafe { device.get_buffer_opaque_capture_address(&of) };
+ let mof = vk::DeviceMemoryOpaqueCaptureAddressInfo::default().memory(memory);
+ allocation.opaque_memory_address =
+ unsafe { device.get_device_memory_opaque_capture_address(&mof) };
+ }
(core.spans).made(
buffer,
allocation.address,
diff --git a/crates/metal2vulkan-runtime/src/places.rs b/crates/metal2vulkan-runtime/src/places.rs
index 137fb5790de850552affd179497df69d9912266a..3d679bbaa5285e87d1639a7cc140e0025b49e84f 100644
--- a/crates/metal2vulkan-runtime/src/places.rs
+++ b/crates/metal2vulkan-runtime/src/places.rs
@@ -248,6 +248,33 @@ impl Ranges {
Some(at)
}
+ /// Takes the exact range `at..at + len` if it is completely free.
+ pub(crate) fn take_at(&mut self, at: u64, len: u64) -> bool {
+ let Some(stop) = at.checked_add(len) else {
+ return false;
+ };
+ let Some(index) = self
+ .free
+ .iter()
+ .position(|&(start, end)| start <= at && stop <= end)
+ else {
+ return false;
+ };
+ let (start, end) = self.free[index];
+ match (start < at, stop < end) {
+ (false, false) => {
+ self.free.remove(index);
+ }
+ (true, false) => self.free[index] = (start, at),
+ (false, true) => self.free[index] = (stop, end),
+ (true, true) => {
+ self.free[index] = (start, at);
+ self.free.insert(index + 1, (stop, end));
+ }
+ }
+ true
+ }
+
/// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it.
pub(crate) fn give(&mut self, offset: u64, len: u64) {
let end = offset + len;
@@ -1,524 +0,0 @@
diff --git a/src/http.rs b/src/http.rs
index 69aeb817b8dc1ff2cebb91bbcad5d4ad749b1540..777a7d8adf65faaff0f08e228a4165ed48984e42 100644
--- a/src/http.rs
+++ b/src/http.rs
@@ -13,13 +13,15 @@
use crate::progress::{self, Reporter};
use anyhow::{Context, Result, bail};
use std::fs::{File, OpenOptions};
-use std::io::{Read, Seek, SeekFrom, Write};
+use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
+use std::thread;
use std::time::Duration;
use ureq::Agent;
/// The most each request asks for.
pub const SEGMENT: u64 = 64 << 20;
+const PARALLEL_REQUESTS: usize = 4;
/// How long a request may take to send its range: a stall is noticed within this. (On a
/// connection too slow to send a whole range in it, each request sends what it can.)
pub const SEGMENT_BUDGET: Duration = Duration::from_secs(180);
@@ -124,6 +126,8 @@ pub struct Download<'a> {
/// For requests the server refuses (401, 403): new headers, such as a fresh asset token.
pub refresh: Option<&'a mut dyn FnMut() -> Result<Headers>>,
pub user_agent: Option<&'static str>,
+ /// Fetch the public installer package in parallel within each checked segment.
+ pub parallel: bool,
/// Failed requests in a row, with no byte received between them, before it gives up:
/// [`MAX_FAILURES`], or fewer when there is another place to download the file from.
pub tries: u32,
@@ -138,6 +142,7 @@ impl Download<'_> {
size: None,
refresh: None,
user_agent: None,
+ parallel: false,
tries: MAX_FAILURES,
}
}
@@ -229,6 +234,8 @@ pub fn download(
let mut failures = 0u32;
let mut bad_chunks = 0u32;
let mut buf = vec![0u8; 1 << 18];
+ let mut parallel =
+ d.parallel && check.verifies() && d.headers.is_empty() && d.user_agent.is_none();
r.progress(have, total);
'requests: loop {
@@ -240,94 +247,116 @@ pub fn download(
Some(t) => (have + SEGMENT).min(t) - 1,
None => have + SEGMENT - 1,
};
- let mut req = agent
- .get(&d.url)
- .header("Range", format!("bytes={have}-{end}"));
- for (k, v) in &d.headers {
- req = req.header(k, v);
- }
- let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET));
- if let Some(ua) = d.user_agent {
- cfg = cfg.user_agent(ua);
- }
- let resp = match cfg.build().call() {
- Ok(resp) => resp,
- Err(e) => {
- failures += 1;
- retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?;
- continue;
+ // Keep one segment in memory and commit it through the same ordered
+ // writer and chunk checker used by serial downloads.
+ let batch = if parallel
+ && let Some(size) = total
+ && end - have >= (PARALLEL_REQUESTS - 1) as u64
+ {
+ match read_parallel_segment(agent, &d.url, have, end, size, r) {
+ Ok(bytes) => Some(bytes),
+ Err(_) => {
+ progress::check(r)?;
+ parallel = false;
+ r.note("Parallel ranges could not be read. Continuing with one connection.");
+ None
+ }
}
+ } else {
+ None
};
- let status = resp.status().as_u16();
- match status {
- 206 => {
- let range = resp
- .headers()
- .get("content-range")
- .and_then(|v| v.to_str().ok())
- .and_then(content_range)
- .with_context(|| format!("{} sent a range without Content-Range", d.url))?;
- if range.0 != have {
- bail!(
- "{} sent bytes from {} when asked for {have}",
- d.url,
- range.0
- );
+ let mut body: Box<dyn Read> = if let Some(bytes) = batch {
+ Box::new(Cursor::new(bytes))
+ } else {
+ let mut req = agent
+ .get(&d.url)
+ .header("Range", format!("bytes={have}-{end}"));
+ for (k, v) in &d.headers {
+ req = req.header(k, v);
+ }
+ let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET));
+ if let Some(ua) = d.user_agent {
+ cfg = cfg.user_agent(ua);
+ }
+ let resp = match cfg.build().call() {
+ Ok(resp) => resp,
+ Err(e) => {
+ failures += 1;
+ retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?;
+ continue;
+ }
+ };
+ let status = resp.status().as_u16();
+ match status {
+ 206 => {
+ let range = resp
+ .headers()
+ .get("content-range")
+ .and_then(|v| v.to_str().ok())
+ .and_then(content_range)
+ .with_context(|| format!("{} sent a range without Content-Range", d.url))?;
+ if range.0 != have {
+ bail!(
+ "{} sent bytes from {} when asked for {have}",
+ d.url,
+ range.0
+ );
+ }
+ match (total, range.1) {
+ (Some(t), Some(rt)) if t != rt => bail!(
+ "{} is {} long, not the expected {}: it changed on the server",
+ d.url,
+ rt,
+ t
+ ),
+ (None, Some(rt)) => {
+ total = Some(rt);
+ r.progress(have, total);
+ }
+ _ => {}
+ }
}
- match (total, range.1) {
- (Some(t), Some(rt)) if t != rt => bail!(
- "{} is {} long, not the expected {}: it changed on the server",
- d.url,
- rt,
- t
- ),
- (None, Some(rt)) => {
- total = Some(rt);
- r.progress(have, total);
+ 200 => {
+ // The whole file: the server ignored the range.
+ if have > 0 {
+ cut(file, 0)?;
+ have = 0;
+ check.restart_at(0);
+ }
+ if total.is_none() {
+ total = resp.body().content_length();
}
- _ => {}
}
- }
- 200 => {
- // The whole file: the server ignored the range.
- if have > 0 {
+ 416 if total.is_some_and(|t| have >= t) => break,
+ 416 => {
+ // Past the end: the file on the server is shorter than what we have.
+ if have == 0 {
+ bail!("{} refused every range", d.url);
+ }
+ r.note("The file changed on the server: starting over");
cut(file, 0)?;
have = 0;
check.restart_at(0);
+ continue;
}
- if total.is_none() {
- total = resp.body().content_length();
- }
- }
- 416 if total.is_some_and(|t| have >= t) => break,
- 416 => {
- // Past the end: the file on the server is shorter than what we have.
- if have == 0 {
- bail!("{} refused every range", d.url);
+ 401 | 403 if d.refresh.is_some() && failures < 3 => {
+ failures += 1;
+ if let Some(f) = d.refresh.as_mut() {
+ d.headers = f()?;
+ }
+ continue;
}
- r.note("The file changed on the server: starting over");
- cut(file, 0)?;
- have = 0;
- check.restart_at(0);
- continue;
- }
- 401 | 403 if d.refresh.is_some() && failures < 3 => {
- failures += 1;
- if let Some(f) = d.refresh.as_mut() {
- d.headers = f()?;
+ 408 | 429 | 500..=599 => {
+ failures += 1;
+ retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?;
+ continue;
}
- continue;
- }
- 408 | 429 | 500..=599 => {
- failures += 1;
- retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?;
- continue;
+ _ => bail!("{} answered HTTP {status}", d.url),
}
- _ => bail!("{} answered HTTP {status}", d.url),
- }
+ Box::new(resp.into_body().into_reader())
+ };
file.seek(SeekFrom::Start(base + have))?;
- let mut body = resp.into_body().into_reader();
let start = have;
loop {
if r.cancelled() {
@@ -389,6 +418,79 @@ pub fn download(
Ok(())
}
+fn read_parallel_segment(
+ agent: &Agent,
+ url: &str,
+ start: u64,
+ end: u64,
+ total: u64,
+ r: &dyn Reporter,
+) -> Result<Vec<u8>> {
+ let mut segment = vec![0; (end - start + 1) as usize];
+ let request_size = segment.len().div_ceil(PARALLEL_REQUESTS);
+ thread::scope(|scope| -> Result<()> {
+ let mut requests = Vec::with_capacity(PARALLEL_REQUESTS);
+ for (index, chunk) in segment.chunks_mut(request_size).enumerate() {
+ let first = start + (index * request_size) as u64;
+ let request = thread::Builder::new().spawn_scoped(scope, move || {
+ read_exact_range(agent, url, first, total, chunk, r)
+ })?;
+ requests.push(request);
+ }
+ for request in requests {
+ request
+ .join()
+ .map_err(|_| anyhow::anyhow!("range worker failed"))??;
+ }
+ Ok(())
+ })?;
+ Ok(segment)
+}
+
+fn read_exact_range(
+ agent: &Agent,
+ url: &str,
+ start: u64,
+ total: u64,
+ mut remaining: &mut [u8],
+ r: &dyn Reporter,
+) -> Result<()> {
+ let end = start + remaining.len() as u64 - 1;
+ progress::check(r)?;
+ let response = agent
+ .get(url)
+ .header("Range", format!("bytes={start}-{end}"))
+ .header("Accept-Encoding", "identity")
+ .config()
+ .timeout_recv_body(Some(SEGMENT_BUDGET))
+ .build()
+ .call()?;
+ let expected = format!("bytes {start}-{end}/{total}");
+ if response.status().as_u16() != 206
+ || response
+ .headers()
+ .get("Content-Range")
+ .and_then(|value| value.to_str().ok())
+ != Some(expected.as_str())
+ {
+ bail!("server did not return the requested byte range");
+ }
+ let mut body = response.into_body().into_reader();
+ while !remaining.is_empty() {
+ progress::check(r)?;
+ let n = body.read(remaining)?;
+ if n == 0 {
+ bail!("range body ended before its declared length");
+ }
+ remaining = &mut remaining[n..];
+ }
+ progress::check(r)?;
+ if body.read(&mut [0u8; 1])? != 0 {
+ bail!("range body exceeded its declared length");
+ }
+ Ok(())
+}
+
fn retry_or_fail(
failures: &mut u32,
tries: u32,
@@ -455,6 +557,173 @@ pub fn hex(b: &[u8]) -> String {
#[cfg(test)]
mod tests {
use super::*;
+ use std::io::{BufRead, BufReader};
+ use std::net::{TcpListener, TcpStream};
+
+ struct Silent;
+
+ impl Reporter for Silent {
+ fn event(&self, _: progress::Event) {}
+ }
+
+ fn read_request(stream: &TcpStream) -> Result<String> {
+ stream.set_read_timeout(Some(Duration::from_secs(5)))?;
+ let mut reader = BufReader::new(stream);
+ let mut range = String::new();
+ loop {
+ let mut line = String::new();
+ if reader.read_line(&mut line)? == 0 || line == "\r\n" {
+ break;
+ }
+ if let Some((name, value)) = line.split_once(':')
+ && name.eq_ignore_ascii_case("range")
+ {
+ range = value.trim().to_string();
+ }
+ }
+ Ok(range)
+ }
+
+ #[test]
+ fn sends_four_ranges_before_waiting_for_their_bodies() -> Result<()> {
+ let listener = TcpListener::bind("127.0.0.1:0")?;
+ listener.set_nonblocking(true)?;
+ let url = format!("http://{}", listener.local_addr()?);
+ let server = thread::spawn(move || -> Result<()> {
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ let mut requests = std::collections::BTreeMap::new();
+ while requests.len() < 4 {
+ match listener.accept() {
+ Ok((stream, _)) => {
+ let range = read_request(&stream)?;
+ requests.insert(range, stream);
+ }
+ Err(e)
+ if e.kind() == std::io::ErrorKind::WouldBlock
+ && std::time::Instant::now() < deadline =>
+ {
+ thread::sleep(Duration::from_millis(5));
+ }
+ Err(e) => {
+ return Err(e).context("waiting for four simultaneous range requests");
+ }
+ }
+ }
+ // No worker gets a response until all four requests have arrived.
+ let data = b"abcdefghijklmnop";
+ for offset in (0..data.len()).step_by(4).rev() {
+ let mut stream = requests
+ .remove(&format!("bytes={offset}-{}", offset + 3))
+ .context("missing requested range")?;
+ write!(
+ stream,
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes {offset}-{}/16\r\nConnection: close\r\n\r\n",
+ offset + 3
+ )?;
+ stream.write_all(&data[offset..offset + 4])?;
+ }
+ Ok(())
+ });
+ let data = read_parallel_segment(&test_agent(), &url, 0, 15, 16, &Silent);
+ server
+ .join()
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
+ assert_eq!(data?, b"abcdefghijklmnop");
+ Ok(())
+ }
+
+ #[test]
+ fn rejects_ignored_misaligned_and_truncated_ranges() -> Result<()> {
+ let listener = TcpListener::bind("127.0.0.1:0")?;
+ let url = format!("http://{}", listener.local_addr()?);
+ let server = thread::spawn(move || -> Result<()> {
+ for reply in [
+ "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\nabcd",
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes 5-8/16\r\nConnection: close\r\n\r\nabcd",
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 4-7/16\r\nConnection: close\r\n\r\nabc",
+ ] {
+ let (mut stream, _) = listener.accept()?;
+ read_request(&stream)?;
+ stream.write_all(reply.as_bytes())?;
+ }
+ Ok(())
+ });
+ let agent = test_agent();
+ for _ in 0..3 {
+ assert!(read_exact_range(&agent, &url, 4, 16, &mut [0; 4], &Silent).is_err());
+ }
+ server
+ .join()
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
+ Ok(())
+ }
+
+ #[test]
+ fn falls_back_to_a_single_request_from_the_verified_prefix() -> Result<()> {
+ use crate::chunklist::{ChunkCheck, Chunklist, Signature};
+ use sha2::{Digest, Sha256};
+
+ let data = b"abcdefghijklmnop";
+ let listener = TcpListener::bind("127.0.0.1:0")?;
+ let url = format!("http://{}", listener.local_addr()?);
+ let server = thread::spawn(move || -> Result<()> {
+ for _ in 0..PARALLEL_REQUESTS {
+ let (mut stream, _) = listener.accept()?;
+ read_request(&stream)?;
+ stream.write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ )?;
+ }
+ let (mut stream, _) = listener.accept()?;
+ assert_eq!(read_request(&stream)?, "bytes=4-15");
+ stream.write_all(
+ b"HTTP/1.1 206 Partial Content\r\nContent-Length: 12\r\nContent-Range: bytes 4-15/16\r\nConnection: close\r\n\r\n",
+ )?;
+ stream.write_all(&data[4..])?;
+ Ok(())
+ });
+ let dir = std::env::temp_dir().join(format!("reims-util-fallback-{}", std::process::id()));
+ std::fs::create_dir_all(&dir)?;
+ let path = dir.join("download");
+ std::fs::write(part_path(&path), &data[..4])?;
+ let chunks = data
+ .chunks_exact(4)
+ .map(|chunk| (4, Sha256::digest(chunk).into()))
+ .collect();
+ let mut check = ChunkCheck::new(Chunklist {
+ chunks,
+ signature: Signature::Digest,
+ });
+ let mut request = Download::new(&url, "Test download".into());
+ request.size = Some(data.len() as u64);
+ request.parallel = true;
+ let result = download(
+ &test_agent(),
+ request,
+ Dest::File(&path),
+ &mut check,
+ &Silent,
+ );
+ let actual = std::fs::read(&path);
+ let _ = std::fs::remove_file(&path);
+ let _ = std::fs::remove_file(part_path(&path));
+ let _ = std::fs::remove_dir(&dir);
+ result?;
+ server
+ .join()
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
+ assert_eq!(actual?, data);
+ Ok(())
+ }
+
+ fn test_agent() -> Agent {
+ Agent::config_builder()
+ .proxy(None)
+ .http_status_as_error(false)
+ .timeout_global(Some(Duration::from_secs(5)))
+ .build()
+ .into()
+ }
#[test]
fn parses_content_range() {
diff --git a/src/installer.rs b/src/installer.rs
index 7c17423300c153fd24fe9e031de3a835dcda57e1..265031a5d2ff54e0b8c9b752bad579c5927c5ef1 100644
--- a/src/installer.rs
+++ b/src/installer.rs
@@ -475,6 +475,7 @@ pub fn offline_installer(inst: &Installer, dir: &Path, r: &dyn Reporter) -> Resu
progress::check(r)?;
let mut d = Download::new(&inst.url, format!("Downloading {}", inst.label()));
d.size = Some(inst.size);
+ d.parallel = true;
let pkg = Dest::Region {
file: &mut f,
offset: pkg_at,
@@ -746,6 +747,7 @@ mod tests {
/// macOS 12's and 26's do, through `<target>Applications`), and where it fails after placing
/// the app (as Big Sur's does, needing zsh), the app gets the package as SharedSupport.dmg
/// and the script starts its startosinstall on the volume.
+ #[cfg(unix)]
#[test]
fn install_script_runs_without_dirname_or_zsh() {
use std::os::unix::fs::{PermissionsExt, symlink};
diff --git a/src/recovery.rs b/src/recovery.rs
index fe4eadc745ac4867802254a53197821acac3d411..11406e790884549b7e4e6b297f29c3a0285c606f 100644
--- a/src/recovery.rs
+++ b/src/recovery.rs
@@ -311,6 +311,7 @@ impl Image {
size: Some(self.size()),
refresh: Some(&mut refresh),
user_agent: Some(USER_AGENT),
+ parallel: false,
tries: http::MAX_FAILURES,
};
http::download(&self.agent, d, dest, check, r)
+2 -4
View File
@@ -1,8 +1,6 @@
# Patch queue, in the order the patches are applied (see patches/README.md).
# One patch per line: <target> <file>.
# The runtime forks contain the Reims vGPU and QEMU changes.
# This queue applies additional patches to their pinned dependencies.
# Runtime components are built from the pinned Reims-Go organization forks.
# The queue is reserved for temporary patches to those pinned checkouts.
# CI (runtime-preview.yml via scripts/apply-patch-series.ps1) and
# scripts/pack-runtime.ps1 both read this file; add or retire patches here.
reims-util reims-util-parallel-offline-download.patch
metal2vulkan metal2vulkan-snapshot-replay.patch
@@ -0,0 +1,261 @@
From 7f323d0c8ed194ba81fcd3d33bfa2d3624d47e34 Mon Sep 17 00:00:00 2001
From: Reims-Go Builder <builder@reims-go.local>
Date: Thu, 3 Dec 2026 17:30:03 +0800
Subject: [PATCH 1/3] patches/series.txt: apply 4 pinned vendor/qemu patches
---
target/i386/whpx/whpx-all.c | 117 +++++++++++++++++++++++++++++++++---
util/coroutine-windows.c | 32 +++++++++-
2 files changed, 137 insertions(+), 12 deletions(-)
diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c
index 5aa46bc3..f093b59c 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[] = {
@@ -530,7 +531,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);
@@ -1680,6 +1682,7 @@ HRESULT whpx_set_exception_exit_bitmap(UINT64 exceptions)
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;
@@ -2388,6 +2391,53 @@ static void whpx_inject_exceptions(CPUState* cpu)
}
}
+/* 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;
@@ -2519,6 +2569,14 @@ int whpx_vcpu_run(CPUState *cpu)
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);
@@ -3211,22 +3269,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)
@@ -3442,9 +3534,8 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
&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;
}
}
@@ -3584,6 +3675,12 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
* 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/util/coroutine-windows.c b/util/coroutine-windows.c
index 7db2e8f8..57f59ae3 100644
--- 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;
@@ -72,10 +74,25 @@ static void CALLBACK coroutine_trampoline(void *co_)
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 @@ Coroutine *qemu_coroutine_self(void)
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;
}
--
2.55.0.windows.5
@@ -0,0 +1,389 @@
From a9b206aa666c59a62160dfa5c5c4a4a20e2805ae Mon Sep 17 00:00:00 2001
From: Reims-Go Builder <builder@reims-go.local>
Date: Thu, 3 Dec 2026 17:34:07 +0800
Subject: [PATCH 2/3] reims-go: hosted ARM64 display transport and 128-slot TCG
jump cache (control baseline)
---
accel/tcg/tb-hash.h | 10 +-
accel/tcg/tb-jmp-cache.h | 5 +
hw/display/reims-graphics-pci.c | 240 ++++++++++++++++++++++++++++++--
3 files changed, 240 insertions(+), 15 deletions(-)
diff --git a/accel/tcg/tb-hash.h b/accel/tcg/tb-hash.h
index f7b159f0..29ee4936 100644
--- a/accel/tcg/tb-hash.h
+++ b/accel/tcg/tb-hash.h
@@ -31,7 +31,7 @@
/* Only the bottom TB_JMP_PAGE_BITS of the jump cache hash bits vary for
addresses on the same page. The top bits are the same. This allows
TLB invalidation to quickly clear a subset of the hash table. */
-#define TB_JMP_PAGE_BITS (TB_JMP_CACHE_BITS / 2)
+#define TB_JMP_PAGE_BITS ((TB_JMP_CACHE_BITS + 1) / 2)
#define TB_JMP_PAGE_SIZE (1 << TB_JMP_PAGE_BITS)
#define TB_JMP_ADDR_MASK (TB_JMP_PAGE_SIZE - 1)
#define TB_JMP_PAGE_MASK (TB_JMP_CACHE_SIZE - TB_JMP_PAGE_SIZE)
@@ -45,10 +45,10 @@ static inline unsigned int tb_jmp_cache_hash_page(vaddr pc)
static inline unsigned int tb_jmp_cache_hash_func(vaddr pc)
{
- vaddr tmp;
- tmp = pc ^ (pc >> (TARGET_PAGE_BITS - TB_JMP_PAGE_BITS));
- return (((tmp >> (TARGET_PAGE_BITS - TB_JMP_PAGE_BITS)) & TB_JMP_PAGE_MASK)
- | (tmp & TB_JMP_ADDR_MASK));
+ /* Fold address bits above the slot index to spread aligned targets. */
+ vaddr slot = pc ^ (pc >> TB_JMP_PAGE_BITS);
+
+ return tb_jmp_cache_hash_page(pc) | (slot & TB_JMP_ADDR_MASK);
}
#else
diff --git a/accel/tcg/tb-jmp-cache.h b/accel/tcg/tb-jmp-cache.h
index c3a505e3..a7d434c2 100644
--- a/accel/tcg/tb-jmp-cache.h
+++ b/accel/tcg/tb-jmp-cache.h
@@ -12,7 +12,12 @@
#include "qemu/rcu.h"
#include "exec/cpu-common.h"
+#ifdef CONFIG_SOFTMMU
+/* Keep 64 page groups, with twice as many slots per group. */
+#define TB_JMP_CACHE_BITS 13
+#else
#define TB_JMP_CACHE_BITS 12
+#endif
#define TB_JMP_CACHE_SIZE (1 << TB_JMP_CACHE_BITS)
/*
diff --git a/hw/display/reims-graphics-pci.c b/hw/display/reims-graphics-pci.c
index db10858b..3f7e50df 100644
--- a/hw/display/reims-graphics-pci.c
+++ b/hw/display/reims-graphics-pci.c
@@ -245,6 +245,18 @@ struct ReimsGraphicsPCIState {
char *resolution; /* the property: each window's first size, or NULL */
uint32_t displays; /* the property: 1 to RVG_GRAPHICS_DISPLAYS_MAX */
+ bool hosted_arm64; /* ARM64 protocol over an x86 host transport */
+ uint32_t hosted_irq_generation; /* atomic; written by Reims callbacks */
+ uint64_t hosted_ram_guest_pa;
+ uint64_t hosted_ram_host_gpa;
+ uint64_t hosted_ram_bytes;
+ struct {
+ uint64_t guest_pa;
+ uint64_t host_gpa;
+ uint64_t bytes;
+ } hosted_ram_staged[64];
+ uint32_t hosted_ram_staged_count;
+ uint32_t hosted_ram_committed_count;
/* Mutable state (BQL protected) */
uint32_t input_buttons; /* RVG_WINDOW_BUTTON_* bits the guest was sent */
@@ -321,6 +333,11 @@ static void reims_graphics_pci_raise_interrupt_cb(void *ctx, uint32_t vector)
ReimsGraphicsInterruptJob *job;
bool sent = false;
+ if (s->hosted_arm64) {
+ /* The callback follows publication of the completion bytes. */
+ qatomic_inc(&s->hosted_irq_generation);
+ return;
+ }
if (qatomic_load_acquire(&s->irqfd_on)) {
event_notifier_set(&s->irqfd);
return;
@@ -1037,9 +1054,29 @@ static const MemoryRegionOps reims_graphics_pci_ops = {
* The doorbell pages: no register to read, and a write to the library on the
* vCPU, as a DOORBELL write is.
*/
+static void reims_graphics_commit_hosted_ram(ReimsGraphicsPCIState *s);
+
static uint64_t reims_graphics_doorbells_read(void *opaque, hwaddr offset,
unsigned size)
{
+ ReimsGraphicsPCIState *s = opaque;
+ uint64_t end = memory_region_size(&s->doorbells);
+
+ /* Hosted-translator-only control/IRQ readouts at top of BAR 4. */
+ if (s->hosted_arm64) {
+ if (offset == end - 0x08) {
+ return 0x52495251; /* RIRQ */
+ }
+ if (offset == end - 0x04) {
+ return qatomic_load_acquire(&s->hosted_irq_generation);
+ }
+ if (offset == end - 0x10) {
+ return 0x524d4150; /* RMAP */
+ }
+ if (offset == end - 0x14) {
+ return s->hosted_ram_committed_count;
+ }
+ }
return 0;
}
@@ -1047,6 +1084,51 @@ static void reims_graphics_doorbells_write(void *opaque, hwaddr offset,
uint64_t value, unsigned size)
{
ReimsGraphicsPCIState *s = opaque;
+ uint64_t end = memory_region_size(&s->doorbells);
+
+ if (s->hosted_arm64 && offset >= end - 0x2c && offset <= end - 0x14) {
+ uint64_t v = value & 0xffffffffULL;
+ if (offset == end - 0x2c) {
+ s->hosted_ram_guest_pa = (s->hosted_ram_guest_pa & 0xffffffff00000000ULL) | v;
+ return;
+ }
+ if (offset == end - 0x28) {
+ s->hosted_ram_guest_pa = (s->hosted_ram_guest_pa & 0x00000000ffffffffULL) | (v << 32);
+ return;
+ }
+ if (offset == end - 0x24) {
+ s->hosted_ram_host_gpa = (s->hosted_ram_host_gpa & 0xffffffff00000000ULL) | v;
+ return;
+ }
+ if (offset == end - 0x20) {
+ s->hosted_ram_host_gpa = (s->hosted_ram_host_gpa & 0x00000000ffffffffULL) | (v << 32);
+ return;
+ }
+ if (offset == end - 0x1c) {
+ s->hosted_ram_bytes = (s->hosted_ram_bytes & 0xffffffff00000000ULL) | v;
+ return;
+ }
+ if (offset == end - 0x18) {
+ s->hosted_ram_bytes = (s->hosted_ram_bytes & 0x00000000ffffffffULL) | (v << 32);
+ return;
+ }
+ if (offset == end - 0x14) {
+ if (v == 1) {
+ s->hosted_ram_staged_count = 0;
+ s->hosted_ram_committed_count = 0;
+ } else if (v == 2) {
+ if (s->hosted_ram_staged_count < 64 && s->hosted_ram_bytes != 0) {
+ uint32_t idx = s->hosted_ram_staged_count++;
+ s->hosted_ram_staged[idx].guest_pa = s->hosted_ram_guest_pa;
+ s->hosted_ram_staged[idx].host_gpa = s->hosted_ram_host_gpa;
+ s->hosted_ram_staged[idx].bytes = s->hosted_ram_bytes;
+ }
+ } else if (v == 3) {
+ reims_graphics_commit_hosted_ram(s);
+ }
+ return;
+ }
+ }
rvg_graphics_device_doorbell_write(s->device, offset, value);
}
@@ -2278,6 +2360,130 @@ static bool reims_graphics_add_memory_range(Int128 start, Int128 len,
return false;
}
+typedef struct {
+ ReimsGraphicsMemoryWalk *walk;
+ uint64_t guest_pa;
+ uint64_t host_gpa;
+ uint64_t bytes;
+} ReimsHostedClipWalk;
+
+static bool reims_graphics_clip_hosted_range(Int128 start, Int128 len,
+ const MemoryRegion *mr,
+ hwaddr offset_in_region,
+ void *opaque)
+{
+ ReimsHostedClipWalk *cw = opaque;
+ RAMBlock *rb = mr->ram_block;
+ uint64_t mr_start, mr_end, req_end, clip_start, clip_end, clip_len;
+ uint8_t *host;
+ RvgMemoryRange range;
+#ifdef _WIN32
+ RvgMemoryRangeFile file = { .handle = NULL };
+ HANDLE section;
+#else
+ RvgMemoryRangeFile file = { .fd = -1 };
+ int fd;
+#endif
+
+ if (!memory_access_is_direct(mr, true, MEMTXATTRS_UNSPECIFIED)) {
+ return false;
+ }
+ if (qemu_ram_pagesize(rb) != qemu_real_host_page_size()) {
+ return false;
+ }
+#ifdef _WIN32
+ section = qemu_ram_get_section(rb);
+ if (!section) {
+ return false;
+ }
+#else
+ fd = memory_region_get_fd(mr);
+#ifndef CONFIG_DARWIN
+ if (fd < 0 || !qemu_ram_is_shared(rb)) {
+ return false;
+ }
+#endif
+#endif
+ mr_start = int128_get64(start);
+ mr_end = mr_start + int128_get64(len);
+ req_end = cw->host_gpa + cw->bytes;
+ if (mr_end <= cw->host_gpa || mr_start >= req_end) {
+ return false;
+ }
+ clip_start = mr_start > cw->host_gpa ? mr_start : cw->host_gpa;
+ clip_end = mr_end < req_end ? mr_end : req_end;
+ clip_len = clip_end - clip_start;
+ host = (uint8_t *)memory_region_get_ram_ptr(mr) + offset_in_region +
+ (clip_start - mr_start);
+ range = (RvgMemoryRange) {
+ .physical_address = cw->guest_pa + (clip_start - cw->host_gpa),
+ .physical_length = clip_len,
+ .host_address = host,
+ };
+#if defined(_WIN32)
+ file.handle = section;
+ file.offset = qemu_ram_block_host_offset(rb, host);
+#elif !defined(CONFIG_DARWIN)
+ file.fd = fd;
+ file.offset = qemu_ram_block_host_offset(rb, host) +
+ qemu_ram_get_fd_offset(rb);
+#else
+ (void)fd;
+#endif
+ g_array_append_val(cw->walk->ranges, range);
+ g_array_append_val(cw->walk->files, file);
+ return false;
+}
+
+static void reims_graphics_commit_hosted_ram(ReimsGraphicsPCIState *s)
+{
+ ReimsGraphicsMemoryWalk walk = {
+ .ranges = g_array_new(false, false, sizeof(RvgMemoryRange)),
+ .files = g_array_new(false, false, sizeof(RvgMemoryRangeFile)),
+ };
+ FlatView *fv = address_space_to_flatview(&address_space_memory);
+ uint64_t total_bytes = 0;
+ RvgMemoryMap memory_map;
+ RvgStatus status;
+
+ s->hosted_ram_committed_count = 0;
+ for (uint32_t i = 0; i < s->hosted_ram_staged_count; i++) {
+ ReimsHostedClipWalk cw = {
+ .walk = &walk,
+ .guest_pa = s->hosted_ram_staged[i].guest_pa,
+ .host_gpa = s->hosted_ram_staged[i].host_gpa,
+ .bytes = s->hosted_ram_staged[i].bytes,
+ };
+ flatview_for_each_range(fv, reims_graphics_clip_hosted_range, &cw);
+ }
+ if (walk.ranges->len == 0) {
+ warn_report("%s: hosted ARM64 RAM map commit matched 0 shared RAM ranges "
+ "(ensure -object memory-backend-ram,id=ram,...,share=on)",
+ TYPE_REIMS_GRAPHICS_PCI);
+ goto out;
+ }
+ for (guint i = 0; i < walk.ranges->len; i++) {
+ total_bytes += g_array_index(walk.ranges, RvgMemoryRange, i).physical_length;
+ }
+ memory_map = (RvgMemoryMap) {
+ .ranges = (const RvgMemoryRange *)walk.ranges->data,
+ .range_count = walk.ranges->len,
+ };
+ status = rvg_graphics_device_set_memory_map(
+ s->device, &memory_map, (const RvgMemoryRangeFile *)walk.files->data);
+ if (status != RVG_OK) {
+ warn_report("%s: rvg_graphics_device_set_memory_map failed: %s",
+ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status));
+ goto out;
+ }
+ s->hosted_ram_committed_count = walk.ranges->len;
+ info_report("%s: hosted ARM64 zero-copy RAM map installed (%u ranges, %" PRIu64 " MiB)",
+ TYPE_REIMS_GRAPHICS_PCI, walk.ranges->len, total_bytes >> 20);
+out:
+ g_array_free(walk.ranges, true);
+ g_array_free(walk.files, true);
+}
+
/*
* Warns where the machine leaves BAR 2 no address in a macOS guest. macOS
* lays every 64-bit prefetchable BAR out below 4 GiB, where the region's
@@ -2503,15 +2709,15 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
const RvgWindowConfig *display_windows[RVG_GRAPHICS_DISPLAYS_MAX - 1];
bool window = reims_graphics_window_wanted();
/*
- * The guest's architecture is this QEMU's target: the device answers an
- * arm64 guest's Metal as an Apple silicon Mac's GPU answers where the two
- * kinds of Mac differ (isFramebufferReadSupported).
+ * The device answers Metal for the architecture that speaks the
+ * graphics protocol. A hosted ARM64 translator can use the x86
+ * PCI transport for an ARM64 guest.
*/
RvgGraphicsDeviceConfig config = {
.struct_size = sizeof(config),
.callbacks = &callbacks,
- .guest_arch = target_aarch64() ? RVG_GUEST_ARCH_ARM64
- : RVG_GUEST_ARCH_X86_64,
+ .guest_arch = (target_aarch64() || s->hosted_arm64)
+ ? RVG_GUEST_ARCH_ARM64 : RVG_GUEST_ARCH_X86_64,
/* BAR 4 is registered below, its writes sent to the library. */
.doorbell_pages = 1,
};
@@ -2533,6 +2739,11 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
uint64_t pool_room = 0;
uint32_t i;
+ if (s->hosted_arm64 && !g_str_equal(target_name(), "x86_64")) {
+ error_setg(errp, "%s: x-hosted-arm64 requires the x86_64 target",
+ TYPE_REIMS_GRAPHICS_PCI);
+ return;
+ }
if (!reims_graphics_linux_floor(errp)) {
return;
}
@@ -2603,8 +2814,15 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
* views of the map's pages while the device lives, so they must stay the
* guest's RAM: no balloon or hot-unplug may discard them.
*/
- flatview_for_each_range(address_space_to_flatview(&address_space_memory),
- reims_graphics_add_memory_range, &walk);
+ /*
+ * A hosted guest's addresses belong to the inner address space.
+ * Until the translator supplies a mapping, share only the device's
+ * own region, never the outer VM's RAM.
+ */
+ if (!s->hosted_arm64) {
+ flatview_for_each_range(address_space_to_flatview(&address_space_memory),
+ reims_graphics_add_memory_range, &walk);
+ }
if (walk.ranges->len > 0) {
memory_map = (RvgMemoryMap) {
.ranges = (const RvgMemoryRange *)walk.ranges->data,
@@ -2612,7 +2830,7 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
};
config.memory_map = &memory_map;
config.memory_files = (const RvgMemoryRangeFile *)walk.files->data;
- } else {
+ } else if (!s->hosted_arm64) {
warn_report("%s: no guest RAM is "
#if defined(_WIN32)
"a shared section "
@@ -2630,8 +2848,9 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
* room as the host GPU's memory heaps hold, summed, and the range is
* reserved once it answers (reims_graphics_pool_reserve).
*/
- if (reims_graphics_pool_room(dev, &pool_base, &pool_room) ||
- reims_graphics_pool_room_machine(&pool_base, &pool_room)) {
+ if (!s->hosted_arm64 &&
+ (reims_graphics_pool_room(dev, &pool_base, &pool_room) ||
+ reims_graphics_pool_room_machine(&pool_base, &pool_room))) {
config.pool_physical_address = pool_base;
config.pool_physical_length = pool_room;
}
@@ -2785,6 +3004,7 @@ static void reims_graphics_pci_finalize(Object *obj)
static const Property reims_graphics_pci_properties[] = {
DEFINE_PROP_STRING("resolution", ReimsGraphicsPCIState, resolution),
DEFINE_PROP_UINT32("displays", ReimsGraphicsPCIState, displays, 1),
+ DEFINE_PROP_BOOL("x-hosted-arm64", ReimsGraphicsPCIState, hosted_arm64, false),
};
static void reims_graphics_pci_class_init(ObjectClass *klass, const void *data)
--
2.55.0.windows.5
@@ -0,0 +1,497 @@
From fa0519c7b77668dd17b7ba710a3d3ecd802aa669 Mon Sep 17 00:00:00 2001
From: Reims-Go Builder <builder@reims-go.local>
Date: Thu, 3 Dec 2026 17:34:13 +0800
Subject: [PATCH 3/3] block/win32, nvme: complete cached Win32 file I/O inline
on I/O SQ doorbell
---
block/block-backend.c | 63 ++++++++++++++
block/file-win32.c | 90 ++++++++++++++++++++
hw/nvme/ctrl.c | 58 ++++++++++++-
hw/nvme/nvme.h | 1 +
include/system/block-backend-io.h | 6 ++
include/system/dma.h | 6 ++
system/dma-helpers.c | 135 ++++++++++++++++++++++++++++++
7 files changed, 358 insertions(+), 1 deletion(-)
diff --git a/block/block-backend.c b/block/block-backend.c
index 656c0aed..b8b616f9 100644
--- a/block/block-backend.c
+++ b/block/block-backend.c
@@ -1654,6 +1654,69 @@ static void coroutine_fn blk_aio_write_entry(void *opaque)
blk_aio_complete(acb);
}
+/*
+ * Like blk_aio_prwv(), but when called outside a coroutine and the underlying
+ * request completes synchronously without yielding, deliver the completion
+ * immediately and return NULL instead of scheduling a deferred BH.
+ */
+static BlockAIOCB *blk_aio_prwv_syncok(BlockBackend *blk, int64_t offset,
+ int64_t bytes, void *iobuf,
+ CoroutineEntry co_entry,
+ BdrvRequestFlags flags,
+ BlockCompletionFunc *cb,
+ void *opaque)
+{
+ BlkAioEmAIOCB *acb;
+ Coroutine *co;
+
+ blk_inc_in_flight(blk);
+ acb = blk_aio_get(&blk_aio_em_aiocb_info, blk, cb, opaque);
+ acb->rwco = (BlkRwCo) {
+ .blk = blk,
+ .offset = offset,
+ .iobuf = iobuf,
+ .flags = flags,
+ .ret = NOT_DONE,
+ };
+ acb->bytes = bytes;
+ acb->has_returned = false;
+
+ co = qemu_coroutine_create(co_entry, acb);
+ aio_co_enter(qemu_get_current_aio_context(), co);
+
+ acb->has_returned = true;
+ if (acb->rwco.ret != NOT_DONE) {
+ if (!qemu_in_coroutine()) {
+ blk_aio_complete(acb);
+ return NULL;
+ }
+ replay_bh_schedule_oneshot_event(qemu_get_current_aio_context(),
+ blk_aio_complete_bh, acb);
+ }
+
+ return &acb->common;
+}
+
+BlockAIOCB *blk_aio_preadv_syncok(BlockBackend *blk, int64_t offset,
+ QEMUIOVector *qiov,
+ BdrvRequestFlags flags,
+ BlockCompletionFunc *cb, void *opaque)
+{
+ assert((uint64_t)qiov->size <= INT64_MAX);
+ return blk_aio_prwv_syncok(blk, offset, qiov->size, qiov,
+ blk_aio_read_entry, flags, cb, opaque);
+}
+
+BlockAIOCB *blk_aio_pwritev_syncok(BlockBackend *blk, int64_t offset,
+ QEMUIOVector *qiov,
+ BdrvRequestFlags flags,
+ BlockCompletionFunc *cb, void *opaque)
+{
+ assert((uint64_t)qiov->size <= INT64_MAX);
+ return blk_aio_prwv_syncok(blk, offset, qiov->size, qiov,
+ blk_aio_write_entry, flags, cb, opaque);
+}
+
BlockAIOCB *blk_aio_pwrite_zeroes(BlockBackend *blk, int64_t offset,
int64_t bytes, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque)
diff --git a/block/file-win32.c b/block/file-win32.c
index b63ce1c1..308dfc6f 100644
--- a/block/file-win32.c
+++ b/block/file-win32.c
@@ -33,6 +33,7 @@
#include "trace.h"
#include "block/thread-pool.h"
#include "qemu/iov.h"
+#include "qemu/coroutine.h"
#include "qobject/qdict.h"
#include "qobject/qstring.h"
#include <windows.h>
@@ -436,6 +437,93 @@ static BlockAIOCB *raw_aio_pwritev(BlockDriverState *bs,
}
}
+/*
+ * Synchronous cached Windows file I/O fast path.
+ * Non-overlapped ReadFile/WriteFile on cached FTYPE_FILE handles hits
+ * NTFS FastIoRead/FastIoWrite directly on the caller thread; raw devices,
+ * aio=native, BDRV_O_NOCACHE, and all flush/discard requests still take
+ * the thread pool.
+ */
+static int coroutine_fn GRAPH_RDLOCK
+raw_co_prw(BlockDriverState *bs, int64_t offset, int64_t bytes,
+ QEMUIOVector *qiov, bool is_write)
+{
+ BDRVRawState *s = bs->opaque;
+ int64_t cur_offset = offset;
+ size_t total_done = 0;
+ int i;
+
+ if (s->aio != NULL || s->type != FTYPE_FILE ||
+ (bs->open_flags & BDRV_O_NOCACHE)) {
+ RawWin32AIOData *acb = g_new(RawWin32AIOData, 1);
+ acb->bs = bs;
+ acb->hfile = s->hfile;
+ acb->aio_type = is_write ? QEMU_AIO_WRITE : QEMU_AIO_READ;
+ acb->aio_iov = qiov->iov;
+ acb->aio_niov = qiov->niov;
+ acb->aio_nbytes = bytes;
+ acb->aio_offset = offset;
+ return thread_pool_submit_co(aio_worker, acb);
+ }
+
+ for (i = 0; i < qiov->niov; i++) {
+ size_t rem = qiov->iov[i].iov_len;
+ uint8_t *base = qiov->iov[i].iov_base;
+
+ while (rem > 0) {
+ DWORD chunk = (DWORD)MIN(rem, (size_t)0x7ffff000U);
+ OVERLAPPED ov;
+ DWORD done = 0;
+ BOOL ok;
+
+ memset(&ov, 0, sizeof(ov));
+ ov.Offset = (DWORD)cur_offset;
+ ov.OffsetHigh = (DWORD)((uint64_t)cur_offset >> 32);
+ if (is_write) {
+ ok = WriteFile(s->hfile, base, chunk, &done, &ov);
+ } else {
+ ok = ReadFile(s->hfile, base, chunk, &done, &ov);
+ }
+ if (!ok) {
+ DWORD err = GetLastError();
+ if (!is_write && err == ERROR_HANDLE_EOF) {
+ qemu_iovec_memset(qiov, total_done, 0, bytes - total_done);
+ return 0;
+ }
+ return -EIO;
+ }
+ if (done < chunk) {
+ if (!is_write) {
+ qemu_iovec_memset(qiov, total_done + done, 0,
+ bytes - (total_done + done));
+ return 0;
+ }
+ return -EINVAL;
+ }
+ cur_offset += done;
+ total_done += done;
+ base += done;
+ rem -= done;
+ }
+ }
+
+ return 0;
+}
+
+static int coroutine_fn GRAPH_RDLOCK
+raw_co_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
+ QEMUIOVector *qiov, BdrvRequestFlags flags)
+{
+ return raw_co_prw(bs, offset, bytes, qiov, false);
+}
+
+static int coroutine_fn GRAPH_RDLOCK
+raw_co_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
+ QEMUIOVector *qiov, BdrvRequestFlags flags)
+{
+ return raw_co_prw(bs, offset, bytes, qiov, true);
+}
+
static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
BlockCompletionFunc *cb, void *opaque)
{
@@ -727,6 +815,8 @@ BlockDriver bdrv_file = {
.bdrv_aio_preadv = raw_aio_preadv,
.bdrv_aio_pwritev = raw_aio_pwritev,
.bdrv_aio_flush = raw_aio_flush,
+ .bdrv_co_preadv = raw_co_preadv,
+ .bdrv_co_pwritev = raw_co_pwritev,
.bdrv_co_truncate = raw_co_truncate,
.bdrv_co_getlength = raw_co_getlength,
diff --git a/hw/nvme/ctrl.c b/hw/nvme/ctrl.c
index 10e5d976..48d23118 100644
--- a/hw/nvme/ctrl.c
+++ b/hw/nvme/ctrl.c
@@ -216,6 +216,7 @@
#include "migration/vmstate.h"
#include "nvme.h"
+#include "qemu/coroutine.h"
#include "dif.h"
#include "trace.h"
@@ -1479,6 +1480,21 @@ static inline void nvme_blk_read(BlockBackend *blk, int64_t offset,
{
assert(req->sg.flags & NVME_SG_ALLOC);
+ if (!qemu_in_coroutine() && !req->ns->lbaf.ms) {
+ BlockAIOCB *aiocb;
+ if (req->sg.flags & NVME_SG_DMA) {
+ aiocb = dma_blk_read_syncok(blk, &req->sg.qsg, offset, align,
+ cb, req);
+ } else {
+ aiocb = blk_aio_preadv_syncok(blk, offset, &req->sg.iov, 0,
+ cb, req);
+ }
+ if (aiocb) {
+ req->aiocb = aiocb;
+ }
+ return;
+ }
+
if (req->sg.flags & NVME_SG_DMA) {
req->aiocb = dma_blk_read(blk, &req->sg.qsg, offset, align, cb, req);
} else {
@@ -1492,6 +1508,21 @@ static inline void nvme_blk_write(BlockBackend *blk, int64_t offset,
{
assert(req->sg.flags & NVME_SG_ALLOC);
+ if (!qemu_in_coroutine() && !req->ns->lbaf.ms) {
+ BlockAIOCB *aiocb;
+ if (req->sg.flags & NVME_SG_DMA) {
+ aiocb = dma_blk_write_syncok(blk, &req->sg.qsg, offset, align,
+ cb, req);
+ } else {
+ aiocb = blk_aio_pwritev_syncok(blk, offset, &req->sg.iov, 0,
+ cb, req);
+ }
+ if (aiocb) {
+ req->aiocb = aiocb;
+ }
+ return;
+ }
+
if (req->sg.flags & NVME_SG_DMA) {
req->aiocb = dma_blk_write(blk, &req->sg.qsg, offset, align, cb, req);
} else {
@@ -1598,6 +1629,19 @@ static void nvme_enqueue_req_completion(NvmeCQueue *cq, NvmeRequest *req)
QTAILQ_REMOVE(&req->sq->out_req_list, req, entry);
QTAILQ_INSERT_TAIL(&cq->req_list, req, entry);
+ if (req->sq->inline_processing) {
+ /* Batch CQEs into the single post_cqes() flush at end of nvme_process_db(). */
+ return;
+ }
+ if (!DEVICE(cq->ctrl)->mem_reentrancy_guard.engaged_in_io &&
+ !qemu_in_coroutine()) {
+ /* Mirror aio_bh_call() guarded reentrancy state for async main-loop completions. */
+ DEVICE(cq->ctrl)->mem_reentrancy_guard.engaged_in_io = true;
+ nvme_post_cqes(cq);
+ DEVICE(cq->ctrl)->mem_reentrancy_guard.engaged_in_io = false;
+ return;
+ }
+
qemu_bh_schedule(cq->bh);
}
@@ -8690,7 +8734,19 @@ static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val)
stl_le_pci_dma(pci, sq->db_addr, sq->tail, MEMTXATTRS_UNSPECIFIED);
}
- qemu_bh_schedule(sq->bh);
+ if (qid != 0 && !n->dbbuf_enabled && !sq->inline_processing &&
+ !qemu_in_coroutine()) {
+ NvmeCQueue *cq = n->cq[sq->cqid];
+ assert(DEVICE(n)->mem_reentrancy_guard.engaged_in_io);
+ sq->inline_processing = true;
+ nvme_process_sq(sq);
+ sq->inline_processing = false;
+ if (cq && !QTAILQ_EMPTY(&cq->req_list)) {
+ nvme_post_cqes(cq);
+ }
+ } else {
+ qemu_bh_schedule(sq->bh);
+ }
}
}
diff --git a/hw/nvme/nvme.h b/hw/nvme/nvme.h
index a4b2c01a..78eca196 100644
--- a/hw/nvme/nvme.h
+++ b/hw/nvme/nvme.h
@@ -523,6 +523,7 @@ typedef struct NvmeSQueue {
QEMUBH *bh;
EventNotifier notifier;
bool ioeventfd_enabled;
+ bool inline_processing;
NvmeRequest *io_req;
QTAILQ_HEAD(, NvmeRequest) req_list;
QTAILQ_HEAD(, NvmeRequest) out_req_list;
diff --git a/include/system/block-backend-io.h b/include/system/block-backend-io.h
index 78d410b8..b6b577a3 100644
--- a/include/system/block-backend-io.h
+++ b/include/system/block-backend-io.h
@@ -51,6 +51,12 @@ BlockAIOCB *blk_aio_preadv(BlockBackend *blk, int64_t offset,
BlockAIOCB *blk_aio_pwritev(BlockBackend *blk, int64_t offset,
QEMUIOVector *qiov, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque);
+BlockAIOCB *blk_aio_preadv_syncok(BlockBackend *blk, int64_t offset,
+ QEMUIOVector *qiov, BdrvRequestFlags flags,
+ BlockCompletionFunc *cb, void *opaque);
+BlockAIOCB *blk_aio_pwritev_syncok(BlockBackend *blk, int64_t offset,
+ QEMUIOVector *qiov, BdrvRequestFlags flags,
+ BlockCompletionFunc *cb, void *opaque);
BlockAIOCB *blk_aio_flush(BlockBackend *blk,
BlockCompletionFunc *cb, void *opaque);
BlockAIOCB *blk_aio_zone_report(BlockBackend *blk, int64_t offset,
diff --git a/include/system/dma.h b/include/system/dma.h
index 82e7ad54..cc3790ee 100644
--- a/include/system/dma.h
+++ b/include/system/dma.h
@@ -299,6 +299,12 @@ BlockAIOCB *dma_blk_read(BlockBackend *blk,
BlockAIOCB *dma_blk_write(BlockBackend *blk,
QEMUSGList *sg, uint64_t offset, uint32_t align,
BlockCompletionFunc *cb, void *opaque);
+BlockAIOCB *dma_blk_read_syncok(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ BlockCompletionFunc *cb, void *opaque);
+BlockAIOCB *dma_blk_write_syncok(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ BlockCompletionFunc *cb, void *opaque);
MemTxResult dma_buf_read(void *ptr, dma_addr_t len, dma_addr_t *residual,
QEMUSGList *sg, MemTxAttrs attrs);
MemTxResult dma_buf_write(void *ptr, dma_addr_t len, dma_addr_t *residual,
diff --git a/system/dma-helpers.c b/system/dma-helpers.c
index 0d592f64..830d7407 100644
--- a/system/dma-helpers.c
+++ b/system/dma-helpers.c
@@ -274,6 +274,141 @@ BlockAIOCB *dma_blk_write(BlockBackend *blk,
DMA_DIRECTION_TO_DEVICE);
}
+static void dma_blk_cb_syncok(void *opaque, int ret)
+{
+ DMAAIOCB *dbs = (DMAAIOCB *)opaque;
+ AioContext *ctx = dbs->ctx;
+ dma_addr_t cur_addr, cur_len;
+ void *mem;
+ BlockAIOCB *child_acb;
+
+ trace_dma_blk_cb(dbs, ret);
+
+ assert(ctx == qemu_get_current_aio_context());
+
+ dbs->acb = NULL;
+ dbs->offset += dbs->iov.size;
+
+ if (dbs->sg_cur_index == dbs->sg->nsg || ret < 0) {
+ dma_complete(dbs, ret);
+ return;
+ }
+ dma_blk_unmap(dbs);
+
+ while (dbs->sg_cur_index < dbs->sg->nsg) {
+ cur_addr = dbs->sg->sg[dbs->sg_cur_index].base + dbs->sg_cur_byte;
+ cur_len = dbs->sg->sg[dbs->sg_cur_index].len - dbs->sg_cur_byte;
+ mem = dma_memory_map(dbs->sg->as, cur_addr, &cur_len, dbs->dir,
+ MEMTXATTRS_UNSPECIFIED);
+ if (mem && icount_enabled() && dbs->dir == DMA_DIRECTION_FROM_DEVICE) {
+ int i;
+ for (i = 0; i < dbs->iov.niov; ++i) {
+ if (ranges_overlap((intptr_t)dbs->iov.iov[i].iov_base,
+ dbs->iov.iov[i].iov_len, (intptr_t)mem,
+ cur_len)) {
+ dma_memory_unmap(dbs->sg->as, mem, cur_len,
+ dbs->dir, cur_len);
+ mem = NULL;
+ break;
+ }
+ }
+ }
+ if (!mem) {
+ break;
+ }
+ qemu_iovec_add(&dbs->iov, mem, cur_len);
+ dbs->sg_cur_byte += cur_len;
+ if (dbs->sg_cur_byte == dbs->sg->sg[dbs->sg_cur_index].len) {
+ dbs->sg_cur_byte = 0;
+ ++dbs->sg_cur_index;
+ }
+ }
+
+ if (dbs->iov.size == 0) {
+ trace_dma_map_wait(dbs);
+ dbs->bh = aio_bh_new(ctx, reschedule_dma, dbs);
+ address_space_register_map_client(dbs->sg->as, dbs->bh);
+ return;
+ }
+
+ if (!QEMU_IS_ALIGNED(dbs->iov.size, dbs->align)) {
+ qemu_iovec_discard_back(&dbs->iov,
+ QEMU_ALIGN_DOWN(dbs->iov.size, dbs->align));
+ }
+
+ child_acb = dbs->io_func(dbs->offset, &dbs->iov,
+ dma_blk_cb_syncok, dbs, dbs->io_func_opaque);
+ if (child_acb) {
+ dbs->acb = child_acb;
+ }
+}
+
+static BlockAIOCB *dma_blk_io_syncok(
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ DMAIOFunc *io_func, void *io_func_opaque,
+ BlockCompletionFunc *cb,
+ void *opaque, DMADirection dir)
+{
+ DMAAIOCB *dbs = qemu_aio_get(&dma_aiocb_info, NULL, cb, opaque);
+
+ trace_dma_blk_io(dbs, io_func_opaque, offset, (dir == DMA_DIRECTION_TO_DEVICE));
+
+ dbs->acb = NULL;
+ dbs->sg = sg;
+ dbs->ctx = qemu_get_current_aio_context();
+ dbs->offset = offset;
+ dbs->align = align;
+ dbs->sg_cur_index = 0;
+ dbs->sg_cur_byte = 0;
+ dbs->dir = dir;
+ dbs->io_func = io_func;
+ dbs->io_func_opaque = io_func_opaque;
+ dbs->bh = NULL;
+ qemu_iovec_init(&dbs->iov, sg->nsg);
+ qemu_aio_ref(dbs);
+ dma_blk_cb_syncok(dbs, 0);
+ if (!dbs->acb && !dbs->bh) {
+ qemu_aio_unref(dbs);
+ return NULL;
+ }
+ qemu_aio_unref(dbs);
+ return &dbs->common;
+}
+
+static BlockAIOCB *dma_blk_read_syncok_io_func(int64_t offset, QEMUIOVector *iov,
+ BlockCompletionFunc *cb,
+ void *cb_opaque, void *opaque)
+{
+ BlockBackend *blk = opaque;
+ return blk_aio_preadv_syncok(blk, offset, iov, 0, cb, cb_opaque);
+}
+
+BlockAIOCB *dma_blk_read_syncok(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ void (*cb)(void *opaque, int ret), void *opaque)
+{
+ return dma_blk_io_syncok(sg, offset, align,
+ dma_blk_read_syncok_io_func, blk, cb, opaque,
+ DMA_DIRECTION_FROM_DEVICE);
+}
+
+static BlockAIOCB *dma_blk_write_syncok_io_func(int64_t offset, QEMUIOVector *iov,
+ BlockCompletionFunc *cb,
+ void *cb_opaque, void *opaque)
+{
+ BlockBackend *blk = opaque;
+ return blk_aio_pwritev_syncok(blk, offset, iov, 0, cb, cb_opaque);
+}
+
+BlockAIOCB *dma_blk_write_syncok(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ void (*cb)(void *opaque, int ret), void *opaque)
+{
+ return dma_blk_io_syncok(sg, offset, align,
+ dma_blk_write_syncok_io_func, blk, cb, opaque,
+ DMA_DIRECTION_TO_DEVICE);
+}
+
static MemTxResult dma_buf_rw(void *buf, dma_addr_t len, dma_addr_t *residual,
QEMUSGList *sg, DMADirection dir,
--
2.55.0.windows.5
@@ -0,0 +1,3 @@
0001-qemu-win32-compatibility.patch
0002-qemu-stambha-hosted-graphics.patch
0003-qemu-win32-nvme-inline-io.patch
@@ -27,6 +27,8 @@ param(
[string]$Zstd,
[string[]]$AppliedPatches = @(),
[string]$RequiredCapability = '',
[string]$RequiredSuspendCompatID = '',
[string]$RequiredPackagingCommit = '',
[switch]$RequireSlim,
# Only for checking packages built before the 2026-11-28 rename ("candidate").
[string]$ExpectChannel = 'alpha',
@@ -86,6 +88,13 @@ try {
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" }
if ($RequiredSuspendCompatID -and ($m.suspend_compat_id -cne $RequiredSuspendCompatID -or
$Commit -cnotmatch ('^' + [regex]::Escape($RequiredSuspendCompatID) + '(?:-p[1-9][0-9]*)?$'))) {
throw "manifest suspend_compat_id is $($m.suspend_compat_id), expected $RequiredSuspendCompatID for $Commit"
}
if ($RequiredPackagingCommit -and $m.packaging_commit -cne $RequiredPackagingCommit) {
throw "manifest packaging_commit is $($m.packaging_commit), expected $RequiredPackagingCommit"
}
$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)
@@ -0,0 +1,127 @@
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Mandatory)] [string]$AssetDir,
[Parameter(Mandatory)] [ValidatePattern('^[a-z0-9][a-z0-9.-]{0,63}$')] [string]$ReleaseId,
[Parameter(Mandatory)] [string]$Zstd
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'stambha-runtime-files.ps1')
$tar = Join-Path $env:SystemRoot 'System32/tar.exe'
$assets = (Resolve-Path -LiteralPath $AssetDir).Path
$runtime = "reims-stambha-runtime-win-x64-$ReleaseId"
$sources = "reims-stambha-runtime-src-$ReleaseId"
$sums = Get-Content -LiteralPath (Join-Path $assets 'SHA256SUMS.txt')
foreach ($base in @($runtime, $sources)) {
$name = "$base.tar.zst"
$line = Get-Content -Raw -LiteralPath (Join-Path $assets "$name.sha256")
$fields = $line.TrimEnd() -split ' ', 2
if ($fields.Count -ne 2 -or $fields[1] -cne $name -or $line.TrimEnd() -cnotin $sums) {
throw "Invalid or mismatched release checksum for $name"
}
Assert-StambhaHash (Join-Path $assets $name) $fields[0]
}
function Expand-StambhaAsset([string]$Stage, [string]$Name) {
$tarball = Join-Path $Stage "$Name.tar"
[void](Invoke-StambhaCommand $Zstd @('-d', '-q', (Join-Path $assets "$Name.tar.zst"), '-o', $tarball))
$entries = @(Invoke-StambhaCommand $tar @('-tf', $tarball))
$seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($entry in $entries) {
$normalized = $entry.TrimEnd('/')
$segments = $normalized -split '/'
if ($segments[0] -cne $Name -or $normalized -match '[\x00-\x1f:\\]' -or
($segments | Where-Object { $_ -in @('', '.', '..') }) -or !$seen.Add($normalized)) {
throw "Unexpected path in ${Name}: $entry"
}
}
$types = @(Invoke-StambhaCommand $tar @('-tvf', $tarball))
if (($types.Count -ne $entries.Count) -or ($types | Where-Object { $_ -notmatch '^[-d]' })) {
throw "Unexpected member type in $Name"
}
[void](Invoke-StambhaCommand $tar @('-xf', $tarball, '-C', $Stage))
Remove-Item -LiteralPath $tarball
Join-Path $Stage $Name
}
$parent = Split-Path -Parent $assets
$stage = Join-Path $parent ('.stambha-check-' + [guid]::NewGuid().ToString('N'))
[void][IO.Directory]::CreateDirectory($stage)
try {
$payload = Expand-StambhaAsset $stage $runtime
$source = Expand-StambhaAsset $stage $sources
$manifest = Get-Content -Raw -LiteralPath (Join-Path $payload 'manifest.json') | ConvertFrom-Json -AsHashtable
if ($manifest.schema_version -ne 2 -or $manifest.commit -cne $ReleaseId -or
$manifest.kind -cne 'stambha-hosted' -or $manifest.runtime_api -cne '0.1.0' -or
$manifest.platform -cne 'windows-x86_64' -or $manifest.channel -cne 'alpha' -or
$manifest.source_package -cne "$sources.tar.zst" -or !$manifest.license) {
throw 'Unexpected Stambha runtime manifest'
}
$files = @(Get-ChildItem -LiteralPath $payload -Force -Recurse -File)
$bytes = [long](($files | Measure-Object Length -Sum).Sum)
if ($files.Count -ne $manifest.file_count -or $bytes -ne $manifest.raw_bytes -or
$manifest.sha256.Count -ne ($files.Count - 1) -or
@($files | Where-Object { $_.Extension -ceq '.dll' }).Count -ne $manifest.dll_count) {
throw 'Manifest file counts, byte count, or hash coverage do not match the archive'
}
foreach ($file in $files) {
$relative = [IO.Path]::GetRelativePath($payload, $file.FullName).Replace('\', '/')
if ($relative -ceq 'manifest.json') { continue }
if (!(Test-StambhaPayloadPath $relative)) { throw "Unexpected runtime file: $relative" }
Assert-StambhaHash $file.FullName $manifest.sha256[$relative]
}
foreach ($name in $StambhaRequiredFiles) {
if (!$manifest.sha256[$name]) { throw "Missing runtime file: $name" }
}
$receipt = Get-Content -Raw -LiteralPath (Join-Path $source 'provenance.json') | ConvertFrom-Json -AsHashtable
foreach ($field in @('components', 'patches')) {
if (($receipt[$field] | ConvertTo-Json -Depth 8 -Compress) -cne
($manifest[$field] | ConvertTo-Json -Depth 8 -Compress)) { throw "Runtime and source $field differ" }
}
if ($receipt.sha256.Count -ne $manifest.sha256.Count -or
($manifest.sha256.Keys | Where-Object { $manifest.sha256[$_] -cne $receipt.sha256[$_] })) {
throw 'Runtime and source payload digests differ'
}
foreach ($item in $receipt.sources) {
if ($item.file -cnotmatch '^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.tar\.(gz|xz|zst)$') {
throw "Invalid source archive name: $($item.file)"
}
Assert-StambhaHash (Join-Path $source "sources/$($item.file)") $item.sha256
}
foreach ($patch in $receipt.patches) {
if ($patch.name -cnotmatch '^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.patch$') { throw "Invalid patch name: $($patch.name)" }
Assert-StambhaHash (Join-Path $source "patches/$($patch.name)") $patch.sha256
}
if (!(Test-Path -LiteralPath (Join-Path $source 'BUILD.md') -PathType Leaf) -or
$receipt.msys2_source -cnotin @($receipt.sources | ForEach-Object { $_.file })) {
throw 'Missing build instructions or MSYS2 corresponding source'
}
$version = Test-StambhaExecutables $payload
if ($version -cne $manifest.qemu_version) { throw 'QEMU version differs from the manifest' }
$media = Join-Path $stage 'probe-media'
$vm = Join-Path $stage 'probe-vm'
[void][IO.Directory]::CreateDirectory((Join-Path $media 'EFI/BOOT'))
[void][IO.Directory]::CreateDirectory((Join-Path $media 'EFI/stela'))
Copy-Item -LiteralPath (Join-Path $payload 'firmware/stambha.efi') -Destination (Join-Path $media 'EFI/BOOT/BOOTX64.EFI')
Write-StambhaText (Join-Path $media 'EFI/stela/stela.cfg') "# Packaging boot-plan probe`n"
$qemu = Join-Path $payload 'qemu/bin/qemu-system-x86_64.exe'
$engine = Join-Path $payload 'bin/stambha-engine.exe'
$plan = (Invoke-StambhaCommand $engine @(
'boot-plan', '--qemu', $qemu,
'--firmware-code', (Join-Path $payload 'firmware/edk2-code.fd'),
'--firmware-vars', (Join-Path $payload 'firmware/edk2-vars.fd'),
'--vm-dir', $vm, '--memory-mib', '8192', '--cpus', '4', '--boot-volume', $media
)) | ConvertFrom-Json
if ($plan.runtime_api -cne '0.1.0' -or $plan.exe_path -ne $qemu -or $plan.work_dir -ne $vm -or
!$plan.args.Count -or !(Test-Path -LiteralPath (Join-Path $vm 'uefi-vars.fd') -PathType Leaf)) {
throw 'The bundled engine did not produce the expected EDK2 boot plan'
}
Write-Host "PASS $ReleaseId runtime, source, payload hashes, engine, boot plan and $version"
} finally {
if ((Split-Path -Parent ([IO.Path]::GetFullPath($stage))) -eq $parent) {
Remove-Item -LiteralPath $stage -Recurse -Force
}
}
@@ -33,9 +33,10 @@ param(
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'runtime-zstd.ps1')
$localDb = Join-Path $Msys2 'var\lib\pacman\local'
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
$zstd = Join-Path $Msys2 'usr\bin\zstd.exe'
$zstd = Resolve-Zstd -Msys2 $Msys2
function Write-Utf8([string]$path, [string]$text) {
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
@@ -49,12 +49,17 @@ param(
# Release identifier for archive names and manifest.commit (defaults to short
# upstream commit; e.g. "3731afd-p2" for a patch-queue rebuild of 3731afd).
[string]$ReleaseId = '',
[ValidatePattern('^(?:[0-9a-f]{7,40})?$')]
[string]$SuspendCompatID = '',
[ValidatePattern('^(?:[0-9a-f]{40})?$')]
[string]$PackagingCommit = '',
# Names from patches/series.txt actually applied. Not given: all of them.
# Given but empty: none (every patch already upstream).
[string[]]$Patches = @()
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'runtime-zstd.ps1')
$repoRoot = Split-Path -Parent $PSScriptRoot
$patchesDir = Join-Path $repoRoot 'patches'
$CargoBin = Join-Path $CargoHome 'bin'
@@ -93,17 +98,7 @@ function Write-Utf8([string]$path, [string]$text) {
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
}
function Resolve-Zstd {
@(
(Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
(Join-Path $Msys2 'usr\bin\zstd.exe'),
(Join-Path $Msys2 'clang64\bin\zstd.exe')
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
}
function New-TarZst([string]$parent, [string]$name, [string]$archive) {
$zstd = Resolve-Zstd
if (-not $zstd) { throw 'zstd not found (install MSYS2 zstd or put zstd.exe on PATH)' }
$tar = Join-Path $TempRoot "$name.tar"
Invoke-Native 'tar.exe' @('-cf', $tar, '-C', $parent, $name)
Invoke-Native $zstd @('-T0', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive)
@@ -128,6 +123,9 @@ foreach ($p in @($ctlExe, $utilExe, $qemuExe)) {
$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim()
$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim()
$id = if ($ReleaseId -and $ReleaseId.Trim()) { $ReleaseId.Trim() } else { $commit }
if ($SuspendCompatID -and $id -cnotmatch ('^' + [regex]::Escape($SuspendCompatID) + '(?:-p[1-9][0-9]*)?$')) {
throw "Suspend compatibility ID $SuspendCompatID does not match release $id"
}
$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
@@ -140,10 +138,9 @@ 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')
if ($utilSrc -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found in reims_util.rs' }
$utilCommit = $Matches[1]
$pins = & (Join-Path $PSScriptRoot 'read-runtime-dependencies.ps1') -RuntimeRepo $ReimsRepo
$utilCommit = $pins.Util.Rev
$m2vCommit = $pins.Metal.Rev
$checkouts = Join-Path $CargoHome 'git\checkouts'
$utilTree = if ($UtilRepo) {
(Resolve-Path -LiteralPath $UtilRepo).Path
@@ -156,15 +153,6 @@ if (-not $utilTree) { throw "reims-util source at $utilCommit not found" }
$actualUtil = git -C $utilTree rev-parse HEAD
if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" }
# metal2vulkan's pinned commit (workspace Cargo.toml, falling back to Cargo.lock).
$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.toml')
if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') {
$m2vCommit = $Matches[1]
} else {
$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock')
if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' }
$m2vCommit = $Matches[1]
}
$m2vTree = if ($Metal2VulkanRepo) {
(Resolve-Path -LiteralPath $Metal2VulkanRepo).Path
} else {
@@ -455,7 +443,9 @@ foreach ($extra in @(
}
New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null
Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\"
foreach ($ps in $patchSpecs) {
Copy-Item -LiteralPath (Join-Path "$bundleDir\patches" $ps.Name) -Destination "$srcDir\patches\"
}
Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt"
Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md"
$m2vBuildSteps = if ($byTarget.Contains('metal2vulkan')) {
@@ -468,7 +458,7 @@ and point Cargo at the patched checkout via ```$CARGO_HOME/config.toml``:
$m2vApply
cat >> "`${CARGO_HOME:-`$HOME/.cargo}/config.toml" <<EOF
[patch."https://github.com/steelbrain/metal2vulkan"]
[patch."$($pins.Metal.Url)"]
metal2vulkan = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan" }
metal2vulkan-runtime = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan-runtime" }
EOF
@@ -491,6 +481,14 @@ $utilApply
"@
}
$applyRuntimePatches = @(
foreach ($ps in $patchSpecs) {
switch ($ps.Target) {
'reims-vgpu' { " git -C reims-vgpu-$commit apply ../patches/$($ps.Name)" }
'vendor/qemu' { " git -C reims-vgpu-$commit/vendor/qemu apply ../../../patches/$($ps.Name)" }
}
}
)
Write-Utf8 "$srcDir\README.md" @"
# Source for $bundleName
@@ -500,21 +498,18 @@ Corresponding source for the binaries in ``$bundleName.tar.zst``.
| :-- | :-- | :-- |
| ``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`` |
| ``reims-util-$($utilCommit.Substring(0, 7))/`` | $($pins.Util.Url) | ``$utilCommit`` |
| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | $($pins.Metal.Url) | ``$m2vCommit`` |
The archive exports the commits above. Apply the patches in ``patches/``
before compiling:
$(
if ($applyRuntimePatches) {
"Apply the runtime patches from the archive root.`n`n" + ($applyRuntimePatches -join "`n")
}
)
cd reims-vgpu-$commit
$((($patchSpecs | Where-Object { $_.Target -eq 'reims-vgpu' } | ForEach-Object { " git apply ../patches/$($_.Name)" }) -join "`n"))
cd vendor/qemu
$((($patchSpecs | Where-Object { $_.Target -eq 'vendor/qemu' } | ForEach-Object { " git apply ../../../patches/$($_.Name)" }) -join "`n"))
(``patch -p1`` works too.)
$m2vBuildSteps
Then build as upstream documents (``scripts/install-ctl.sh``
in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2
From ``reims-vgpu-$commit/``, run ``scripts/install-ctl.sh``
in an MSYS2 CLANG64 shell. The DLLs in ``qemu/bin`` come from the MSYS2
packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources.
$utilBuildSteps
"@
@@ -534,7 +529,9 @@ $manifest = [ordered]@{
full_commit = $fullCommit
vendor_qemu_repo = $qemuSource
vendor_qemu_commit = $qemuCommit
util_repo = $pins.Util.Url
util_commit = $utilCommit
metal2vulkan_repo = $pins.Metal.Url
metal2vulkan_commit = $m2vCommit
patches = $patchEntries
capabilities = $capabilities
@@ -549,11 +546,14 @@ $manifest = [ordered]@{
raw_bytes = [int64]((Get-ChildItem -LiteralPath $bundleDir -Recurse -File | Measure-Object Length -Sum).Sum) # Add the manifest's own size after writing it below.
sha256 = $hashes
}
if ($SuspendCompatID) { $manifest['suspend_compat_id'] = $SuspendCompatID }
if ($PackagingCommit) { $manifest['packaging_commit'] = $PackagingCommit }
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
$manifest.raw_bytes += (Get-Item -LiteralPath "$bundleDir\manifest.json").Length
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
# ── 6. Archives and sums ─────────────────────────────────────
$zstd = Resolve-Zstd -Msys2 $Msys2
Write-Host '==> Compressing runtime'
$runtimeArchive = Join-Path $OutDir "$bundleName.tar.zst"
New-TarZst $stageRoot $bundleName $runtimeArchive
@@ -0,0 +1,177 @@
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Mandatory)] [string]$InputRoot,
[Parameter(Mandatory)] [string]$OutDir,
[Parameter(Mandatory)] [ValidatePattern('^[a-z0-9][a-z0-9.-]{0,63}$')] [string]$ReleaseId,
[string]$Msys2 = "$env:SystemDrive/msys64",
[ValidateRange(1, 12)] [int]$ZstdLevel = 6
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'runtime-zstd.ps1')
. (Join-Path $PSScriptRoot 'stambha-runtime-files.ps1')
$zstd = Resolve-Zstd $Msys2
$tar = Join-Path $env:SystemRoot 'System32/tar.exe'
$input = (Resolve-Path -LiteralPath $InputRoot).Path
$out = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutDir)
if (Test-Path -LiteralPath $out) { throw "Output directory already exists: $out" }
$receiptPath = Join-Path $input 'provenance.json'
$receipt = Get-Content -LiteralPath $receiptPath -Raw | ConvertFrom-Json -AsHashtable
if ($receipt.schema_version -ne 1) { throw 'Unsupported provenance.json schema' }
$srcFiles = @{}
foreach ($source in $receipt.sources) {
$name = $source.file
if ($name -cnotmatch '^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.tar\.(gz|xz|zst)$' -or $srcFiles.ContainsKey($name)) {
throw "Invalid or duplicate corresponding source archive: $name"
}
$path = Join-Path $input "sources/$name"
Assert-StambhaHash $path $source.sha256
$srcFiles.Add($name, $path)
}
if (!$receipt.msys2_source -or !$srcFiles.ContainsKey($receipt.msys2_source)) {
throw 'The MSYS2 corresponding source archive is required'
}
$componentNames = @('reims-vgpu', 'qemu', 'qemu-img', 'metal2vulkan', 'stela', 'stambha-engine', 'edk2-code', 'edk2-vars')
$components = @{}
foreach ($component in $receipt.components) {
$name = $component.name
if ($name -cnotin $componentNames -or $components.ContainsKey($name) -or
$component.repo -cnotmatch '^https://[^\s]+$' -or $component.commit -cnotmatch '^[0-9a-f]{40}$' -or
($component.base_commit -and $component.base_commit -cnotmatch '^[0-9a-f]{40}$') -or
!$component.source -or !$srcFiles.ContainsKey($component.source)) {
throw "Invalid, duplicate or incomplete provenance for $name"
}
$components.Add($name, $component)
}
foreach ($name in $componentNames) {
if (!$components.ContainsKey($name)) { throw "Missing provenance for $name" }
}
$patchNames = @{}
foreach ($patch in $receipt.patches) {
$name = $patch.name
if ($name -cnotmatch '^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.patch$' -or $patchNames.ContainsKey($name) -or
$patch.target -cnotin $componentNames) { throw "Invalid or duplicate patch: $name" }
$path = Join-Path $input "patches/$name"
Assert-StambhaHash $path $patch.sha256
$patchNames.Add($name, $path)
}
if (!$patchNames.Count) { throw 'The hosted runtime must declare its applied patches' }
$payload = Join-Path $input 'payload'
$files = @{}
foreach ($item in Get-ChildItem -LiteralPath $payload -Force -Recurse) {
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
throw "Reparse points are not supported in the runtime payload: $($item.FullName)"
}
if ($item.PSIsContainer) { continue }
$relative = [IO.Path]::GetRelativePath($payload, $item.FullName).Replace('\', '/')
if (!(Test-StambhaPayloadPath $relative)) { throw "Unexpected runtime file: $relative" }
$files.Add($relative, $item)
}
foreach ($name in $StambhaRequiredFiles) {
if (!$files.ContainsKey($name)) { throw "Missing runtime file: $name" }
}
if ($files.Count -ne $receipt.sha256.Count) { throw 'Provenance SHA256 keys differ from runtime files' }
foreach ($name in $files.Keys) { Assert-StambhaHash $files[$name].FullName $receipt.sha256[$name] }
function New-StambhaArchive([string]$Stage, [string]$Name, [string]$Assets) {
$tarball = Join-Path $Stage "$Name.tar"
[void](Invoke-StambhaCommand $tar @('-cf', $tarball, '-C', $Stage, $Name))
$archive = Join-Path $Assets "$Name.tar.zst"
[void](Invoke-StambhaCommand $zstd @('-q', '-T2', "-$ZstdLevel", $tarball, '-o', $archive))
Remove-Item -LiteralPath $tarball
"$Name.tar.zst"
}
$parent = Split-Path -Parent $out
[void][IO.Directory]::CreateDirectory($parent)
$stage = Join-Path $parent ('.stambha-pack-' + [guid]::NewGuid().ToString('N'))
try {
$assets = Join-Path $stage 'assets'
$runtimeName = "reims-stambha-runtime-win-x64-$ReleaseId"
$sourceName = "reims-stambha-runtime-src-$ReleaseId"
$runtimeDir = Join-Path $stage $runtimeName
$sourceDir = Join-Path $stage $sourceName
foreach ($dir in @($assets, $runtimeDir, "$sourceDir/sources", "$sourceDir/patches", "$sourceDir/packaging/scripts")) {
[void][IO.Directory]::CreateDirectory($dir)
}
$hashes = [ordered]@{}
$payloadBytes = [long]0
foreach ($name in $files.Keys | Sort-Object) {
$dest = Join-Path $runtimeDir $name
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
Copy-Item -LiteralPath $files[$name].FullName -Destination $dest
Assert-StambhaHash $dest $receipt.sha256[$name]
$hashes[$name] = $receipt.sha256[$name]
$payloadBytes += $files[$name].Length
}
$qemuVersion = Test-StambhaExecutables $runtimeDir
$manifest = [ordered]@{
schema_version = 2
name = $runtimeName
platform = 'windows-x86_64'
kind = 'stambha-hosted'
runtime_api = '0.1.0'
commit = $ReleaseId
channel = 'alpha'
origin = 'third-party'
publisher = 'Reims-Go'
license = 'GPL-2.0-only and GPL-3.0-or-later with other component licenses; see NOTICE.md and licenses/'
upstream_repo = $components['reims-vgpu'].repo
full_commit = $components['reims-vgpu'].commit
vendor_qemu_commit = $components.qemu.commit
qemu_version = $qemuVersion
metal2vulkan_commit = $components.metal2vulkan.commit
source_package = "$sourceName.tar.zst"
patches = @($receipt.patches)
components = @($receipt.components)
capabilities = @('stambha.uefi', 'stambha.qemu.boot-plan', 'stambha.hosted-reims')
built_at = [DateTimeOffset]::UtcNow.ToString('O')
file_count = $files.Count + 1
dll_count = @($files.Keys | Where-Object { $_.EndsWith('.dll') }).Count
raw_bytes = $payloadBytes
sha256 = $hashes
}
$manifestPath = Join-Path $runtimeDir 'manifest.json'
do {
$previous = $manifest.raw_bytes
Write-StambhaText $manifestPath (($manifest | ConvertTo-Json -Depth 8) + "`n")
$manifest.raw_bytes = $payloadBytes + (Get-Item -LiteralPath $manifestPath).Length
} until ($manifest.raw_bytes -eq $previous)
function Write-AssetSum([string]$Name) {
$line = "$(Get-StambhaHash (Join-Path $assets $name)) $name`n"
Write-StambhaText (Join-Path $assets "$name.sha256") $line
$line
}
$runtimeAsset = New-StambhaArchive $stage $runtimeName $assets
$runtimeSum = Write-AssetSum $runtimeAsset
Write-Host "Runtime staged for host smoke testing: $(Join-Path $assets $runtimeAsset)"
foreach ($name in $srcFiles.Keys) {
Copy-Item -LiteralPath $srcFiles[$name] -Destination (Join-Path $sourceDir "sources/$name")
}
foreach ($name in $patchNames.Keys) {
Copy-Item -LiteralPath $patchNames[$name] -Destination (Join-Path $sourceDir "patches/$name")
}
Copy-Item -LiteralPath $receiptPath, (Join-Path $input 'BUILD.md') -Destination $sourceDir
Copy-Item -LiteralPath (Join-Path (Split-Path -Parent $PSScriptRoot) 'LICENSE') -Destination "$sourceDir/packaging"
foreach ($name in @('runtime-zstd.ps1', 'stambha-runtime-files.ps1', 'pack-stambha-runtime.ps1', 'check-stambha-runtime.ps1')) {
Copy-Item -LiteralPath (Join-Path $PSScriptRoot $name) -Destination "$sourceDir/packaging/scripts"
}
$sourceAsset = New-StambhaArchive $stage $sourceName $assets
$sums = @($runtimeSum, (Write-AssetSum $sourceAsset))
Write-StambhaText (Join-Path $assets 'SHA256SUMS.txt') ($sums -join '')
& (Join-Path $PSScriptRoot 'check-stambha-runtime.ps1') -AssetDir $assets -ReleaseId $ReleaseId -Zstd $zstd
[IO.Directory]::Move($assets, $out)
Write-Host "Packaged Stambha preview: $out"
} finally {
if ((Split-Path -Parent ([IO.Path]::GetFullPath($stage))) -eq $parent -and
(Test-Path -LiteralPath $stage -PathType Container)) { Remove-Item -LiteralPath $stage -Recurse -Force }
}
@@ -0,0 +1,141 @@
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RuntimeRepo,
[Parameter(Mandatory)][ValidatePattern('^[0-9a-f]{40}$')][string]$RuntimeCommit,
[Parameter(Mandatory)][string]$PackagingRepo,
[Parameter(Mandatory)][ValidatePattern('^[0-9a-f]{40}$')][string]$PackagingCommit,
[Parameter(Mandatory)][string]$Repository,
[switch]$Rebuild,
[switch]$PackagingPush
)
$ErrorActionPreference = 'Stop'
$tagPattern = '^runtime-(?<base>[0-9a-f]{7,40})(?:-p(?<revision>[1-9][0-9]*))?$'
function Invoke-VersionCommand([string]$command, [string[]]$argv) {
$result = & $command @argv
if ($LASTEXITCODE -ne 0) { throw "$command $($argv -join ' ') failed ($LASTEXITCODE)" }
return $result
}
function Test-InputsChanged([string]$Repo, [string]$From, [string]$To, [string[]]$Paths) {
& git -C $Repo diff --quiet $From $To -- @Paths
if ($LASTEXITCODE -gt 1) { throw "Could not compare suspend inputs from $From to $To" }
return $LASTEXITCODE -eq 1
}
function New-VersionPlan([string]$ReleaseId, [string]$Family, [string]$Evidence = '', [string]$Predecessor = '') {
return [pscustomobject]@{
Skip = $false
ReleaseId = $ReleaseId
SuspendCompatID = $Family
Evidence = $Evidence
Predecessor = $Predecessor
}
}
$remoteTags = @{}
foreach ($line in (Invoke-VersionCommand git @('-C', $RuntimeRepo, 'ls-remote', '--tags', 'origin', 'refs/tags/runtime-*'))) {
if ($line -match '^(?<sha>[0-9a-f]{40})\s+refs/tags/(?<tag>runtime-[^\s^]+)(?<peeled>\^\{\})?$') {
if ($Matches.peeled -or !$remoteTags.ContainsKey($Matches.tag)) {
$remoteTags[$Matches.tag] = $Matches.sha
}
}
}
$pages = (Invoke-VersionCommand gh @('api', '--paginate', '--slurp', "repos/$Repository/releases?per_page=100")) -join "`n"
$releasePages = $pages | ConvertFrom-Json -NoEnumerate
$published = @(foreach ($page in $releasePages) {
foreach ($release in $page) {
if ($release.draft -or $release.tag_name -notmatch $tagPattern) { continue }
$family = $Matches.base
$revision = if ($Matches.revision) { [int]$Matches.revision } else { 0 }
$tag = $release.tag_name
if (!$remoteTags.ContainsKey($tag)) { throw "Published runtime tag $tag was not found in Git" }
$packaging = if ($release.body -match '(?m)^Packaging commit: `([0-9a-f]{40})`\s*$') { $Matches[1] } else { '' }
$verifiedFamily = if ($release.body -match '(?m)^Suspend compatibility ID: `([0-9a-f]{7,40})`\s*$') { $Matches[1] } else { '' }
[pscustomobject]@{
Tag = $tag
RuntimeCommit = $remoteTags[$tag]
Packaging = $packaging
Family = $family
Revision = $revision
VerifiedFamily = $verifiedFamily
PublishedAt = [DateTimeOffset]$release.published_at
}
}
})
$sameRuntime = @($published | Where-Object RuntimeCommit -eq $RuntimeCommit)
if ($sameRuntime.Count -and (!$Rebuild -or ($PackagingPush -and ($sameRuntime | Where-Object Packaging -eq $PackagingCommit)))) {
Write-Host "Skipping the already published runtime $RuntimeCommit."
return [pscustomobject]@{ Skip = $true }
}
# The verification belongs to the changed commit and names its exact other input.
$approvalRepo = if ($PackagingPush -or $Rebuild) { $PackagingRepo } else { $RuntimeRepo }
$approvalCommit = if ($PackagingPush -or $Rebuild) { $PackagingCommit } else { $RuntimeCommit }
$otherInput = if ($PackagingPush -or $Rebuild) { $RuntimeCommit } else { $PackagingCommit }
$message = (Invoke-VersionCommand git @('-C', $approvalRepo, 'show', '-s', '--format=%B', $approvalCommit)) -join "`n"
$trailers = $message | git interpret-trailers --parse
if ($LASTEXITCODE -ne 0) { throw 'Could not read suspend compatibility trailers' }
$approval = @{}
foreach ($line in $trailers) {
if ($line -match '^(Suspend-Compatible-With|Suspend-Verified-Inputs|Suspend-Verification):\s+(.+)$') {
if ($approval.ContainsKey($Matches[1])) { throw "Repeated compatibility trailer: $($Matches[1])" }
$approval[$Matches[1]] = $Matches[2].Trim()
}
}
if ($approval.Count) {
$previous = $published | Where-Object Tag -eq $approval['Suspend-Compatible-With']
$evidence = $approval['Suspend-Verification']
if (!$previous -or !$previous.Packaging -or $previous.VerifiedFamily -ne $previous.Family -or
$approval['Suspend-Verified-Inputs'] -ne $otherInput -or $evidence -notmatch '^https://[^\s<>]+$') {
Write-Warning 'Compatibility evidence does not match these inputs and a published compatibility baseline.'
} else {
$latest = $published | Sort-Object PublishedAt, Revision -Descending | Select-Object -First 1
$familyTip = $published | Where-Object Family -eq $previous.Family | Sort-Object Revision -Descending | Select-Object -First 1
& git -C $RuntimeRepo merge-base --is-ancestor $previous.RuntimeCommit $RuntimeCommit
if ($LASTEXITCODE -gt 1) { throw 'Could not verify the runtime baseline ancestry' }
$ancestor = $LASTEXITCODE -eq 0
# Direct changes to these inputs require a fresh family even with a trailer.
$runtimePaths = @(
'vendor/qemu', 'guest', 'firmware', ':(glob)crates/reims-vgpu*/**',
'.cargo', 'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', 'reims-go-runtime.json',
'scripts/install-ctl.sh', 'scripts/install.ps1',
'crates/reims-ctl/Cargo.toml', 'crates/reims-ctl/Cargo.lock',
'crates/reims-ctl/src/qemu.rs', 'crates/reims-ctl/src/runtime.rs',
'crates/reims-ctl/src/main.rs', 'crates/reims-ctl/src/cli.rs', 'crates/reims-ctl/src/vm.rs',
'crates/reims-ctl/src/opencore.rs', 'crates/reims-ctl/src/reims_util.rs',
'crates/reims-ctl/src/host.rs', 'crates/reims-ctl/src/os'
)
$packagingPaths = @(
':(glob)packaging/windows-runtime/patches/*.patch',
'packaging/windows-runtime/patches/series.txt',
'packaging/windows-runtime/scripts/apply-patch-series.ps1'
)
if ($ancestor -and $previous.Tag -eq $latest.Tag -and $previous.Tag -eq $familyTip.Tag) {
& git -C $PackagingRepo cat-file -e "$($previous.Packaging)^{commit}" 2>$null
if ($LASTEXITCODE -ne 0) {
Invoke-VersionCommand git @('-C', $PackagingRepo, 'fetch', '-q', '--no-tags', 'origin', $previous.Packaging)
}
$runtimeChange = Test-InputsChanged $RuntimeRepo $previous.RuntimeCommit $RuntimeCommit $runtimePaths
$packagingChange = Test-InputsChanged $PackagingRepo $previous.Packaging $PackagingCommit $packagingPaths
if (!$runtimeChange -and !$packagingChange) {
$id = "$($previous.Family)-p$($familyTip.Revision + 1)"
if ($remoteTags.ContainsKey("runtime-$id")) { throw "Runtime tag runtime-$id is already reserved" }
return New-VersionPlan $id $previous.Family $evidence $previous.Tag
}
Write-Warning 'Suspend inputs changed. A new runtime family is required.'
} else {
Write-Warning 'The verification must cover the latest published runtime and its highest family revision.'
}
}
}
$base = (Invoke-VersionCommand git @('-C', $RuntimeRepo, 'rev-parse', '--short=7', $RuntimeCommit)).Trim()
if ($sameRuntime.Count -or $remoteTags.ContainsKey("runtime-$base")) {
throw 'A new runtime baseline commit is required, or record verified compatibility for these exact build inputs.'
}
return New-VersionPlan $base $base
@@ -0,0 +1,31 @@
param([Parameter(Mandatory)][string]$RuntimeRepo)
$ErrorActionPreference = 'Stop'
$githubUrl = 'https://github\.com/[\w.-]+/[\w.-]+'
$util = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'crates/reims-ctl/src/reims_util.rs')
$utilUrl = [regex]::Match($util, "pub const REPO: &str = ""($githubUrl)"";").Groups[1].Value
$utilRev = [regex]::Match($util, 'pub const REV: &str = "([0-9a-f]{40})";').Groups[1].Value
if (-not $utilUrl -or -not $utilRev) { throw 'reims-util REPO or REV is missing from reims_util.rs' }
$cargo = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'Cargo.toml')
$metal = foreach ($name in 'metal2vulkan', 'metal2vulkan-runtime') {
$entry = [regex]::Match($cargo, "(?m)^$name\s*=\s*\{([^}]+)\}").Groups[1].Value
$url = [regex]::Match($entry, "git\s*=\s*""($githubUrl)""").Groups[1].Value
if (-not $url) { throw "$name git URL is missing from Cargo.toml" }
$rev = [regex]::Match($entry, 'rev\s*=\s*"([0-9a-f]{40})"').Groups[1].Value
if (-not $rev) {
$lock = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'Cargo.lock')
$pin = '(?m)^source = "git\+' + [regex]::Escape($url) + '\?rev=([0-9a-f]{40})#[0-9a-f]{40}"'
$rev = [regex]::Match($lock, $pin).Groups[1].Value
}
if (-not $rev) { throw "$name revision is missing from Cargo.toml and Cargo.lock" }
[pscustomobject]@{ Url = $url; Rev = $rev }
}
if ($metal[0].Url -cne $metal[1].Url -or $metal[0].Rev -cne $metal[1].Rev) {
throw 'metal2vulkan and metal2vulkan-runtime must use the same repository and commit'
}
[pscustomobject]@{
Util = [pscustomobject]@{ Url = $utilUrl; Rev = $utilRev }
Metal = $metal[0]
}
@@ -0,0 +1,25 @@
function Resolve-Zstd([string]$Msys2) {
$candidates = @(
Get-Command zstd.exe -CommandType Application -All -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty Source
Join-Path $Msys2 'usr\bin\zstd.exe'
Join-Path $Msys2 'clang64\bin\zstd.exe'
)
$failures = @()
foreach ($candidate in ($candidates | Select-Object -Unique)) {
if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { continue }
# A binary can exist but fail to load its DLLs outside the MSYS2 shell.
try {
& $candidate --version *> $null
if ($LASTEXITCODE -eq 0) { return $candidate }
$failures += "$candidate (exit $LASTEXITCODE)"
} catch {
$failures += "$candidate ($($_.Exception.Message))"
}
}
if ($failures.Count) { throw "Could not run zstd.exe: $($failures -join '; ')" }
throw "zstd.exe not found on PATH or in MSYS2 at $Msys2"
}
@@ -0,0 +1,71 @@
# The installable Stambha runtime is separate from the ordinary Reims runtime.
$StambhaRequiredFiles = @(
'bin/stambha-engine.exe'
'firmware/edk2-code.fd'
'firmware/edk2-vars.fd'
'firmware/stambha.efi'
'qemu/bin/qemu-img.exe'
'qemu/bin/qemu-system-x86_64.exe'
'qemu/bin/reims-vgpu-compile.exe'
'qemu/share/vgabios-stdvga.bin'
'NOTICE.md'
'MSYS2-PACKAGES.txt'
'licenses/stambha/NOTICE'
'licenses/stambha/LICENSE'
'licenses/stambha/LICENSES/GPL-3.0-or-later.txt'
'licenses/edk2-licenses.txt'
)
function Get-StambhaHash([string]$Path) {
(Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
function Assert-StambhaHash([string]$Path, [string]$Expected) {
if ($Expected -cnotmatch '^[0-9a-f]{64}$') { throw "Missing or invalid SHA256 for $Path" }
if ((Get-StambhaHash $Path) -cne $Expected) { throw "SHA256 mismatch for $Path" }
}
function Test-StambhaPayloadPath([string]$Path) {
$Path -cin $StambhaRequiredFiles -or
$Path -cmatch '^qemu/bin/[a-zA-Z0-9_.+-]+\.dll$' -or
$Path -cmatch '^qemu/share/(bios(-256k)?\.bin|kvmvapic\.bin|vgabios\.bin|(efi|pxe)-virtio\.rom)$' -or
$Path -ceq 'licenses/cargo/index.json' -or
$Path -ceq 'licenses/msys2/libjpeg-turbo/simd/jsimdext.inc' -or
$Path -match '^licenses/([A-Z0-9_+.-]+/)*([A-Z0-9_+.-]+\.(txt|md)|(LICEN[CS]E|COPYING|NOTICE|COPYRIGHT|README|AUTHORS)[A-Z0-9_.+-]*|[A-Z0-9-]+-[0-9]+\.[A-Z0-9_.+-]+|GPL|MIT|Linux-Syscall-Note)$'
}
function Write-StambhaText([string]$Path, [string]$Value) {
[IO.File]::WriteAllText($Path, $Value.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
}
function Invoke-StambhaCommand([string]$Executable, [string[]]$Arguments) {
$output = & $Executable @Arguments
if ($LASTEXITCODE -ne 0) { throw "$Executable $($Arguments -join ' ') failed ($LASTEXITCODE)" }
$output
}
function Test-StambhaExecutables([string]$Payload) {
$originalPath = $env:PATH
try {
$qemuBin = Join-Path $Payload 'qemu/bin'
$env:PATH = "$qemuBin;$env:SystemRoot\System32;$env:SystemRoot"
$engine = Join-Path $Payload 'bin/stambha-engine.exe'
$info = (Invoke-StambhaCommand $engine @('info')) | ConvertFrom-Json
if ($info.runtime_kind -cne 'stambha-hosted' -or $info.runtime_api -cne '0.1.0' -or
$info.host_os -cne 'windows' -or $info.host_arch -cne 'x86_64' -or
!$info.capabilities.qemu_uefi_boot_plan) { throw 'Unexpected Stambha boot-plan engine or API' }
$selfTest = (Invoke-StambhaCommand $engine @('self-test')) | ConvertFrom-Json
if ($selfTest.result -ne 42 -or $selfTest.guest_arch -cne 'arm64') {
throw 'Stambha translated ARM64 self-test failed'
}
$qemu = Join-Path $qemuBin 'qemu-system-x86_64.exe'
$features = (Invoke-StambhaCommand $qemu @('-device', 'reims-graphics-pci,help')) -join "`n"
if ($features -notmatch '(?m)^\s*x-hosted-arm64=') { throw 'QEMU lacks hosted ARM64 Reims graphics' }
$accelerators = (Invoke-StambhaCommand $qemu @('-accel', 'help')) -join "`n"
if ($accelerators -notmatch '(?m)^\s*whpx\s*$') { throw 'QEMU lacks WHPX' }
[void](Invoke-StambhaCommand (Join-Path $qemuBin 'qemu-img.exe') @('--version'))
(Invoke-StambhaCommand $qemu @('--version')) | Select-Object -First 1
} finally {
$env:PATH = $originalPath
}
}
@@ -0,0 +1,117 @@
[CmdletBinding()]
param([Parameter(Mandatory)][string]$TempRoot)
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path -LiteralPath $TempRoot).Path
$fixture = Join-Path $root ("alpha-version-test-" + [guid]::NewGuid())
$planner = Join-Path $PSScriptRoot 'plan-runtime-release.ps1'
$source = Join-Path $fixture 'runtime'
$packaging = Join-Path $fixture 'packaging'
$fixtureReleases = [System.Collections.Generic.List[hashtable]]::new()
$testRepo = 'test/runtime'
function gh {
$global:LASTEXITCODE = 0
'[' + (ConvertTo-Json -InputObject $fixtureReleases.ToArray() -Depth 5 -Compress) + ']'
}
function Test-Git([string]$repo, [string[]]$argv) {
$result = & git -C $repo @argv
if ($LASTEXITCODE) { throw "git $($argv -join ' ') failed in fixture" }
return $result
}
function Write-Commit([string]$repo, [string]$path, [string]$content, [string]$message = 'Fixture update') {
$file = Join-Path $repo $path
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $file) | Out-Null
Set-Content -LiteralPath $file -Encoding utf8NoBOM -Value $content
Test-Git $repo @('add', '--', $path) | Out-Null
Test-Git $repo @('commit', '-q', '-m', $message) | Out-Null
return Test-Git $repo @('rev-parse', 'HEAD')
}
function Add-Published([string]$id, [string]$commit, [string]$pack, [string]$family) {
$tag = "runtime-$id"
Test-Git $source @('tag', $tag, $commit) | Out-Null
$fixtureReleases.Add(@{
tag_name = $tag
draft = $false
published_at = [DateTimeOffset]::UnixEpoch.AddMinutes($fixtureReleases.Count).ToString('o')
body = "Packaging commit: ``$pack```nSuspend compatibility ID: ``$family``"
})
}
function Approval([string]$predecessor, [string]$other) {
return "Fixture verified`n`nSuspend-Compatible-With: $predecessor`nSuspend-Verified-Inputs: $other`nSuspend-Verification: https://example.invalid/runtime-test"
}
function Plan([string]$commit, [string]$pack, [switch]$PackagingPush) {
& $planner -RuntimeRepo $source -RuntimeCommit $commit -PackagingRepo $packaging -PackagingCommit $pack `
-Repository $testRepo -Rebuild:$PackagingPush -PackagingPush:$PackagingPush
}
function Assert-Version($plan, [string]$id, [string]$family) {
if ($plan.Skip -or $plan.ReleaseId -ne $id -or $plan.SuspendCompatID -ne $family) {
throw "Expected $id in family $family, got $($plan | ConvertTo-Json -Compress)"
}
}
try {
foreach ($repo in $source, $packaging) {
New-Item -ItemType Directory -Path $repo -Force | Out-Null
Test-Git $repo @('init', '-q') | Out-Null
Test-Git $repo @('config', 'user.name', 'Version Fixture') | Out-Null
Test-Git $repo @('config', 'user.email', 'fixture@example.invalid') | Out-Null
}
Test-Git $source @('remote', 'add', 'origin', $source) | Out-Null
$old = Write-Commit $source 'crates/reims-ctl/src/qemu.rs' 'original state path'
$pack = Write-Commit $packaging 'packaging/windows-runtime/patches/series.txt' 'original patch queue'
$base = Test-Git $source @('rev-parse', '--short=7', $old)
Assert-Version (Plan $old $pack) $base $base
Add-Published $base $old $pack $base
if (!(Plan $old $pack).Skip -or !(Plan $old $pack -PackagingPush).Skip) {
throw 'Already published build was not skipped'
}
$compatiblePack = Write-Commit $packaging 'packaging/windows-runtime/notice.txt' 'packaging adjustment' (Approval "runtime-$base" $old)
Assert-Version (Plan $old $compatiblePack -PackagingPush) "$base-p1" $base
$breakingPack = Write-Commit $packaging 'packaging/windows-runtime/patches/series.txt' 'changed snapshot patch queue' (Approval "runtime-$base" $old)
try {
$null = Plan $old $breakingPack -PackagingPush
throw 'Incompatible packaging change reused the old runtime commit'
} catch {
if ($_ -notmatch 'A new runtime baseline commit is required') { throw }
}
$compatible = Write-Commit $source 'docs/build.md' 'safe runtime change' (Approval "runtime-$base" $pack)
Assert-Version (Plan $compatible $pack) "$base-p1" $base
Add-Published "$base-p1" $compatible $pack $base
if (!(Plan $compatible $pack).Skip) {
throw 'A published revision with a different source prefix rebuilt'
}
$next = Write-Commit $source 'docs/build.md' 'another verified change' (Approval "runtime-$base-p1" $pack)
Assert-Version (Plan $next $pack) "$base-p2" $base
$breaking = Write-Commit $source 'crates/reims-ctl/src/qemu.rs' 'different state path' (Approval "runtime-$base-p1" $pack)
$breakingBase = Test-Git $source @('rev-parse', '--short=7', $breaking)
Assert-Version (Plan $breaking $pack) $breakingBase $breakingBase
Add-Published $breakingBase $breaking $pack $breakingBase
$reverted = Write-Commit $source 'crates/reims-ctl/src/qemu.rs' 'original state path' (Approval "runtime-$base-p1" $pack)
$revertedBase = Test-Git $source @('rev-parse', '--short=7', $reverted)
Assert-Version (Plan $reverted $pack) $revertedBase $revertedBase
$unverified = Write-Commit $source 'docs/build.md' 'unverified change'
$unverifiedBase = Test-Git $source @('rev-parse', '--short=7', $unverified)
Assert-Version (Plan $unverified $pack) $unverifiedBase $unverifiedBase
Write-Host 'PASS Alpha family selection, exact-source deduplication, and suspend input guards'
} finally {
if (Test-Path -LiteralPath $fixture) {
$resolved = (Resolve-Path -LiteralPath $fixture).Path
if ($resolved -ne $fixture -or (Split-Path -Parent $resolved) -ne $root) {
throw "Unexpected test fixture path: $resolved"
}
Remove-Item -LiteralPath $resolved -Recurse -Force
}
}
@@ -0,0 +1,78 @@
# Stambha ARM64 macOS runtime preview
The `stambha-hosted` runtime runs on Windows x86-64 with WHPX. Stambha translates the ARM64 guest, and QEMU connects Stambha to Reims vGPU. The preview pack has its own QEMU and EDK2 firmware and can be imported in a Reims-Go client with the Stambha driver. Its runtime API is `0.1.0`.
Each release includes the runtime archive, the corresponding-source archive, and checksums. Users supply their own macOS boot media or virtual disk. Keep Apple system images, macOS installation material, signing tickets, and VM state outside the runtime package.
## Validated preview baseline
The first preview uses the A5000 `B-disk` configuration. This variant passed the Reims-Go client startup test, a Finder cold restart, and disk persistence checks. QEMU uses the display transport and NVMe changes in [the ARM-only patch series](patches/stambha-qemu/series.txt). The regular runtime workflow uses its own patch series.
| Component | Source revision |
| --- | --- |
| Reims vGPU | [`3731afd9b13416a24f74ec27a90b3913aef2dcc0`](https://github.com/steelbrain/reims-vgpu/commit/3731afd9b13416a24f74ec27a90b3913aef2dcc0) plus the hosted graphics sources archived with the preview |
| QEMU | [`4571bc5fecb039e8cfd6837e077810fbe074e11b`](https://github.com/steelbrain/qemu-reims-vgpu/commit/4571bc5fecb039e8cfd6837e077810fbe074e11b) plus the three patches below, archived as `fa0519c7b77668dd17b7ba710a3d3ecd802aa669` |
| `qemu-img` | The same QEMU base with the Win32 compatibility patch, reused from the tested base build |
| Metal2Vulkan | [`0b0ac58eb0f69ed3b37007fbdf3b135a46f90699`](https://github.com/steelbrain/metal2vulkan/commit/0b0ac58eb0f69ed3b37007fbdf3b135a46f90699) |
| Stela EFI | `d6d1ad81cf0c0940c8ee6713871fbc8ecca6d177`, based on Stambha v0.6.2 [`65340914732f3afd08de01a5c82560d27449df92`](https://github.com/garvitsurana271/stambha/commit/65340914732f3afd08de01a5c82560d27449df92) with the hosted Reims graphics and default GPU interrupt polling |
| `stambha-engine` | [`5e3d6f76266de89df321e6f16f7305e523c242c2`](https://github.com/yxc0915/stambha/commit/5e3d6f76266de89df321e6f16f7305e523c242c2) |
Apply the QEMU patches to a separate checkout of the baseline above, in the order listed. The Windows build targets `x86_64-softmmu` under MSYS2 CLANG64 and links Reims vGPU through its dist tree. The archived recipe and component sources record the complete inputs for each binary.
```powershell
$series = 'packaging/windows-runtime/patches/stambha-qemu'
foreach ($patch in Get-Content -LiteralPath "$series/series.txt") {
$file = (Resolve-Path -LiteralPath "$series/$patch").Path
git -C $qemuRepo apply --check $file
if ($LASTEXITCODE) { throw "Could not apply $patch" }
git -C $qemuRepo apply $file
if ($LASTEXITCODE) { throw "Could not apply $patch" }
}
```
## Assemble a preview from verified build outputs
Prepare an input directory using build outputs from the same validated configuration. Separate the hosted display and NVMe QEMU patches from the regular Intel runtime. Preserve the boot engine, outer-QEMU executable, `qemu-img`, both EDK2 images, and the Stela EFI at the tested revisions. Record the components and build commands in `BUILD.md` with the archive.
```text
input/
BUILD.md
provenance.json
patches/<applied-patch>.patch
sources/<component-source>.tar.gz
sources/<copyleft-msys2-source>.tar.zst
payload/
bin/stambha-engine.exe
firmware/edk2-code.fd
firmware/edk2-vars.fd
firmware/stambha.efi
qemu/bin/qemu-system-x86_64.exe
qemu/bin/qemu-img.exe
qemu/bin/reims-vgpu-compile.exe
qemu/bin/<required DLLs>
qemu/share/vgabios-stdvga.bin
MSYS2-PACKAGES.txt
NOTICE.md
licenses/
edk2-licenses.txt
stambha/NOTICE
stambha/LICENSE
stambha/LICENSES/GPL-3.0-or-later.txt
<other component and dependency license texts>
```
The provenance receipt uses `schema_version: 1`. Include the following fields.
- `components` lists `reims-vgpu`, `qemu`, `qemu-img`, `metal2vulkan`, `stela`, `stambha-engine`, `edk2-code`, and `edk2-vars`. Each object has `name`, `repo`, `commit`, and `source`. `commit` is the full Git object ID. Include `base_commit` for a patched revision when applicable. `source` is the filename of its archive in `sources/`.
- `sources` lists each archive with `file` and `sha256`. Set `msys2_source` to the archive of corresponding sources for the copyleft DLLs. Keep `MSYS2-PACKAGES.txt` in the payload so users can identify the package versions behind the DLLs.
- `patches` lists each applied patch in order with `name`, `target`, and `sha256`. Supply the matching patch files even when their changes appear in an exported source tree.
- `sha256` maps every payload-relative path to its lowercase SHA-256, including licenses and notices. The package verifier requires the entire payload to match.
The Stambha source package must include the source and license materials for both the hosted engine and EFI and the required `third_party/` submodules at their pins. Include Reims vGPU and Metal2Vulkan sources used to link QEMU, QEMU's required source dependencies, and the corresponding EDK2 source material.
```powershell
pwsh -File packaging/windows-runtime/scripts/pack-stambha-runtime.ps1 `
-InputRoot $input -OutDir $releaseFolder -ReleaseId $revision
```
The output folder must be new. The packer reopens the emitted archives, verifies provenance and payload checksums, and runs the engine ARM64 self-test and QEMU graphics-device and WHPX feature checks with a restricted Windows `PATH`. A Windows host smoke test with user-supplied boot media verifies the import and boot path.
+54
View File
@@ -0,0 +1,54 @@
# Alpha 运行时编号与挂起兼容性规范
本规范用于 Windows 便携运行时的 Alpha 发布。主编号表示挂起兼容边界,`-pN` 表示同一主编号下的发布修订。
## 编号规则
| 变更判定 | 发布编号 | 旧挂起文件 |
| :--- | :--- | :--- |
| 同一主编号下首次发布 | `runtime-a1b2c3d` | 作为该主编号的兼容基线 |
| 交付内容有变更,旧挂起文件仍可用新版恢复 | `runtime-a1b2c3d-p1`、`runtime-a1b2c3d-p2`,按顺序递增 | 支持从该主编号下已验证的早期版本升级恢复 |
| 直接修改挂起或恢复逻辑、影响挂起功能,或暂时无法确认兼容 | `runtime-d4e5f6a`,使用新的主编号 | 新版拒绝加载上一主编号的挂起文件 |
同一版本的发布标识、归档名称和 `manifest.json` 的 `commit` 使用同一份编号。`full_commit` 和 `vendor_qemu_commit` 分别记录实际构建所用的运行时与 QEMU 完整提交。`-pN` 递增时,源码记录随实际构建更新。发布过的主编号和修订号不得换包或重新分配。
新主编号采用新兼容基线对应的运行时提交短 SHA。若不兼容变更来自打包仓库或依赖补丁,先在运行时维护分支提交新的兼容基线记录,再以该提交生成新主编号。
## 兼容性判定
发布前比较上一版实际交付的运行时、QEMU、依赖补丁、固件和启动参数。仅在确认新版能读取旧挂起状态,并验证恢复后虚拟机可继续运行时,才能沿用主编号。
- **可以沿用主编号的场景** 包括下载、日志或打包调整。前提是这些调整没有改变挂起所用的文件、启动配置或恢复行为,并通过跨版本恢复验证。
- **必须更换主编号的场景** 包括挂起保存、状态写入、恢复加载和相关校验逻辑的变更。迁移流或设备状态的格式、版本有变,以及 QEMU、WHPX、vGPU 或依赖调整会影响挂起功能时,也必须更换主编号。默认机型、CPU 特性、设备布局、固件、RAM 映射、磁盘控制器、QMP 恢复顺序和介质校验规则的变更也要纳入判定。
- **影响不明确时使用新主编号。** 目录名和提交标题可用于定位审查范围。变更实际触达的状态和跨版本恢复结果决定能否沿用主编号。
例如,网络修复需要核对它是否改动可迁移网卡、网络设备状态或恢复顺序。只修改网络相关文件仍需完成这项检查。
## 客户端恢复契约
客户端将发布标识用于下载、安装和定位归档。跨修订恢复使用清单中明确声明的挂起兼容标识,并在保存挂起时将该标识写入记录。获得同一兼容标识的发布必须符合本规范的同主编号规则。客户端仍要验证挂起记录的格式、虚拟硬件配置、附加介质和状态文件完整性。
清单和挂起记录使用 `suspend_compat_id` 保存挂起兼容标识,其值为发布编号中 `-pN` 前的主编号。打包提交记录在清单的 `packaging_commit` 中。
不兼容的挂起文件应在启动 QEMU 加载前被拦截。客户端保留原挂起状态,并提示用户选择原运行时重新恢复,或在用户明确放弃挂起后冷启动。
现有 Reims-Go 校验会比较 `vendor_qemu_commit` 和完整的运行时编号。即使 QEMU 提交相同,`a1b2c3d` 与 `a1b2c3d-p1` 的完整编号也会触发拒绝。客户端支持明确的兼容标识后,Alpha 才可向使用该客户端的用户承诺跨 `-pN` 恢复。缺少兼容标识的旧记录继续使用原有校验。若要承诺旧记录可以升级恢复,必须另行验证并明确列出可接受的旧运行时和 QEMU 提交组合。 [现有运行时校验](https://github.com/Nwflower/Reims-Go/blob/08b3089569b2f3a705e06fbe6d37846c7faf7d47/internal/macos/reims/suspend.go#L159-L189) · [挂起文件及介质校验](https://github.com/Nwflower/Reims-Go/blob/08b3089569b2f3a705e06fbe6d37846c7faf7d47/internal/macos/reims/suspend_transaction.go#L139-L184)
## 发布验证
1. **确认比较基线。** 记录旧包和新包的发布标识、运行时与 QEMU 完整提交、依赖和补丁变更,以及本次编号判定。
2. **沿用主编号。** 在虚拟机副本上,用旧包正常运行并挂起,再切到新版恢复。核对桌面和原应用状态、磁盘可写性及受影响的设备。验证上一修订和本系列最早承诺可升级的版本,并覆盖这次受影响的宿主或后端。
3. **更换主编号。** 用上一主编号的挂起记录确认新版在加载前拦截,并验证新版能冷启动及完成自己的挂起与恢复。保留测试证据和可用于恢复旧状态的原运行时。
4. **确认发布。** 核对编号与运行时清单、校验和、源码附件和 Release 说明。Alpha 经 CI 构建和检查后以预发布交付,正式版由人工确认和发布。 [Alpha 构建流程](../../.github/workflows/runtime-preview.yml)
## 自动编号的验证记录
沿用主编号前,在触发构建的提交末尾记录已验证的上一修订、另一侧的完整提交和验收记录链接。运行时分支提交记录打包提交,打包变更和手动重建由打包提交记录运行时提交。
```text
Suspend-Compatible-With: runtime-a1b2c3d-p2
Suspend-Verified-Inputs: 0123456789abcdef0123456789abcdef01234567
Suspend-Verification: https://example.com/runtime-resume-check
```
CI 使用最新已发布且声明兼容标识的运行时作为验证基线,该版本还必须是所属主编号下的最高修订。运行时和打包输入必须与该次验证对应。QEMU 指针、挂起相关源码或依赖补丁变化会要求新主编号。没有满足这些条件的验证记录时,CI 按新主编号处理。若运行时提交已发布且本次只是更换打包输入,先提交新的运行时基线,再发布。