Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c64ad41aa | ||
|
|
f13f143001 | ||
|
|
4f7c54c458 | ||
|
|
28457772f4 | ||
|
|
116ef68ae8 | ||
|
|
1bc441947c | ||
|
|
c0b03faa85 | ||
|
|
57024d3ab1 | ||
|
|
e8083c97ea | ||
|
|
3bbf37b149 | ||
|
|
98f1677b5f | ||
|
|
9a6ace7a3a | ||
|
|
add539cd0f | ||
|
|
3cb5384b33 | ||
|
|
ca116e4f36 | ||
|
|
9a57f0644d | ||
|
|
f152e84bba |
No files matched your search
@@ -0,0 +1,112 @@
|
||||
name: Merge upstream updates
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '37 */4 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: merge-upstream-intel-vm-suspend
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
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: intel-vm-suspend
|
||||
UPSTREAM_REPO: steelbrain/reims-vgpu
|
||||
UPSTREAM_BRANCH: master
|
||||
GIT_AUTHOR_NAME: YXC0915
|
||||
GIT_AUTHOR_EMAIL: 62410385+yxc0915@users.noreply.github.com
|
||||
GIT_COMMITTER_NAME: 'github-actions[bot]'
|
||||
GIT_COMMITTER_EMAIL: '41898282+github-actions[bot]@users.noreply.github.com'
|
||||
GIT_TERMINAL_PROMPT: '0'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
summary() {
|
||||
printf '%s\n' "$1" | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
}
|
||||
|
||||
# Check ancestry on GitHub first so routine polls do not fetch QEMU history.
|
||||
target_ref=${TARGET_BRANCH//\//%2F}
|
||||
upstream_ref=${UPSTREAM_BRANCH//\//%2F}
|
||||
status=$(gh api "repos/$GITHUB_REPOSITORY/compare/$target_ref...${UPSTREAM_REPO%%/*}:$upstream_ref?per_page=1" --jq .status)
|
||||
case "$status" in
|
||||
identical|behind)
|
||||
summary "$TARGET_BRANCH already contains $UPSTREAM_REPO:$UPSTREAM_BRANCH."
|
||||
exit 0
|
||||
;;
|
||||
ahead|diverged) ;;
|
||||
*)
|
||||
echo "::error::Unexpected upstream comparison status: $status"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
git init --bare --quiet "$RUNNER_TEMP/upstream-sync.git"
|
||||
cd "$RUNNER_TEMP/upstream-sync.git"
|
||||
git remote add origin "https://github.com/$GITHUB_REPOSITORY.git"
|
||||
git remote add upstream "https://github.com/$UPSTREAM_REPO.git"
|
||||
git fetch --no-tags --refmap= origin "refs/heads/$TARGET_BRANCH:refs/remotes/origin/target"
|
||||
git fetch --no-tags --refmap= upstream "refs/heads/$UPSTREAM_BRANCH:refs/remotes/upstream/source"
|
||||
target=$(git rev-parse refs/remotes/origin/target)
|
||||
source=$(git rev-parse refs/remotes/upstream/source)
|
||||
|
||||
# Recheck ancestry using the exact commits that were fetched.
|
||||
if git merge-base --is-ancestor "$source" "$target"; then
|
||||
summary "$TARGET_BRANCH already contains upstream commit $source."
|
||||
exit 0
|
||||
fi
|
||||
if git merge-base --is-ancestor "$target" "$source"; then
|
||||
merged=$source
|
||||
elif tree=$(git merge-tree --write-tree "$target" "$source"); then
|
||||
merged=$(git commit-tree "$tree" -p "$target" -p "$source" \
|
||||
-m "Merge $UPSTREAM_REPO:$UPSTREAM_BRANCH into $TARGET_BRANCH")
|
||||
else
|
||||
result=$?
|
||||
printf '%s\n' "$tree" | sed 's/^/ /'
|
||||
if [[ "$result" != 1 ]]; then
|
||||
exit "$result"
|
||||
fi
|
||||
echo "::warning::Upstream merge has conflicts. The maintenance branch was not updated."
|
||||
summary "Skipped merging $source into $TARGET_BRANCH at $target because of merge conflicts. See the job log."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# A normal push rejects a competing branch update and leaves its work intact.
|
||||
auth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)
|
||||
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
|
||||
@@ -1,25 +0,0 @@
|
||||
name: Queue Runtime Alpha
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [intel-vm-suspend]
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
|
||||
concurrency:
|
||||
group: queue-runtime-alpha
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
alpha:
|
||||
if: github.repository == 'reims-go/reims-vgpu'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Queue Alpha for the pushed commit
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh workflow run runtime-preview.yml --repo "$GITHUB_REPOSITORY" --ref master \
|
||||
-f upstream_commit="$GITHUB_SHA" -f publish=true -f supersede=true
|
||||
@@ -0,0 +1,294 @@
|
||||
name: Publish Runtime Preview
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
paths:
|
||||
- "packaging/windows-runtime/**"
|
||||
schedule:
|
||||
- cron: "23 3 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
upstream_commit:
|
||||
description: "Reims vGPU fork commit (empty = runtime branch HEAD)"
|
||||
required: false
|
||||
default: ""
|
||||
publish:
|
||||
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: "Plan a rebuild of an already published runtime using verified compatibility"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
UPSTREAM_URL: ${{ github.server_url }}/${{ github.repository }}.git
|
||||
UPSTREAM_BRANCH: intel-vm-suspend
|
||||
|
||||
jobs:
|
||||
resolve:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
commit: ${{ steps.r.outputs.commit }}
|
||||
skip: ${{ steps.r.outputs.skip }}
|
||||
steps:
|
||||
- id: r
|
||||
env:
|
||||
WANT: ${{ inputs.upstream_commit }}
|
||||
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"
|
||||
if [[ "$CURRENT_ONLY" == true && "$commit" != "$(git -C up rev-parse HEAD)" ]]; then
|
||||
echo "Skipping superseded runtime commit $commit"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
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:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
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:
|
||||
msystem: CLANG64
|
||||
update: true
|
||||
install: >-
|
||||
git zstd tar mingw-w64-clang-x86_64-toolchain
|
||||
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-meson
|
||||
mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf
|
||||
mingw-w64-clang-x86_64-glib2 mingw-w64-clang-x86_64-pixman
|
||||
mingw-w64-clang-x86_64-gtk3 mingw-w64-clang-x86_64-libslirp
|
||||
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-libva
|
||||
mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader
|
||||
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
|
||||
|
||||
- name: Check out the runtime forks and apply dependency patches
|
||||
if: steps.plan.outputs.skip != 'true'
|
||||
id: patches
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$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 }
|
||||
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' }
|
||||
$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)"
|
||||
}
|
||||
$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()
|
||||
|
||||
# Applies what applies, skips what upstream already has, stops on a
|
||||
# conflict without touching the patch (AGENTS.md rule 4).
|
||||
$resultFile = Join-Path $env:RUNNER_TEMP 'patches.json'
|
||||
try {
|
||||
pwsh -NoProfile -File packaging/windows-runtime/scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -Metal2VulkanRepo $m2vRepo -ResultFile $resultFile
|
||||
$ok = $LASTEXITCODE -eq 0
|
||||
} finally {
|
||||
if (Test-Path $resultFile) {
|
||||
$r = Get-Content -Raw $resultFile | ConvertFrom-Json
|
||||
"merged=$(@($r.merged) -join ',')" >> $env:GITHUB_OUTPUT
|
||||
"APPLIED_PATCHES=$(@($r.applied) -join ',')" >> $env:GITHUB_ENV
|
||||
}
|
||||
}
|
||||
if (-not $ok) { throw 'patch queue does not apply' }
|
||||
$cargoHome = Join-Path $env:RUNNER_TEMP 'cargo'
|
||||
$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" }
|
||||
"@
|
||||
[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
|
||||
"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"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$(cygpath -u "$UPSTREAM_DIR")"
|
||||
# Upstream's own non-interactive CLANG64 build script.
|
||||
bash scripts/install-ctl.sh --yes
|
||||
util_repo="$(cygpath -u "$REIMS_UTIL_DIR")"
|
||||
if [[ -n "$(git -C "$util_repo" status --porcelain)" ]]; then
|
||||
toolchain="$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)"
|
||||
export PATH="$(cygpath -u "$CARGO_HOME")/bin:$PATH"
|
||||
CC=clang CXX=clang++ AR=llvm-ar cargo +"$toolchain-x86_64-pc-windows-gnullvm" install \
|
||||
--locked --force --root "$CARGO_HOME" --path "$REIMS_UTIL_DIR"
|
||||
fi
|
||||
|
||||
- name: Package alpha runtime and source archives
|
||||
if: steps.plan.outputs.skip != 'true'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$outDir = Join-Path $env:RUNNER_TEMP 'releases'
|
||||
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
|
||||
# In-process call, so an empty list (every patch already upstream) binds
|
||||
# as an empty array rather than being dropped as an empty argument.
|
||||
$applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
|
||||
& ./packaging/windows-runtime/scripts/pack-runtime.ps1 `
|
||||
-ReimsRepo $env:UPSTREAM_DIR `
|
||||
-UtilRepo $env:REIMS_UTIL_DIR `
|
||||
-Metal2VulkanRepo $env:METAL2VULKAN_DIR `
|
||||
-CargoHome $env:CARGO_HOME `
|
||||
-QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') `
|
||||
-Msys2 '${{ steps.msys2.outputs.msys2-location }}' `
|
||||
-OutDir $outDir `
|
||||
-TempRoot $env:RUNNER_TEMP `
|
||||
-Channel alpha `
|
||||
-ReleaseId $env:RELEASE_ID `
|
||||
-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
|
||||
path: |
|
||||
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
|
||||
${{ runner.temp }}/releases/SHA256SUMS.txt
|
||||
retention-days: 14
|
||||
|
||||
- name: Publish alpha prerelease (never stable)
|
||||
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$', ''
|
||||
$dir = Join-Path $env:RUNNER_TEMP 'releases'
|
||||
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$c.tar.zst", 'SHA256SUMS.txt') |
|
||||
ForEach-Object { Join-Path $dir $_ }
|
||||
$applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' }
|
||||
$merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' }
|
||||
$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 }}).
|
||||
|
||||
Preview for Windows x64. Stable promotion requires a real-host smoke test with ``packaging/windows-runtime/scripts/smoke-runtime.ps1`` and human approval.
|
||||
|
||||
Local patches applied (sources and patches are in the attached source packages):
|
||||
$applied$merged
|
||||
|
||||
The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis.
|
||||
|
||||
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 --latest=false --title "Portable Runtime runtime-$c (alpha)" --notes $notes
|
||||
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
[submodule "vendor/qemu"]
|
||||
path = vendor/qemu
|
||||
url = https://github.com/reims-go/qemu-reims-vgpu.git
|
||||
branch = intel-vm-suspend
|
||||
url = https://github.com/steelbrain/qemu-reims-vgpu
|
||||
branch = steelbrain/reims-vgpu-rebase-2
|
||||
Generated
-3
@@ -213,7 +213,6 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
[[package]]
|
||||
name = "metal2vulkan"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"metal2vulkan-air",
|
||||
@@ -224,7 +223,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metal2vulkan-air"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
|
||||
dependencies = [
|
||||
"sha2 0.11.1",
|
||||
]
|
||||
@@ -232,7 +230,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metal2vulkan-runtime"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"libc",
|
||||
|
||||
+2
-2
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
|
||||
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
|
||||
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
|
||||
# from metal2vulkan's public repository at the commit both name.
|
||||
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "19090d5f2e60185359200046e0b72e96ce60099a" }
|
||||
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
|
||||
# The Vulkan platform's runtime (architecture D1), metal2vulkan-runtime: a Metal-shaped API on
|
||||
# Vulkan, one path for every device, under reims-vgpu-vulkan's `rt_platform` and `seam` and
|
||||
# reims-vgpu's `pool::rt_blocks`.
|
||||
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "19090d5f2e60185359200046e0b72e96ce60099a" }
|
||||
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
|
||||
# The hashes of the Vulkan platform's metallib sources (reims-vgpu-vulkan/build.rs).
|
||||
sha2 = "0.10.9"
|
||||
# A display window's swapchain on Linux (reims-vgpu-vulkan/src/swapchain.rs), at the runtime's
|
||||
|
||||
@@ -21,7 +21,6 @@ mod opencore;
|
||||
mod os;
|
||||
mod paths;
|
||||
mod prebuilt;
|
||||
mod processor;
|
||||
mod qemu;
|
||||
mod qmp;
|
||||
mod reims_util;
|
||||
|
||||
@@ -18,9 +18,8 @@ use crate::vm::{Graphics, ImageFormat, Vm};
|
||||
use crate::{paths, prebuilt, reims_util, runtime};
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::fs::File;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
@@ -50,7 +49,7 @@ pub struct Config(plist::Dictionary);
|
||||
|
||||
impl Config {
|
||||
pub fn read(path: &Path, format: ImageFormat) -> Result<Config> {
|
||||
let bytes = read_file(path, format, CONFIG_PLIST)?
|
||||
let bytes = read_file(path, format, "EFI/OC/config.plist")?
|
||||
.context("its EFI system partition has no EFI/OC/config.plist")?;
|
||||
Config::parse(&bytes)
|
||||
}
|
||||
@@ -133,171 +132,6 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
const CONFIG_PLIST: &str = "EFI/OC/config.plist";
|
||||
|
||||
/// Update the type used by macOS's About This Mac when OpenCore is set to automatic.
|
||||
pub fn match_processor_type(vm: &Vm, value: u16) -> Result<bool> {
|
||||
let Some(q) = vm.config.q35.as_ref() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let image = vm.path(&q.opencore);
|
||||
if !fs::symlink_metadata(&image)?.is_file() {
|
||||
return Ok(false);
|
||||
}
|
||||
let format = q.opencore_format;
|
||||
let stamp = Stamp::of(&image).context("read OpenCore image metadata")?;
|
||||
let Some(bytes) = read_file(&image, format, CONFIG_PLIST)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(edited) = with_processor_type(&bytes, value)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
ensure_opencore_unused(vm, &image)?;
|
||||
|
||||
// Keep the original until the candidate is synced and read back. Each caller owns its copy.
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let part = image.with_extension(format!(
|
||||
"cpu-{}-{}-{}.part",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)?
|
||||
.as_nanos(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&part)?;
|
||||
let result = (|| -> Result<()> {
|
||||
let mut source = File::open(&image)?;
|
||||
file.set_permissions(source.metadata()?.permissions())?;
|
||||
std::io::copy(&mut source, &mut &file)?;
|
||||
drop(source);
|
||||
let disk = Disk::from_file(file, format)?;
|
||||
let fat = Fat32::open(&disk, esp_start(&disk)?)?;
|
||||
ensure!(
|
||||
fat.holds(CONFIG_PLIST, &bytes)? == Some(true),
|
||||
"OpenCore config changed while copying"
|
||||
);
|
||||
fat.overwrite(CONFIG_PLIST, &edited)?;
|
||||
disk.file().sync_all()?;
|
||||
drop(disk);
|
||||
ensure!(
|
||||
read_file(&part, format, CONFIG_PLIST)?.as_deref() == Some(&edited),
|
||||
"the new OpenCore config did not read back"
|
||||
);
|
||||
|
||||
ensure_opencore_unused(vm, &image)?;
|
||||
ensure!(
|
||||
Stamp::of(&image) == Some(stamp),
|
||||
"OpenCore image changed while copying"
|
||||
);
|
||||
fs::rename(&part, &image).with_context(|| format!("replace {}", image.display()))
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
let _ = fs::remove_file(&part);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
KEPT.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&image);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn ensure_opencore_unused(vm: &Vm, image: &Path) -> Result<()> {
|
||||
ensure!(!runtime::running(vm), "{} is running", vm.name());
|
||||
let image = fs::canonicalize(image)?;
|
||||
for entry in crate::vm::Registry::load()?.vms {
|
||||
if runtime::pid_at(&crate::vm::pidfile_in(&entry.dir)).is_none() {
|
||||
continue;
|
||||
}
|
||||
let other = Vm::load(&entry.dir)
|
||||
.with_context(|| format!("read settings of running VM {}", entry.name))?;
|
||||
if let Some(q) = &other.config.q35 {
|
||||
let other_image = fs::canonicalize(other.path(&q.opencore))?;
|
||||
ensure!(
|
||||
other_image != image,
|
||||
"{} is running on this OpenCore image",
|
||||
entry.name
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replace the integer in the plist without resizing the FAT file. The parsed comparison
|
||||
/// guards against editing a similarly named key elsewhere in the XML.
|
||||
fn with_processor_type(bytes: &[u8], value: u16) -> Result<Option<Vec<u8>>> {
|
||||
let mut expected = Config::parse(bytes)?.0;
|
||||
let vault = expected
|
||||
.get("Misc")
|
||||
.and_then(plist::Value::as_dictionary)
|
||||
.and_then(|misc| misc.get("Security"))
|
||||
.and_then(plist::Value::as_dictionary)
|
||||
.and_then(|security| security.get("Vault"))
|
||||
.and_then(plist::Value::as_string);
|
||||
if vault != Some("Optional") {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(platform) = expected
|
||||
.get_mut("PlatformInfo")
|
||||
.and_then(plist::Value::as_dictionary_mut)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if platform.get("Automatic").and_then(plist::Value::as_boolean) != Some(true)
|
||||
|| platform
|
||||
.get("UpdateSMBIOS")
|
||||
.and_then(plist::Value::as_boolean)
|
||||
!= Some(true)
|
||||
|| platform
|
||||
.get("UpdateSMBIOSMode")
|
||||
.and_then(plist::Value::as_string)
|
||||
!= Some("Create")
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(processor) = platform
|
||||
.get_mut("Generic")
|
||||
.and_then(plist::Value::as_dictionary_mut)
|
||||
.and_then(|generic| generic.get_mut("ProcessorType"))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if value == 0 || processor.as_unsigned_integer() != Some(0) {
|
||||
return Ok(None);
|
||||
}
|
||||
*processor = plist::Value::Integer(value.into());
|
||||
|
||||
const KEY: &[u8] = b"<key>ProcessorType</key>";
|
||||
let start = bytes
|
||||
.windows(KEY.len())
|
||||
.position(|w| w == KEY)
|
||||
.context("OpenCore config has no XML ProcessorType key")?
|
||||
+ KEY.len();
|
||||
let whitespace = bytes[start..]
|
||||
.iter()
|
||||
.take_while(|b| b.is_ascii_whitespace())
|
||||
.count();
|
||||
const ZERO: &[u8] = b"<integer>0</integer>";
|
||||
let integer = start + whitespace;
|
||||
let replacement = format!("<integer>{value}</integer>");
|
||||
let growth = replacement.len() - ZERO.len();
|
||||
ensure!(
|
||||
bytes[integer..].starts_with(ZERO) && whitespace >= growth,
|
||||
"OpenCore ProcessorType cannot be replaced at its original length"
|
||||
);
|
||||
let mut edited = bytes.to_vec();
|
||||
edited[integer - growth..integer + ZERO.len()].copy_from_slice(replacement.as_bytes());
|
||||
ensure!(
|
||||
Config::parse(&edited)?.0 == expected,
|
||||
"OpenCore config would change beyond ProcessorType"
|
||||
);
|
||||
Ok(Some(edited))
|
||||
}
|
||||
|
||||
/// Whether a VM's OpenCore image shows its boot picker; `None` for an image reims-ctl cannot
|
||||
/// read, or a VM with no OpenCore.
|
||||
pub fn shows_picker(vm: &Vm) -> Option<bool> {
|
||||
@@ -711,10 +545,6 @@ pub(crate) enum Disk {
|
||||
impl Disk {
|
||||
pub(crate) fn open(path: &Path, format: ImageFormat) -> Result<Disk> {
|
||||
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
|
||||
Self::from_file(file, format)
|
||||
}
|
||||
|
||||
fn from_file(file: File, format: ImageFormat) -> Result<Disk> {
|
||||
Ok(match format {
|
||||
ImageFormat::Raw => Disk::Raw {
|
||||
size: file.metadata()?.len(),
|
||||
@@ -724,29 +554,6 @@ impl Disk {
|
||||
})
|
||||
}
|
||||
|
||||
fn file(&self) -> &File {
|
||||
match self {
|
||||
Disk::Raw { file, .. } => file,
|
||||
Disk::Qcow2(q) => &q.file,
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, offset: u64, buf: &[u8]) -> Result<()> {
|
||||
let size = match self {
|
||||
Disk::Raw { size, .. } => *size,
|
||||
Disk::Qcow2(q) => q.size,
|
||||
};
|
||||
ensure!(
|
||||
offset.saturating_add(buf.len() as u64) <= size,
|
||||
"write past image end"
|
||||
);
|
||||
match self {
|
||||
Disk::Raw { file, .. } => file.write_all_at(buf, offset)?,
|
||||
Disk::Qcow2(q) => q.write(offset, buf)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn read(&self, offset: u64, buf: &mut [u8]) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
{
|
||||
@@ -812,8 +619,8 @@ impl Qcow2 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Host offset and whether the cluster is exclusively owned.
|
||||
fn cluster(&self, index: u64) -> Result<Option<(u64, bool)>> {
|
||||
/// Where guest cluster `index` is in the file; None where it reads as zeros.
|
||||
fn cluster(&self, index: u64) -> Result<Option<u64>> {
|
||||
let per_table = 1u64 << (self.cluster_bits - 3);
|
||||
let l1 = self
|
||||
.l1
|
||||
@@ -829,32 +636,7 @@ impl Qcow2 {
|
||||
let e = u64::from_be_bytes(e);
|
||||
ensure!(e & 1 << 62 == 0, "a qcow2 image with compressed clusters");
|
||||
// Bit 0: a zero cluster.
|
||||
let exclusive = l1 & e & (1 << 63) != 0;
|
||||
Ok((e & 1 == 0 && e & QCOW2_OFFSET != 0).then_some((e & QCOW2_OFFSET, exclusive)))
|
||||
}
|
||||
|
||||
fn write(&self, offset: u64, buf: &[u8]) -> Result<()> {
|
||||
let mut snapshots = [0; 4];
|
||||
self.file.read_exact_at(&mut snapshots, 60)?;
|
||||
ensure!(snapshots == [0; 4], "OpenCore image has internal snapshots");
|
||||
|
||||
let cluster = 1u64 << self.cluster_bits;
|
||||
let mut done = 0;
|
||||
while done < buf.len() {
|
||||
let at = offset + done as u64;
|
||||
let within = at & (cluster - 1);
|
||||
let n = ((cluster - within) as usize).min(buf.len() - done);
|
||||
let (host, true) = self
|
||||
.cluster(at >> self.cluster_bits)?
|
||||
.context("OpenCore QCOW2 cluster is unallocated")?
|
||||
else {
|
||||
bail!("OpenCore QCOW2 cluster is shared");
|
||||
};
|
||||
self.file
|
||||
.write_all_at(&buf[done..done + n], host + within)?;
|
||||
done += n;
|
||||
}
|
||||
Ok(())
|
||||
Ok((e & 1 == 0 && e & QCOW2_OFFSET != 0).then_some(e & QCOW2_OFFSET))
|
||||
}
|
||||
|
||||
fn read(&self, offset: u64, buf: &mut [u8]) -> Result<()> {
|
||||
@@ -866,7 +648,7 @@ impl Qcow2 {
|
||||
let n = ((cluster - within) as usize).min(buf.len() - done);
|
||||
let part = &mut buf[done..done + n];
|
||||
match self.cluster(at >> self.cluster_bits)? {
|
||||
Some((c, _)) => self.file.read_exact_at(part, c + within)?,
|
||||
Some(c) => self.file.read_exact_at(part, c + within)?,
|
||||
None => part.fill(0),
|
||||
}
|
||||
done += n;
|
||||
@@ -950,29 +732,6 @@ impl<'a> Fat32<'a> {
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
/// Overwrite only changed clusters of a file whose size stays the same.
|
||||
fn overwrite(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
let entry = self
|
||||
.find(path)?
|
||||
.with_context(|| format!("missing {path}"))?;
|
||||
ensure!(entry.size as usize == bytes.len(), "{path} changed size");
|
||||
let mut rest = bytes;
|
||||
self.chain(
|
||||
entry.cluster,
|
||||
bytes.len() as u64,
|
||||
&mut |offset, original| {
|
||||
let (new, remaining) = rest.split_at(original.len());
|
||||
if new != original {
|
||||
self.disk.write(offset, new)?;
|
||||
}
|
||||
rest = remaining;
|
||||
Ok(true)
|
||||
},
|
||||
)?;
|
||||
ensure!(rest.is_empty(), "{path} is cut short");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the file at `path` (as [`Fat32::find`] takes it) holds `bytes`, however many: its
|
||||
/// entry's size first, then its clusters, a cluster at a time, to the first that differs, so
|
||||
/// none of it is read where its size differs, and no more than `bytes` holds where it does;
|
||||
@@ -985,12 +744,12 @@ impl<'a> Fat32<'a> {
|
||||
return Ok(Some(false));
|
||||
}
|
||||
let mut rest = bytes;
|
||||
self.chain(e.cluster, bytes.len() as u64, &mut |_, part| {
|
||||
self.chain(e.cluster, bytes.len() as u64, &mut |part| {
|
||||
let same = rest.starts_with(part);
|
||||
if same {
|
||||
rest = &rest[part.len()..];
|
||||
}
|
||||
Ok(same)
|
||||
same
|
||||
})?;
|
||||
// A chain that ends before the file's size does not hold the rest.
|
||||
Ok(Some(rest.is_empty()))
|
||||
@@ -999,21 +758,16 @@ impl<'a> Fat32<'a> {
|
||||
/// The bytes of the clusters from `first`, at most `most`.
|
||||
fn read_chain(&self, first: u32, most: u64) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
self.chain(first, most, &mut |_, part| {
|
||||
self.chain(first, most, &mut |part| {
|
||||
out.extend_from_slice(part);
|
||||
Ok(true)
|
||||
true
|
||||
})?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Gives `part` the bytes of the clusters from `first`, a cluster at a time, until the chain
|
||||
/// ends, `most` bytes are given (the last cluster's cut to them), or `part` returns false.
|
||||
fn chain(
|
||||
&self,
|
||||
first: u32,
|
||||
most: u64,
|
||||
part: &mut impl FnMut(u64, &[u8]) -> Result<bool>,
|
||||
) -> Result<()> {
|
||||
fn chain(&self, first: u32, most: u64, part: &mut dyn FnMut(&[u8]) -> bool) -> Result<()> {
|
||||
let mut buf = vec![0u8; self.cluster_size as usize];
|
||||
let mut c = first;
|
||||
let mut given = 0;
|
||||
@@ -1021,7 +775,7 @@ impl<'a> Fat32<'a> {
|
||||
let n = (most - given).min(self.cluster_size) as usize;
|
||||
let offset = self.data + u64::from(c - 2) * self.cluster_size;
|
||||
self.disk.read(offset, &mut buf[..n])?;
|
||||
if !part(offset, &buf[..n])? {
|
||||
if !part(&buf[..n]) {
|
||||
break;
|
||||
}
|
||||
given += n as u64;
|
||||
@@ -2006,152 +1760,4 @@ pub(crate) mod tests {
|
||||
assert!(!with("<key>ShowPicker</key><false/>").shows_picker());
|
||||
assert!(with("<key>ShowPicker</key><true/>").shows_picker());
|
||||
}
|
||||
|
||||
fn plist_with_processor_type(processor_type: u16) -> String {
|
||||
plist(&enabled("Example.kext"))
|
||||
.replacen(
|
||||
" <key>PlatformInfo</key>",
|
||||
concat!(
|
||||
" <key>Misc</key><dict><key>Security</key><dict>",
|
||||
"<key>Vault</key><string>Optional</string></dict></dict>\n",
|
||||
" <key>PlatformInfo</key>",
|
||||
),
|
||||
1,
|
||||
)
|
||||
.replacen(
|
||||
" <key>Automatic</key><true/>",
|
||||
concat!(
|
||||
" <key>Automatic</key><true/>\n",
|
||||
" <key>UpdateSMBIOS</key><true/>\n",
|
||||
" <key>UpdateSMBIOSMode</key><string>Create</string>",
|
||||
),
|
||||
1,
|
||||
)
|
||||
.replacen(
|
||||
" <key>ROM</key>",
|
||||
&format!(
|
||||
" <key>ProcessorType</key>\n <integer>{processor_type}</integer>\n <key>ROM</key>"
|
||||
),
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_type_updates_only_the_generated_config() {
|
||||
let env = crate::testenv::Env::new("processor-type");
|
||||
let original = plist_with_processor_type(0);
|
||||
let expected = plist_with_processor_type(0x0609);
|
||||
let unrelated = b"unrelated EFI payload";
|
||||
let raw = image_of(&[
|
||||
("EFI/OC/config.plist", original.as_bytes()),
|
||||
("EFI/OC/Other.txt", unrelated),
|
||||
]);
|
||||
|
||||
for format in [ImageFormat::Raw, ImageFormat::Qcow2] {
|
||||
let dir = env.root.join(format!("{format:?}"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = match format {
|
||||
ImageFormat::Raw => raw.clone(),
|
||||
ImageFormat::Qcow2 => qcow2(&raw),
|
||||
};
|
||||
let vm = on_reims_vgpu(&dir, &source, format);
|
||||
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
|
||||
|
||||
assert!(match_processor_type(&vm, 0x0609).unwrap(), "{format:?}");
|
||||
let written = std::fs::read(&path).unwrap();
|
||||
assert_eq!(written.len(), source.len(), "{format:?}");
|
||||
assert_eq!(
|
||||
Config::read(&path, format).unwrap().0,
|
||||
Config::parse(expected.as_bytes()).unwrap().0,
|
||||
"{format:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
read_file(&path, format, "EFI/OC/Other.txt")
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some(unrelated.as_slice()),
|
||||
"{format:?}"
|
||||
);
|
||||
|
||||
assert!(!match_processor_type(&vm, 0x0609).unwrap(), "{format:?}");
|
||||
assert!(!match_processor_type(&vm, 0x0709).unwrap(), "{format:?}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), written, "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_type_preserves_explicit_or_unsupported_configs() {
|
||||
let env = crate::testenv::Env::new("processor-type-custom");
|
||||
let baseline = plist_with_processor_type(0);
|
||||
for (label, config) in [
|
||||
("explicit", plist_with_processor_type(0x0709)),
|
||||
(
|
||||
"manual",
|
||||
baseline.replace(
|
||||
"<key>Automatic</key><true/>",
|
||||
"<key>Automatic</key><false/>",
|
||||
),
|
||||
),
|
||||
(
|
||||
"no-smbios-update",
|
||||
baseline.replace(
|
||||
"<key>UpdateSMBIOS</key><true/>",
|
||||
"<key>UpdateSMBIOS</key><false/>",
|
||||
),
|
||||
),
|
||||
(
|
||||
"other-mode",
|
||||
baseline.replace("<string>Create</string>", "<string>Custom</string>"),
|
||||
),
|
||||
(
|
||||
"secure",
|
||||
baseline.replace("<string>Optional</string>", "<string>Secure</string>"),
|
||||
),
|
||||
(
|
||||
"basic",
|
||||
baseline.replace("<string>Optional</string>", "<string>Basic</string>"),
|
||||
),
|
||||
] {
|
||||
let dir = env.root.join(label);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = image(config.as_bytes());
|
||||
let vm = on_reims_vgpu(&dir, &source, ImageFormat::Raw);
|
||||
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
|
||||
|
||||
assert!(!match_processor_type(&vm, 0x0609).unwrap(), "{label}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), source, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_type_preserves_qcow2_with_shared_or_snapshotted_clusters() {
|
||||
let env = crate::testenv::Env::new("processor-type-shared-clusters");
|
||||
let config = plist_with_processor_type(0);
|
||||
let generated = qcow2(&image(config.as_bytes()));
|
||||
let mut shared = generated.clone();
|
||||
let l1 = be64(&shared, 40) as usize;
|
||||
let l1_size = be32(&shared, 36) as usize * 8;
|
||||
for entry in shared[l1..l1 + l1_size].chunks_exact_mut(8) {
|
||||
entry[0] &= 0x7f;
|
||||
}
|
||||
let mut snapshot = generated;
|
||||
snapshot[60..64].copy_from_slice(&1u32.to_be_bytes());
|
||||
|
||||
for (label, source) in [("shared", shared), ("snapshots", snapshot)] {
|
||||
let dir = env.root.join(label);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let vm = on_reims_vgpu(&dir, &source, ImageFormat::Qcow2);
|
||||
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
|
||||
|
||||
let error = match_processor_type(&vm, 0x0609).unwrap_err().to_string();
|
||||
assert!(error.contains(label), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), source, "{label}");
|
||||
assert!(std::fs::read_dir(&dir).unwrap().all(|file| {
|
||||
file.unwrap()
|
||||
.path()
|
||||
.extension()
|
||||
.is_none_or(|ext| ext != "part")
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
//! Apple SMBIOS processor types for the host CPU family shown in an x86-64 macOS guest.
|
||||
|
||||
/// Returns the OpenCore ProcessorType for this host's CPU family and the guest's vCPU count.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn for_host(cpus: u32) -> Option<u16> {
|
||||
use std::arch::x86_64::__cpuid;
|
||||
|
||||
if __cpuid(0x8000_0000).eax < 0x8000_0004 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let bytes: Vec<u8> = (0x8000_0002..=0x8000_0004)
|
||||
.flat_map(|leaf| {
|
||||
let registers = __cpuid(leaf);
|
||||
[registers.eax, registers.ebx, registers.ecx, registers.edx]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
})
|
||||
.collect();
|
||||
let brand = String::from_utf8_lossy(&bytes);
|
||||
for_brand(
|
||||
brand.trim_matches(|c: char| c == '\0' || c.is_whitespace()),
|
||||
cpus,
|
||||
)
|
||||
}
|
||||
|
||||
/// Other host architectures do not expose an x86 CPU brand.
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
pub fn for_host(_cpus: u32) -> Option<u16> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86_64", test))]
|
||||
fn for_brand(brand: &str, cpus: u32) -> Option<u16> {
|
||||
let normalized = brand
|
||||
.to_ascii_lowercase()
|
||||
.replace("(r)", " ")
|
||||
.replace("(tm)", " ");
|
||||
let words: Vec<_> = normalized
|
||||
.split(|c: char| c.is_whitespace() || c == '-')
|
||||
.filter(|word| !word.is_empty())
|
||||
.collect();
|
||||
if words
|
||||
.iter()
|
||||
.any(|word| matches!(*word, "xeon" | "threadripper" | "epyc"))
|
||||
{
|
||||
// macOS counts 5–8 vCPUs as eight cores, which has a name in the Xeon W family.
|
||||
return match cpus {
|
||||
1..=4 => Some(0x0501),
|
||||
5..=16 => Some(0x0F01),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
|
||||
// Apple's name table is keyed by family and the core count reported by the guest.
|
||||
// Keep automatic detection where this family has no label for the VM's topology.
|
||||
let processor_type = |rank: &str| match (rank, cpus) {
|
||||
("3", 2..=4) => Some(0x0909),
|
||||
("5", 2..=8) => Some(0x0609),
|
||||
("7", 2..=8) => Some(0x0709),
|
||||
("9", 5..=8) => Some(0x1009),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(value) = words
|
||||
.iter()
|
||||
.find_map(|word| word.strip_prefix('i').and_then(processor_type))
|
||||
{
|
||||
return Some(value);
|
||||
}
|
||||
|
||||
// Intel Core and AMD Ryzen ranks share Apple's corresponding display families.
|
||||
words.iter().enumerate().find_map(|(index, word)| {
|
||||
let qualifiers: &[&str] = match *word {
|
||||
"core" => &["ultra"],
|
||||
"ryzen" => &["ai", "pro"],
|
||||
_ => return None,
|
||||
};
|
||||
let rank = words[index + 1..]
|
||||
.iter()
|
||||
.find(|word| !qualifiers.contains(word))?;
|
||||
processor_type(rank)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn host_brand_maps_to_an_apple_processor_type() {
|
||||
for (brand, cpus, expected) in [
|
||||
("Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz", 4, 0x0709),
|
||||
("Intel(R) Core(TM) i3-8100B CPU @ 3.60GHz", 4, 0x0909),
|
||||
("Intel(R) Core(TM) i5-1035G1 CPU @ 1.00GHz", 4, 0x0609),
|
||||
("12th Gen Intel(R) Core(TM) i5-12400", 8, 0x0609),
|
||||
("12th Gen Intel(R) Core(TM) i7-12700H", 8, 0x0709),
|
||||
("13th Gen Intel(R) Core(TM) i9-13900H", 8, 0x1009),
|
||||
("Intel(R) Core(TM) Ultra 5 125H", 6, 0x0609),
|
||||
("Intel(R) Core(TM) Ultra 7 155H", 8, 0x0709),
|
||||
("Intel(R) Core(TM) Ultra 9 275HX", 8, 0x1009),
|
||||
("Intel(R) Core(TM) 3 100U", 4, 0x0909),
|
||||
("Intel(R) Core(TM) 7 150U", 8, 0x0709),
|
||||
("Intel(R) Xeon(R) W-2145 CPU @ 3.70GHz", 4, 0x0501),
|
||||
("Intel(R) Xeon(R) W-2145 CPU @ 3.70GHz", 5, 0x0F01),
|
||||
("Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz", 6, 0x0F01),
|
||||
("Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz", 8, 0x0F01),
|
||||
("AMD Ryzen 3 3200G with Radeon Vega Graphics", 4, 0x0909),
|
||||
("AMD Ryzen 5 5600X 6-Core Processor", 6, 0x0609),
|
||||
("AMD Ryzen 5 PRO 4650G with Radeon Graphics", 8, 0x0609),
|
||||
("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics", 4, 0x0709),
|
||||
("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics", 8, 0x0709),
|
||||
("AMD Ryzen 7 8745H w/ Radeon 780M Graphics", 8, 0x0709),
|
||||
("AMD Ryzen 9 7950X 16-Core Processor", 8, 0x1009),
|
||||
("AMD Ryzen AI 9 HX 370 w/ Radeon 890M Graphics", 8, 0x1009),
|
||||
("AMD Ryzen AI 7 PRO 360 w/ Radeon 880M Graphics", 8, 0x0709),
|
||||
("AMD Ryzen Threadripper PRO 5995WX 64-Cores", 1, 0x0501),
|
||||
("AMD EPYC 7763 64-Core Processor", 8, 0x0F01),
|
||||
] {
|
||||
assert_eq!(for_brand(brand, cpus), Some(expected), "{brand}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_without_a_label_for_the_core_count_keeps_automatic_detection() {
|
||||
for (brand, cpus) in [
|
||||
("Intel Core i3-8100B", 8),
|
||||
("Intel Core i5-12400", 1),
|
||||
("Intel Core i7-12700", 10),
|
||||
("Intel Core i9-13900H", 4),
|
||||
("Intel Xeon E5-2680", 17),
|
||||
] {
|
||||
assert_eq!(for_brand(brand, cpus), None, "{brand}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrecognized_host_leaves_processor_type_to_opencore() {
|
||||
for brand in [
|
||||
"Intel(R) Core(TM)2 Duo CPU E8400 @ 3.00GHz",
|
||||
"Intel(R) Core(TM) m3-7Y30 CPU @ 1.00GHz",
|
||||
"Intel(R) Pentium(R) Gold 7505 @ 2.00GHz",
|
||||
"Intel(R) Celeron(R) N4020 CPU @ 1.10GHz",
|
||||
"Intel(R) N100",
|
||||
"AMD Athlon Silver 3050U with Radeon Graphics",
|
||||
"AMD Ryzen AI Max+ 395 w/ Radeon 8060S",
|
||||
"AMD Ryzen Z1 Extreme",
|
||||
"Intel Core Processor (Skylake, IBRS, no TSX)",
|
||||
"",
|
||||
] {
|
||||
assert_eq!(for_brand(brand, 8), None, "{brand}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,33 +195,6 @@ pub fn opt(s: &str) -> String {
|
||||
s.replace(',', ",,")
|
||||
}
|
||||
|
||||
/// Compute the qcow2 L2 cache size in MiB needed to cover the full virtual disk
|
||||
/// (`virtual_size / cluster_size * 8` bytes), clamped to `..=32 MiB`, returning `Some(mib)` only
|
||||
/// when the image needs more than QEMU's 8 MiB non-Linux default.
|
||||
fn qcow2_l2_cache_mib(path: &Path) -> Option<u64> {
|
||||
use std::io::Read;
|
||||
let mut hdr = [0u8; 32];
|
||||
let mut f = std::fs::File::open(path).ok()?;
|
||||
f.read_exact(&mut hdr).ok()?;
|
||||
if &hdr[0..4] != b"QFI\xfb" {
|
||||
return None;
|
||||
}
|
||||
let version = u32::from_be_bytes(hdr[4..8].try_into().ok()?);
|
||||
if version < 2 || version > 3 {
|
||||
return None;
|
||||
}
|
||||
let cluster_bits = u32::from_be_bytes(hdr[20..24].try_into().ok()?);
|
||||
if !(9..=21).contains(&cluster_bits) {
|
||||
return None;
|
||||
}
|
||||
let virtual_size = u64::from_be_bytes(hdr[24..32].try_into().ok()?);
|
||||
let cluster_size = 1u64 << cluster_bits;
|
||||
let clusters = virtual_size.div_ceil(cluster_size);
|
||||
let l2_bytes = clusters.saturating_mul(8);
|
||||
let mib = l2_bytes.div_ceil(1024 * 1024).min(32);
|
||||
(mib > 8).then_some(mib)
|
||||
}
|
||||
|
||||
fn optp(p: &Path) -> String {
|
||||
opt(&p.to_string_lossy())
|
||||
}
|
||||
@@ -405,13 +378,6 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
c.disk_format.as_str(),
|
||||
optp(&vm.disk())
|
||||
);
|
||||
// QEMU caps default qcow2 L2 cache at 8 MiB on non-Linux hosts (covering only 64 GiB at 64 KiB
|
||||
// clusters). Size l2-cache-size to cover the image's virtual capacity (capped at 32 MiB).
|
||||
if matches!(c.disk_format, crate::vm::ImageFormat::Qcow2) {
|
||||
if let Some(mib) = qcow2_l2_cache_mib(&vm.disk()) {
|
||||
disk.push_str(&format!(",l2-cache-size={mib}M"));
|
||||
}
|
||||
}
|
||||
// An install's flushes, which the module's doc measures, are dropped while the installer is
|
||||
// attached.
|
||||
if q.installer.is_some() {
|
||||
@@ -432,15 +398,12 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
"-device",
|
||||
&format!("ide-hd,bus=sata.{},drive=disk,rotation_rate=1", q.disk_port),
|
||||
]),
|
||||
// Pass guest TRIMs (`discard=unmap`) like NVMe and offload block handling to a dedicated
|
||||
// iothread so disk completions do not contend with QEMU's main event loop.
|
||||
// SATA's drive options, at the first slot no other device takes.
|
||||
DiskController::Virtio => push(&[
|
||||
"-object",
|
||||
"iothread,id=io0",
|
||||
"-drive",
|
||||
&format!("{disk},discard=unmap"),
|
||||
&disk,
|
||||
"-device",
|
||||
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
|
||||
"virtio-blk-pci,drive=disk,addr=0x6",
|
||||
]),
|
||||
}
|
||||
// The installer, on port 4, past OpenCore's, or on 5 past an AHCI disk on 4.
|
||||
@@ -1791,12 +1754,10 @@ pub(crate) mod tests {
|
||||
assert!(has(
|
||||
&a,
|
||||
&[
|
||||
"-object",
|
||||
"iothread,id=io0",
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,discard=unmap",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2",
|
||||
"-device",
|
||||
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
|
||||
"virtio-blk-pci,drive=disk,addr=0x6",
|
||||
]
|
||||
));
|
||||
assert!(
|
||||
@@ -1821,12 +1782,10 @@ pub(crate) mod tests {
|
||||
assert!(has(
|
||||
&a,
|
||||
&[
|
||||
"-object",
|
||||
"iothread,id=io0",
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on,discard=unmap",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on",
|
||||
"-device",
|
||||
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
|
||||
"virtio-blk-pci,drive=disk,addr=0x6",
|
||||
]
|
||||
));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! reims-util (<https://github.com/reims-go/reims-util>) makes what a new x86-64 VM boots from:
|
||||
//! reims-util (<https://github.com/steelbrain/reims-util>) makes what a new x86-64 VM boots from:
|
||||
//! an OpenCore image, with OVMF's code and variables beside it, and a macOS installer, downloaded
|
||||
//! from Apple and checked against Apple's chunklists. It also makes an existing VM a new OpenCore
|
||||
//! image presenting the same Mac (opencore.rs). For a VM on reims-vgpu's own device, an image
|
||||
@@ -43,9 +43,9 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const REPO: &str = "https://github.com/reims-go/reims-util";
|
||||
pub const REPO: &str = "https://github.com/steelbrain/reims-util";
|
||||
/// The commit [`install`] installs.
|
||||
pub const REV: &str = "573d4a5ffacfc31430ff7372727fce287fef89e1";
|
||||
pub const REV: &str = "7867384c0ab703b4c6aae36cbbb1a35fcffc8321";
|
||||
|
||||
/// The reims-util binary: `REIMS_CTL_UTIL`, else the one beside reims-ctl, where both are
|
||||
/// installed, else the first on PATH.
|
||||
|
||||
@@ -725,22 +725,6 @@ pub fn prepare(vm: &mut Vm, progress: &mut dyn FnMut(&str)) -> Vec<String> {
|
||||
)),
|
||||
}
|
||||
}
|
||||
if vm.config.profile == Profile::Q35X86_64
|
||||
&& !vm
|
||||
.config
|
||||
.extra_args
|
||||
.iter()
|
||||
.any(|arg| arg == "-incoming" || arg.starts_with("-incoming="))
|
||||
&& let Some(value) = crate::processor::for_host(vm.config.cpus)
|
||||
{
|
||||
match crate::opencore::match_processor_type(vm, value) {
|
||||
Ok(true) => progress("updated the OpenCore processor type for About This Mac"),
|
||||
Ok(false) => {}
|
||||
Err(error) => w.push(format!(
|
||||
"{name}: could not update the OpenCore processor type ({error:#})"
|
||||
)),
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
|
||||
@@ -853,22 +853,12 @@ fn random_bytes<const N: usize>() -> [u8; N] {
|
||||
.and_then(|mut f| f.read_exact(&mut b))
|
||||
.is_err()
|
||||
{
|
||||
// Windows has no /dev/urandom. The clock alone is no random source there: it counts
|
||||
// 100 ns, so its low bytes hold some 22 bits, the first of them a multiple of 4, and the
|
||||
// pid, shifted past them, changes none. std's RandomState is keyed from the OS's random
|
||||
// source (ProcessPrng on Windows), so a hash it keys is unpredictable; the clock and the
|
||||
// pid are hashed in too.
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
let t = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
let keys = std::collections::hash_map::RandomState::new();
|
||||
for (i, chunk) in b.chunks_mut(8).enumerate() {
|
||||
let mut h = keys.build_hasher();
|
||||
h.write_usize(i);
|
||||
h.write_u128(t.as_nanos());
|
||||
h.write_u32(std::process::id());
|
||||
chunk.copy_from_slice(&h.finish().to_le_bytes()[..chunk.len()]);
|
||||
let seed = t.as_nanos() ^ (std::process::id() as u128) << 64;
|
||||
for (i, x) in b.iter_mut().enumerate() {
|
||||
*x = (seed >> (i * 8)) as u8;
|
||||
}
|
||||
}
|
||||
b
|
||||
|
||||
@@ -942,45 +942,6 @@ RvgStatus rvg_graphics_device_read_display_at(RvgGraphicsDevice *device,
|
||||
RvgDisplayCoord rvg_graphics_device_cursor_position_at(const RvgGraphicsDevice *device,
|
||||
uint32_t display);
|
||||
|
||||
// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
|
||||
// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
|
||||
// and waits for GPU idle.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_quiesce(RvgGraphicsDevice *device);
|
||||
|
||||
// Resumes VBLANK and ring threads after a snapshot finishes or fails.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_unquiesce(RvgGraphicsDevice *device);
|
||||
|
||||
// Serializes the full graphics device state into a heap-allocated buffer owned by the caller
|
||||
// and released with [`rvg_graphics_snapshot_free`].
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers.
|
||||
RvgStatus rvg_graphics_device_snapshot_save(RvgGraphicsDevice *device,
|
||||
uint8_t **out_data,
|
||||
size_t *out_len);
|
||||
|
||||
// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`].
|
||||
//
|
||||
// # Safety
|
||||
// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not
|
||||
// be freed more than once.
|
||||
void rvg_graphics_snapshot_free(uint8_t *data, size_t len);
|
||||
|
||||
// Restores the full graphics device state from a snapshot buffer produced by
|
||||
// [`rvg_graphics_device_snapshot_save`].
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle; `data` points to `len` readable bytes.
|
||||
RvgStatus rvg_graphics_device_snapshot_load(RvgGraphicsDevice *device,
|
||||
const uint8_t *data,
|
||||
size_t len);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif // __cplusplus
|
||||
|
||||
@@ -1180,124 +1180,5 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position_at(
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
|
||||
/// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
|
||||
/// and waits for GPU idle.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_quiesce(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, "rvg_graphics_device_quiesce") };
|
||||
match d.device.quiesce() {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Resumes VBLANK and ring threads after a snapshot finishes or fails.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_unquiesce(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, "rvg_graphics_device_unquiesce") };
|
||||
d.device.unquiesce();
|
||||
RVG_OK
|
||||
})
|
||||
}
|
||||
|
||||
/// Serializes the full graphics device state into a heap-allocated buffer owned by the caller
|
||||
/// and released with [`rvg_graphics_snapshot_free`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_snapshot_save(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
out_data: *mut *mut u8,
|
||||
out_len: *mut usize,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
if out_data.is_null() || out_len.is_null() {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, "rvg_graphics_device_snapshot_save") };
|
||||
match d.device.snapshot_save() {
|
||||
Ok(bytes) => {
|
||||
let mut boxed = bytes.into_boxed_slice();
|
||||
let len = boxed.len();
|
||||
let ptr = boxed.as_mut_ptr();
|
||||
std::mem::forget(boxed);
|
||||
// SAFETY: non-null checked above.
|
||||
unsafe {
|
||||
*out_data = ptr;
|
||||
*out_len = len;
|
||||
}
|
||||
RVG_OK
|
||||
}
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not
|
||||
/// be freed more than once.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_snapshot_free(data: *mut u8, len: usize) {
|
||||
ffi::export(|| {
|
||||
if !data.is_null() {
|
||||
// SAFETY: matches Box::<[u8]>::into_raw layout above.
|
||||
unsafe {
|
||||
let _ = Box::from_raw(std::ptr::slice_from_raw_parts_mut(data, len));
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Restores the full graphics device state from a snapshot buffer produced by
|
||||
/// [`rvg_graphics_device_snapshot_save`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle; `data` points to `len` readable bytes.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_snapshot_load(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
data: *const u8,
|
||||
len: usize,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
if data.is_null() && len > 0 {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, "rvg_graphics_device_snapshot_load") };
|
||||
let slice = if len == 0 {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: caller's contract.
|
||||
unsafe { std::slice::from_raw_parts(data, len) }
|
||||
};
|
||||
match d.device.snapshot_load(slice) {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -241,11 +241,6 @@ static void check_graphics(void) {
|
||||
CHECK(wait_for(&graphics_moved, 2));
|
||||
at = rvg_graphics_device_cursor_position(d);
|
||||
CHECK(at.x == 0 && at.y == 0);
|
||||
CHECK_STATUS(rvg_graphics_device_quiesce(d), RVG_OK);
|
||||
CHECK_STATUS(rvg_graphics_device_snapshot_save(d, NULL, NULL), RVG_ERR_INVALID_ARGUMENT);
|
||||
CHECK_STATUS(rvg_graphics_device_snapshot_load(d, NULL, 1), RVG_ERR_INVALID_ARGUMENT);
|
||||
rvg_graphics_snapshot_free(NULL, 0);
|
||||
CHECK_STATUS(rvg_graphics_device_unquiesce(d), RVG_OK);
|
||||
rvg_graphics_device_release(d);
|
||||
#if defined(_WIN32)
|
||||
CloseHandle(bell);
|
||||
|
||||
@@ -242,7 +242,7 @@ fn c_harness_calls_every_function() {
|
||||
// A function with a form of each OS's (Windows's under `#if defined(_WIN32)`, the others'
|
||||
// under `#if !defined(_WIN32)`) is declared once per form, one after the other.
|
||||
declared.dedup();
|
||||
assert_eq!(declared.len(), 24, "{declared:?}");
|
||||
assert_eq!(declared.len(), 19, "{declared:?}");
|
||||
let missing: Vec<&str> = declared
|
||||
.iter()
|
||||
.copied()
|
||||
|
||||
@@ -1104,8 +1104,6 @@ pub(crate) struct Shared {
|
||||
reset_owed: AtomicBool,
|
||||
/// Set at the device's end.
|
||||
ending: AtomicBool,
|
||||
/// Set while quiesced for checkpointing.
|
||||
quiesced: AtomicBool,
|
||||
/// The control thread's own wake.
|
||||
wake: Wake,
|
||||
/// The host's doorbell file for ring 0, once given.
|
||||
@@ -1876,7 +1874,6 @@ impl Device {
|
||||
epoch: AtomicU64::new(0),
|
||||
reset_owed: AtomicBool::new(false),
|
||||
ending: AtomicBool::new(false),
|
||||
quiesced: AtomicBool::new(false),
|
||||
wake: Wake::new()?,
|
||||
doorbell: OnceLock::new(),
|
||||
submit: Mutex::new(Submit {
|
||||
@@ -2122,26 +2119,6 @@ impl Device {
|
||||
pub fn reset(&self) {
|
||||
self.shared.reset();
|
||||
}
|
||||
|
||||
/// Quiesces the device for stopped-VM checkpointing.
|
||||
pub fn quiesce(&self) {
|
||||
self.shared.quiesce();
|
||||
}
|
||||
|
||||
/// Resumes VBLANK ticks and ring consumption after quiesce.
|
||||
pub fn unquiesce(&self) {
|
||||
self.shared.unquiesce();
|
||||
}
|
||||
|
||||
/// Exports the quiescent device's BAR0/ring/display/queue/region state.
|
||||
pub fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot {
|
||||
self.shared.export_snapshot()
|
||||
}
|
||||
|
||||
/// Restores device state on a freshly created device (after QEMU restored BAR2).
|
||||
pub fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> {
|
||||
self.shared.import_snapshot(snap)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `COMPLETE` a ring-0 command owes, which the host gives from any thread once it has carried
|
||||
@@ -2600,219 +2577,6 @@ impl Shared {
|
||||
/// The reset (the module doc). It waits for the message the control thread is taking, and
|
||||
/// for a take of a queue's ring or a post onto one under way, none of which waits for the
|
||||
/// host; the host is told on the control thread ([`Self::tell_reset`]).
|
||||
fn quiesce(&self) {
|
||||
self.quiesced.store(true, Ordering::Release);
|
||||
self.wake.wake();
|
||||
let active_queues: Vec<Arc<QueueShared>> = {
|
||||
self.queues.lock().by_obj.values().cloned().collect()
|
||||
};
|
||||
for q in &active_queues {
|
||||
q.wake.wake();
|
||||
}
|
||||
{
|
||||
let _taking = self.taking.lock();
|
||||
}
|
||||
self.take_messages();
|
||||
self.lanes.wait_idle();
|
||||
if self.control_handing.load(Ordering::Acquire) {
|
||||
self.post_behind_control_handed(None);
|
||||
}
|
||||
for q in &active_queues {
|
||||
let poster = self.queue_poster(q);
|
||||
self.take_queue_messages(q, &poster);
|
||||
if q.handing.load(Ordering::Acquire) {
|
||||
self.post_handed(q);
|
||||
}
|
||||
}
|
||||
self.lanes.wait_idle();
|
||||
}
|
||||
|
||||
fn unquiesce(&self) {
|
||||
self.quiesced.store(false, Ordering::Release);
|
||||
self.wake.wake();
|
||||
let active_queues: Vec<Arc<QueueShared>> = {
|
||||
self.queues.lock().by_obj.values().cloned().collect()
|
||||
};
|
||||
for q in &active_queues {
|
||||
q.wake.wake();
|
||||
}
|
||||
}
|
||||
|
||||
fn export_snapshot(&self) -> crate::snapshot::DeviceSnapshot {
|
||||
use crate::snapshot::{DeviceSnapshot, DisplaySnapshot, QueueSnapshot};
|
||||
let status = self.status.load(Ordering::Acquire);
|
||||
let driver_features = self.driver_features.load(Ordering::Acquire);
|
||||
let control_done = self.control_done.load(Ordering::Acquire);
|
||||
let (control_submit_count, control_submit_broken) = {
|
||||
let s = self.submit.lock();
|
||||
(s.consumer.consumed(), s.broken)
|
||||
};
|
||||
let control_completion_count = self.completion.lock().produced();
|
||||
let vt_ring_count = self.vt_ring.lock().produced();
|
||||
let pages: Vec<u32> = self.pages.iter().map(|p| p.load(Ordering::Acquire)).collect();
|
||||
let displays: Vec<DisplaySnapshot> = self
|
||||
.displays
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let st = d.state.lock();
|
||||
DisplaySnapshot {
|
||||
scanout: st.scanout,
|
||||
vblank: st.vblank,
|
||||
asleep: st.asleep,
|
||||
refreshes: st.refreshes,
|
||||
told: st.told,
|
||||
changed: st.changed,
|
||||
cursor_image: st.cursor_image.clone(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let region_blocks = self.region.export_blocks();
|
||||
let mut queue_list: Vec<Arc<QueueShared>> =
|
||||
self.queues.lock().by_obj.values().cloned().collect();
|
||||
queue_list.sort_by_key(|q| q.obj_id);
|
||||
let queues: Vec<QueueSnapshot> = queue_list
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let s = q.submit.lock();
|
||||
let c = q.complete.lock();
|
||||
QueueSnapshot {
|
||||
create_bytes: q.create.as_bytes().to_vec(),
|
||||
flags: q.flags,
|
||||
taken_seqno: q.taken_seqno.load(Ordering::Acquire),
|
||||
taken_buffer_seqno: q.taken_buffer_seqno.load(Ordering::Acquire),
|
||||
submit_count: s.consumer.consumed(),
|
||||
submit_broken: s.broken,
|
||||
complete_count: c.produced(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
DeviceSnapshot {
|
||||
status,
|
||||
driver_features,
|
||||
control_done,
|
||||
control_submit_count,
|
||||
control_submit_broken,
|
||||
control_completion_count,
|
||||
vt_ring_count,
|
||||
pages,
|
||||
displays,
|
||||
region_blocks,
|
||||
queues,
|
||||
}
|
||||
}
|
||||
|
||||
fn import_snapshot(&self, snap: &crate::snapshot::DeviceSnapshot) -> Result<(), &'static str> {
|
||||
self.quiesced.store(true, Ordering::Release);
|
||||
self.region.import_blocks(&snap.region_blocks);
|
||||
self.driver_features.store(snap.driver_features, Ordering::Release);
|
||||
if snap.driver_features != 0 {
|
||||
self.host.driver_ready(snap.driver_features);
|
||||
}
|
||||
let mut any_page = false;
|
||||
for (dst, &val) in self.pages.iter().zip(snap.pages.iter()) {
|
||||
dst.store(val, Ordering::Release);
|
||||
if val != 0 {
|
||||
any_page = true;
|
||||
}
|
||||
}
|
||||
if any_page {
|
||||
self.pages_bound.store(true, Ordering::Release);
|
||||
}
|
||||
{
|
||||
let mut submit = self.submit.lock();
|
||||
submit.consumer.set_count(snap.control_submit_count);
|
||||
submit.broken = snap.control_submit_broken;
|
||||
submit.backlog.clear();
|
||||
}
|
||||
self.control_done.store(snap.control_done, Ordering::Release);
|
||||
self.completion.lock().set_count(snap.control_completion_count);
|
||||
self.vt_ring.lock().set_count(snap.vt_ring_count);
|
||||
self.reset_owed.store(false, Ordering::Release);
|
||||
for (display, ds) in self.displays.iter().zip(snap.displays.iter()) {
|
||||
{
|
||||
let mut st = display.state.lock();
|
||||
st.scanout = ds.scanout;
|
||||
st.vblank = ds.vblank;
|
||||
st.asleep = ds.asleep;
|
||||
st.refreshes = ds.refreshes;
|
||||
st.told = ds.told;
|
||||
st.changed = ds.changed;
|
||||
st.cursor_image = ds.cursor_image.clone();
|
||||
}
|
||||
display.screen.scanout(ds.scanout);
|
||||
display.screen.cursor_image(ds.cursor_image.clone());
|
||||
display.screen.power(!ds.asleep);
|
||||
}
|
||||
self.status.store(snap.status, Ordering::Release);
|
||||
let epoch = self.epoch.load(Ordering::Acquire);
|
||||
for qs in &snap.queues {
|
||||
let Ok(q) = RgfxQueueCreate::read_from_bytes(&qs.create_bytes) else {
|
||||
return Err("malformed RgfxQueueCreate in snapshot");
|
||||
};
|
||||
let Some((submit_at, complete_at)) = self.validate_rings(&q) else {
|
||||
return Err("queue rings invalid against restored BAR2 block ledger");
|
||||
};
|
||||
let Some(me) = self.weak_self.get().and_then(Weak::upgrade) else {
|
||||
return Err("device weak_self missing");
|
||||
};
|
||||
let Some(wake) = Wake::new() else {
|
||||
return Err("queue wake allocation failed");
|
||||
};
|
||||
let bell = if self.driver_took(RGFX_FEATURE_DOORBELL_ASKS) {
|
||||
wake::bell()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut consumer = Consumer::new(submit_at);
|
||||
consumer.set_count(qs.submit_count);
|
||||
let mut producer = Producer::new(complete_at);
|
||||
producer.set_count(qs.complete_count);
|
||||
let queue = Arc::new(QueueShared {
|
||||
obj_id: q.obj_id,
|
||||
context: (q.obj_id >> RGFX_CONTEXT_OBJ_ID_SHIFT) as u32,
|
||||
create: q,
|
||||
flags: qs.flags,
|
||||
epoch,
|
||||
ring_id: q.submit_offset,
|
||||
vector: q.vector,
|
||||
submit: Mutex::new(Submit {
|
||||
consumer,
|
||||
broken: qs.submit_broken,
|
||||
backlog: Backlog::default(),
|
||||
asleep: false,
|
||||
}),
|
||||
taken_seqno: AtomicU64::new(qs.taken_seqno),
|
||||
taken_buffer_seqno: AtomicU64::new(qs.taken_buffer_seqno),
|
||||
consuming: Mutex::new(None),
|
||||
complete: Mutex::new(producer),
|
||||
room: Room::default(),
|
||||
full: AtomicBool::new(false),
|
||||
untold: Mutex::new(Untold::default()),
|
||||
handed: Mutex::new(Handed::default()),
|
||||
handing: AtomicBool::new(false),
|
||||
wake,
|
||||
bell,
|
||||
route: AtomicU64::new(0),
|
||||
route_page: AtomicU32::new(u32::MAX),
|
||||
ending: AtomicBool::new(false),
|
||||
trip: trip::Queue::default(),
|
||||
});
|
||||
{
|
||||
let mut queues = self.queues.lock();
|
||||
queues.by_obj.insert(q.obj_id, Arc::clone(&queue));
|
||||
queues.by_ring.insert(q.submit_offset, Arc::clone(&queue));
|
||||
}
|
||||
let service = Arc::clone(&queue);
|
||||
std::thread::Builder::new()
|
||||
.name(format!("reims-vgpu.graphics-queue-{:#x}", q.obj_id))
|
||||
.spawn(move || me.queue_service_restored(&service))
|
||||
.map_err(|_| "failed to spawn restored queue thread")?;
|
||||
self.route(&queue);
|
||||
self.host.queue_made(&self.queue_poster(&queue));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
self.status.store(RGFX_STATUS_RESET, Ordering::Release);
|
||||
self.driver_features.store(0, Ordering::Release);
|
||||
@@ -3490,10 +3254,6 @@ impl Shared {
|
||||
/// The control thread (the module doc).
|
||||
fn control_thread(&self) {
|
||||
while !self.ending() {
|
||||
if self.quiesced.load(Ordering::Acquire) {
|
||||
self.wake.sleep_for(None, Some(Duration::from_millis(20)));
|
||||
continue;
|
||||
}
|
||||
// The answers handed over to it, posted first, as a post onto the ring would.
|
||||
if self.control_handing.load(Ordering::Acquire) {
|
||||
self.post_behind_control_handed(None);
|
||||
@@ -4678,23 +4438,6 @@ impl Shared {
|
||||
/// A queue's service thread (the module doc): it takes the queue's submission ring with the
|
||||
/// control thread's `consumer_idle` handshake, hands each message to the host, and sleeps on
|
||||
/// the queue's own wake, woken by its doorbell or its end.
|
||||
fn queue_service_restored(&self, queue: &Arc<QueueShared>) {
|
||||
let poster = self.queue_poster(queue);
|
||||
self.queue_loop(queue, &poster);
|
||||
self.close_handed(queue);
|
||||
if !self.ending() && self.epoch.load(Ordering::Acquire) == queue.epoch {
|
||||
let destroy = RgfxObjectDestroy {
|
||||
header: RgfxMsgHeader {
|
||||
r#type: RGFX_CMD_OBJECT_DESTROY,
|
||||
size: size_of::<RgfxObjectDestroy>() as u32,
|
||||
seqno: 0,
|
||||
},
|
||||
obj_id: queue.obj_id,
|
||||
};
|
||||
self.host.stage3_message(&poster, destroy.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_service(&self, queue: &Arc<QueueShared>) {
|
||||
let poster = self.queue_poster(queue);
|
||||
// The host makes the queue's handle first, so a command buffer on it can name it.
|
||||
@@ -4721,10 +4464,6 @@ impl Shared {
|
||||
/// The loop of a queue's service thread: take, then sleep, until the queue or the device ends.
|
||||
fn queue_loop(&self, queue: &Arc<QueueShared>, poster: &CompletionPoster) {
|
||||
while !self.ending() && !queue.ended() {
|
||||
if self.quiesced.load(Ordering::Acquire) {
|
||||
queue.wake.sleep_for(None, Some(Duration::from_millis(20)));
|
||||
continue;
|
||||
}
|
||||
// The records handed over to it, posted first, as far as its ring has room: those
|
||||
// left wait for its next look, while it takes the guest's buffers meanwhile.
|
||||
if queue.handing.load(Ordering::Acquire) {
|
||||
@@ -5335,9 +5074,6 @@ impl Shared {
|
||||
/// that sees it ([`Self::displays_seen`]) alone: a guest that did not take
|
||||
/// [`RGFX_FEATURE_MULTI_DISPLAY`] gets none of a display but 0's.
|
||||
pub(crate) fn refresh(&self, id: u32, now: u64) {
|
||||
if self.quiesced.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let Some(display) = self.displays.get(id as usize) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -1035,19 +1035,6 @@ impl Lanes {
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until no lane is running or has queued jobs (or the device ends).
|
||||
pub(super) fn wait_idle(&self) {
|
||||
let mut state = self.state.lock();
|
||||
while !state.ended
|
||||
&& state
|
||||
.lanes
|
||||
.values()
|
||||
.any(|lane| lane.running.is_some() || !lane.jobs.is_empty())
|
||||
{
|
||||
self.moved.wait(&mut state);
|
||||
}
|
||||
}
|
||||
|
||||
/// The device ended: the lanes' threads go at their next look, and so do those that wait for
|
||||
/// a lane.
|
||||
pub(super) fn end(&self) {
|
||||
|
||||
@@ -31,7 +31,6 @@ pub mod keep;
|
||||
pub mod managed;
|
||||
pub mod ops;
|
||||
pub mod region;
|
||||
pub mod snapshot;
|
||||
mod ring;
|
||||
// The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header.
|
||||
/// cbindgen:ignore
|
||||
|
||||
@@ -60,19 +60,6 @@ pub struct Region {
|
||||
}
|
||||
|
||||
/// A block's size and who holds it.
|
||||
/// Serializable snapshot of a granted or shared BAR2 region block.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RegionBlockSnapshot {
|
||||
/// Byte offset inside BAR2.
|
||||
pub offset: u64,
|
||||
/// Block size in bytes.
|
||||
pub size: u64,
|
||||
/// Context IDs holding this block.
|
||||
pub holders: Vec<u32>,
|
||||
/// Whether this block was shared (`BLOCK_SHARE`).
|
||||
pub shared: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct Held {
|
||||
size: u64,
|
||||
@@ -226,37 +213,6 @@ impl Region {
|
||||
}
|
||||
|
||||
/// No block is anyone's any more (the device's reset): the kext grants them again.
|
||||
/// Exports all currently granted/shared BAR2 blocks for checkpointing.
|
||||
pub fn export_blocks(&self) -> Vec<RegionBlockSnapshot> {
|
||||
let blocks = self.blocks.lock();
|
||||
blocks
|
||||
.iter()
|
||||
.map(|(&offset, held)| RegionBlockSnapshot {
|
||||
offset,
|
||||
size: held.size,
|
||||
holders: held.holders.clone(),
|
||||
shared: held.shared,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Replaces the BAR2 block ledger from a checkpoint.
|
||||
pub fn import_blocks(&self, snap: &[RegionBlockSnapshot]) {
|
||||
let mut blocks = self.blocks.lock();
|
||||
blocks.clear();
|
||||
for b in snap {
|
||||
blocks.insert(
|
||||
b.offset,
|
||||
Held {
|
||||
size: b.size,
|
||||
holders: b.holders.clone(),
|
||||
shared: b.shared,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Revokes all active BAR2 region grants prior to snapshot restore.
|
||||
pub fn revoke_all(&self) {
|
||||
self.blocks.lock().clear();
|
||||
}
|
||||
|
||||
@@ -202,11 +202,6 @@ impl Consumer {
|
||||
self.count
|
||||
}
|
||||
|
||||
/// Restores the host's consumed byte count from a checkpoint (BAR2 already holds header).
|
||||
pub(crate) fn set_count(&mut self, count: u64) {
|
||||
self.count = count;
|
||||
}
|
||||
|
||||
/// The guest's published count (the ring's producer), read with an acquire load.
|
||||
pub(crate) fn published_count(&self, region: &Region) -> u64 {
|
||||
region
|
||||
@@ -560,16 +555,6 @@ impl Producer {
|
||||
}
|
||||
|
||||
/// Back to a ring nothing has passed through ([`RingAt::initialize`]), `consumer_idle` 0.
|
||||
/// Returns the host's published byte count.
|
||||
pub(crate) fn produced(&self) -> u64 {
|
||||
self.count
|
||||
}
|
||||
|
||||
/// Restores the host's published byte count from a checkpoint (BAR2 already holds header).
|
||||
pub(crate) fn set_count(&mut self, count: u64) {
|
||||
self.count = count;
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&mut self, region: &Region) {
|
||||
self.count = 0;
|
||||
self.at.initialize(region, false);
|
||||
|
||||
@@ -1,293 +0,0 @@
|
||||
//! Binary snapshot codec for [`Device`](crate::Device) state (Layer B).
|
||||
|
||||
use crate::display::{CursorImage, Mode, Scanout};
|
||||
use crate::region::RegionBlockSnapshot;
|
||||
|
||||
/// Serializable display state.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DisplaySnapshot {
|
||||
/// Active BAR2 scanout, if any.
|
||||
pub scanout: Option<Scanout>,
|
||||
/// Whether VBLANK delivery is enabled.
|
||||
pub vblank: bool,
|
||||
/// Whether the panel is off (`SET_DISPLAY_POWER`).
|
||||
pub asleep: bool,
|
||||
/// Refresh counter since reset.
|
||||
pub refreshes: u64,
|
||||
/// Last mode told to the guest.
|
||||
pub told: Option<Mode>,
|
||||
/// Whether a `DISPLAY_CHANGED` event is owed.
|
||||
pub changed: bool,
|
||||
/// Current guest cursor image, if any.
|
||||
pub cursor_image: Option<CursorImage>,
|
||||
}
|
||||
|
||||
/// Serializable per-command-queue ring state.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct QueueSnapshot {
|
||||
/// Raw `RgfxQueueCreate` wire message bytes.
|
||||
pub create_bytes: Vec<u8>,
|
||||
/// Accepted `RGFX_QUEUE_*` flags.
|
||||
pub flags: u32,
|
||||
/// Highest message seqno taken off the queue's submission ring.
|
||||
pub taken_seqno: u64,
|
||||
/// Highest command-buffer seqno taken off the queue's submission ring.
|
||||
pub taken_buffer_seqno: u64,
|
||||
/// Host consumer byte count on the queue's submission ring.
|
||||
pub submit_count: u64,
|
||||
/// Whether the queue's submission ring was marked broken.
|
||||
pub submit_broken: bool,
|
||||
/// Host producer byte count on the queue's completion ring.
|
||||
pub complete_count: u64,
|
||||
}
|
||||
|
||||
/// Complete serializable snapshot of `reims_vgpu_graphics::Device` (BAR0/rings/displays/queues).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DeviceSnapshot {
|
||||
/// `STATUS` register value.
|
||||
pub status: u32,
|
||||
/// Negotiated `DRIVER_FEATURES` bitmask.
|
||||
pub driver_features: u64,
|
||||
/// Control submission ring `control_done` count.
|
||||
pub control_done: u64,
|
||||
/// Control submission ring consumer byte count.
|
||||
pub control_submit_count: u64,
|
||||
/// Whether control submission ring is broken.
|
||||
pub control_submit_broken: bool,
|
||||
/// Control completion ring producer byte count.
|
||||
pub control_completion_count: u64,
|
||||
/// VideoToolbox ring producer byte count.
|
||||
pub vt_ring_count: u64,
|
||||
/// Doorbell page context bindings (`RGFX_REG_DOORBELL_PAGE_BIND`).
|
||||
pub pages: Vec<u32>,
|
||||
/// Per-display state.
|
||||
pub displays: Vec<DisplaySnapshot>,
|
||||
/// Active BAR2 granted/shared blocks.
|
||||
pub region_blocks: Vec<RegionBlockSnapshot>,
|
||||
/// Active per-queue rings.
|
||||
pub queues: Vec<QueueSnapshot>,
|
||||
}
|
||||
|
||||
fn put_u8(o: &mut Vec<u8>, v: u8) { o.push(v); }
|
||||
fn put_u32(o: &mut Vec<u8>, v: u32) { o.extend_from_slice(&v.to_le_bytes()); }
|
||||
fn put_u64(o: &mut Vec<u8>, v: u64) { o.extend_from_slice(&v.to_le_bytes()); }
|
||||
fn put_bytes(o: &mut Vec<u8>, b: &[u8]) {
|
||||
put_u64(o, b.len() as u64);
|
||||
o.extend_from_slice(b);
|
||||
}
|
||||
|
||||
fn get_u8(i: &mut &[u8]) -> Option<u8> {
|
||||
let (&b, rest) = i.split_first()?;
|
||||
*i = rest;
|
||||
Some(b)
|
||||
}
|
||||
fn get_u32(i: &mut &[u8]) -> Option<u32> {
|
||||
if i.len() < 4 { return None; }
|
||||
let (a, rest) = i.split_at(4);
|
||||
*i = rest;
|
||||
Some(u32::from_le_bytes(a.try_into().ok()?))
|
||||
}
|
||||
fn get_u64(i: &mut &[u8]) -> Option<u64> {
|
||||
if i.len() < 8 { return None; }
|
||||
let (a, rest) = i.split_at(8);
|
||||
*i = rest;
|
||||
Some(u64::from_le_bytes(a.try_into().ok()?))
|
||||
}
|
||||
fn get_bytes(i: &mut &[u8]) -> Option<Vec<u8>> {
|
||||
let n = usize::try_from(get_u64(i)?).ok()?;
|
||||
if i.len() < n { return None; }
|
||||
let (a, rest) = i.split_at(n);
|
||||
*i = rest;
|
||||
Some(a.to_vec())
|
||||
}
|
||||
fn checked_count(i: &mut &[u8], min_item_bytes: usize) -> Option<usize> {
|
||||
let count = usize::try_from(get_u32(i)?).ok()?;
|
||||
let min_bytes = min_item_bytes.max(1);
|
||||
if count > i.len() / min_bytes {
|
||||
return None;
|
||||
}
|
||||
Some(count)
|
||||
}
|
||||
fn read_vec<T>(
|
||||
i: &mut &[u8],
|
||||
min_item_bytes: usize,
|
||||
mut f: impl FnMut(&mut &[u8]) -> Option<T>,
|
||||
) -> Option<Vec<T>> {
|
||||
let count = checked_count(i, min_item_bytes)?;
|
||||
let mut out = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
out.push(f(i)?);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
impl DeviceSnapshot {
|
||||
/// Encodes this device snapshot into `out`.
|
||||
pub fn encode(&self, o: &mut Vec<u8>) {
|
||||
put_u32(o, 1);
|
||||
put_u32(o, self.status);
|
||||
put_u64(o, self.driver_features);
|
||||
put_u64(o, self.control_done);
|
||||
put_u64(o, self.control_submit_count);
|
||||
put_u8(o, u8::from(self.control_submit_broken));
|
||||
put_u64(o, self.control_completion_count);
|
||||
put_u64(o, self.vt_ring_count);
|
||||
|
||||
put_u32(o, self.pages.len() as u32);
|
||||
for &p in &self.pages { put_u32(o, p); }
|
||||
|
||||
put_u32(o, self.displays.len() as u32);
|
||||
for d in &self.displays {
|
||||
match d.scanout {
|
||||
Some(s) => {
|
||||
put_u8(o, 1);
|
||||
put_u32(o, s.width); put_u32(o, s.height);
|
||||
put_u32(o, s.stride); put_u64(o, s.offset);
|
||||
}
|
||||
None => put_u8(o, 0),
|
||||
}
|
||||
put_u8(o, u8::from(d.vblank));
|
||||
put_u8(o, u8::from(d.asleep));
|
||||
put_u64(o, d.refreshes);
|
||||
match d.told {
|
||||
Some(m) => {
|
||||
put_u8(o, 1);
|
||||
put_u32(o, m.width); put_u32(o, m.height);
|
||||
put_u32(o, m.refresh_mhz); put_u32(o, m.scale_120ths);
|
||||
}
|
||||
None => put_u8(o, 0),
|
||||
}
|
||||
put_u8(o, u8::from(d.changed));
|
||||
match &d.cursor_image {
|
||||
Some(c) => {
|
||||
put_u8(o, 1);
|
||||
put_u32(o, c.width); put_u32(o, c.height);
|
||||
put_u32(o, c.hot_spot.0); put_u32(o, c.hot_spot.1);
|
||||
put_bytes(o, &c.rgba);
|
||||
}
|
||||
None => put_u8(o, 0),
|
||||
}
|
||||
}
|
||||
|
||||
put_u32(o, self.region_blocks.len() as u32);
|
||||
for b in &self.region_blocks {
|
||||
put_u64(o, b.offset); put_u64(o, b.size);
|
||||
put_u8(o, u8::from(b.shared));
|
||||
put_u32(o, b.holders.len() as u32);
|
||||
for &h in &b.holders { put_u32(o, h); }
|
||||
}
|
||||
|
||||
put_u32(o, self.queues.len() as u32);
|
||||
for q in &self.queues {
|
||||
put_bytes(o, &q.create_bytes);
|
||||
put_u32(o, q.flags);
|
||||
put_u64(o, q.taken_seqno);
|
||||
put_u64(o, q.taken_buffer_seqno);
|
||||
put_u64(o, q.submit_count);
|
||||
put_u8(o, u8::from(q.submit_broken));
|
||||
put_u64(o, q.complete_count);
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes a device snapshot from `i`.
|
||||
pub fn decode(i: &mut &[u8]) -> Option<Self> {
|
||||
if get_u32(i)? != 1 { return None; }
|
||||
let status = get_u32(i)?;
|
||||
let driver_features = get_u64(i)?;
|
||||
let control_done = get_u64(i)?;
|
||||
let control_submit_count = get_u64(i)?;
|
||||
let control_submit_broken = get_u8(i)? != 0;
|
||||
let control_completion_count = get_u64(i)?;
|
||||
let vt_ring_count = get_u64(i)?;
|
||||
|
||||
let pages = read_vec(i, 4, get_u32)?;
|
||||
let displays = read_vec(i, 14, |i| {
|
||||
let scanout = if get_u8(i)? != 0 {
|
||||
Some(Scanout {
|
||||
width: get_u32(i)?, height: get_u32(i)?,
|
||||
stride: get_u32(i)?, offset: get_u64(i)?,
|
||||
})
|
||||
} else { None };
|
||||
let vblank = get_u8(i)? != 0;
|
||||
let asleep = get_u8(i)? != 0;
|
||||
let refreshes = get_u64(i)?;
|
||||
let told = if get_u8(i)? != 0 {
|
||||
Some(Mode {
|
||||
width: get_u32(i)?, height: get_u32(i)?,
|
||||
refresh_mhz: get_u32(i)?, scale_120ths: get_u32(i)?,
|
||||
})
|
||||
} else { None };
|
||||
let changed = get_u8(i)? != 0;
|
||||
let cursor_image = if get_u8(i)? != 0 {
|
||||
Some(CursorImage {
|
||||
width: get_u32(i)?, height: get_u32(i)?,
|
||||
hot_spot: (get_u32(i)?, get_u32(i)?),
|
||||
rgba: get_bytes(i)?,
|
||||
})
|
||||
} else { None };
|
||||
Some(DisplaySnapshot { scanout, vblank, asleep, refreshes, told, changed, cursor_image })
|
||||
})?;
|
||||
let region_blocks = read_vec(i, 21, |i| {
|
||||
let offset = get_u64(i)?;
|
||||
let size = get_u64(i)?;
|
||||
let shared = get_u8(i)? != 0;
|
||||
let holders = read_vec(i, 4, get_u32)?;
|
||||
Some(RegionBlockSnapshot { offset, size, holders, shared })
|
||||
})?;
|
||||
let queues = read_vec(i, 45, |i| {
|
||||
Some(QueueSnapshot {
|
||||
create_bytes: get_bytes(i)?,
|
||||
flags: get_u32(i)?,
|
||||
taken_seqno: get_u64(i)?,
|
||||
taken_buffer_seqno: get_u64(i)?,
|
||||
submit_count: get_u64(i)?,
|
||||
submit_broken: get_u8(i)? != 0,
|
||||
complete_count: get_u64(i)?,
|
||||
})
|
||||
})?;
|
||||
|
||||
Some(DeviceSnapshot {
|
||||
status, driver_features, control_done,
|
||||
control_submit_count, control_submit_broken,
|
||||
control_completion_count, vt_ring_count,
|
||||
pages, displays, region_blocks, queues,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_oversized_counts_without_allocating() {
|
||||
// Minimal valid header (version=1 + fixed scalar fields = 49 bytes).
|
||||
let mut base = Vec::new();
|
||||
let empty = DeviceSnapshot {
|
||||
status: 1,
|
||||
driver_features: 2,
|
||||
control_done: 3,
|
||||
control_submit_count: 4,
|
||||
control_submit_broken: false,
|
||||
control_completion_count: 5,
|
||||
vt_ring_count: 6,
|
||||
pages: vec![],
|
||||
displays: vec![],
|
||||
region_blocks: vec![],
|
||||
queues: vec![],
|
||||
};
|
||||
empty.encode(&mut base);
|
||||
let mut s = base.as_slice();
|
||||
assert_eq!(DeviceSnapshot::decode(&mut s), Some(empty));
|
||||
assert!(s.is_empty());
|
||||
|
||||
// Overwrite each of the 4 top-level collection counts with u32::MAX.
|
||||
// Header length before pages count: 4 + 4 + 8 + 8 + 8 + 1 + 8 + 8 = 49.
|
||||
for offset in [49usize, 53, 57, 61] {
|
||||
let mut bad = base.clone();
|
||||
bad[offset..offset + 4].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
let mut sl = bad.as_slice();
|
||||
assert!(DeviceSnapshot::decode(&mut sl).is_none(), "offset {offset} must fail");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -564,44 +564,4 @@ pub trait GpuDevice<P: Platform>: Handle {
|
||||
&self,
|
||||
desc: &FullComputePipelineDesc<'_, P>,
|
||||
) -> Result<Option<P::ComputePipeline>, NsErrorText>;
|
||||
|
||||
/// Waits for all submitted GPU work on this device to complete without tearing down the device.
|
||||
fn wait_idle(&self) {}
|
||||
|
||||
/// Reads the current timeline value of a non-shared `MTLEvent` (0 if unsupported).
|
||||
fn event_signaled_value(&self, _event: &P::Event) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
/// Restores a non-shared `MTLEvent`'s timeline value across host process restart.
|
||||
fn event_restore_signaled_value(&self, _event: &P::Event, _value: u64) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Reads the contents of a standalone GPU buffer (Shared/Managed/Private) for snapshotting.
|
||||
/// Returns `Ok(None)` if the buffer has no backed contents or this platform does not support
|
||||
/// readback; returns `Err(...)` if a GPU transfer fails.
|
||||
fn read_standalone_buffer(&self, _buffer: &P::Buffer) -> Result<Option<Vec<u8>>, &'static str> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Restores the contents of a standalone GPU buffer from snapshot bytes.
|
||||
fn write_standalone_buffer(&self, _buffer: &P::Buffer, _data: &[u8]) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Reads all mip levels and array/cube slices of a standalone GPU texture into packed bytes.
|
||||
/// Returns `Ok(None)` for non-transferable formats (MSAA, Memoryless, depth/stencil) or on
|
||||
/// platforms without readback; returns `Err(...)` if a GPU transfer fails.
|
||||
fn read_standalone_texture(
|
||||
&self,
|
||||
_texture: &P::Texture,
|
||||
) -> Result<Option<Vec<u8>>, &'static str> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Uploads packed mip/slice bytes back into a standalone GPU texture.
|
||||
fn write_standalone_texture(&self, _texture: &P::Texture, _data: &[u8]) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -4570,151 +4570,6 @@ mod tests {
|
||||
(platform, device)
|
||||
}
|
||||
|
||||
/// A draw batch records the original Metal calls in order, including each new buffer offset.
|
||||
#[test]
|
||||
fn on_vulkan_draw_batches_record_each_bind_and_draw() {
|
||||
use crate::core::platform::Platform as _;
|
||||
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _, WorkNames};
|
||||
use crate::core::platform::descriptor::RenderPassDescriptor as _;
|
||||
use crate::core::platform::device::GpuDevice as _;
|
||||
use crate::core::platform::render::{RenderCmd, RenderEncoder as _, VertexDraw};
|
||||
use crate::core::platform::resource::Library as _;
|
||||
use crate::core::platform::values::{
|
||||
ColorAttachmentDesc, ColorAttachmentSet, FullRenderPipelineDesc, TextureDesc,
|
||||
};
|
||||
use crate::core::raise::OnFault;
|
||||
|
||||
in_recording_child(
|
||||
"recorder::tests::on_vulkan_draw_batches_record_each_bind_and_draw",
|
||||
|streams| {
|
||||
let run = || -> Result<(), &'static str> {
|
||||
let (platform, device) = recording_device();
|
||||
let on = OnFault::Return;
|
||||
let function = |bytes: &[u8], name| {
|
||||
let Ok(Ok(Some(library))) = device.new_library(bytes) else {
|
||||
return Err("no library");
|
||||
};
|
||||
library
|
||||
.new_function(on, name)
|
||||
.ok()
|
||||
.flatten()
|
||||
.ok_or("no function")
|
||||
};
|
||||
let vertex = function(
|
||||
include_bytes!("../../../tests/shaders/vert.metallib"),
|
||||
"tri_vert",
|
||||
)?;
|
||||
let fragment = function(
|
||||
include_bytes!("../../../tests/shaders/frag.metallib"),
|
||||
"tri_frag",
|
||||
)?;
|
||||
let mut desc = FullRenderPipelineDesc::new(&vertex, Some(&fragment));
|
||||
desc.colors = vec![(
|
||||
0,
|
||||
ColorAttachmentDesc {
|
||||
pixel_format: 80,
|
||||
..ColorAttachmentDesc::default()
|
||||
},
|
||||
)];
|
||||
let Ok(Some(pipeline)) = device.new_render_pipeline_state_full(&desc) else {
|
||||
return Err("no pipeline");
|
||||
};
|
||||
let Ok(Some(buffer)) = device.new_buffer_of_length(on, 256, 0) else {
|
||||
return Err("no vertex buffer");
|
||||
};
|
||||
let Ok(Some(target)) = device.new_texture(
|
||||
on,
|
||||
&platform.texture_descriptor(&TextureDesc {
|
||||
pixel_format: 80,
|
||||
width: 4,
|
||||
height: 4,
|
||||
usage: 4,
|
||||
..TextureDesc::default()
|
||||
}),
|
||||
) else {
|
||||
return Err("no render target");
|
||||
};
|
||||
let queue = device.new_command_queue().ok_or("no queue")?;
|
||||
let Ok(Some(cb)) = queue.command_buffer(on) else {
|
||||
return Err("no command buffer");
|
||||
};
|
||||
cb.names_work(&std::sync::Arc::new(WorkNames::new(1)));
|
||||
let pass = platform.render_pass_descriptor();
|
||||
assert_eq!(
|
||||
pass.set_color_attachment(
|
||||
on,
|
||||
0,
|
||||
&ColorAttachmentSet {
|
||||
texture: Some(Some(&target)),
|
||||
load_action: Some(2),
|
||||
store_action: Some(1),
|
||||
..ColorAttachmentSet::default()
|
||||
}
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
let Ok(Some(encoder)) = cb.render_encoder(on, &pass) else {
|
||||
return Err("no render encoder");
|
||||
};
|
||||
assert_eq!(
|
||||
encoder.encode(
|
||||
on,
|
||||
RenderCmd::SetRenderPipelineState {
|
||||
pipeline_state: Some(&pipeline),
|
||||
}
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
let draw = VertexDraw {
|
||||
buffer: Some(&buffer),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
primitive_type: 3,
|
||||
vertex_start: 0,
|
||||
vertex_count: 3,
|
||||
};
|
||||
let draws = [draw, VertexDraw { offset: 16, ..draw }];
|
||||
assert_eq!(encoder.encode_draws(on, &draws), Ok(()));
|
||||
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
|
||||
|
||||
let receiver = id_at(encoder.rec_ptr()).ok_or("no encoder stream id")?;
|
||||
let buffer = id_at(buffer.rec_ptr()).ok_or("no buffer stream id")?;
|
||||
let (calls, _) = recorded(streams, |calls| {
|
||||
calls
|
||||
.iter()
|
||||
.any(|c| c.receiver == receiver && c.selector == "endEncoding")
|
||||
});
|
||||
let selectors_and_args: Vec<_> = calls
|
||||
.iter()
|
||||
.filter(|c| c.receiver == receiver)
|
||||
.map(|c| (c.selector.as_str(), c.args.as_slice()))
|
||||
.collect();
|
||||
assert_eq!(selectors_and_args.len(), 6, "{calls:?}");
|
||||
let bind =
|
||||
|offset| [Value::Object(buffer), Value::Uint(offset), Value::Uint(0)];
|
||||
let primitives = [Value::Uint(3), Value::Uint(0), Value::Uint(3)];
|
||||
assert_eq!(
|
||||
selectors_and_args[1..5],
|
||||
[
|
||||
("setVertexBuffer:offset:atIndex:", bind(0).as_slice()),
|
||||
(
|
||||
"drawPrimitives:vertexStart:vertexCount:",
|
||||
primitives.as_slice()
|
||||
),
|
||||
("setVertexBuffer:offset:atIndex:", bind(16).as_slice()),
|
||||
(
|
||||
"drawPrimitives:vertexStart:vertexCount:",
|
||||
primitives.as_slice()
|
||||
),
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
};
|
||||
assert_eq!(run(), Ok(()));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// A stream starts with the device's making and then its identity, rt's `deviceName` and
|
||||
/// `hasUnifiedMemory`, before any call on the device.
|
||||
#[test]
|
||||
|
||||
@@ -47,7 +47,6 @@
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use metal2vulkan::metal::format;
|
||||
use metal2vulkan_runtime as rt;
|
||||
|
||||
use crate::core::platform::Platform;
|
||||
@@ -57,11 +56,10 @@ use crate::core::raise::{OnFault, RaiseResult};
|
||||
use crate::core::sync::Mutex;
|
||||
|
||||
use super::command::{Kept, OpenMark};
|
||||
use super::copied::Used;
|
||||
use super::diag::Use;
|
||||
use super::fault::{EncoderKind, EncoderNames, Naming, Operands};
|
||||
use super::unbuilt::{RtRefusal, Unbuilt, refuse, refused_as, rt_refused_texture};
|
||||
use super::{RtBuffer, RtObj, RtPlatform, RtTexture};
|
||||
use super::{RtObj, RtPlatform, RtTexture};
|
||||
|
||||
/// `id<MTLBlitCommandEncoder>` on metal2vulkan-runtime.
|
||||
pub struct RtBlitEncoder {
|
||||
@@ -107,9 +105,10 @@ impl RtBlitEncoder {
|
||||
|
||||
/// Notes `cmd`'s textures in its command buffer's `kept`: its copies' as uses
|
||||
/// ([`Kept::used`]), and a mipmap generation's and a synchronize's as tiled textures' uses
|
||||
/// alone (`super::tiled`); and the copies these textures and synchronized buffers lie over
|
||||
/// alone (`super::tiled`); and the copies its buffers and textures lie over
|
||||
/// ([`super::copied::Used`]).
|
||||
fn note_uses(&self, cmd: &BlitCmd<'_, RtPlatform>) {
|
||||
self.note_copies(cmd);
|
||||
let (from, into) = match *cmd {
|
||||
BlitCmd::CopyBufferToTexture {
|
||||
destination_texture,
|
||||
@@ -147,12 +146,6 @@ impl RtBlitEncoder {
|
||||
self.kept.copies().add(texture.copied(), true);
|
||||
(None, None)
|
||||
}
|
||||
BlitCmd::SynchronizeResource {
|
||||
resource: Some(ResourceRef::Buffer(buffer)),
|
||||
} => {
|
||||
self.kept.copies().buffer(buffer);
|
||||
(None, None)
|
||||
}
|
||||
_ => (None, None),
|
||||
};
|
||||
if let Some(texture) = from {
|
||||
@@ -162,6 +155,47 @@ impl RtBlitEncoder {
|
||||
self.kept.used(texture, Use::BlittedInto);
|
||||
}
|
||||
}
|
||||
|
||||
/// Notes the copies `cmd`'s buffers lie over in its command buffer's `kept`
|
||||
/// ([`super::copied::Used`]); its textures' are noted with their uses.
|
||||
fn note_copies(&self, cmd: &BlitCmd<'_, RtPlatform>) {
|
||||
if !super::copied::any() {
|
||||
return;
|
||||
}
|
||||
let used = self.kept.copies();
|
||||
match *cmd {
|
||||
BlitCmd::CopyBufferToTexture {
|
||||
source_buffer: buffer,
|
||||
..
|
||||
} => used.buffer_read(buffer),
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
destination_buffer: buffer,
|
||||
..
|
||||
}
|
||||
| BlitCmd::FillBufferPattern4 { buffer, .. }
|
||||
| BlitCmd::FillBuffer { buffer, .. }
|
||||
| BlitCmd::SynchronizeResource {
|
||||
resource: Some(ResourceRef::Buffer(buffer)),
|
||||
} => used.buffer(buffer),
|
||||
BlitCmd::CopyBufferToTextureOptions {
|
||||
source_buffer: buffer,
|
||||
..
|
||||
} => buffer.iter().for_each(|b| used.buffer_read(b)),
|
||||
BlitCmd::CopyTextureToBufferOptions {
|
||||
destination_buffer: buffer,
|
||||
..
|
||||
} => buffer.iter().for_each(|b| used.buffer(b)),
|
||||
BlitCmd::CopyBufferToBuffer {
|
||||
source_buffer,
|
||||
destination_buffer,
|
||||
..
|
||||
} => {
|
||||
source_buffer.iter().for_each(|b| used.buffer_read(b));
|
||||
destination_buffer.iter().for_each(|b| used.buffer(b));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Notes in `operands` what `cmd`, a command of an encoder of a command buffer of the host's own,
|
||||
@@ -404,24 +438,17 @@ fn copy_texture(
|
||||
/// ([`super::unbuilt::refusal_detail`]), and is counted with the command ([`report`]).
|
||||
fn copy_bytes(
|
||||
e: &mut rt::BlitCommandEncoder,
|
||||
(sel, used): (&'static str, &Used),
|
||||
(buffer, lies): (&RtBuffer, rt::BufferLayout),
|
||||
sel: &'static str,
|
||||
(buffer, lies): (&rt::Buffer, rt::BufferLayout),
|
||||
size: [u32; 3],
|
||||
(texture, place): (&RtTexture, rt::TexturePlace),
|
||||
into: bool,
|
||||
option: rt::BlitOption,
|
||||
) -> Result<(), Stop> {
|
||||
let copied = if into {
|
||||
e.copy_from_buffer_with_options(buffer.rt(), lies, size, texture.rt(), place, option)
|
||||
e.copy_from_buffer_with_options(buffer, lies, size, texture.rt(), place, option)
|
||||
} else {
|
||||
e.copy_from_texture_to_buffer_with_options(
|
||||
texture.rt(),
|
||||
place,
|
||||
size,
|
||||
buffer.rt(),
|
||||
lies,
|
||||
option,
|
||||
)
|
||||
e.copy_from_texture_to_buffer_with_options(texture.rt(), place, size, buffer, lies, option)
|
||||
};
|
||||
copied.map_err(|error| {
|
||||
let (texture, buffer) = (Copied::of(texture, place), Copied::Buffer(lies));
|
||||
@@ -438,70 +465,7 @@ fn copy_bytes(
|
||||
};
|
||||
super::unbuilt::refusal_detail(sel, &error, Some(&what));
|
||||
Stop::Rt(error)
|
||||
})?;
|
||||
if buffer.copied().is_some() {
|
||||
match buffer_image_ranges(texture.rt().descriptor(), size, lies, option) {
|
||||
Some(ranges) => used.buffer_ranges(buffer, !into, ranges),
|
||||
None => used.add(buffer.copied(), !into),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The buffer bytes of an accepted image copy, excluding padding between rows and images.
|
||||
fn buffer_image_ranges(
|
||||
desc: &rt::TextureDescriptor,
|
||||
[width, mut height, mut depth]: [u32; 3],
|
||||
layout: rt::BufferLayout,
|
||||
option: rt::BlitOption,
|
||||
) -> Option<impl Iterator<Item = Range<u64>>> {
|
||||
if height == 0
|
||||
&& matches!(
|
||||
desc.texture_type,
|
||||
rt::TextureType::Type1D | rt::TextureType::Type1DArray
|
||||
)
|
||||
{
|
||||
height = 1;
|
||||
}
|
||||
if depth == 0 && desc.texture_type != rt::TextureType::Type3D {
|
||||
depth = 1;
|
||||
}
|
||||
let format = desc.pixel_format;
|
||||
let bytes = match (option, format) {
|
||||
(rt::BlitOption::StencilFromDepthStencil, _) | (NONE, rt::PixelFormat::Stencil8) => 1,
|
||||
(NONE | rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth16Unorm) => 2,
|
||||
(NONE | rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth32Float)
|
||||
| (rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth32FloatStencil8) => 4,
|
||||
(NONE, _) if format::aspects(format) == Some(metal2vulkan::vk::ImageAspectFlags::COLOR) => {
|
||||
format::byte_format(format)?.block()?.size
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
// At a compressed mip's edge, rt clips a whole block to the edge without changing the
|
||||
// number of blocks transferred.
|
||||
let [bw, bh] = format::block_extent(format).unwrap_or([1, 1]);
|
||||
let row = u64::from(width.div_ceil(bw)) * u64::from(bytes);
|
||||
let mut rows = u64::from(height.div_ceil(bh));
|
||||
let mut images = if row == 0 || rows == 0 {
|
||||
0
|
||||
} else {
|
||||
u64::from(depth)
|
||||
};
|
||||
let mut run = row;
|
||||
if images > 0 && (rows == 1 || layout.bytes_per_row == row) {
|
||||
run = row.checked_mul(rows)?;
|
||||
rows = 1;
|
||||
if images == 1 || layout.bytes_per_image == run {
|
||||
run = run.checked_mul(images)?;
|
||||
images = 1;
|
||||
}
|
||||
}
|
||||
Some((0..images).flat_map(move |image| {
|
||||
(0..rows).map(move |row| {
|
||||
let start = layout.offset + image * layout.bytes_per_image + row * layout.bytes_per_row;
|
||||
start..start + run
|
||||
})
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// What a copy of texels asked of rt, for the process's first line of each kind of rt's refusals
|
||||
@@ -635,11 +599,7 @@ impl std::fmt::Display for CopyDetail {
|
||||
}
|
||||
|
||||
/// Encodes `cmd` into `e`, rt's open encoder (the module's docs); `EndEncoding` is the caller's.
|
||||
fn encode(
|
||||
e: &mut rt::BlitCommandEncoder,
|
||||
cmd: BlitCmd<'_, RtPlatform>,
|
||||
used: &Used,
|
||||
) -> Result<(), Stop> {
|
||||
fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Result<(), Stop> {
|
||||
let sel = cmd.selector();
|
||||
match cmd {
|
||||
BlitCmd::EndEncoding => {}
|
||||
@@ -656,17 +616,9 @@ fn encode(
|
||||
} => {
|
||||
let to = place(destination_slice, destination_level, destination_origin)?;
|
||||
let lies = layout(source_offset, source_bytes_per_row, source_bytes_per_image);
|
||||
let (source, destination) = (source_buffer, destination_texture);
|
||||
let (source, destination) = (source_buffer.rt(), destination_texture);
|
||||
let size = size(source_size)?;
|
||||
copy_bytes(
|
||||
e,
|
||||
(sel, used),
|
||||
(source, lies),
|
||||
size,
|
||||
(destination, to),
|
||||
true,
|
||||
NONE,
|
||||
)?;
|
||||
copy_bytes(e, sel, (source, lies), size, (destination, to), true, NONE)?;
|
||||
}
|
||||
BlitCmd::CopyBufferToTextureOptions {
|
||||
source_buffer,
|
||||
@@ -686,10 +638,11 @@ fn encode(
|
||||
let option = blit_option(options)?;
|
||||
let to = place(destination_slice, destination_level, destination_origin)?;
|
||||
let lies = layout(source_offset, source_bytes_per_row, source_bytes_per_image);
|
||||
let (source, destination) = (source.rt(), destination);
|
||||
let size = size(source_size)?;
|
||||
copy_bytes(
|
||||
e,
|
||||
(sel, used),
|
||||
sel,
|
||||
(source, lies),
|
||||
size,
|
||||
(destination, to),
|
||||
@@ -712,18 +665,6 @@ fn encode(
|
||||
(destination.rt(), destination_offset),
|
||||
);
|
||||
e.copy_from_buffer_to_buffer(from.0, from.1, to.0, to.1, size)?;
|
||||
if size != 0 {
|
||||
used.buffer_ranges(
|
||||
source,
|
||||
false,
|
||||
std::iter::once(source_offset..source_offset + size),
|
||||
);
|
||||
used.buffer_ranges(
|
||||
destination,
|
||||
true,
|
||||
std::iter::once(destination_offset..destination_offset + size),
|
||||
);
|
||||
}
|
||||
}
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
source_texture,
|
||||
@@ -742,11 +683,11 @@ fn encode(
|
||||
destination_bytes_per_row,
|
||||
destination_bytes_per_image,
|
||||
);
|
||||
let (source, destination) = (source_texture, destination_buffer);
|
||||
let (source, destination) = (source_texture, destination_buffer.rt());
|
||||
let size = size(source_size)?;
|
||||
copy_bytes(
|
||||
e,
|
||||
(sel, used),
|
||||
sel,
|
||||
(destination, lies),
|
||||
size,
|
||||
(source, from),
|
||||
@@ -776,10 +717,11 @@ fn encode(
|
||||
destination_bytes_per_row,
|
||||
destination_bytes_per_image,
|
||||
);
|
||||
let (source, destination) = (source, destination.rt());
|
||||
let size = size(source_size)?;
|
||||
copy_bytes(
|
||||
e,
|
||||
(sel, used),
|
||||
sel,
|
||||
(destination, lies),
|
||||
size,
|
||||
(source, from),
|
||||
@@ -863,19 +805,13 @@ fn encode(
|
||||
if rest.iter().any(|&byte| byte != value) {
|
||||
return Err(Stop::Unbuilt(Unbuilt::Blit));
|
||||
}
|
||||
let bytes = bytes(range)?;
|
||||
e.fill_buffer(buffer.rt(), bytes.clone(), value)?;
|
||||
used.buffer_ranges(buffer, true, std::iter::once(bytes));
|
||||
e.fill_buffer(buffer.rt(), bytes(range)?, value)?;
|
||||
}
|
||||
BlitCmd::FillBuffer {
|
||||
buffer,
|
||||
range,
|
||||
value,
|
||||
} => {
|
||||
let bytes = bytes(range)?;
|
||||
e.fill_buffer(buffer.rt(), bytes.clone(), value)?;
|
||||
used.buffer_ranges(buffer, true, std::iter::once(bytes));
|
||||
}
|
||||
} => e.fill_buffer(buffer.rt(), bytes(range)?, value)?,
|
||||
BlitCmd::FillTexture { .. } => return Err(Stop::Unbuilt(Unbuilt::FillTexture)),
|
||||
BlitCmd::FillTextureColor { .. } => return Err(Stop::Unbuilt(Unbuilt::Blit)),
|
||||
BlitCmd::GenerateMipmaps { texture } => {
|
||||
@@ -938,7 +874,7 @@ impl BlitEncoder<RtPlatform> for RtObj<RtBlitEncoder> {
|
||||
note_operands(operands, &cmd);
|
||||
}
|
||||
let stopped = match open.encoder.as_mut() {
|
||||
Some(e) => encode(e, cmd, self.kept.copies()).err(),
|
||||
Some(e) => encode(e, cmd).err(),
|
||||
None => Some(Stop::Metal("a command after endEncoding")),
|
||||
};
|
||||
if ending && let Some(e) = open.encoder.take() {
|
||||
|
||||
@@ -498,8 +498,6 @@ pub struct RtBuffer {
|
||||
/// The copy of host pages it lies over (`super::copied`), which a command buffer that uses it
|
||||
/// syncs; `None` for any other.
|
||||
copied: Option<Arc<super::copied::Copied>>,
|
||||
/// Whether the buffer was placed over an existing copy by its address or mapping.
|
||||
aliases_copy: bool,
|
||||
/// The guest's object id for it, which its release's entry in the device's history names
|
||||
/// (`super::fault`).
|
||||
named: super::fault::Named,
|
||||
@@ -674,11 +672,6 @@ impl RtBuffer {
|
||||
pub(super) fn copied(&self) -> Option<&Arc<super::copied::Copied>> {
|
||||
self.copied.as_ref()
|
||||
}
|
||||
|
||||
/// A buffer placed by a heap or made over an existing block's mapping.
|
||||
pub(super) fn copied_alias(&self) -> bool {
|
||||
self.in_heap || self.aliases_copy
|
||||
}
|
||||
}
|
||||
|
||||
/// The longest a deferred buffer's memory took to make, in nanoseconds
|
||||
@@ -1209,7 +1202,6 @@ fn deferred_as(
|
||||
#[cfg(unix)]
|
||||
exported: OnceLock::new(),
|
||||
copied: None,
|
||||
aliases_copy: false,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1339,17 +1331,17 @@ fn made(
|
||||
|
||||
/// The buffer's handle, of rt's buffer `rt` answering `options`.
|
||||
fn buffer(device: &RtObj<RtDevice>, rt: rt::Buffer, options: u64) -> RtObj<RtBuffer> {
|
||||
buffer_of(device, rt, options, (false, None, false), None)
|
||||
buffer_of(device, rt, options, (false, None), None)
|
||||
}
|
||||
|
||||
/// The buffer's handle, of rt's buffer `rt` answering `options`, placed by a heap where `in_heap`,
|
||||
/// lying over `copied` where it lies over a copy of host pages (`super::copied`). A buffer
|
||||
/// placed by address or mapping `aliases_copy`. Runs `deallocator` as it goes where given.
|
||||
/// lying over `copied` where it lies over a copy of host pages (`super::copied`), running
|
||||
/// `deallocator` as it goes where given.
|
||||
pub(super) fn buffer_of(
|
||||
device: &RtObj<RtDevice>,
|
||||
rt: rt::Buffer,
|
||||
options: u64,
|
||||
(in_heap, copied, aliases_copy): (bool, Option<Arc<super::copied::Copied>>, bool),
|
||||
(in_heap, copied): (bool, Option<Arc<super::copied::Copied>>),
|
||||
deallocator: Option<Slot>,
|
||||
) -> RtObj<RtBuffer> {
|
||||
RtObj::new(RtBuffer {
|
||||
@@ -1364,7 +1356,6 @@ pub(super) fn buffer_of(
|
||||
#[cfg(unix)]
|
||||
exported: OnceLock::new(),
|
||||
copied,
|
||||
aliases_copy,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1388,7 +1379,6 @@ pub(super) fn with_export(
|
||||
deallocator: None,
|
||||
exported: OnceLock::from(exported),
|
||||
copied: None,
|
||||
aliases_copy: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1438,17 +1428,7 @@ fn in_known(
|
||||
};
|
||||
let (block, offset) = known_at(device, pin, length, class, None)?;
|
||||
match device.rt().new_buffer(block.id, offset, length, zero_from) {
|
||||
Ok(made) => {
|
||||
let copied = super::copied::of(block.id);
|
||||
let aliases_copy = copied.is_some();
|
||||
Some(Some(buffer_of(
|
||||
device,
|
||||
made,
|
||||
o.answered,
|
||||
(false, copied, aliases_copy),
|
||||
None,
|
||||
)))
|
||||
}
|
||||
Ok(made) => Some(Some(buffer(device, made, o.answered))),
|
||||
Err(error) => {
|
||||
rt_refused_create(sel, &error);
|
||||
Some(None)
|
||||
@@ -1659,7 +1639,7 @@ fn no_copy(
|
||||
if in_place {
|
||||
read_only(sel);
|
||||
}
|
||||
let placed = (false, super::copied::of(block.id), deallocator.is_some());
|
||||
let placed = (false, super::copied::of(block.id));
|
||||
Some(buffer_of(device, made, o.answered, placed, deallocator))
|
||||
}
|
||||
|
||||
@@ -5537,85 +5517,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_blits_sync_only_the_buffer_rows_on_vulkan() -> Result<(), &'static str> {
|
||||
use crate::core::platform::types::{MtlOrigin, MtlSize};
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let source = over_a_copy(&device, false);
|
||||
let destination = over_a_copy(&device, false);
|
||||
let page = device.facts().page_size;
|
||||
let pitch = page;
|
||||
let offset = 16;
|
||||
let descriptor = platform.texture_descriptor(&TextureDesc {
|
||||
pixel_format: 70,
|
||||
width: 4,
|
||||
height: 2,
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let texture = device
|
||||
.new_texture(OnFault::Return, &descriptor)
|
||||
.map_err(|_| "texture creation raised")?
|
||||
.ok_or("no texture")?;
|
||||
// SAFETY: the two 16-byte rows and the padding are inside the source's two pages.
|
||||
unsafe {
|
||||
source
|
||||
.pages
|
||||
.wrapping_add(offset)
|
||||
.as_ptr::<u8>()
|
||||
.write_bytes(0x22, 16);
|
||||
source
|
||||
.pages
|
||||
.wrapping_add(offset + pitch)
|
||||
.as_ptr::<u8>()
|
||||
.write_bytes(0x33, 16);
|
||||
destination
|
||||
.pages
|
||||
.wrapping_add(offset + 16)
|
||||
.as_ptr::<u8>()
|
||||
.write(0x44);
|
||||
}
|
||||
let size = MtlSize::new(4, 2, 1);
|
||||
let origin = MtlOrigin::new(0, 0, 0);
|
||||
blit_and_wait(
|
||||
&queue,
|
||||
vec![
|
||||
BlitCmd::CopyBufferToTexture {
|
||||
source_buffer: &source.buffer,
|
||||
source_offset: offset,
|
||||
source_bytes_per_row: pitch,
|
||||
source_bytes_per_image: 0,
|
||||
source_size: size,
|
||||
destination_texture: &texture,
|
||||
destination_slice: 0,
|
||||
destination_level: 0,
|
||||
destination_origin: origin,
|
||||
},
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
source_texture: &texture,
|
||||
source_slice: 0,
|
||||
source_level: 0,
|
||||
source_origin: origin,
|
||||
source_size: size,
|
||||
destination_buffer: &destination.buffer,
|
||||
destination_offset: offset,
|
||||
destination_bytes_per_row: pitch,
|
||||
destination_bytes_per_image: 0,
|
||||
},
|
||||
],
|
||||
);
|
||||
let mut first = [0x22; 17];
|
||||
first[16] = 0x44;
|
||||
assert_eq!(read(destination.pages.wrapping_add(offset), 17), first);
|
||||
assert_eq!(
|
||||
read(destination.pages.wrapping_add(offset + pitch), 16),
|
||||
[0x33; 16]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// On the GPU the test holds: a copy a compute encoder declares with `useResources:`, as a
|
||||
/// shader that reaches it through an argument buffer's address asks, and binds not, is synced
|
||||
/// for its command buffer: the CPU's bytes copied in at the commit, and, declared for writing
|
||||
|
||||
@@ -58,9 +58,8 @@
|
||||
//! copy.
|
||||
//! - **Copied in at the commits that use it** ([`copy_in`], from `super::command`'s commit,
|
||||
//! before rt is handed the command buffer, so before the work that reads it): every byte of the
|
||||
//! pages in a chunk the work can read or write that differs from the base is written into the
|
||||
//! copy and the base. A byte the CPU did not change is never written, so a GPU write to the copy
|
||||
//! by work still in flight stays. Where
|
||||
//! pages that differs from the base is written into the copy and the base. A byte the CPU did
|
||||
//! not change is never written, so a GPU write to the copy by work still in flight stays. Where
|
||||
//! the device's Shared memory type is host-coherent, the GPU reads the bytes written with no
|
||||
//! flush; where it is not, rt flushes the Shared memory the command buffer keeps before it
|
||||
//! submits it, and flushes then invalidates what it may write before its completed handlers run
|
||||
@@ -69,10 +68,9 @@
|
||||
//! are dropped is written whole instead ("Writes dropped").
|
||||
//! - **Merged back at the completions of the command buffers that can write it** ([`merging`],
|
||||
//! the first of the command buffer's completed handlers, so before core's and before a waiter
|
||||
//! returns): every byte of the copy in a chunk the work can write that differs from the base
|
||||
//! is written into the pages where the pages' byte still is the base's, and the base takes the
|
||||
//! copy's byte. A byte both sides changed keeps the CPU's, which the next commit that uses it
|
||||
//! copies in, as Metal keeps the
|
||||
//! returns): every byte of the copy that differs from the base is written into the pages where
|
||||
//! the pages' byte still is the base's, and the base takes the copy's byte. A byte both sides
|
||||
//! changed keeps the CPU's, which the next commit that uses it copies in, as Metal keeps the
|
||||
//! later of two writes. A byte the guest writes between the merge's read of it and its store is
|
||||
//! lost only where the GPU changed it too. A command buffer whose uses of a copy can only read
|
||||
//! it neither merges it back nor puts back its bytes: its work wrote none of them.
|
||||
@@ -121,7 +119,6 @@
|
||||
//! ([`DECLARATIONS_CODE`]), with the commits that declared one ([`DECLARING_COMMITS_CODE`]).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::Range;
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
@@ -505,80 +502,16 @@ impl Drop for Fresh {
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy a command buffer uses, with byte ranges relative to the start of its block.
|
||||
/// A copy a command buffer uses, and whether a use of it can write it ([`Used`]).
|
||||
#[derive(Clone)]
|
||||
pub(super) struct CopyUse {
|
||||
/// The copy.
|
||||
copied: Arc<Copied>,
|
||||
reads: Ranges,
|
||||
writes: Ranges,
|
||||
/// Whether a use of it can write it.
|
||||
writes: bool,
|
||||
}
|
||||
|
||||
const MAX_RANGES: usize = 16;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum Ranges {
|
||||
Known(Vec<Range<usize>>),
|
||||
All,
|
||||
}
|
||||
|
||||
impl Ranges {
|
||||
const EMPTY: Self = Self::Known(Vec::new());
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
matches!(self, Self::Known(ranges) if ranges.is_empty())
|
||||
}
|
||||
|
||||
fn add(&mut self, bytes: Range<usize>) {
|
||||
let Self::Known(ranges) = self else { return };
|
||||
let first = ranges.partition_point(|range| range.end < bytes.start);
|
||||
let count = ranges[first..].partition_point(|range| range.start <= bytes.end);
|
||||
if count == 0 {
|
||||
if ranges.len() == MAX_RANGES {
|
||||
*self = Self::All;
|
||||
} else {
|
||||
ranges.insert(first, bytes);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let last = first + count - 1;
|
||||
ranges[first] = bytes.start.min(ranges[first].start)..bytes.end.max(ranges[last].end);
|
||||
ranges.drain(first + 1..last + 1);
|
||||
}
|
||||
|
||||
/// The union of two sets, rounded out to chunks. Ranges in separate sets can touch the same
|
||||
/// chunk even when their bytes do not.
|
||||
fn chunks<'a>(
|
||||
&'a self,
|
||||
other: &'a Self,
|
||||
len: usize,
|
||||
) -> impl Iterator<Item = Range<usize>> + 'a {
|
||||
let (mut first, mut second, mut whole) = match (self, other) {
|
||||
(Self::Known(first), Self::Known(second)) => (&first[..], &second[..], None),
|
||||
_ => (&[][..], &[][..], Some(0..len / CHUNK)),
|
||||
};
|
||||
let mut end = 0;
|
||||
std::iter::from_fn(move || {
|
||||
if whole.is_some() {
|
||||
return whole.take();
|
||||
}
|
||||
while let Some(next) = match (first.first(), second.first()) {
|
||||
(Some(a), Some(b)) if a.start <= b.start => first.split_off_first(),
|
||||
(_, Some(_)) => second.split_off_first(),
|
||||
_ => first.split_off_first(),
|
||||
} {
|
||||
let start = end.max(next.start / CHUNK);
|
||||
let past = next.end.div_ceil(CHUNK);
|
||||
if start < past {
|
||||
end = past;
|
||||
return Some(start..past);
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The copies a command buffer uses, each once, with the ranges it can read or write ("Synced
|
||||
/// The copies a command buffer uses, each once, with whether a use of it can write it ("Synced
|
||||
/// for the command buffers that use it"), noted by its encoders as they set or declare an object
|
||||
/// over one, and taken at its commit.
|
||||
#[derive(Clone, Default)]
|
||||
@@ -591,88 +524,24 @@ impl Used {
|
||||
let Some(copied) = copied else {
|
||||
return;
|
||||
};
|
||||
self.note(copied, |u| {
|
||||
u.reads = Ranges::All;
|
||||
if writes {
|
||||
u.writes = Ranges::All;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn note(&self, copied: &Arc<Copied>, note: impl FnOnce(&mut CopyUse)) {
|
||||
let mut used = self.0.lock();
|
||||
match used.iter_mut().find(|u| Arc::ptr_eq(&u.copied, copied)) {
|
||||
Some(u) => note(u),
|
||||
None => {
|
||||
let mut use_ = CopyUse {
|
||||
copied: Arc::clone(copied),
|
||||
reads: Ranges::EMPTY,
|
||||
writes: Ranges::EMPTY,
|
||||
};
|
||||
note(&mut use_);
|
||||
if !use_.reads.is_empty() || !use_.writes.is_empty() {
|
||||
used.push(use_);
|
||||
}
|
||||
}
|
||||
Some(u) => u.writes |= writes,
|
||||
None => used.push(CopyUse {
|
||||
copied: Arc::clone(copied),
|
||||
writes,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// A blit reads or writes these buffer-relative byte ranges.
|
||||
pub(super) fn buffer_ranges(
|
||||
&self,
|
||||
buffer: &RtBuffer,
|
||||
writes: bool,
|
||||
ranges: impl IntoIterator<Item = Range<u64>>,
|
||||
) {
|
||||
let Some(copied) = buffer.copied() else {
|
||||
return;
|
||||
};
|
||||
// A Managed buffer with a separate GPU copy uploads any pending `didModifyRange:` ranges
|
||||
// from its Shared backing at commit time, even if this blit touches a different page.
|
||||
if buffer.copied_alias() || buffer.gpu_copy_apart() {
|
||||
if ranges.into_iter().any(|bytes| !bytes.is_empty()) {
|
||||
self.add(Some(copied), writes);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.add_ranges(copied, writes, buffer.rt().offset(), ranges);
|
||||
}
|
||||
|
||||
fn add_ranges(
|
||||
&self,
|
||||
copied: &Arc<Copied>,
|
||||
writes: bool,
|
||||
offset: u64,
|
||||
ranges: impl IntoIterator<Item = Range<u64>>,
|
||||
) {
|
||||
self.note(copied, |u| {
|
||||
let used = if writes { &mut u.writes } else { &mut u.reads };
|
||||
for bytes in ranges {
|
||||
if *used == Ranges::All {
|
||||
break;
|
||||
}
|
||||
let at = |byte: u64| {
|
||||
offset
|
||||
.saturating_add(byte)
|
||||
.min(copied.len.to_u64())
|
||||
.to_usize()
|
||||
};
|
||||
let bytes = at(bytes.start)..at(bytes.end);
|
||||
if !bytes.is_empty() {
|
||||
used.add(bytes);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The command buffer uses `buffer` where its work can write it (bound to a shader's slot, a
|
||||
/// synchronize): its copy, where it lies over one.
|
||||
/// blit's destination or fill): its copy, where it lies over one.
|
||||
pub(super) fn buffer(&self, buffer: &RtBuffer) {
|
||||
self.add(buffer.copied(), true);
|
||||
}
|
||||
|
||||
/// The command buffer's work reads `buffer` alone (as indices, as an indirect or tessellation
|
||||
/// factor buffer): its copy, where it lies over one.
|
||||
/// factor buffer, as a blit's source): its copy, where it lies over one.
|
||||
pub(super) fn buffer_read(&self, buffer: &RtBuffer) {
|
||||
self.add(buffer.copied(), false);
|
||||
}
|
||||
@@ -751,7 +620,7 @@ pub(super) fn declare(
|
||||
pub(super) fn writes(copies: &[CopyUse]) -> bool {
|
||||
copies
|
||||
.iter()
|
||||
.any(|u| !u.writes.is_empty() && u.copied.kind != Kind::Drops)
|
||||
.any(|u| u.writes && u.copied.kind != Kind::Drops)
|
||||
}
|
||||
|
||||
/// Counts a render pass `sel` made whose attachments lie in the blocks `blocks` where one is a
|
||||
@@ -787,10 +656,12 @@ pub(super) fn copy_in(copies: &[CopyUse]) {
|
||||
let mut tally = Tally::default();
|
||||
for u in copies {
|
||||
let at = clock.now_mono();
|
||||
// A write needs the pre-submit CPU bytes in the base too. Otherwise merge_back
|
||||
// would see those bytes as CPU writes made during the submission.
|
||||
let chunks = u.reads.chunks(&u.writes, u.copied.len);
|
||||
tally.note(&u.copied, u.copied.copy_in(chunks), (&clock, at));
|
||||
let written = u.copied.copy_in();
|
||||
let bytes = match u.copied.kind {
|
||||
Kind::Merges | Kind::Drops => u.copied.len.to_u64(),
|
||||
Kind::Unchanging { .. } => 0,
|
||||
};
|
||||
tally.note(&u.copied, (written, bytes), (&clock, at));
|
||||
}
|
||||
tally.count(true);
|
||||
synced(IN_BYTES_CODE, tally.written, &clock, began);
|
||||
@@ -817,16 +688,14 @@ fn merge_back(copies: &[CopyUse]) {
|
||||
let clock = crate::os::OsClock::new();
|
||||
let began = clock.now_mono();
|
||||
let mut tally = Tally::default();
|
||||
for u in copies.iter().filter(|u| !u.writes.is_empty()) {
|
||||
for u in copies.iter().filter(|u| u.writes) {
|
||||
let at = clock.now_mono();
|
||||
let bytes = match u.copied.kind {
|
||||
Kind::Merges => u
|
||||
.copied
|
||||
.merge_back(u.writes.chunks(&Ranges::EMPTY, u.copied.len)),
|
||||
let written = match u.copied.kind {
|
||||
Kind::Merges => u.copied.merge_back(),
|
||||
Kind::Drops => continue,
|
||||
Kind::Unchanging { .. } => (u.copied.copy_whole(), u.copied.len.to_u64()),
|
||||
Kind::Unchanging { .. } => u.copied.copy_whole(),
|
||||
};
|
||||
tally.note(&u.copied, bytes, (&clock, at));
|
||||
tally.note(&u.copied, (written, u.copied.len.to_u64()), (&clock, at));
|
||||
}
|
||||
tally.count(false);
|
||||
synced(BACK_BYTES_CODE, tally.written, &clock, began);
|
||||
@@ -946,20 +815,16 @@ impl Copied {
|
||||
/// Writes into the copy the bytes of the pages that differ from the base, and the base takes
|
||||
/// them: the bytes written. The whole of the pages for a copy of read-only pages that may
|
||||
/// change ("Writes dropped"); nothing for one of unchanging pages ("Unchanging pages").
|
||||
fn copy_in(&self, chunks: impl Iterator<Item = Range<usize>>) -> (u64, u64) {
|
||||
fn copy_in(&self) -> u64 {
|
||||
match self.kind {
|
||||
Kind::Merges => {}
|
||||
Kind::Drops => return (self.copy_whole(), self.len.to_u64()),
|
||||
Kind::Unchanging { .. } => return (0, 0),
|
||||
Kind::Drops => return self.copy_whole(),
|
||||
Kind::Unchanging { .. } => return 0,
|
||||
}
|
||||
let mut base = self.base.lock();
|
||||
let mut now = [0_u64; WORDS];
|
||||
let mut written = 0;
|
||||
let mut scanned = 0;
|
||||
let base = base.as_chunks_mut::<WORDS>().0;
|
||||
for chunk in chunks.flatten() {
|
||||
scanned += CHUNK.to_u64();
|
||||
let was = &mut base[chunk];
|
||||
for (chunk, was) in base.as_chunks_mut::<WORDS>().0.iter_mut().enumerate() {
|
||||
let at = chunk * CHUNK;
|
||||
// SAFETY: the chunk lies in the pages, mapped until the copy goes (`new`'s contract).
|
||||
unsafe { read_chunk(self.home.as_ptr().add(at), &mut now) };
|
||||
@@ -977,20 +842,16 @@ impl Copied {
|
||||
}
|
||||
}
|
||||
}
|
||||
(written, scanned)
|
||||
written
|
||||
}
|
||||
|
||||
/// Writes into the pages the bytes of the copy that differ from the base where the pages'
|
||||
/// still are the base's, and the base takes the copy's: the bytes written.
|
||||
fn merge_back(&self, chunks: impl Iterator<Item = Range<usize>>) -> (u64, u64) {
|
||||
fn merge_back(&self) -> u64 {
|
||||
let mut base = self.base.lock();
|
||||
let (mut gpu, mut cpu) = ([0_u64; WORDS], [0_u64; WORDS]);
|
||||
let mut written = 0;
|
||||
let mut scanned = 0;
|
||||
let base = base.as_chunks_mut::<WORDS>().0;
|
||||
for chunk in chunks.flatten() {
|
||||
scanned += CHUNK.to_u64();
|
||||
let was = &mut base[chunk];
|
||||
for (chunk, was) in base.as_chunks_mut::<WORDS>().0.iter_mut().enumerate() {
|
||||
let at = chunk * CHUNK;
|
||||
// SAFETY: the chunk lies in the copy's first bytes, the length of the pages.
|
||||
unsafe { read_chunk(self.copy.as_ptr().add(at), &mut gpu) };
|
||||
@@ -1010,7 +871,7 @@ impl Copied {
|
||||
}
|
||||
}
|
||||
}
|
||||
(written, scanned)
|
||||
written
|
||||
}
|
||||
|
||||
/// Writes the whole of the pages into the copy again, the GPU's writes to it put back ("Writes
|
||||
@@ -1093,163 +954,6 @@ mod tests {
|
||||
unsafe { Copied::new(home, len, kind, (copy, cap, None)) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blit_ranges_coalesce_clamp_and_fall_back_independently() -> Result<(), &'static str> {
|
||||
let mut pages = chunks(3);
|
||||
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
|
||||
let len = 3 * CHUNK;
|
||||
// SAFETY: the pages outlive the copy.
|
||||
let copied = Arc::new(unsafe { copy_of(home, len, Kind::Merges) }.ok_or("copy")?);
|
||||
let used = Used::default();
|
||||
let end = len.to_u64();
|
||||
used.add_ranges(&copied, false, 10, [3..3, end..u64::MAX]);
|
||||
assert!(used.take().is_empty());
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
false,
|
||||
10,
|
||||
[12..20, 0..7, 6..12, end - 11..u64::MAX],
|
||||
);
|
||||
used.add_ranges(&copied, true, 0, std::iter::once(1..2));
|
||||
let uses = used.take();
|
||||
assert_eq!(uses[0].reads, Ranges::Known(vec![10..30, len - 1..len]));
|
||||
assert_eq!(
|
||||
uses[0]
|
||||
.reads
|
||||
.chunks(&uses[0].writes, len)
|
||||
.collect::<Vec<_>>(),
|
||||
[0..1, 2..3],
|
||||
);
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
true,
|
||||
0,
|
||||
(0..=MAX_RANGES.to_u64()).map(|n| 2 * n..2 * n + 1),
|
||||
);
|
||||
used.add_ranges(&copied, false, 0, std::iter::once(2..3));
|
||||
let uses = used.take();
|
||||
assert_eq!(uses[0].writes, Ranges::All);
|
||||
assert_eq!(
|
||||
uses[0].reads,
|
||||
Ranges::Known(std::iter::once(2..3).collect())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_shader_use_expands_a_local_blit_use() -> Result<(), &'static str> {
|
||||
let mut pages = chunks(2);
|
||||
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
|
||||
// SAFETY: the pages outlive the copy.
|
||||
let copied = Arc::new(unsafe { copy_of(home, 2 * CHUNK, Kind::Merges) }.ok_or("copy")?);
|
||||
let used = Used::default();
|
||||
for shader_writes in [false, true] {
|
||||
used.add_ranges(&copied, true, 0, std::iter::once(5..8));
|
||||
used.add(Some(&copied), shader_writes);
|
||||
let uses = used.take();
|
||||
assert_eq!(uses.len(), 1);
|
||||
assert_eq!(uses[0].reads, Ranges::All);
|
||||
let expected = if shader_writes {
|
||||
Ranges::All
|
||||
} else {
|
||||
Ranges::Known(std::iter::once(5..8).collect())
|
||||
};
|
||||
assert_eq!(uses[0].writes, expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_blit_syncs_only_its_chunks_and_keeps_cpu_writes() -> Result<(), &'static str> {
|
||||
let mut pages = chunks(5);
|
||||
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
|
||||
let len = 5 * CHUNK;
|
||||
// SAFETY: the pages outlive the copy.
|
||||
let copied = Arc::new(unsafe { copy_of(home, len, Kind::Merges) }.ok_or("copy")?);
|
||||
let used = Used::default();
|
||||
let (read, write, outside) = (CHUNK, 2 * CHUNK + 8, 4 * CHUNK);
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
false,
|
||||
read.to_u64(),
|
||||
std::iter::once(0..CHUNK.to_u64()),
|
||||
);
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
true,
|
||||
write.to_u64(),
|
||||
std::iter::once(0..CHUNK.to_u64()),
|
||||
);
|
||||
let uses = used.take();
|
||||
// SAFETY: each byte range lies inside its respective allocation.
|
||||
unsafe {
|
||||
home.as_ptr().add(read).write_bytes(0x11, CHUNK);
|
||||
home.as_ptr().add(write).write_bytes(0x22, CHUNK);
|
||||
home.as_ptr().add(outside).write(0x33);
|
||||
}
|
||||
copy_in(&uses);
|
||||
// SAFETY: same bounds as above, including the eight bytes before the destination.
|
||||
unsafe {
|
||||
assert_eq!(bytes(copied.copy.add(read), CHUNK), [0x11; CHUNK]);
|
||||
assert_eq!(bytes(copied.copy.add(write), CHUNK), [0x22; CHUNK]);
|
||||
assert_eq!(copied.copy.as_ptr().add(outside).read(), 0);
|
||||
copied.copy.as_ptr().add(write).write_bytes(0x44, CHUNK);
|
||||
home.as_ptr().add(write).write(0x55);
|
||||
home.as_ptr().add(write - 1).write(0x66);
|
||||
copied.copy.as_ptr().add(outside + 1).write(0x77);
|
||||
}
|
||||
merge_back(&uses);
|
||||
// SAFETY: same bounds as above.
|
||||
unsafe {
|
||||
assert_eq!(bytes(home.add(write - 1), 2), [0x66, 0x55]);
|
||||
assert_eq!(bytes(home.add(write + 1), CHUNK - 1), [0x44; CHUNK - 1]);
|
||||
assert_eq!(bytes(home.add(outside), 2), [0x33, 0]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_64_mib_copy_scans_only_the_chunks_of_a_4_kib_blit() -> Result<(), &'static str> {
|
||||
let len = 64 * 1024 * 1024;
|
||||
let mut pages = chunks(len / CHUNK);
|
||||
let mut memory = chunks(len / CHUNK);
|
||||
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
|
||||
let copy = NonNull::new(memory.as_mut_ptr().cast::<u8>()).ok_or("copy memory")?;
|
||||
// SAFETY: both allocations are disjoint, aligned and outlive the copy.
|
||||
let copied = Arc::new(
|
||||
unsafe { Copied::new(home, len, Kind::Merges, (copy, len, None)) }.ok_or("copy")?,
|
||||
);
|
||||
let clock = crate::os::OsClock::new();
|
||||
for (offset, expected) in [(len / 2, 1), (len / 2 + 4, 2)] {
|
||||
let used = Used::default();
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
true,
|
||||
offset.to_u64(),
|
||||
std::iter::once(0..CHUNK.to_u64()),
|
||||
);
|
||||
let uses = used.take();
|
||||
for (label, ranges, want) in [
|
||||
("whole", &Ranges::All, 16_384),
|
||||
("local", &uses[0].writes, expected),
|
||||
] {
|
||||
let began = clock.now_mono();
|
||||
let (_, in_bytes) = copied.copy_in(ranges.chunks(&Ranges::EMPTY, len));
|
||||
let incoming = clock.now_mono().saturating_duration_since(began);
|
||||
let began = clock.now_mono();
|
||||
let (_, back_bytes) = copied.merge_back(ranges.chunks(&Ranges::EMPTY, len));
|
||||
let outgoing = clock.now_mono().saturating_duration_since(began);
|
||||
let segments = (in_bytes / CHUNK.to_u64(), back_bytes / CHUNK.to_u64());
|
||||
assert_eq!(segments, (want, want));
|
||||
eprintln!(
|
||||
"64 MiB / 4 KiB, offset {offset}, {label}: copy_in {} chunks {incoming:?}, merge_back {} chunks {outgoing:?}",
|
||||
segments.0, segments.1
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A copy holds its pages' bytes and zeros past them; a commit's copy in writes the bytes the
|
||||
/// CPU changed and leaves the copy's others, which the GPU may have written meanwhile; a
|
||||
/// completion's merge back writes the bytes the GPU changed where the CPU did not, a byte both
|
||||
@@ -1267,13 +971,7 @@ mod tests {
|
||||
// SAFETY: the copy's memory holds `TAIL` bytes past the pages'.
|
||||
let tail = bytes(unsafe { copied.copy.add(len) }, TAIL);
|
||||
assert_eq!(tail, vec![0; TAIL], "zeros past the pages' bytes");
|
||||
assert_eq!(
|
||||
(
|
||||
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
|
||||
copied.merge_back(std::iter::once(0..len / CHUNK)).0
|
||||
),
|
||||
(0, 0)
|
||||
);
|
||||
assert_eq!((copied.copy_in(), copied.merge_back()), (0, 0));
|
||||
|
||||
// The CPU writes 3 bytes of the pages; the GPU, meanwhile, a byte of the copy beside one.
|
||||
// SAFETY: inside the pages and the copy.
|
||||
@@ -1281,7 +979,7 @@ mod tests {
|
||||
home.as_ptr().add(5).write_bytes(0x22, 3);
|
||||
copied.copy.as_ptr().add(8).write(0x33);
|
||||
}
|
||||
assert_eq!(copied.copy_in(std::iter::once(0..len / CHUNK)).0, 3);
|
||||
assert_eq!(copied.copy_in(), 3);
|
||||
let copy = bytes(copied.copy, 16);
|
||||
assert_eq!(copy[..5], [0x11; 5]);
|
||||
assert_eq!(copy[5..8], [0x22; 3]);
|
||||
@@ -1296,20 +994,14 @@ mod tests {
|
||||
copied.copy.as_ptr().add(far + 8).write(0x55);
|
||||
home.as_ptr().add(far + 8).write(0x66);
|
||||
}
|
||||
assert_eq!(copied.merge_back(std::iter::once(0..len / CHUNK)).0, 1 + 8);
|
||||
assert_eq!(copied.merge_back(), 1 + 8);
|
||||
let back = bytes(home, len);
|
||||
assert_eq!(back[8], 0x33);
|
||||
assert_eq!(back[far..far + 8], [0x44; 8]);
|
||||
assert_eq!(back[far + 8], 0x66);
|
||||
assert_eq!(copied.copy_in(std::iter::once(0..len / CHUNK)).0, 1);
|
||||
assert_eq!(copied.copy_in(), 1);
|
||||
assert_eq!(bytes(copied.copy, len), back);
|
||||
assert_eq!(
|
||||
(
|
||||
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
|
||||
copied.merge_back(std::iter::once(0..len / CHUNK)).0
|
||||
),
|
||||
(0, 0)
|
||||
);
|
||||
assert_eq!((copied.copy_in(), copied.merge_back()), (0, 0));
|
||||
}
|
||||
|
||||
/// The count of `code` in the degradation counts' line.
|
||||
@@ -1382,11 +1074,7 @@ mod tests {
|
||||
);
|
||||
let why_now = [why_counts[0] + 1, why_counts[1] + len.to_u64()];
|
||||
assert_eq!(whys.map(counted), why_now, "by the guest's why");
|
||||
assert_eq!(
|
||||
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
|
||||
len.to_u64(),
|
||||
"whole at each"
|
||||
);
|
||||
assert_eq!(copied.copy_in(), len.to_u64(), "whole at each");
|
||||
}
|
||||
|
||||
/// A command buffer's completion merges back only the copies a use of which can write them:
|
||||
@@ -1423,7 +1111,7 @@ mod tests {
|
||||
used.add(Some(written), true);
|
||||
used.add(None, true);
|
||||
let copies = used.take();
|
||||
let uses: Vec<bool> = copies.iter().map(|u| !u.writes.is_empty()).collect();
|
||||
let uses: Vec<bool> = copies.iter().map(|u| u.writes).collect();
|
||||
assert_eq!(uses, [false, false, true], "each copy once");
|
||||
assert!(writes(&copies));
|
||||
assert!(used.take().is_empty(), "taken");
|
||||
@@ -1530,11 +1218,7 @@ mod tests {
|
||||
read.add(Some(&copied), false);
|
||||
let reads = read.take();
|
||||
copy_in(&reads);
|
||||
assert_eq!(
|
||||
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
|
||||
0,
|
||||
"never copied in"
|
||||
);
|
||||
assert_eq!(copied.copy_in(), 0, "never copied in");
|
||||
merge_back(&reads);
|
||||
let mut gpu = vec![0x11; len];
|
||||
gpu[CHUNK + 16..CHUNK + 24].fill(0x44);
|
||||
|
||||
@@ -2625,327 +2625,6 @@ impl GpuDevice<RtPlatform> for RtObj<RtDevice> {
|
||||
crate::recorder::rec_done!(recorded_call, recorded_answer);
|
||||
recorded_answer
|
||||
}
|
||||
|
||||
fn wait_idle(&self) {
|
||||
let _ = self.rt().wait_idle();
|
||||
}
|
||||
|
||||
fn event_signaled_value(&self, event: &<RtPlatform as Platform>::Event) -> u64 {
|
||||
event.signaled_value()
|
||||
}
|
||||
|
||||
fn event_restore_signaled_value(
|
||||
&self,
|
||||
event: &<RtPlatform as Platform>::Event,
|
||||
value: u64,
|
||||
) -> bool {
|
||||
if value > 0 {
|
||||
event.restore_signaled_value(value).is_ok()
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn read_standalone_buffer(
|
||||
&self,
|
||||
buffer: &<RtPlatform as Platform>::Buffer,
|
||||
) -> Result<Option<Vec<u8>>, &'static str> {
|
||||
let Some(rt_buf) = buffer.made_rt() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let len = rt_buf.length();
|
||||
if len == 0 {
|
||||
return Ok(Some(Vec::new()));
|
||||
}
|
||||
if let Some(ptr) = rt_buf.contents() {
|
||||
return Ok(Some(unsafe {
|
||||
std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec()
|
||||
}));
|
||||
}
|
||||
let rt = self.rt();
|
||||
let alloc_len = (len.max(4096) + 4095) & !4095;
|
||||
let stage = rt
|
||||
.take_block(rt::MemoryClass::Shared, alloc_len)
|
||||
.map_err(|_| "standalone buffer readback: staging take_block failed")?;
|
||||
let res = (|| -> Result<Vec<u8>, &'static str> {
|
||||
let dst_buf = rt
|
||||
.new_buffer(stage.id, 0, len, None)
|
||||
.map_err(|_| "standalone buffer readback: staging new_buffer failed")?;
|
||||
let q = rt
|
||||
.new_command_queue(4)
|
||||
.map_err(|_| "standalone buffer readback: new_command_queue failed")?;
|
||||
let cb = q
|
||||
.command_buffer()
|
||||
.map_err(|_| "standalone buffer readback: command_buffer failed")?;
|
||||
let mut blit = cb
|
||||
.blit_command_encoder()
|
||||
.map_err(|_| "standalone buffer readback: blit_command_encoder failed")?;
|
||||
blit.copy_from_buffer_to_buffer(rt_buf, 0, &dst_buf, 0, len)
|
||||
.map_err(|_| "standalone buffer readback: copy_from_buffer_to_buffer failed")?;
|
||||
blit.end_encoding();
|
||||
cb.commit()
|
||||
.map_err(|_| "standalone buffer readback: commit failed")?;
|
||||
cb.wait_until_completed()
|
||||
.map_err(|_| "standalone buffer readback: wait_until_completed failed")?;
|
||||
let ptr = stage
|
||||
.contents
|
||||
.ok_or("standalone buffer readback: staging block not host-mapped")?;
|
||||
let out = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec() };
|
||||
drop(dst_buf);
|
||||
Ok(out)
|
||||
})();
|
||||
let _ = rt.release_block(stage);
|
||||
res.map(Some)
|
||||
}
|
||||
|
||||
fn write_standalone_buffer(
|
||||
&self,
|
||||
buffer: &<RtPlatform as Platform>::Buffer,
|
||||
data: &[u8],
|
||||
) -> bool {
|
||||
let Some(rt_buf) = buffer.made_rt() else {
|
||||
return false;
|
||||
};
|
||||
let len = rt_buf.length();
|
||||
if data.len() as u64 != len {
|
||||
return false;
|
||||
}
|
||||
if len == 0 {
|
||||
return true;
|
||||
}
|
||||
if let Some(ptr) = rt_buf.contents() {
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize);
|
||||
}
|
||||
let _ = rt_buf.did_modify_range(0, len);
|
||||
return true;
|
||||
}
|
||||
let rt = self.rt();
|
||||
let alloc_len = (len.max(4096) + 4095) & !4095;
|
||||
let Ok(stage) = rt.take_block(rt::MemoryClass::Shared, alloc_len) else {
|
||||
return false;
|
||||
};
|
||||
if let Some(ptr) = stage.contents {
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize);
|
||||
}
|
||||
} else {
|
||||
let _ = rt.release_block(stage);
|
||||
return false;
|
||||
}
|
||||
let ok = (|| -> Result<(), rt::Error> {
|
||||
let src_buf = rt.new_buffer(stage.id, 0, len, None)?;
|
||||
let q = rt.new_command_queue(4)?;
|
||||
let cb = q.command_buffer()?;
|
||||
let mut blit = cb.blit_command_encoder()?;
|
||||
blit.copy_from_buffer_to_buffer(&src_buf, 0, rt_buf, 0, len)?;
|
||||
blit.end_encoding();
|
||||
cb.commit()?;
|
||||
cb.wait_until_completed()?;
|
||||
drop(src_buf);
|
||||
Ok(())
|
||||
})()
|
||||
.is_ok();
|
||||
let _ = rt.release_block(stage);
|
||||
ok
|
||||
}
|
||||
|
||||
fn read_standalone_texture(
|
||||
&self,
|
||||
texture: &<RtPlatform as Platform>::Texture,
|
||||
) -> Result<Option<Vec<u8>>, &'static str> {
|
||||
let rt_tex = texture.rt();
|
||||
let desc = rt_tex.descriptor();
|
||||
let Some((plan, total)) = texture_copy_plan(self.rt(), desc) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if total == 0 {
|
||||
return Ok(Some(Vec::new()));
|
||||
}
|
||||
let rt = self.rt();
|
||||
let alloc_len = (total.max(4096) + 4095) & !4095;
|
||||
let stage = rt
|
||||
.take_block(rt::MemoryClass::Shared, alloc_len)
|
||||
.map_err(|_| "standalone texture readback: staging take_block failed")?;
|
||||
let res = (|| -> Result<Vec<u8>, &'static str> {
|
||||
let dst_buf = rt
|
||||
.new_buffer(stage.id, 0, total, None)
|
||||
.map_err(|_| "standalone texture readback: staging new_buffer failed")?;
|
||||
let q = rt
|
||||
.new_command_queue(4)
|
||||
.map_err(|_| "standalone texture readback: new_command_queue failed")?;
|
||||
let cb = q
|
||||
.command_buffer()
|
||||
.map_err(|_| "standalone texture readback: command_buffer failed")?;
|
||||
let mut blit = cb
|
||||
.blit_command_encoder()
|
||||
.map_err(|_| "standalone texture readback: blit_command_encoder failed")?;
|
||||
for step in &plan {
|
||||
blit.copy_from_texture_to_buffer(
|
||||
rt_tex,
|
||||
rt::TexturePlace {
|
||||
slice: step.slice,
|
||||
level: step.level,
|
||||
origin: [0, 0, 0],
|
||||
},
|
||||
step.size,
|
||||
&dst_buf,
|
||||
rt::BufferLayout {
|
||||
offset: step.offset,
|
||||
bytes_per_row: step.bytes_per_row,
|
||||
bytes_per_image: step.bytes_per_image,
|
||||
},
|
||||
)
|
||||
.map_err(|_| "standalone texture readback: copy_from_texture_to_buffer failed")?;
|
||||
}
|
||||
blit.end_encoding();
|
||||
cb.commit()
|
||||
.map_err(|_| "standalone texture readback: commit failed")?;
|
||||
cb.wait_until_completed()
|
||||
.map_err(|_| "standalone texture readback: wait_until_completed failed")?;
|
||||
let ptr = stage
|
||||
.contents
|
||||
.ok_or("standalone texture readback: staging block not host-mapped")?;
|
||||
let out = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), total as usize).to_vec() };
|
||||
drop(dst_buf);
|
||||
Ok(out)
|
||||
})();
|
||||
let _ = rt.release_block(stage);
|
||||
res.map(Some)
|
||||
}
|
||||
|
||||
fn write_standalone_texture(
|
||||
&self,
|
||||
texture: &<RtPlatform as Platform>::Texture,
|
||||
data: &[u8],
|
||||
) -> bool {
|
||||
let rt_tex = texture.rt();
|
||||
let desc = rt_tex.descriptor();
|
||||
let Some((plan, total)) = texture_copy_plan(self.rt(), desc) else {
|
||||
return false;
|
||||
};
|
||||
if data.len() as u64 != total {
|
||||
return false;
|
||||
}
|
||||
if total == 0 {
|
||||
return true;
|
||||
}
|
||||
let rt = self.rt();
|
||||
let alloc_len = (total.max(4096) + 4095) & !4095;
|
||||
let Ok(stage) = rt.take_block(rt::MemoryClass::Shared, alloc_len) else {
|
||||
return false;
|
||||
};
|
||||
if let Some(ptr) = stage.contents {
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), total as usize);
|
||||
}
|
||||
} else {
|
||||
let _ = rt.release_block(stage);
|
||||
return false;
|
||||
}
|
||||
let ok = (|| -> Result<(), rt::Error> {
|
||||
let src_buf = rt.new_buffer(stage.id, 0, total, None)?;
|
||||
let q = rt.new_command_queue(4)?;
|
||||
let cb = q.command_buffer()?;
|
||||
let mut blit = cb.blit_command_encoder()?;
|
||||
for step in &plan {
|
||||
blit.copy_from_buffer(
|
||||
&src_buf,
|
||||
rt::BufferLayout {
|
||||
offset: step.offset,
|
||||
bytes_per_row: step.bytes_per_row,
|
||||
bytes_per_image: step.bytes_per_image,
|
||||
},
|
||||
step.size,
|
||||
rt_tex,
|
||||
rt::TexturePlace {
|
||||
slice: step.slice,
|
||||
level: step.level,
|
||||
origin: [0, 0, 0],
|
||||
},
|
||||
)?;
|
||||
}
|
||||
blit.end_encoding();
|
||||
cb.commit()?;
|
||||
cb.wait_until_completed()?;
|
||||
drop(src_buf);
|
||||
Ok(())
|
||||
})()
|
||||
.is_ok();
|
||||
let _ = rt.release_block(stage);
|
||||
ok
|
||||
}
|
||||
}
|
||||
|
||||
struct TextureCopyStep {
|
||||
slice: u32,
|
||||
level: u32,
|
||||
size: [u32; 3],
|
||||
offset: u64,
|
||||
bytes_per_row: u64,
|
||||
bytes_per_image: u64,
|
||||
}
|
||||
|
||||
fn texture_copy_plan(
|
||||
rt: &rt::Device,
|
||||
desc: &rt::TextureDescriptor,
|
||||
) -> Option<(Vec<TextureCopyStep>, u64)> {
|
||||
if desc.sample_count > 1 || desc.storage_mode == rt::StorageMode::Memoryless {
|
||||
return None;
|
||||
}
|
||||
let raw_fmt = u64::from(desc.pixel_format.as_raw());
|
||||
if (250..=262).contains(&raw_fmt) {
|
||||
return None;
|
||||
}
|
||||
let info = rt.pixel_format_info(u64::from(desc.pixel_format.as_raw()));
|
||||
let block_bytes = info.words[0];
|
||||
if block_bytes == 0 {
|
||||
return None;
|
||||
}
|
||||
let (block_w, block_h, block_d) = if info.flags & 0x400 != 0 {
|
||||
(info.words[1].max(1), info.words[2].max(1), info.words[3].max(1))
|
||||
} else {
|
||||
(1, 1, 1)
|
||||
};
|
||||
let slices = match desc.texture_type {
|
||||
rt::TextureType::Cube | rt::TextureType::CubeArray => desc.array_length.checked_mul(6)?,
|
||||
rt::TextureType::Type3D => 1,
|
||||
_ => desc.array_length.max(1),
|
||||
};
|
||||
let levels = desc.mipmap_level_count.max(1);
|
||||
let mut plan = Vec::with_capacity((slices as usize).saturating_mul(levels as usize));
|
||||
let mut offset: u64 = 0;
|
||||
for slice in 0..slices {
|
||||
for level in 0..levels {
|
||||
let w = (desc.width >> level).max(1);
|
||||
let h = match desc.texture_type {
|
||||
rt::TextureType::Type1D | rt::TextureType::Type1DArray => 1,
|
||||
_ => (desc.height >> level).max(1),
|
||||
};
|
||||
let d = match desc.texture_type {
|
||||
rt::TextureType::Type3D => (desc.depth >> level).max(1),
|
||||
_ => 1,
|
||||
};
|
||||
let bx = u64::from(w).div_ceil(block_w);
|
||||
let by = u64::from(h).div_ceil(block_h);
|
||||
let bz = u64::from(d).div_ceil(block_d);
|
||||
let raw_bpr = bx.checked_mul(block_bytes)?;
|
||||
let bpr = (raw_bpr + 15) & !15;
|
||||
let bpi = bpr.checked_mul(by)?;
|
||||
let step_bytes = bpi.checked_mul(bz)?;
|
||||
offset = (offset + 15) & !15;
|
||||
plan.push(TextureCopyStep {
|
||||
slice,
|
||||
level,
|
||||
size: [w, h, d],
|
||||
offset,
|
||||
bytes_per_row: bpr,
|
||||
bytes_per_image: bpi,
|
||||
});
|
||||
offset = offset.checked_add(step_bytes)?;
|
||||
}
|
||||
}
|
||||
Some((plan, offset))
|
||||
}
|
||||
|
||||
/// The identity of `device` ([`answers::identity`]): rt's linear and texture-buffer alignments
|
||||
|
||||
@@ -464,7 +464,7 @@ impl Heap<RtPlatform> for RtObj<RtHeap> {
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
let placed = (true, self.copied.clone(), false);
|
||||
let placed = (true, self.copied.clone());
|
||||
let buffer = buffer::buffer_of(&self.device, made, self.options, placed, None);
|
||||
Ok(Some(buffer))
|
||||
});
|
||||
|
||||
@@ -109,7 +109,7 @@ use metal2vulkan::metal::{
|
||||
};
|
||||
use metal2vulkan_runtime as rt;
|
||||
|
||||
use crate::core::platform::render::{RenderCmd, RenderEncoder, VertexDraw, encode_each};
|
||||
use crate::core::platform::render::{RenderCmd, RenderEncoder};
|
||||
use crate::core::platform::types::{MtlScissorRect, MtlViewport};
|
||||
use crate::core::platform::{Handle, ObjId};
|
||||
use crate::core::raise::{OnFault, RaiseResult};
|
||||
@@ -123,7 +123,7 @@ use super::diag::{self, Bound, Point, Target, Use};
|
||||
use super::fault::{EncoderKind, EncoderNames, Naming};
|
||||
use super::render_pipeline::{Formats, Raster, RtRenderPipeline};
|
||||
use super::texture::RtTexture;
|
||||
use super::unbuilt::{Named, Unbuilt, naming_functions, refuse};
|
||||
use super::unbuilt::{Unbuilt, naming_functions, refuse};
|
||||
use super::{RtBuffer, RtObj, RtPlatform};
|
||||
|
||||
/// A count, a base or an index past rt's 32 bits.
|
||||
@@ -250,40 +250,6 @@ impl RtRenderEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a draw gap's details and returns the functions to name when reporting the refusal.
|
||||
#[cold]
|
||||
fn refusal_functions(
|
||||
&self,
|
||||
seen: &Seen,
|
||||
sel: &'static str,
|
||||
stopped: &Stop,
|
||||
draw: bool,
|
||||
primitive: Option<u64>,
|
||||
viewports: Option<Viewports<'_>>,
|
||||
) -> Named {
|
||||
let functions = match (stopped, &seen.state) {
|
||||
(Stop::Rt(_) | Stop::Unbuilt(_), Some(state)) if draw => state.functions(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if let Stop::Rt(error @ rt::Error::Unsupported(rt::Gap::Draw { kind })) = stopped {
|
||||
let what = DrawDetail {
|
||||
primitive,
|
||||
raster: seen.state.as_ref().map(|state| state.raster()),
|
||||
formats: (*kind == rt::DrawKind::AttachmentFormats).then(|| self.formats(seen)),
|
||||
viewports,
|
||||
};
|
||||
naming_functions(functions.clone(), || {
|
||||
super::unbuilt::refusal_detail(sel, error, Some(&what));
|
||||
});
|
||||
match kind {
|
||||
rt::DrawKind::AttachmentRead => self.attachment_read(seen),
|
||||
rt::DrawKind::FetchedAttachment => self.fetched_attachment(seen),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
functions
|
||||
}
|
||||
|
||||
/// Encodes `cmd` but `endEncoding`, which the caller ends.
|
||||
fn command(&self, open: &mut Open, cmd: RenderCmd<'_, RtPlatform>) -> Result<(), Stop> {
|
||||
let Open {
|
||||
@@ -302,7 +268,8 @@ impl RtRenderEncoder {
|
||||
vertex_count,
|
||||
} => {
|
||||
set(*pipeline)?;
|
||||
draw_primitives(e, primitive_type, vertex_start, vertex_count)?;
|
||||
let (start, count) = (small(vertex_start)?, small(vertex_count)?);
|
||||
e.draw_primitives(primitive(primitive_type)?, start, count, 1, 0)?;
|
||||
}
|
||||
RenderCmd::DrawPrimitivesInstances {
|
||||
primitive_type,
|
||||
@@ -721,18 +688,6 @@ fn set(pipeline: Option<ObjId>) -> Result<(), Stop> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The short draw form, after checking that a pipeline is bound.
|
||||
fn draw_primitives(
|
||||
encoder: &mut rt::RenderCommandEncoder,
|
||||
primitive_type: u64,
|
||||
vertex_start: u64,
|
||||
vertex_count: u64,
|
||||
) -> Result<(), Stop> {
|
||||
let (start, count) = (small(vertex_start)?, small(vertex_count)?);
|
||||
encoder.draw_primitives(primitive(primitive_type)?, start, count, 1, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `Ok` where a setting rt has none of is at Metal's default (`at_default`); unbuilt otherwise.
|
||||
fn unbuilt_unless(at_default: bool) -> Result<(), Stop> {
|
||||
match at_default {
|
||||
@@ -1149,9 +1104,30 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
|
||||
note_names(names, &cmd);
|
||||
}
|
||||
let stopped = self.command(&mut open, cmd).err();
|
||||
let functions = stopped.as_ref().map_or_else(Vec::new, |stop| {
|
||||
self.refusal_functions(&open.seen, sel, stop, draw, primitive, viewports)
|
||||
});
|
||||
let functions = match (&stopped, &open.seen.state) {
|
||||
(Some(Stop::Rt(_) | Stop::Unbuilt(_)), Some(state)) if draw => state.functions(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if let Some(Stop::Rt(error @ rt::Error::Unsupported(rt::Gap::Draw { kind }))) = &stopped
|
||||
{
|
||||
let raster = open.seen.state.as_ref().map(|state| state.raster());
|
||||
let formats =
|
||||
(*kind == rt::DrawKind::AttachmentFormats).then(|| self.formats(&open.seen));
|
||||
let what = DrawDetail {
|
||||
primitive,
|
||||
raster,
|
||||
formats,
|
||||
viewports,
|
||||
};
|
||||
naming_functions(functions.clone(), || {
|
||||
super::unbuilt::refusal_detail(sel, error, Some(&what));
|
||||
});
|
||||
match kind {
|
||||
rt::DrawKind::AttachmentRead => self.attachment_read(&open.seen),
|
||||
rt::DrawKind::FetchedAttachment => self.fetched_attachment(&open.seen),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let icb_gap = |error: &rt::Error| {
|
||||
matches!(
|
||||
error,
|
||||
@@ -1177,69 +1153,6 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
|
||||
recorded_answer
|
||||
}
|
||||
|
||||
fn encode_draws(&self, on: OnFault, draws: &[VertexDraw<'_, RtPlatform>]) -> RaiseResult<()> {
|
||||
if draws.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if crate::recorder::on() || super::copied::any() {
|
||||
return encode_each(self, on, draws);
|
||||
}
|
||||
let held = self.open.lock();
|
||||
let mut open = held.borrow_mut();
|
||||
let Open {
|
||||
rt,
|
||||
pipeline,
|
||||
seen,
|
||||
naming,
|
||||
} = &mut *open;
|
||||
let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else {
|
||||
drop(open);
|
||||
drop(held);
|
||||
return encode_each(self, on, draws);
|
||||
};
|
||||
let mut last = None;
|
||||
let mut buffer = None;
|
||||
for (i, draw) in draws.iter().enumerate() {
|
||||
if let Some(bound) = draw.buffer {
|
||||
names.bound_buffers.add_named(bound.named());
|
||||
}
|
||||
let key = draw.buffer.map(std::ptr::from_ref);
|
||||
if key != last {
|
||||
last = key;
|
||||
buffer = draw.buffer.map(|b| b.rt());
|
||||
}
|
||||
let bound = small(draw.index).and_then(|index| {
|
||||
encoder
|
||||
.set_vertex_buffer(buffer, draw.offset, index)
|
||||
.map_err(Stop::from)
|
||||
});
|
||||
// A refusal is reported once. After a refused bind, the draw still sees the
|
||||
// encoder's existing binding, and only commands that have yet to run go to encode.
|
||||
if let Err(stop) = bound {
|
||||
drop(open);
|
||||
drop(held);
|
||||
report(draw.vertex_buffer().selector(), Some(stop));
|
||||
self.encode(on, draw.primitives())?;
|
||||
return encode_each(self, on, &draws[i + 1..]);
|
||||
}
|
||||
if let Err(stop) = draw_primitives(
|
||||
encoder,
|
||||
draw.primitive_type,
|
||||
draw.vertex_start,
|
||||
draw.vertex_count,
|
||||
) {
|
||||
let sel = draw.primitives().selector();
|
||||
let functions =
|
||||
self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None);
|
||||
drop(open);
|
||||
drop(held);
|
||||
naming_functions(functions, || report(sel, Some(stop)));
|
||||
return encode_each(self, on, &draws[i + 1..]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Holds the encoder for `run` ([`RtRenderEncoder`]'s `open`): the commands `run` sends take
|
||||
/// its lock again on this thread, and another thread's wait for it to end.
|
||||
fn encoding<T>(&self, run: impl FnOnce() -> T) -> T {
|
||||
@@ -1602,382 +1515,6 @@ mod tests {
|
||||
words.iter().flat_map(|w| w.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// Each draw, including the draw after a refused bind, uses the binding it would see
|
||||
/// alone. The visibility result counts the draws even when a later one covers their pixels.
|
||||
#[test]
|
||||
fn draw_batches_match_individual_commands_on_vulkan() -> Result<(), &'static str> {
|
||||
check_draw_batch(DrawBatchCase::Existing)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_clear_and_rebind_a_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
|
||||
check_draw_batch(DrawBatchCase::Unbind)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_report_a_gap_and_continue_on_vulkan() -> Result<(), &'static str> {
|
||||
check_draw_batch(DrawBatchCase::Gap)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_record_bound_buffer_names_on_vulkan() -> Result<(), &'static str> {
|
||||
check_draw_batch(DrawBatchCase::Names)
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
enum DrawBatchCase {
|
||||
Existing,
|
||||
Unbind,
|
||||
Gap,
|
||||
Names,
|
||||
}
|
||||
|
||||
fn check_draw_batch(case: DrawBatchCase) -> Result<(), &'static str> {
|
||||
use crate::core::platform::command::WorkNames;
|
||||
use crate::rt_platform::fault::{Ids, Operands, name_buffer};
|
||||
use std::sync::Arc;
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let state = vdesc_state(&device, &function(&device, COLOR, "render_color"));
|
||||
let (red, green, cyan, blue) = (
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255],
|
||||
[0, 255, 255, 255],
|
||||
[0, 0, 255, 255],
|
||||
);
|
||||
let a = shared(&device, &vertices(&[green, cyan]));
|
||||
let b = shared(&device, &vertices(&[blue]));
|
||||
name_buffer(&a, 7);
|
||||
let results = shared(&device, &[0; 8]);
|
||||
let on = OnFault::Return;
|
||||
let Ok(Some(target)) = device.new_texture(
|
||||
on,
|
||||
&platform.texture_descriptor(&TextureDesc {
|
||||
width: 4,
|
||||
height: 4,
|
||||
usage: 5,
|
||||
..TextureDesc::default()
|
||||
}),
|
||||
) else {
|
||||
return Err("no render target");
|
||||
};
|
||||
let pass = pass(&target, 2);
|
||||
pass.set_pass(&PassSet {
|
||||
visibility_result_buffer: Some(Some(&results)),
|
||||
..PassSet::default()
|
||||
});
|
||||
let draw_a = VertexDraw {
|
||||
buffer: Some(&a),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
primitive_type: TRIANGLE,
|
||||
vertex_start: 0,
|
||||
vertex_count: 3,
|
||||
};
|
||||
let next_a = VertexDraw {
|
||||
offset: 36,
|
||||
..draw_a
|
||||
};
|
||||
let draw_b = VertexDraw {
|
||||
buffer: Some(&b),
|
||||
..draw_a
|
||||
};
|
||||
let bad_bind = VertexDraw {
|
||||
index: 31,
|
||||
..draw_b
|
||||
};
|
||||
let bad_draw = VertexDraw {
|
||||
primitive_type: u64::MAX,
|
||||
..draw_b
|
||||
};
|
||||
let codes = [RtRefusal::Refused, RtRefusal::Ours, RtRefusal::Gap].map(RtRefusal::code);
|
||||
let render = |draws: &[VertexDraw<'_, RtPlatform>],
|
||||
batch,
|
||||
operands: bool,
|
||||
no_pipeline: bool,
|
||||
ended| {
|
||||
let Ok(Some(cb)) = queue.command_buffer(on) else {
|
||||
return Err("no command buffer");
|
||||
};
|
||||
if !operands {
|
||||
cb.names_work(&Arc::new(WorkNames::new(1)));
|
||||
}
|
||||
let Ok(Some(encoder)) = cb.render_encoder(on, &pass) else {
|
||||
return Err("no render encoder");
|
||||
};
|
||||
if !no_pipeline {
|
||||
assert_eq!(
|
||||
encoder.encode(
|
||||
on,
|
||||
RenderCmd::SetRenderPipelineState {
|
||||
pipeline_state: Some(&state),
|
||||
},
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
encoder.encode(
|
||||
on,
|
||||
RenderCmd::SetVisibilityResultMode { mode: 2, offset: 0 }
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
if case == DrawBatchCase::Gap {
|
||||
// Triangles still draw; the line in the middle hits rt's DrawKind::LineWidth.
|
||||
encoder
|
||||
.open
|
||||
.lock()
|
||||
.borrow_mut()
|
||||
.rt
|
||||
.as_mut()
|
||||
.ok_or("no rt encoder")?
|
||||
.set_line_width(2.0);
|
||||
}
|
||||
if ended {
|
||||
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
|
||||
}
|
||||
let before = codes.map(counted);
|
||||
let answer = if batch {
|
||||
encoder.encode_draws(on, draws)
|
||||
} else {
|
||||
encode_each(&encoder, on, draws)
|
||||
};
|
||||
assert_eq!(answer, Ok(()));
|
||||
let refused = std::array::from_fn(|i| counted(codes[i]) - before[i]);
|
||||
let names = encoder.open.lock().borrow_mut().naming.names().cloned();
|
||||
if let Some(names) = &names {
|
||||
assert_eq!(names.operands, operands.then(Operands::default));
|
||||
}
|
||||
if !ended {
|
||||
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
|
||||
}
|
||||
assert_eq!(cb.commit(on), Ok(()));
|
||||
assert_eq!(cb.wait_until_completed(on), Ok(()));
|
||||
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED);
|
||||
let mut pixels = [0; 64];
|
||||
target.read_pixels(&mut pixels, 16);
|
||||
// SAFETY: the Shared result buffer is mapped for eight bytes and the GPU has finished.
|
||||
let samples =
|
||||
u64::from_le_bytes(unsafe { results.contents().as_ptr::<[u8; 8]>().read() });
|
||||
Ok((
|
||||
pixels,
|
||||
samples,
|
||||
refused,
|
||||
names.map(|names| names.bound_buffers),
|
||||
))
|
||||
};
|
||||
|
||||
if case != DrawBatchCase::Existing {
|
||||
let (draws, colour, samples, refused) = match case {
|
||||
DrawBatchCase::Unbind => (
|
||||
vec![
|
||||
draw_a,
|
||||
VertexDraw {
|
||||
buffer: None,
|
||||
..draw_a
|
||||
},
|
||||
next_a,
|
||||
],
|
||||
cyan,
|
||||
32,
|
||||
[0, 1, 0],
|
||||
),
|
||||
DrawBatchCase::Gap => (
|
||||
vec![
|
||||
draw_a,
|
||||
VertexDraw {
|
||||
primitive_type: 1,
|
||||
vertex_count: 2,
|
||||
..draw_b
|
||||
},
|
||||
next_a,
|
||||
],
|
||||
cyan,
|
||||
32,
|
||||
[0, 0, 1],
|
||||
),
|
||||
DrawBatchCase::Names => (vec![draw_a, next_a, draw_b, draw_b], blue, 64, [0, 0, 0]),
|
||||
DrawBatchCase::Existing => unreachable!("handled by the cases below"),
|
||||
};
|
||||
let batch = render(&draws, true, true, false, false)?;
|
||||
assert_eq!(batch, render(&draws, false, true, false, false)?);
|
||||
let mut bound = Ids::default();
|
||||
bound.add(7);
|
||||
match case {
|
||||
DrawBatchCase::Gap => bound.add(0),
|
||||
DrawBatchCase::Names => {
|
||||
bound.add(0);
|
||||
bound.add(0);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
assert_eq!(
|
||||
batch,
|
||||
(
|
||||
std::array::from_fn(|i| colour[i % 4]),
|
||||
samples,
|
||||
refused,
|
||||
Some(bound)
|
||||
)
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for (draws, operands, no_pipeline, ended, colour, samples, refusals) in [
|
||||
(&[][..], false, false, false, red, 0, 0),
|
||||
(&[draw_a, next_a][..], false, false, false, cyan, 32, 0),
|
||||
(
|
||||
&[draw_a, next_a, draw_b][..],
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
blue,
|
||||
48,
|
||||
0,
|
||||
),
|
||||
(
|
||||
&[draw_a, next_a, draw_b][..],
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
blue,
|
||||
48,
|
||||
0,
|
||||
),
|
||||
(&[draw_a, bad_bind][..], false, false, false, green, 32, 1),
|
||||
(
|
||||
&[draw_a, bad_bind, next_a][..],
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
cyan,
|
||||
48,
|
||||
1,
|
||||
),
|
||||
(
|
||||
&[draw_a, bad_draw, bad_bind][..],
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
blue,
|
||||
32,
|
||||
2,
|
||||
),
|
||||
(&[draw_a, draw_b][..], false, true, false, red, 0, 2),
|
||||
(&[draw_a, draw_b][..], false, false, true, red, 0, 4),
|
||||
(&[][..], false, false, true, red, 0, 0),
|
||||
] {
|
||||
let batch = render(draws, true, operands, no_pipeline, ended)?;
|
||||
assert_eq!(batch, render(draws, false, operands, no_pipeline, ended)?);
|
||||
assert_eq!(
|
||||
(batch.0, batch.1, batch.2[0]),
|
||||
(std::array::from_fn(|i| colour[i % 4]), samples, refusals)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
|
||||
use crate::core::host::HostPtr;
|
||||
use crate::core::num::ToUsize as _;
|
||||
use crate::core::platform::HostRange;
|
||||
use std::alloc::{Layout, alloc_zeroed, dealloc};
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let on = OnFault::Return;
|
||||
let page = device.facts().page_size;
|
||||
let layout =
|
||||
Layout::from_size_align(page.to_usize(), page.to_usize()).map_err(|_| "page layout")?;
|
||||
// SAFETY: the page layout has nonzero size.
|
||||
let memory = HostPtr::from_ptr(unsafe { alloc_zeroed(layout) });
|
||||
if memory == HostPtr::from_ptr(std::ptr::null_mut::<u8>()) {
|
||||
return Err("page allocation");
|
||||
}
|
||||
// SAFETY: the page lives until the buffer's deallocator runs.
|
||||
let bytes = unsafe { HostRange::new(memory, page) };
|
||||
let buffer = device
|
||||
.new_buffer_over_host_memory(
|
||||
on,
|
||||
bytes,
|
||||
super::super::buffer::READ_ONLY,
|
||||
// SAFETY: this frees the page once the copy and its users let it go.
|
||||
Some(Box::new(move || unsafe {
|
||||
dealloc(memory.as_ptr(), layout)
|
||||
})),
|
||||
)
|
||||
.map_err(|_| "buffer creation raised")?
|
||||
.ok_or("no copied buffer")?;
|
||||
assert!(buffer.copied().is_some());
|
||||
assert!(super::super::copied::any());
|
||||
let green = [0, 255, 0, 255];
|
||||
let data = vertices(&[green]);
|
||||
// SAFETY: the vertices fit in the mapped page, and the copy was already initialized.
|
||||
unsafe {
|
||||
memory
|
||||
.as_ptr::<u8>()
|
||||
.copy_from_nonoverlapping(data.as_ptr(), data.len())
|
||||
};
|
||||
let state = vdesc_state(&device, &function(&device, COLOR, "render_color"));
|
||||
let target = device
|
||||
.new_texture(
|
||||
on,
|
||||
&platform.texture_descriptor(&TextureDesc {
|
||||
width: 4,
|
||||
height: 4,
|
||||
usage: 5,
|
||||
..TextureDesc::default()
|
||||
}),
|
||||
)
|
||||
.map_err(|_| "texture creation raised")?
|
||||
.ok_or("no render target")?;
|
||||
let pass = pass(&target, 2);
|
||||
let commands = queue
|
||||
.command_buffer(on)
|
||||
.map_err(|_| "command buffer raised")?
|
||||
.ok_or("no command buffer")?;
|
||||
let encoder = commands
|
||||
.render_encoder(on, &pass)
|
||||
.map_err(|_| "render encoder raised")?
|
||||
.ok_or("no render encoder")?;
|
||||
assert_eq!(
|
||||
encoder.encode(
|
||||
on,
|
||||
RenderCmd::SetRenderPipelineState {
|
||||
pipeline_state: Some(&state)
|
||||
}
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert_eq!(
|
||||
encoder.encode_draws(
|
||||
on,
|
||||
&[VertexDraw {
|
||||
buffer: Some(&buffer),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
primitive_type: TRIANGLE,
|
||||
vertex_start: 0,
|
||||
vertex_count: 3,
|
||||
}]
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
|
||||
assert_eq!(commands.commit(on), Ok(()));
|
||||
assert_eq!(commands.wait_until_completed(on), Ok(()));
|
||||
assert_eq!(commands.status(), CommandBufferStatus::COMPLETED);
|
||||
let mut pixels = [0; 64];
|
||||
target.read_pixels(&mut pixels, 16);
|
||||
assert_eq!(pixels, std::array::from_fn(|i| green[i % 4]));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A run of `encoding` holds the encoder: the run's own commands go through and draw, and a
|
||||
/// command another thread sends meanwhile waits for the run to end, then goes through.
|
||||
#[test]
|
||||
|
||||
@@ -31,7 +31,6 @@ libc.workspace = true
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Threading",
|
||||
"Win32_UI_Shell",
|
||||
] }
|
||||
|
||||
|
||||
@@ -743,10 +743,8 @@ runtime's own device. The switches above apply, and `resolution=` too.
|
||||
the host's arrow shows over the window, and a minimized window is
|
||||
restored and raised. Where the window draws no more (its GPU lost, or no
|
||||
swapchain), the question shows in SDL's message box instead: zenity's
|
||||
where zenity is installed, else SDL's own X11 dialog. On Windows,
|
||||
Reims-Go can handle the close in its own dialog with Shut down, Suspend
|
||||
and Cancel. When the client handoff fails, SDL shows a task dialog the
|
||||
window owns, Turn Off left of Cancel. Turn Off asks the host
|
||||
where zenity is installed, else SDL's own X11 dialog. On Windows a task
|
||||
dialog the window owns, Turn Off left of Cancel. Turn Off asks the host
|
||||
to end the VM; Cancel, or the question dismissed, leaves the window and
|
||||
the VM running, nothing held in the guest and the input released. From
|
||||
the close to the answer nothing of the window's input reaches the guest:
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
//! shutdown request with the power-off action, which the guest is not asked about). So the window
|
||||
//! asks first, in a question of the host OS's own over the window ([`QUESTION`], [`DETAIL`]), with
|
||||
//! two answers: [`CANCEL`], the default, keeps the VM running, and [`TURN_OFF`] tells the host.
|
||||
//! A Windows VM started by Reims-Go can hand the question to its client
|
||||
//! instead. The client then handles the chosen action.
|
||||
//!
|
||||
//! **When it asks** ([`Asks::request`]): only where the host would hear of the close, while the
|
||||
//! window lives (the display's release takes the host's callbacks back) and the host gave a close
|
||||
@@ -57,9 +55,6 @@ pub(crate) enum Answer {
|
||||
Cancel,
|
||||
/// No question could show: nothing happens, as for Cancel, and the OS's side logs why.
|
||||
Unshown,
|
||||
/// Reims-Go's dialog handles the close.
|
||||
#[cfg(target_os = "windows")]
|
||||
Delegated,
|
||||
}
|
||||
|
||||
/// The process's questions: whether one is open, and whether the person has chosen Turn Off.
|
||||
@@ -113,8 +108,6 @@ pub(crate) fn answered(answer: Answer) -> bool {
|
||||
Answer::TurnOff => "the person chose Turn Off: the host turns the VM off",
|
||||
Answer::Cancel => "the close is cancelled, or its window ended: the host is not told",
|
||||
Answer::Unshown => "no question showed: the host is not told, and the VM runs on",
|
||||
#[cfg(target_os = "windows")]
|
||||
Answer::Delegated => "the close question was handed to Reims-Go",
|
||||
};
|
||||
log::info!(target: "reims_vgpu_window", "{said}");
|
||||
tell
|
||||
@@ -151,13 +144,5 @@ mod tests {
|
||||
assert_eq!(unshown.request(true), Step::Ask);
|
||||
assert!(!unshown.answered(Answer::Unshown));
|
||||
assert_eq!(unshown.request(true), Step::Ask);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let mut delegated = Asks::default();
|
||||
assert_eq!(delegated.request(true), Step::Ask);
|
||||
assert!(!delegated.answered(Answer::Delegated));
|
||||
assert_eq!(delegated.request(true), Step::Ask);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
//! Collects a window's SDL file or text drop and forwards it to the local host bridge.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::io::{self, Write as _};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::mpsc::{self, SyncSender, TrySendError};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::geometry::{self, Rect};
|
||||
|
||||
/// Maximum number of files forwarded in a single drop.
|
||||
const MAX_DROP_PATHS: usize = 256;
|
||||
|
||||
/// Maximum joined UTF-8 text size forwarded in a single drop.
|
||||
const MAX_DROP_TEXT_BYTES: usize = 128 << 10;
|
||||
|
||||
/// Drop contents and guest-image coordinates for one completed host drop.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DropPayload {
|
||||
/// Guest display port that received the drop.
|
||||
pub display_index: u64,
|
||||
/// Horizontal position, clamped to the guest image.
|
||||
pub norm_x: f64,
|
||||
/// Vertical position, clamped to the guest image.
|
||||
pub norm_y: f64,
|
||||
/// Whether the original position was inside the guest image.
|
||||
pub in_image: bool,
|
||||
/// Host paths in the order SDL delivered them.
|
||||
pub paths: Vec<String>,
|
||||
/// Joined text for a drop without files.
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
/// Maps a window point to the guest image, using its center when geometry is unavailable.
|
||||
pub(crate) fn normalize_point(point: Option<(f64, f64)>, image: Rect) -> (f64, f64, bool) {
|
||||
let Some((x, y)) = point else {
|
||||
return (0.5, 0.5, false);
|
||||
};
|
||||
if ![x, y, image.x, image.y, image.width, image.height]
|
||||
.into_iter()
|
||||
.all(f64::is_finite)
|
||||
|| image.width <= 0.0
|
||||
|| image.height <= 0.0
|
||||
{
|
||||
return (0.5, 0.5, false);
|
||||
}
|
||||
(
|
||||
((x - image.x) / image.width).clamp(0.0, 1.0),
|
||||
((y - image.y) / image.height).clamp(0.0, 1.0),
|
||||
geometry::contains(image, (x, y)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Drop state for one SDL window, active from begin or the first file, text or position.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct DropBatch {
|
||||
/// Host paths collected for this batch.
|
||||
paths: Option<Vec<String>>,
|
||||
/// Nonempty input chunks in delivery order, bounded before joining.
|
||||
texts: Option<Vec<String>>,
|
||||
/// Joined bytes consumed, saturated at the limit once a chunk is truncated.
|
||||
text_bytes: usize,
|
||||
/// Most recent finite position, in SDL window coordinates.
|
||||
last_pos: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl DropBatch {
|
||||
/// Starts a new batch, discarding an unfinished drop.
|
||||
pub(crate) fn begin(&mut self) {
|
||||
self.paths = Some(Vec::new());
|
||||
self.texts = None;
|
||||
self.text_bytes = 0;
|
||||
self.last_pos = None;
|
||||
}
|
||||
|
||||
/// Records the most recent usable position.
|
||||
pub(crate) fn position(&mut self, x: f64, y: f64) {
|
||||
if x.is_finite() && y.is_finite() {
|
||||
self.last_pos = Some((x, y));
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts a file even if SDL omitted begin, taking its position as a fallback.
|
||||
pub(crate) fn file(&mut self, path: String, pos: Option<(f64, f64)>) {
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
let paths = self.paths.get_or_insert_with(Vec::new);
|
||||
if paths.len() < MAX_DROP_PATHS {
|
||||
paths.push(path);
|
||||
}
|
||||
if self.last_pos.is_none() && let Some((x, y)) = pos {
|
||||
self.position(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects UTF-8 text up to the byte limit, including separators between chunks.
|
||||
pub(crate) fn text(&mut self, chunk: String, pos: Option<(f64, f64)>) {
|
||||
if chunk.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.last_pos.is_none() && let Some((x, y)) = pos {
|
||||
self.position(x, y);
|
||||
}
|
||||
if self.text_bytes == MAX_DROP_TEXT_BYTES {
|
||||
return;
|
||||
}
|
||||
let separator = usize::from(self.texts.is_some());
|
||||
let remaining = MAX_DROP_TEXT_BYTES - self.text_bytes - separator;
|
||||
let texts = self.texts.get_or_insert_with(Vec::new);
|
||||
if chunk.len() > remaining {
|
||||
let kept = &chunk[..chunk.floor_char_boundary(remaining)];
|
||||
if !kept.is_empty() {
|
||||
texts.push(kept.to_owned());
|
||||
}
|
||||
self.text_bytes = MAX_DROP_TEXT_BYTES;
|
||||
} else {
|
||||
self.text_bytes += separator + chunk.len();
|
||||
texts.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
/// Finishes this batch and yields its files or text and normalized drop position.
|
||||
pub(crate) fn complete(
|
||||
&mut self,
|
||||
display_index: u64,
|
||||
image: Rect,
|
||||
pos: Option<(f64, f64)>,
|
||||
) -> Option<DropPayload> {
|
||||
let point = self.last_pos.take().or(pos);
|
||||
let paths = self.paths.take().unwrap_or_default();
|
||||
let texts = self.texts.take();
|
||||
self.text_bytes = 0;
|
||||
let text = if paths.is_empty() {
|
||||
Some(texts.filter(|chunks| !chunks.is_empty())?.join("\n"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (norm_x, norm_y, in_image) = normalize_point(point, image);
|
||||
Some(DropPayload {
|
||||
display_index,
|
||||
norm_x,
|
||||
norm_y,
|
||||
in_image,
|
||||
paths,
|
||||
text,
|
||||
})
|
||||
}
|
||||
|
||||
/// Discards drop contents and position when the window closes.
|
||||
pub(crate) fn reset(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends one quoted string with RFC 8259 escapes.
|
||||
fn push_json_string(json: &mut String, value: &str) {
|
||||
json.push('"');
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'"' => json.push_str("\\\""),
|
||||
'\\' => json.push_str("\\\\"),
|
||||
'\u{8}' => json.push_str("\\b"),
|
||||
'\u{c}' => json.push_str("\\f"),
|
||||
'\n' => json.push_str("\\n"),
|
||||
'\r' => json.push_str("\\r"),
|
||||
'\t' => json.push_str("\\t"),
|
||||
'\0'..='\u{1f}' => {
|
||||
// Writing to a String is infallible.
|
||||
let _ = write!(json, "\\u{:04x}", u32::from(ch));
|
||||
}
|
||||
_ => json.push(ch),
|
||||
}
|
||||
}
|
||||
json.push('"');
|
||||
}
|
||||
|
||||
/// Encodes a file or text drop as UTF-8 JSON.
|
||||
pub(crate) fn encode_drop_json(payload: &DropPayload) -> String {
|
||||
let mut json = format!(
|
||||
r#"{{"display_index":{},"norm_x":{},"norm_y":{},"in_image":{}"#,
|
||||
payload.display_index, payload.norm_x, payload.norm_y, payload.in_image,
|
||||
);
|
||||
if !payload.paths.is_empty() {
|
||||
json.push_str(r#","paths":["#);
|
||||
for (i, path) in payload.paths.iter().enumerate() {
|
||||
if i != 0 {
|
||||
json.push(',');
|
||||
}
|
||||
push_json_string(&mut json, path);
|
||||
}
|
||||
json.push(']');
|
||||
} else if let Some(text) = &payload.text {
|
||||
json.push_str(r#","text":"#);
|
||||
push_json_string(&mut json, text);
|
||||
}
|
||||
json.push('}');
|
||||
json
|
||||
}
|
||||
|
||||
/// Parses the explicit IPv4 loopback endpoint used by the host drop bridge.
|
||||
fn parse_loopback_drop_url(raw: &str) -> Option<(SocketAddr, String)> {
|
||||
let rest = raw.strip_prefix("http://127.0.0.1:")?;
|
||||
let (port, path) = match rest.find('/') {
|
||||
Some(i) => (&rest[..i], &rest[i..]),
|
||||
None => (rest, "/v1/host-drop"),
|
||||
};
|
||||
if !port.bytes().all(|b| b.is_ascii_digit())
|
||||
|| path.bytes().any(|b| b.is_ascii_control() || b == b' ')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let port: u16 = port.parse().ok()?;
|
||||
(port != 0).then(|| (SocketAddr::from(([127, 0, 0, 1], port)), path.to_owned()))
|
||||
}
|
||||
|
||||
/// SDL's bounded queue to the HTTP worker.
|
||||
static DROP_TX: OnceLock<SyncSender<DropPayload>> = OnceLock::new();
|
||||
|
||||
/// Starts the HTTP worker when the runtime provides a valid local URL and bearer token.
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "linux", target_os = "windows")),
|
||||
expect(dead_code, reason = "only the SDL thread starts the host drop forwarder")
|
||||
)]
|
||||
pub(crate) fn install_host_drop_forwarder() {
|
||||
let Ok(url) = std::env::var("REIMS_GO_DROP_URL") else {
|
||||
return;
|
||||
};
|
||||
let Ok(token) = std::env::var("REIMS_GO_DROP_TOKEN") else {
|
||||
return;
|
||||
};
|
||||
if token.is_empty() || token.contains(['\r', '\n']) || DROP_TX.get().is_some() {
|
||||
return;
|
||||
}
|
||||
let Some((addr, path)) = parse_loopback_drop_url(&url) else {
|
||||
log::warn!(target: "reims_vgpu_window", "ignoring invalid REIMS_GO_DROP_URL");
|
||||
return;
|
||||
};
|
||||
let (tx, rx) = mpsc::sync_channel(16);
|
||||
match std::thread::Builder::new()
|
||||
.name("reims-vgpu.drop".into())
|
||||
.spawn(move || {
|
||||
for payload in rx {
|
||||
if let Err(err) = post_loopback_drop(addr, &path, &token, &payload) {
|
||||
log::warn!(target: "reims_vgpu_window", "could not forward file drop: {err}");
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Ok(_) => {
|
||||
let _ = DROP_TX.set(tx);
|
||||
}
|
||||
Err(err) => log::warn!(target: "reims_vgpu_window", "could not start drop worker: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Enqueues a drop without waiting for network I/O or queue space on the UI thread.
|
||||
pub(crate) fn submit(payload: DropPayload) {
|
||||
if let Some(tx) = DROP_TX.get()
|
||||
&& let Err(TrySendError::Full(_)) = tx.try_send(payload)
|
||||
{
|
||||
log::warn!(target: "reims_vgpu_window", "file drop queue is full");
|
||||
}
|
||||
}
|
||||
|
||||
/// Posts one complete JSON payload to the authenticated IPv4 loopback bridge.
|
||||
fn post_loopback_drop(
|
||||
addr: SocketAddr,
|
||||
path: &str,
|
||||
token: &str,
|
||||
payload: &DropPayload,
|
||||
) -> io::Result<()> {
|
||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_millis(500))?;
|
||||
stream.set_write_timeout(Some(Duration::from_millis(2000)))?;
|
||||
let body = encode_drop_json(payload);
|
||||
write!(
|
||||
stream,
|
||||
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\n\
|
||||
Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
)?;
|
||||
stream.write_all(body.as_bytes())
|
||||
}
|
||||
|
||||
/// Offline tests for window drops and the host bridge protocol.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
use std::net::TcpListener;
|
||||
|
||||
/// Guest image offset from the window edges.
|
||||
const IMAGE: Rect = Rect { x: 10.0, y: 20.0, width: 40.0, height: 80.0 };
|
||||
|
||||
/// Coordinates use half-open image bounds and clamp outside those bounds.
|
||||
#[test]
|
||||
fn normalizes_window_points() {
|
||||
for (point, expected) in [
|
||||
((20.0, 80.0), (0.25, 0.75, true)),
|
||||
((10.0, 20.0), (0.0, 0.0, true)),
|
||||
((50.0, 100.0), (1.0, 1.0, false)),
|
||||
((0.0, 120.0), (0.0, 1.0, false)),
|
||||
] {
|
||||
assert_eq!(normalize_point(Some(point), IMAGE), expected);
|
||||
}
|
||||
let center = (0.5, 0.5, false);
|
||||
for point in [None, Some((f64::NAN, 40.0)), Some((20.0, f64::INFINITY))] {
|
||||
assert_eq!(normalize_point(point, IMAGE), center);
|
||||
}
|
||||
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
for image in [Rect { width: bad, ..IMAGE }, Rect { height: bad, ..IMAGE }] {
|
||||
assert_eq!(normalize_point(Some((20.0, 80.0)), image), center);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Position events override file and completion coordinates, retaining file order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn batch_completes_with_latest_position() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.begin();
|
||||
batch.file("first".into(), Some((50.0, 100.0)));
|
||||
batch.position(20.0, 80.0);
|
||||
batch.position(f64::NAN, 90.0);
|
||||
batch.file("second".into(), Some((40.0, 30.0)));
|
||||
let p = batch.complete(42, IMAGE, Some((30.0, 60.0))).expect("two files");
|
||||
assert_eq!(p.display_index, 42);
|
||||
assert_eq!(p.paths, ["first", "second"]);
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
assert!(batch.complete(42, IMAGE, None).is_none());
|
||||
}
|
||||
|
||||
/// Missing begin, invalid file coordinates, completion fallback and reset are independent.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn handles_partial_batches() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.file("".into(), Some((10.0, 20.0)));
|
||||
batch.file("first".into(), Some((1.0, f64::NAN)));
|
||||
batch.file("second".into(), Some((20.0, 80.0)));
|
||||
batch.file("third".into(), Some((40.0, 30.0)));
|
||||
let p = batch.complete(1, IMAGE, None).expect("file-only drop");
|
||||
assert_eq!(p.paths, ["first", "second", "third"]);
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
batch.file("abandoned".into(), Some((20.0, 80.0)));
|
||||
batch.begin();
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.file("closed".into(), Some((20.0, 80.0)));
|
||||
batch.reset();
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.position(20.0, 80.0);
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.file("next".into(), None);
|
||||
let p = batch.complete(2, IMAGE, Some((60.0, 60.0))).expect("fresh drop");
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (1.0, 0.5, false));
|
||||
}
|
||||
|
||||
/// Oversized drops retain the first 256 paths in order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn caps_paths() {
|
||||
let mut batch = DropBatch::default();
|
||||
for i in 0..260 {
|
||||
batch.file(i.to_string(), None);
|
||||
}
|
||||
let p = batch.complete(0, IMAGE, None).expect("bounded drop");
|
||||
assert_eq!(p.paths, (0..256).map(|i| i.to_string()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// URL drops keep their position and subsequent batches join chunks in order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn collects_url_and_multiline_text() {
|
||||
let mut batch = DropBatch::default();
|
||||
let url = "https://example.org/路径";
|
||||
batch.text(url.into(), Some((20.0, 80.0)));
|
||||
let p = batch.complete(1, IMAGE, None).expect("URL drop");
|
||||
assert_eq!(p.text.as_deref(), Some(url));
|
||||
assert!(p.paths.is_empty());
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
|
||||
batch.text("abandoned".into(), None);
|
||||
batch.begin();
|
||||
batch.text("one\ntwo".into(), None);
|
||||
batch.text(String::new(), None);
|
||||
batch.text("three".into(), None);
|
||||
let p = batch.complete(1, IMAGE, None).expect("multiline drop");
|
||||
assert_eq!(p.text.as_deref(), Some("one\ntwo\nthree"));
|
||||
}
|
||||
|
||||
/// A split UTF-8 character ends collection even when a smaller chunk would fit.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn truncates_text_at_utf8_boundary() {
|
||||
let mut batch = DropBatch::default();
|
||||
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 6);
|
||||
batch.text(prefix.clone(), None);
|
||||
batch.text("界界".into(), None);
|
||||
batch.text("x".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("bounded text drop");
|
||||
assert_eq!(p.text, Some(format!("{prefix}\n界")));
|
||||
|
||||
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 3);
|
||||
batch.text(prefix.clone(), None);
|
||||
batch.text("界".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("two bytes remaining");
|
||||
assert_eq!(p.text, Some(prefix));
|
||||
}
|
||||
|
||||
/// Files take precedence over text regardless of arrival order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn files_take_precedence() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.text("before".into(), None);
|
||||
batch.file("path".into(), None);
|
||||
batch.text("after".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("mixed drop");
|
||||
assert_eq!(p.paths, ["path"]);
|
||||
assert_eq!(p.text, None);
|
||||
assert!(batch.complete(0, IMAGE, None).is_none());
|
||||
}
|
||||
|
||||
/// Text JSON preserves Unicode and escapes quotes, backslashes and newlines.
|
||||
#[test]
|
||||
fn encodes_json_text() {
|
||||
let p = DropPayload {
|
||||
text: Some("你好 \"\\\n".into()),
|
||||
paths: Vec::new(),
|
||||
..sample()
|
||||
};
|
||||
assert_eq!(encode_drop_json(&p), concat!(
|
||||
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"#,
|
||||
r#""text":"你好 \"\\\n"}"#,
|
||||
));
|
||||
}
|
||||
|
||||
/// An example drop containing Unicode, delimiters and control characters.
|
||||
fn sample() -> DropPayload {
|
||||
DropPayload {
|
||||
display_index: 17,
|
||||
norm_x: 0.25,
|
||||
norm_y: 0.75,
|
||||
in_image: true,
|
||||
text: None,
|
||||
paths: vec![r"D:\Downloads\测试.pdf".into(), "\"\u{8}\u{c}\n\r\t\0\u{10}".into()],
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks UTF-8 preservation and each class of RFC 8259 escape.
|
||||
#[test]
|
||||
fn encodes_json_paths() {
|
||||
assert_eq!(encode_drop_json(&sample()), concat!(
|
||||
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"paths":["#,
|
||||
r#""D:\\Downloads\\测试.pdf","\"\b\f\n\r\t\u0000\u0010"]}"#,
|
||||
));
|
||||
}
|
||||
|
||||
/// Only the literal loopback host, a numeric nonzero port and a safe path are accepted.
|
||||
#[test]
|
||||
fn validates_loopback_urls() {
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 42));
|
||||
assert_eq!(parse_loopback_drop_url("http://127.0.0.1:42"), Some((addr, "/v1/host-drop".into())));
|
||||
assert_eq!(parse_loopback_drop_url("http://127.0.0.1:42/drop?q=1"), Some((addr, "/drop?q=1".into())));
|
||||
for raw in [
|
||||
"https://127.0.0.1:42/drop", "http://localhost:42/drop", "http://127.0.0.2:42/drop",
|
||||
"http://[::1]:42/drop", "http://127.0.0.1:/drop", "http://127.0.0.1:0/drop",
|
||||
"http://127.0.0.1:65536/drop", "http://127.0.0.1:+42/drop", "http://127.0.0.1:42@evil/drop",
|
||||
"http://127.0.0.1:42/a b", "http://127.0.0.1:42/a\rheader", "http://127.0.0.1:42/a\nheader",
|
||||
" http://127.0.0.1:42", "http://127.0.0.1:42/drop\r\n",
|
||||
] {
|
||||
assert!(parse_loopback_drop_url(raw).is_none(), "{raw:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A real loopback peer receives the authenticated request and exact UTF-8 byte count.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn posts_the_complete_drop_to_loopback() -> io::Result<()> {
|
||||
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let payload = sample();
|
||||
post_loopback_drop(listener.local_addr()?, "/custom/drop", "test-token", &payload)?;
|
||||
let (mut stream, _) = listener.accept()?;
|
||||
stream.set_nonblocking(false)?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
let mut request = String::new();
|
||||
stream.read_to_string(&mut request)?;
|
||||
let (headers, body) = request.split_once("\r\n\r\n").expect("HTTP headers");
|
||||
assert_eq!(headers.lines().next(), Some("POST /custom/drop HTTP/1.1"));
|
||||
for field in ["Host: 127.0.0.1", "Authorization: Bearer test-token",
|
||||
"Content-Type: application/json", "Connection: close"] {
|
||||
assert!(headers.lines().any(|line| line == field), "{field}");
|
||||
}
|
||||
assert!(headers.lines().any(|line| line == format!("Content-Length: {}", body.len())));
|
||||
assert_eq!(body, encode_drop_json(&payload));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,6 @@
|
||||
//! no window ever captures the keyboard or the pointer ([`crate::capture`]). `1`, `true`,
|
||||
//! `yes` or `on` turns it on. Default: [`CAPTURE_DEFAULT`]. reims-ctl sets it from a VM's
|
||||
//! settings.
|
||||
//! - `REIMS_VGPU_WINDOW_FIXED_MODE`: `1`, `true`, `yes` or `on`, in any case, decouples the
|
||||
//! guest's display mode from the window's pixel size so the display keeps offering the
|
||||
//! configured resolution (e.g. 5120x2880 HiDPI supersampled into a 4K borderless window) and
|
||||
//! scales the frame on the GPU. Default: off.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -29,8 +25,6 @@ pub const SCREENS_VAR: &str = "REIMS_VGPU_WINDOW_SCREENS";
|
||||
pub const IMPL_VAR: &str = "REIMS_VGPU_WINDOW_IMPL";
|
||||
/// The capture switch's variable.
|
||||
pub const CAPTURE_VAR: &str = "REIMS_VGPU_WINDOW_CAPTURE";
|
||||
/// The fixed guest mode switch's variable.
|
||||
pub const FIXED_MODE_VAR: &str = "REIMS_VGPU_WINDOW_FIXED_MODE";
|
||||
|
||||
/// Whether a click into the image captures input where the capture switch is unset.
|
||||
pub const CAPTURE_DEFAULT: bool = true;
|
||||
@@ -46,8 +40,6 @@ pub struct Settings {
|
||||
pub window_impl: WindowImpl,
|
||||
/// Whether a click into the image captures input; off, nothing ever does.
|
||||
pub capture: bool,
|
||||
/// Keep offering the configured guest resolution instead of following the window's pixels.
|
||||
pub fixed_mode: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -57,7 +49,6 @@ impl Default for Settings {
|
||||
screens: Vec::new(),
|
||||
window_impl: WindowImpl::AppKit,
|
||||
capture: CAPTURE_DEFAULT,
|
||||
fixed_mode: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,11 +116,6 @@ fn parse_screens(value: &str) -> Option<Vec<usize>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether fixed guest mode is on (`1`, `true`, `yes` or `on`, in any case); default off.
|
||||
pub fn parse_fixed_mode(value: Option<&str>) -> bool {
|
||||
value.is_some_and(parse_switch)
|
||||
}
|
||||
|
||||
/// The process's settings, read from its environment the first time they are asked for. A
|
||||
/// value that is not UTF-8 counts as unset.
|
||||
pub fn settings() -> &'static Settings {
|
||||
@@ -140,7 +126,6 @@ pub fn settings() -> &'static Settings {
|
||||
Settings {
|
||||
window_impl: parse_impl(var(IMPL_VAR).as_deref()),
|
||||
capture: parse_capture(var(CAPTURE_VAR).as_deref()),
|
||||
fixed_mode: parse_fixed_mode(var(FIXED_MODE_VAR).as_deref()),
|
||||
..parse(borderless.as_deref(), screens.as_deref())
|
||||
}
|
||||
})
|
||||
|
||||
@@ -64,8 +64,6 @@ pub mod scroll;
|
||||
// The SDL3 window: Linux's and Windows's (`native/sdl_thread.rs`), and macOS's with the
|
||||
// `macos-sdl` feature, behind `REIMS_VGPU_WINDOW_IMPL`.
|
||||
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
|
||||
mod drop;
|
||||
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
|
||||
mod sdl;
|
||||
|
||||
pub use config::{
|
||||
|
||||
@@ -657,8 +657,6 @@ fn ask_in_a_dialog(id: u64, ids: Vec<u64>) {
|
||||
super::ui::post(move || {
|
||||
let parent = shell::with_shell(id, |s| (!s.closed).then_some(s.sdl)).flatten();
|
||||
let answer = match parent {
|
||||
#[cfg(target_os = "windows")]
|
||||
Some(_) if super::super::windows::request_client_close() => Answer::Delegated,
|
||||
Some(parent) => question(parent),
|
||||
None => Answer::Cancel,
|
||||
};
|
||||
|
||||
@@ -183,9 +183,6 @@ fn start_video() -> bool {
|
||||
);
|
||||
return false;
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
super::super::windows::install_unicode_input_hook();
|
||||
crate::drop::install_host_drop_forwarder();
|
||||
// SAFETY: SDL's video runs.
|
||||
let kind = unsafe { SDL_RegisterEvents(1) };
|
||||
WAKE.store(kind, Ordering::Release);
|
||||
|
||||
@@ -42,28 +42,18 @@
|
||||
//! taskbar then goes to the bottom of the z-order while the window is active, and that taking
|
||||
//! the mark away leaves the window to the shell's own detection.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::ffi::c_void;
|
||||
use std::io::Write;
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::process::Command;
|
||||
use std::ptr::{NonNull, null, null_mut};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
|
||||
use std::time::Duration;
|
||||
|
||||
use sdl3_sys::everything::{
|
||||
MSG as SDL_MSG, SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties,
|
||||
SDL_PROP_WINDOW_WIN32_HWND_POINTER, SDL_SetWindowsMessageHook, SDL_WINDOW_FULLSCREEN,
|
||||
SDL_Window,
|
||||
SDL_GetPointerProperty, SDL_GetWindowFlags, SDL_GetWindowProperties,
|
||||
SDL_PROP_WINDOW_WIN32_HWND_POINTER, SDL_WINDOW_FULLSCREEN, SDL_Window,
|
||||
};
|
||||
use windows_sys::Win32::Foundation::{FALSE, HWND, RPC_E_CHANGED_MODE, S_FALSE, S_OK, TRUE};
|
||||
use windows_sys::Win32::System::Com::{
|
||||
CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx,
|
||||
CoUninitialize,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
|
||||
use windows_sys::Win32::UI::Shell::TaskbarList;
|
||||
use windows_sys::core::{BOOL, GUID, HRESULT};
|
||||
|
||||
@@ -72,219 +62,6 @@ use crate::capture::HostOs;
|
||||
/// The OS whose names the title gives the release chord's keys: Ctrl+Alt+Win (the module doc).
|
||||
pub(super) const HOST_OS: HostOs = HostOs::Windows;
|
||||
|
||||
/// Asks the Reims-Go desktop instance that started this VM to show its
|
||||
/// close dialog. A failed handoff leaves the SDL dialog available.
|
||||
pub(super) fn request_client_close() -> bool {
|
||||
let Some(executable) = std::env::var_os("REIMS_GO_VM_CLOSE_EXE") else {
|
||||
return false;
|
||||
};
|
||||
let Ok(name) = std::env::var("REIMS_GO_VM_CLOSE_NAME") else {
|
||||
return false;
|
||||
};
|
||||
Command::new(executable)
|
||||
.arg(format!("--close-vm={name}"))
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.status()
|
||||
.is_ok_and(|status| status.success())
|
||||
}
|
||||
|
||||
/// Win32 MSG layout matching winuser.h for SDL_SetWindowsMessageHook.
|
||||
#[repr(C)]
|
||||
struct Win32Msg {
|
||||
/// Target window handle.
|
||||
_hwnd: HWND,
|
||||
/// Message identifier (WM_*).
|
||||
message: u32,
|
||||
/// WPARAM.
|
||||
w_param: usize,
|
||||
/// LPARAM.
|
||||
l_param: isize,
|
||||
/// Message timestamp (GetMessageTime).
|
||||
_time: u32,
|
||||
/// Cursor position (POINT).
|
||||
_pt: [i32; 2],
|
||||
}
|
||||
|
||||
/// WM_KEYDOWN.
|
||||
const WM_KEYDOWN: u32 = 0x0100;
|
||||
/// WM_CHAR.
|
||||
const WM_CHAR: u32 = 0x0102;
|
||||
/// WM_SYSKEYDOWN.
|
||||
const WM_SYSKEYDOWN: u32 = 0x0104;
|
||||
/// WM_UNICHAR.
|
||||
const WM_UNICHAR: u32 = 0x0109;
|
||||
/// WM_IME_CHAR.
|
||||
const WM_IME_CHAR: u32 = 0x0286;
|
||||
/// UNICODE_NOCHAR.
|
||||
const UNICODE_NOCHAR: usize = 0xFFFF;
|
||||
/// VK_PROCESSKEY (host IME intercepted key).
|
||||
const VK_PROCESSKEY: u16 = 0x00E5;
|
||||
/// VK_PACKET (SendInput with KEYEVENTF_UNICODE).
|
||||
const VK_PACKET: u16 = 0x00E7;
|
||||
|
||||
/// Non-blocking channel carrying UTF-16 code units from the SDL UI thread to the HTTP forwarder.
|
||||
static UNICODE_TX: OnceLock<SyncSender<u16>> = OnceLock::new();
|
||||
|
||||
thread_local! {
|
||||
/// Whether the most recent WM_KEYDOWN was unmapped (VK_PACKET or VK_PROCESSKEY).
|
||||
static LAST_KEY_UNMAPPED: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Parses a loopback http://127.0.0.1:<port><path> endpoint from REIMS_GO_INPUT_URL.
|
||||
fn parse_loopback_input_url(raw: &str) -> Option<(SocketAddr, String)> {
|
||||
let rest = raw.trim().strip_prefix("http://127.0.0.1:")?;
|
||||
let (port_str, path) = match rest.find('/') {
|
||||
Some(idx) => (&rest[..idx], &rest[idx..]),
|
||||
None => (rest, "/v1/host-text"),
|
||||
};
|
||||
let port: u16 = port_str.parse().ok()?;
|
||||
if port == 0 || path.contains(['\r', '\n', ' ']) {
|
||||
return None;
|
||||
}
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], port));
|
||||
Some((addr, path.to_owned()))
|
||||
}
|
||||
|
||||
/// Installs a Win32 message hook on SDL's UI thread when REIMS_GO_INPUT_URL and
|
||||
/// REIMS_GO_INPUT_TOKEN are set, forwarding non-keyboard WM_CHAR / WM_UNICHAR /
|
||||
/// WM_IME_CHAR text (remote IMEs, dictation, host IME commits) to the local host bridge.
|
||||
pub(super) fn install_unicode_input_hook() {
|
||||
let Ok(url) = std::env::var("REIMS_GO_INPUT_URL") else {
|
||||
return;
|
||||
};
|
||||
let Ok(token) = std::env::var("REIMS_GO_INPUT_TOKEN") else {
|
||||
return;
|
||||
};
|
||||
if token.is_empty() || token.contains(['\r', '\n']) {
|
||||
return;
|
||||
}
|
||||
let Some((addr, path)) = parse_loopback_input_url(&url) else {
|
||||
log::warn!(target: "reims_vgpu_window", "ignoring non-loopback REIMS_GO_INPUT_URL");
|
||||
return;
|
||||
};
|
||||
let (tx, rx) = mpsc::sync_channel::<u16>(512);
|
||||
if UNICODE_TX.set(tx).is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("reims-vgpu.ime".into())
|
||||
.spawn(move || forward_unicode_loop(rx, addr, path, token));
|
||||
// SAFETY: called on SDL's UI thread right after SDL_Init(SDL_INIT_VIDEO).
|
||||
unsafe { SDL_SetWindowsMessageHook(Some(unicode_message_hook), null_mut()) };
|
||||
}
|
||||
|
||||
/// Enqueues a UTF-16 code unit without blocking the Win32 message loop.
|
||||
fn enqueue_utf16(unit: u16) {
|
||||
if unit != 0
|
||||
&& let Some(tx) = UNICODE_TX.get()
|
||||
{
|
||||
let _ = tx.try_send(unit);
|
||||
}
|
||||
}
|
||||
|
||||
/// SDL Win32 message hook: forwards non-physical WM_CHAR / WM_UNICHAR / WM_IME_CHAR
|
||||
/// events to the local input bridge while leaving all physical keyboard events untouched.
|
||||
unsafe extern "C" fn unicode_message_hook(_userdata: *mut c_void, raw_msg: *mut SDL_MSG) -> bool {
|
||||
if raw_msg.is_null() {
|
||||
return true;
|
||||
}
|
||||
// SAFETY: SDL passes a valid pointer to Win32 MSG for the duration of the callback.
|
||||
let msg = unsafe { &*raw_msg.cast::<Win32Msg>() };
|
||||
match msg.message {
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN => {
|
||||
let vk = (msg.w_param & 0xFFFF) as u16;
|
||||
LAST_KEY_UNMAPPED.set(vk == VK_PACKET || vk == VK_PROCESSKEY);
|
||||
true
|
||||
}
|
||||
WM_CHAR => {
|
||||
let unit = (msg.w_param & 0xFFFF) as u16;
|
||||
let scan_code = (msg.l_param.cast_unsigned() >> 16) & 0xFF;
|
||||
// Any WM_CHAR carrying a hardware scan code came from TranslateMessage on
|
||||
// a physical WM_KEYDOWN that SDL already forwarded as a USB HID key.
|
||||
// Never compare msg.time against WM_KEYDOWN.time: TranslateMessage stamps
|
||||
// WM_CHAR with the current GetTickCount(), not the keydown's time.
|
||||
let non_physical = scan_code == 0
|
||||
&& (LAST_KEY_UNMAPPED.get() || unit >= 0x80 || msg.l_param == 0);
|
||||
if non_physical && (unit >= 0x20 || unit == 0x0D || unit == 0x09) {
|
||||
enqueue_utf16(unit);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
WM_IME_CHAR => {
|
||||
let unit = (msg.w_param & 0xFFFF) as u16;
|
||||
if unit >= 0x20 || unit == 0x0D || unit == 0x09 {
|
||||
enqueue_utf16(unit);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
WM_UNICHAR => {
|
||||
if msg.w_param != UNICODE_NOCHAR
|
||||
&& let Ok(code) = u32::try_from(msg.w_param)
|
||||
&& let Some(ch) = char::from_u32(code)
|
||||
&& (ch >= ' ' || ch == '\r' || ch == '\t')
|
||||
{
|
||||
let mut pair = [0u16; 2];
|
||||
for &mut u in ch.encode_utf16(&mut pair) {
|
||||
enqueue_utf16(u);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes UTF-16 code units, coalesces bursts, and POSTs UTF-8 text to the loopback bridge.
|
||||
fn forward_unicode_loop(rx: mpsc::Receiver<u16>, addr: SocketAddr, path: String, token: String) {
|
||||
let mut units: Vec<u16> = Vec::with_capacity(64);
|
||||
loop {
|
||||
let first = match rx.recv() {
|
||||
Ok(u) => u,
|
||||
Err(_) => return,
|
||||
};
|
||||
units.clear();
|
||||
units.push(first);
|
||||
if first != 0x0D {
|
||||
while units.len() < 128 {
|
||||
match rx.recv_timeout(Duration::from_millis(35)) {
|
||||
Ok(u) => {
|
||||
units.push(u);
|
||||
if u == 0x0D {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => break,
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
let text: String = char::decode_utf16(units.iter().copied())
|
||||
.filter_map(Result::ok)
|
||||
.map(|c| if c == '\r' { '\n' } else { c })
|
||||
.collect();
|
||||
if !text.is_empty() {
|
||||
post_loopback_text(addr, &path, &token, &text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends a minimal HTTP/1.1 POST with UTF-8 text to the local host bridge.
|
||||
fn post_loopback_text(addr: SocketAddr, path: &str, token: &str, text: &str) {
|
||||
let Ok(mut stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else {
|
||||
return;
|
||||
};
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_millis(500)));
|
||||
let req = format!(
|
||||
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
text.len()
|
||||
);
|
||||
let _ = stream.write_all(req.as_bytes());
|
||||
let _ = stream.write_all(text.as_bytes());
|
||||
}
|
||||
|
||||
/// The GPU the compositor composites SDL's window on: none known on Windows (the module doc).
|
||||
///
|
||||
/// # Safety
|
||||
|
||||
@@ -83,8 +83,6 @@ pub(crate) struct Shell {
|
||||
density: f64,
|
||||
/// Its input.
|
||||
pub(crate) input: Input,
|
||||
/// Files and coordinates supplied by SDL for the current drop.
|
||||
drop_batch: crate::drop::DropBatch,
|
||||
/// What its OS keeps of it.
|
||||
pub(crate) os: os::State,
|
||||
/// The guest's cursor, built for SDL.
|
||||
@@ -179,7 +177,6 @@ pub(crate) fn open(window: &Arc<Window>) {
|
||||
layout: Layout::default(),
|
||||
density: 1.0,
|
||||
input: opened.input,
|
||||
drop_batch: crate::drop::DropBatch::default(),
|
||||
os: opened.state,
|
||||
cursor: CursorCache::default(),
|
||||
over_image: false,
|
||||
@@ -207,7 +204,6 @@ pub(crate) fn open(window: &Arc<Window>) {
|
||||
pub(crate) fn close(id: u64) {
|
||||
let gone = with_shell(id, |shell| {
|
||||
ended(shell);
|
||||
shell.drop_batch.reset();
|
||||
shell.closed = true;
|
||||
os::close(shell) || shell.released
|
||||
});
|
||||
@@ -316,14 +312,6 @@ fn settled(before: Option<bool>, kind: u32) -> Option<bool> {
|
||||
pub(crate) fn event(event: &SDL_Event) {
|
||||
// SAFETY: every event starts with its type, and each arm reads the variant its type names.
|
||||
let kind = unsafe { event.r#type };
|
||||
let is_drop = [
|
||||
SDL_EVENT_DROP_BEGIN.0,
|
||||
SDL_EVENT_DROP_POSITION.0,
|
||||
SDL_EVENT_DROP_FILE.0,
|
||||
SDL_EVENT_DROP_TEXT.0,
|
||||
SDL_EVENT_DROP_COMPLETE.0,
|
||||
]
|
||||
.contains(&kind);
|
||||
let sdl_id = match kind {
|
||||
k if (SDL_EVENT_WINDOW_FIRST.0..=SDL_EVENT_WINDOW_LAST.0).contains(&k) => unsafe {
|
||||
event.window.windowID.0
|
||||
@@ -336,20 +324,9 @@ pub(crate) fn event(event: &SDL_Event) {
|
||||
event.button.windowID.0
|
||||
},
|
||||
k if k == SDL_EVENT_MOUSE_WHEEL.0 => unsafe { event.wheel.windowID.0 },
|
||||
_ if is_drop => unsafe { event.drop.windowID.0 },
|
||||
_ => return,
|
||||
};
|
||||
let target = if is_drop && sdl_id == 0 {
|
||||
OPEN.with(|open| {
|
||||
let open = open.borrow();
|
||||
let mut live = open.iter().filter(|shell| !shell.closed);
|
||||
let first = live.next()?;
|
||||
live.next().is_none().then(|| first.window.id())
|
||||
})
|
||||
} else {
|
||||
window_of(sdl_id)
|
||||
};
|
||||
let Some(id) = target else {
|
||||
let Some(id) = window_of(sdl_id) else {
|
||||
return;
|
||||
};
|
||||
with_shell(id, |shell| {
|
||||
@@ -413,54 +390,6 @@ impl Shell {
|
||||
self.refresh_cursor();
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_BEGIN.0 => {
|
||||
self.drop_batch.begin();
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_POSITION.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let (x, y) = unsafe { (event.drop.x, event.drop.y) };
|
||||
self.drop_batch.position(f64::from(x), f64::from(y));
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_FILE.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if !drop.data.is_null() {
|
||||
// SAFETY: SDL3 owns this NUL-terminated path for the event's lifetime.
|
||||
let path = unsafe { std::ffi::CStr::from_ptr(drop.data) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self.drop_batch
|
||||
.file(path, Some((f64::from(drop.x), f64::from(drop.y))));
|
||||
}
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_TEXT.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if !drop.data.is_null() {
|
||||
// SAFETY: SDL3 owns this NUL-terminated text for the event's lifetime.
|
||||
let text = unsafe { std::ffi::CStr::from_ptr(drop.data) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self.drop_batch
|
||||
.text(text, Some((f64::from(drop.x), f64::from(drop.y))));
|
||||
}
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_COMPLETE.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if let Some(payload) = self.drop_batch.complete(
|
||||
self.window.port(),
|
||||
self.layout.image,
|
||||
Some((f64::from(drop.x), f64::from(drop.y))),
|
||||
) {
|
||||
crate::drop::submit(payload);
|
||||
}
|
||||
false
|
||||
}
|
||||
_ => os::input_event(self, kind, event),
|
||||
};
|
||||
self.flush();
|
||||
|
||||
@@ -93,8 +93,7 @@ use reims_vgpu_graphics::wire::{
|
||||
RGFX_FEATURE_TEXTURE_DID_MODIFY_DATA, RGFX_FEATURE_UNCHANGING_PAGES,
|
||||
RGFX_FEATURE_UNSHARED_QUEUES, RGFX_FEATURE_UPLOADS_WRITTEN, RGFX_FEATURE_VT_MESSAGES,
|
||||
RGFX_RESOURCE_ID_CHUNK, RGFX_RESOURCE_ID_CHUNKS, RGFX_STATUS_INVALID_ARGUMENT,
|
||||
RGFX_STATUS_CACHE, RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED,
|
||||
RGFX_VIDEO_CAPS_CODECS,
|
||||
RGFX_STATUS_NOT_FOUND, RGFX_STATUS_OK, RGFX_STATUS_REFUSED, RGFX_VIDEO_CAPS_CODECS,
|
||||
RGFX_VIDEO_CAPS_OFFSET, RGFX_VIDEO_CAPS_OUTPUT_CACHED, RGFX_VIDEO_CAPS_VERSION,
|
||||
RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_CODEC_VP9, RGFX_VIDEO_DECODE,
|
||||
RGFX_VIDEO_H264_BASELINE, RGFX_VIDEO_H264_HIGH, RGFX_VIDEO_H264_MAIN, RGFX_VIDEO_HEVC_MAIN,
|
||||
@@ -191,7 +190,6 @@ mod present;
|
||||
mod read;
|
||||
mod rt_window;
|
||||
mod sink;
|
||||
mod snapshot;
|
||||
mod slow_answers;
|
||||
mod summary;
|
||||
mod trip;
|
||||
@@ -1037,7 +1035,6 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
|
||||
let clock = Arc::clone(&platform);
|
||||
create_waits::CreateWaits::new(Box::new(move || clock.clock().now_mono()))
|
||||
},
|
||||
live_log: snapshot::LiveLog::new(count),
|
||||
});
|
||||
let cursors: Vec<Arc<HostCursor>> = (0..count)
|
||||
.map(|display| {
|
||||
@@ -1353,242 +1350,6 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
|
||||
(self.cursors.get(display as usize)).map_or((0, 0), |cursor| cursor.position())
|
||||
})
|
||||
}
|
||||
|
||||
fn quiesce_device(&self) -> Option<Arc<GraphicsControl<P>>> {
|
||||
self.device.quiesce();
|
||||
if let Some(pool) = &self.pool {
|
||||
pool.quiesce();
|
||||
}
|
||||
let control = self.ending.upgrade()?;
|
||||
control.pool.wait_idle();
|
||||
control.icb_worker.flush();
|
||||
let decoder = control.decoder();
|
||||
decoder.flush_workers();
|
||||
decoder.flush_all_surface_caches(&control.device);
|
||||
control.device.wait_idle();
|
||||
Some(control)
|
||||
}
|
||||
|
||||
/// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
|
||||
/// drains pending compiles and workers, flushes dirty device-cached IOSurfaces back to Guest
|
||||
/// RAM, and waits for GPU idle.
|
||||
pub fn quiesce(&self) -> Result<(), Error> {
|
||||
entry::run(|_| {
|
||||
let _ = self.quiesce_device();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Resumes VBLANK and ring service threads after a snapshot completes or aborts.
|
||||
pub fn unquiesce(&self) {
|
||||
entry::run(|_| {
|
||||
self.device.unquiesce();
|
||||
});
|
||||
}
|
||||
|
||||
/// Serializes the full graphics device state (device rings/displays/queues, Shared Pool,
|
||||
/// Private Blocks + VRAM, live Metal/Vulkan objects, timeline events, and standalone GPU
|
||||
/// buffers/textures) into a portable byte blob for suspend-to-disk.
|
||||
pub fn snapshot_save(&self) -> Result<Vec<u8>, Error> {
|
||||
entry::run(|_| {
|
||||
let t0 = std::time::Instant::now();
|
||||
let control = self.quiesce_device().ok_or(Error::HostResources)?;
|
||||
let decoder = control.decoder();
|
||||
|
||||
let mut device_snapshot = Vec::new();
|
||||
self.device.export_snapshot().encode(&mut device_snapshot);
|
||||
let shared_pool = self.pool.as_ref().map(|p| p.export_snapshot()).transpose()?;
|
||||
let private_blocks = control.private_blocks.export_snapshot()?;
|
||||
let id_chunks = decoder.export_id_chunks();
|
||||
let (live_records, surface_pages, standalone_tex_set, presented_surfaces) =
|
||||
control.live_log.export();
|
||||
|
||||
let mut known_ranges: Vec<(u64, u64)> = Vec::new();
|
||||
if let Some(sp) = &shared_pool {
|
||||
for piece in &sp.pieces {
|
||||
if piece.gpu_address != 0 {
|
||||
known_ranges.push((piece.gpu_address, piece.len));
|
||||
}
|
||||
}
|
||||
}
|
||||
for pb in &private_blocks.blocks {
|
||||
if pb.gpu_address != 0 {
|
||||
known_ranges.push((pb.gpu_address, pb.len));
|
||||
}
|
||||
}
|
||||
let live_values = decoder
|
||||
.export_live_values(&control.device, &known_ranges, &standalone_tex_set)
|
||||
.map_err(|_| Error::HostResources)?;
|
||||
let mut standalone_textures: Vec<u64> = standalone_tex_set.into_iter().collect();
|
||||
standalone_textures.sort_unstable();
|
||||
|
||||
let snap = snapshot::VgpuSnapshot {
|
||||
device_snapshot,
|
||||
shared_pool,
|
||||
private_blocks,
|
||||
id_chunks,
|
||||
surface_pages,
|
||||
live_records,
|
||||
standalone_textures,
|
||||
presented_surfaces,
|
||||
live_values,
|
||||
};
|
||||
let t_exp = t0.elapsed();
|
||||
let n_tex = snap.live_values.textures.len();
|
||||
let tex_bytes: usize = snap.live_values.textures.iter().map(|(_, b)| b.len()).sum();
|
||||
let n_caches = snap.live_values.surface_caches.len();
|
||||
let cache_bytes: usize = snap
|
||||
.live_values
|
||||
.surface_caches
|
||||
.iter()
|
||||
.map(|(_, b)| b.len())
|
||||
.sum();
|
||||
let encoded = snap.encode();
|
||||
log::info!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_save done in {:.2}s (export={:.2}s): total={} B, textures={} ({:.1} MiB), unattached_caches={} ({:.1} MiB)",
|
||||
t0.elapsed().as_secs_f64(),
|
||||
t_exp.as_secs_f64(),
|
||||
encoded.len(),
|
||||
n_tex,
|
||||
tex_bytes as f64 / (1024.0 * 1024.0),
|
||||
n_caches,
|
||||
cache_bytes as f64 / (1024.0 * 1024.0),
|
||||
);
|
||||
Ok(encoded)
|
||||
})
|
||||
}
|
||||
|
||||
/// Restores the full graphics device state from a snapshot produced by [`Self::snapshot_save`]
|
||||
/// in a fresh host process.
|
||||
pub fn snapshot_load(&self, data: &[u8]) -> Result<(), Error> {
|
||||
entry::run(|_| {
|
||||
let snap = snapshot::VgpuSnapshot::decode(data).ok_or(Error::InvalidArgument)?;
|
||||
let mut dev_slice: &[u8] = &snap.device_snapshot;
|
||||
let dev_snap = reims_vgpu_graphics::snapshot::DeviceSnapshot::decode(&mut dev_slice)
|
||||
.ok_or(Error::InvalidArgument)?;
|
||||
if !dev_slice.is_empty() {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
let control = self.ending.upgrade().ok_or(Error::HostResources)?;
|
||||
|
||||
// Keep device rings and VBLANK paused until full object table replay finishes.
|
||||
// Any error below returns without unquiescing so partial restores never report success.
|
||||
self.device.quiesce();
|
||||
|
||||
match (&self.pool, &snap.shared_pool) {
|
||||
(Some(pool), Some(ps)) => pool.import_snapshot(ps)?,
|
||||
(None, Some(ps)) if !ps.pieces.is_empty() => return Err(Error::HostResources),
|
||||
_ => {}
|
||||
}
|
||||
control.private_blocks.import_snapshot(&snap.private_blocks)?;
|
||||
|
||||
self.device.import_snapshot(&dev_snap).map_err(|_| Error::InvalidArgument)?;
|
||||
control
|
||||
.decoder()
|
||||
.set_managed_at_copy(dev_snap.driver_features & RGFX_FEATURE_MANAGED_AT_COPY != 0);
|
||||
|
||||
{
|
||||
let decoder = control.decoder();
|
||||
decoder.import_id_chunks(&snap.id_chunks);
|
||||
for sp in &snap.surface_pages {
|
||||
decoder
|
||||
.replay_surface_pages(
|
||||
&control.device,
|
||||
&sp.pages,
|
||||
&sp.runs,
|
||||
sp.flags,
|
||||
sp.layout,
|
||||
)
|
||||
.map_err(|_| Error::HostResources)?;
|
||||
}
|
||||
}
|
||||
|
||||
let mut records = snap.live_records;
|
||||
records.sort_by_key(|r| r.seq);
|
||||
for rec in &records {
|
||||
control.replay_record(rec)?;
|
||||
}
|
||||
|
||||
let n_surface_pages = snap.surface_pages.len();
|
||||
let n_records = records.len();
|
||||
let standalone_set: std::collections::HashSet<u64> =
|
||||
snap.standalone_textures.into_iter().collect();
|
||||
control.live_log.restore(
|
||||
records,
|
||||
snap.surface_pages,
|
||||
standalone_set,
|
||||
snap.presented_surfaces.clone(),
|
||||
);
|
||||
|
||||
// Wait for any replay-time buffer zeroing to finish, then upload exact saved memory!
|
||||
control.device.wait_idle();
|
||||
if let (Some(pool), Some(ps)) = (&self.pool, &snap.shared_pool) {
|
||||
pool.restore_bytes(ps)?;
|
||||
}
|
||||
control.private_blocks.restore_bytes(&snap.private_blocks)?;
|
||||
|
||||
{
|
||||
let decoder = control.decoder();
|
||||
decoder
|
||||
.import_live_values(&control.device, &snap.live_values)
|
||||
.map_err(|_| Error::HostResources)?;
|
||||
for qs in &dev_snap.queues {
|
||||
let q = reims_vgpu_graphics::wire::RgfxQueueCreate::read_from_bytes(
|
||||
&qs.create_bytes,
|
||||
)
|
||||
.map_err(|_| Error::InvalidArgument)?;
|
||||
let watermark = qs.taken_seqno.max(qs.taken_buffer_seqno);
|
||||
if watermark > 0 {
|
||||
log::info!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"restoring queue {:#x} watermark={watermark} (taken={} buf={})",
|
||||
q.obj_id, qs.taken_seqno, qs.taken_buffer_seqno
|
||||
);
|
||||
decoder.restore_queue_watermark(q.obj_id, watermark);
|
||||
control.presents.restore_finished(q.obj_id, watermark);
|
||||
}
|
||||
}
|
||||
for (display, &iosurface_id) in snap.presented_surfaces.iter().enumerate() {
|
||||
if iosurface_id == 0 {
|
||||
continue;
|
||||
}
|
||||
let presented = control.presented.get(display).ok_or(Error::InvalidArgument)?;
|
||||
let found = decoder.surface_present(iosurface_id).ok_or_else(|| {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_load: presented surface {iosurface_id} for display {display} missing after replay"
|
||||
);
|
||||
Error::HostResources
|
||||
})?;
|
||||
let shown = presented.hold(
|
||||
found.texture,
|
||||
found.view,
|
||||
found.span,
|
||||
found.queued,
|
||||
);
|
||||
let _ = presented.swap(iosurface_id, Some(shown));
|
||||
}
|
||||
}
|
||||
|
||||
log::info!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_load summary: dev_queues={} surface_pages={} records={} presented={:?} events={} shared_events={} bufs={} texs={} caches={}",
|
||||
dev_snap.queues.len(),
|
||||
n_surface_pages,
|
||||
n_records,
|
||||
snap.presented_surfaces,
|
||||
snap.live_values.events.len(),
|
||||
snap.live_values.shared_events.len(),
|
||||
snap.live_values.buffers.len(),
|
||||
snap.live_values.textures.len(),
|
||||
snap.live_values.surface_caches.len(),
|
||||
);
|
||||
control.device.wait_idle();
|
||||
self.device.unquiesce();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> Drop for GraphicsDevice<P> {
|
||||
@@ -1782,7 +1543,6 @@ struct GraphicsControl<P: ApiPlatform> {
|
||||
/// The pipeline creates waiting for their replies, timed for the counts line
|
||||
/// (`create_waits`): from their take ([`Self::handle_stage3`]) to their reply's post.
|
||||
create_waits: create_waits::CreateWaits,
|
||||
live_log: snapshot::LiveLog,
|
||||
}
|
||||
|
||||
/// The longest `COMMAND_BUFFER` message, in bytes, that is walked and committed on its queue's
|
||||
@@ -2436,7 +2196,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
self.pending.cancel_context(context);
|
||||
let (dropped, closed) = decoder.close_tables(&self.device, context);
|
||||
self.pool.context_closed(context);
|
||||
self.live_log.close_context(context);
|
||||
self.presents.context_gone(context);
|
||||
self.queue_sinks
|
||||
.write()
|
||||
@@ -2527,7 +2286,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
}
|
||||
// And every Private block, the objects in them dropped.
|
||||
self.private_blocks.reset();
|
||||
self.live_log.reset();
|
||||
self.presents.reset();
|
||||
self.queue_sinks.write().clear();
|
||||
for color in &self.colors {
|
||||
@@ -2590,7 +2348,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
answer.answer(RGFX_STATUS_REFUSED);
|
||||
return;
|
||||
}
|
||||
self.live_log.forget_surface_pages(release.offset);
|
||||
// Once no display shows or draws a surface over the block, with what was in flight then.
|
||||
let m = Arc::clone(&marks);
|
||||
let in_flight = decoder.in_flight_read(release.context);
|
||||
@@ -2891,10 +2648,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
let _carried = me.reset_gate.read_recursive();
|
||||
let status = (me.decoder())
|
||||
.carry_out_surface_pages(&me.device, &pages, &runs, flags, layout, &settle);
|
||||
if matches!(status, Some(RGFX_STATUS_OK | RGFX_STATUS_CACHE)) {
|
||||
me.live_log
|
||||
.record_surface_pages(pages, runs.clone(), flags, layout);
|
||||
}
|
||||
// Where the guest took IMPORT_ADDRESSES_LATER, answered now, with no address,
|
||||
// before the view is made and given one below.
|
||||
let answer = match status {
|
||||
@@ -2993,197 +2746,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
/// ([`Host::command_buffer`]), which goes to the buffer's lane as it is, with `claim`, its
|
||||
/// queue's claim on its messages, which a buffer carried out here lets go once begun
|
||||
/// ([`Self::carry_out`]).
|
||||
/// Synchronously replays one recorded stage-3 object creation or persistent mutation
|
||||
/// during [`GraphicsDevice::snapshot_load`] without emitting wire completion replies.
|
||||
fn replay_record(&self, rec: &snapshot::LogRecord) -> Result<(), Error> {
|
||||
let mut decoder = self
|
||||
.decoders
|
||||
.sender(Some(rec.context), Sinks::default());
|
||||
match rec.msg_type {
|
||||
snapshot::LOG_TAG_ASSEMBLED_LIBRARY => {
|
||||
let guest_key: Option<decode::LibraryKey> = if rec.bytes.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
rec.bytes
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidArgument)?,
|
||||
)
|
||||
};
|
||||
let job = decoder.prepare_library_bytes(
|
||||
rec.obj_id,
|
||||
rec.inline_bytes.clone(),
|
||||
guest_key,
|
||||
);
|
||||
let made = refusing(|| make_library::<P>(&self.device, &job)).map_err(|raise| {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: library seq={} obj={:#x} raised: {raise}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
Error::HostResources
|
||||
})?;
|
||||
let status = decoder.finish_library(made);
|
||||
if status != RGFX_STATUS_OK {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: library seq={} obj={:#x} failed status={status}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
return Err(Error::HostResources);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
RGFX_CMD_LIBRARY_LOOKUP => {
|
||||
let (_, status) = decoder.lookup_library(&rec.bytes);
|
||||
if status != RGFX_STATUS_OK {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: library lookup seq={} obj={:#x} failed status={status}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
return Err(Error::HostResources);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
RGFX_CMD_RENDER_PIPELINE_CREATE
|
||||
| RGFX_CMD_MESH_RENDER_PIPELINE_CREATE
|
||||
| RGFX_CMD_COMPUTE_PIPELINE_CREATE => {
|
||||
let job = decoder.prepare_pipeline(&rec.bytes).map_err(|e| {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: prepare_pipeline seq={} obj={:#x} failed: {e:?}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
Error::HostResources
|
||||
})?;
|
||||
let seen_from = job.seen_from;
|
||||
let (compiled, _) =
|
||||
stage::making(|| compile_refusing::<P>(&self.device, job));
|
||||
let _ = compiled.finish(0);
|
||||
let ok = compiled.is_made();
|
||||
decoder.finish_pipeline_if(compiled, Some(seen_from), || true);
|
||||
if !ok {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: pipeline compile seq={} type={:#x} obj={:#x} refused",
|
||||
rec.seq, rec.msg_type, rec.obj_id
|
||||
);
|
||||
return Err(Error::HostResources);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
RGFX_CMD_RATE_MAP_CREATE | RGFX_CMD_RATE_MAP_RESET => {
|
||||
let reset = rec.msg_type == RGFX_CMD_RATE_MAP_RESET;
|
||||
match refusing(|| decoder.rate_map_state(&self.device, &rec.bytes, reset)) {
|
||||
Ok(Some(st)) if st.status == RGFX_STATUS_OK => Ok(()),
|
||||
other => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: rate_map seq={} obj={:#x} failed: {other:?}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
Err(Error::HostResources)
|
||||
}
|
||||
}
|
||||
}
|
||||
RGFX_CMD_FUNCTION_HANDLE_CREATE | RGFX_CMD_FUNCTION_TABLE_CREATE => {
|
||||
match refusing(|| decoder.function_pointer_state(&rec.bytes)) {
|
||||
Ok(Some(st)) if st.status == RGFX_STATUS_OK => Ok(()),
|
||||
other => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: function_pointer seq={} obj={:#x} failed: {other:?}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
Err(Error::HostResources)
|
||||
}
|
||||
}
|
||||
}
|
||||
RGFX_CMD_DYNAMIC_LIBRARY_CREATE => {
|
||||
match refusing(|| decoder.dynamic_library_create(&self.device, &rec.bytes)) {
|
||||
Ok(Some((_, RGFX_STATUS_OK))) => Ok(()),
|
||||
other => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: dynamic_library seq={} obj={:#x} failed: {other:?}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
Err(Error::HostResources)
|
||||
}
|
||||
}
|
||||
}
|
||||
RGFX_CMD_SHARED_EVENT_NAME => {
|
||||
let listen_queue = RgfxSharedEventName::read_from_prefix(&rec.bytes)
|
||||
.map_err(|_| Error::InvalidArgument)?
|
||||
.0
|
||||
.listen_queue_obj_id;
|
||||
let listen = self.presents.queue_poster(listen_queue).map(|ring| {
|
||||
Arc::new(move |m: &RgfxEventSignalled| ring.try_post(m.as_bytes()))
|
||||
as ListenSink
|
||||
});
|
||||
let (_, status) = decoder.name_shared_event(&rec.bytes, listen);
|
||||
if status != RGFX_STATUS_OK {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: shared_event_name seq={} obj={:#x} failed status={status}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
return Err(Error::HostResources);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
RGFX_CMD_SHARED_EVENT_IMPORT => {
|
||||
let listen_queue = RgfxSharedEventName::read_from_prefix(&rec.bytes)
|
||||
.map_err(|_| Error::InvalidArgument)?
|
||||
.0
|
||||
.listen_queue_obj_id;
|
||||
let listen = self.presents.queue_poster(listen_queue).map(|ring| {
|
||||
Arc::new(move |m: &RgfxEventSignalled| ring.try_post(m.as_bytes()))
|
||||
as ListenSink
|
||||
});
|
||||
match decoder.import_shared_event(&rec.bytes, listen) {
|
||||
Some(v) if v.status == RGFX_STATUS_OK => Ok(()),
|
||||
other => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: shared_event_import seq={} obj={:#x} failed: {other:?}",
|
||||
rec.seq, rec.obj_id
|
||||
);
|
||||
Err(Error::HostResources)
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => match refusing(|| decoder.decode(&self.device, &rec.bytes)) {
|
||||
Ok(Ok(())) => {
|
||||
log::debug!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: seq={} ctx={} type={:#x} obj={:#x} -> Ok",
|
||||
rec.seq, rec.context, rec.msg_type, rec.obj_id
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: seq={} ctx={} type={:#x} obj={:#x} decode error: {e:?}",
|
||||
rec.seq, rec.context, rec.msg_type, rec.obj_id
|
||||
);
|
||||
Err(Error::HostResources)
|
||||
}
|
||||
Err(raise) => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"replay_record: seq={} ctx={} type={:#x} obj={:#x} raised: {raise}",
|
||||
rec.seq, rec.context, rec.msg_type, rec.obj_id
|
||||
);
|
||||
Err(Error::HostResources)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_stage3(
|
||||
self: &Arc<Self>,
|
||||
poster: &CompletionPoster,
|
||||
@@ -3191,7 +2753,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
claim: Option<&mut QueueClaim<'_>>,
|
||||
) {
|
||||
let message: &[u8] = &bytes;
|
||||
self.live_log.record_stage3(sender_context(poster, message), message);
|
||||
let r#type = RgfxMsgHeader::read_from_prefix(message).map_or(0, |(h, _)| h.r#type);
|
||||
// A queue's command buffer taken from its ring: the presents' late-show lines keep when
|
||||
// the host first saw it (`present`).
|
||||
@@ -4071,10 +3632,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
"library lookup (object {obj_id:#x}, {size} bytes): {}",
|
||||
if status == RGFX_STATUS_OK { "hit" } else { "miss" }
|
||||
);
|
||||
if status == RGFX_STATUS_OK {
|
||||
self.live_log
|
||||
.record_library_lookup(sender_context(poster, message), message);
|
||||
}
|
||||
if let Some(seqno) = seqno {
|
||||
poster.post(complete(seqno, status).as_bytes());
|
||||
}
|
||||
@@ -4584,15 +4141,7 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
.prepare_library(message)
|
||||
});
|
||||
let job = match start {
|
||||
LibraryStart::Make(job) => {
|
||||
self.live_log.record_library(
|
||||
sender_context(poster, message),
|
||||
job.obj_id,
|
||||
job.bytes.clone(),
|
||||
job.guest_key,
|
||||
);
|
||||
job
|
||||
}
|
||||
LibraryStart::Make(job) => job,
|
||||
LibraryStart::Chunk => return,
|
||||
LibraryStart::Refused { error, answer } => {
|
||||
let (ty, seqno, obj_id) = message_identity(message);
|
||||
@@ -4665,7 +4214,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
return;
|
||||
};
|
||||
if iosurface_id == 0 {
|
||||
self.live_log.record_present(display, 0);
|
||||
let color = staging.lock().take();
|
||||
self.presents
|
||||
.present(display, 0, None, color, answer, Vec::new(), None);
|
||||
@@ -4697,7 +4245,6 @@ impl<P: ApiPlatform> GraphicsControl<P> {
|
||||
owner,
|
||||
queued,
|
||||
}) => {
|
||||
self.live_log.record_present(display, iosurface_id);
|
||||
// The process that made the texture over the surface the display shows owns the
|
||||
// scanout (WindowServer): its compiles go first.
|
||||
self.pool.favour(owner);
|
||||
@@ -5241,7 +4788,6 @@ fn vt_decoders(caps: &RgfxVideoCaps) -> Vec<paravirt::Decoder> {
|
||||
/// gate's ([`reims_vgpu_vulkan::exit_gate`]): the process's exit waits for it, and one called
|
||||
/// once the exit began parks its thread for good, on any thread but the exiting one (as an entry
|
||||
/// does, [`entry`]'s module doc).
|
||||
#[track_caller]
|
||||
fn stepped<T>(f: impl FnOnce() -> T) -> T {
|
||||
let Some(_step) = reims_vgpu_vulkan::exit_gate::step() else {
|
||||
reims_vgpu_vulkan::exit_gate::stay()
|
||||
@@ -5775,35 +5321,19 @@ impl Screen for WindowScreen {
|
||||
/// draw).
|
||||
fn mode(&self) -> Mode {
|
||||
let drawn = *self.shown.drawable.lock();
|
||||
let fixed = reims_vgpu_window::env::settings().fixed_mode;
|
||||
let offered = self
|
||||
.window
|
||||
.offered()
|
||||
.map(|(w, h)| (u64::from(w), u64::from(h)));
|
||||
let raw = if fixed {
|
||||
offered
|
||||
.or_else(|| drawn.map(|d| d.pixels))
|
||||
.unwrap_or((1920, 1080))
|
||||
} else {
|
||||
drawn.map_or_else(|| offered.unwrap_or((1920, 1080)), |d| d.pixels)
|
||||
};
|
||||
let (width, height) = geometry::offered_mode(raw);
|
||||
let (width, height) = geometry::offered_mode(drawn.map_or_else(
|
||||
|| {
|
||||
let (w, h) = self.window.offered().unwrap_or((1920, 1080));
|
||||
(u64::from(w), u64::from(h))
|
||||
},
|
||||
|d| d.pixels,
|
||||
));
|
||||
let clamp = |v: u64| u32::try_from(v.max(1)).unwrap_or(u32::MAX);
|
||||
let clamped_w = clamp(width);
|
||||
let clamped_h = clamp(height);
|
||||
let scale_120ths = drawn.map_or(0, |d| {
|
||||
let eff = if fixed && d.pixels.0 > 0 {
|
||||
d.scale * (f64::from(clamped_w) / f64::from(clamp(d.pixels.0)))
|
||||
} else {
|
||||
d.scale
|
||||
};
|
||||
scale_in_120ths(eff)
|
||||
});
|
||||
Mode {
|
||||
width: clamped_w,
|
||||
height: clamped_h,
|
||||
width: clamp(width),
|
||||
height: clamp(height),
|
||||
refresh_mhz: self.refresh_mhz,
|
||||
scale_120ths,
|
||||
scale_120ths: drawn.map_or(0, |d| scale_in_120ths(d.scale)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -582,17 +582,6 @@ impl CompilePool {
|
||||
self.close();
|
||||
}
|
||||
|
||||
/// Waits until all queued and running compile jobs have finished.
|
||||
pub(crate) fn wait_idle(&self) {
|
||||
let mut state = self.shared.state.lock();
|
||||
while state.waiting() > 0
|
||||
|| state.running.values().copied().sum::<usize>() > 0
|
||||
|| state.prepasses_running > 0
|
||||
{
|
||||
self.shared.waiting.wait(&mut state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the threads once nothing waits; later compiles run where they are handed over.
|
||||
fn close(&self) {
|
||||
self.shared.state.lock().closed = true;
|
||||
@@ -683,8 +672,10 @@ fn run(shared: &Shared, queued: Queued) {
|
||||
ms(ended.saturating_duration_since(started)),
|
||||
);
|
||||
shared.state.lock().ended(of.context(), of.kind);
|
||||
// Wake waiters (pre-pass limit or snapshot quiesce wait_idle).
|
||||
shared.waiting.notify_all();
|
||||
// A thread that found the pre-passes' makes at their most may take the next now.
|
||||
if of.kind == CompileKind::Prepass {
|
||||
shared.waiting.notify_one();
|
||||
}
|
||||
reims_vgpu_vulkan::os::make_ended(ended.saturating_duration_since(started));
|
||||
}
|
||||
|
||||
|
||||
@@ -402,9 +402,9 @@ pub(crate) struct LibraryJob<P: Platform> {
|
||||
pub(crate) obj_id: u64,
|
||||
/// The create's seqno, which its `COMPLETE` carries.
|
||||
pub(crate) seqno: u64,
|
||||
pub(crate) bytes: Vec<u8>,
|
||||
bytes: Vec<u8>,
|
||||
/// The key the guest sent with the bytes.
|
||||
pub(crate) guest_key: Option<LibraryKey>,
|
||||
guest_key: Option<LibraryKey>,
|
||||
slot: Arc<LibrarySlot<P>>,
|
||||
/// The device's resets when it was prepared.
|
||||
resets: u64,
|
||||
@@ -697,29 +697,6 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Prepares a [`LibraryJob`] directly from snapshotted library bytes for silent replay.
|
||||
pub(crate) fn prepare_library_bytes(
|
||||
&self,
|
||||
obj_id: u64,
|
||||
bytes: Vec<u8>,
|
||||
guest_key: Option<LibraryKey>,
|
||||
) -> LibraryJob<P> {
|
||||
let slot = LibrarySlot::new();
|
||||
let resets = {
|
||||
let mut libraries = self.shared.libraries.lock();
|
||||
libraries.making.insert(obj_id, Arc::clone(&slot));
|
||||
libraries.resets
|
||||
};
|
||||
LibraryJob {
|
||||
obj_id,
|
||||
seqno: 0,
|
||||
bytes,
|
||||
guest_key,
|
||||
slot,
|
||||
resets,
|
||||
}
|
||||
}
|
||||
|
||||
/// One `LIBRARY_FROM_REGION` chunk: its bytes are copied out once (so the platform parses
|
||||
/// memory the guest cannot change under it), its ack is written so the guest may reuse the
|
||||
/// block, and the library's whole bytes are handed back once the chunks reach its length. A
|
||||
|
||||
@@ -220,7 +220,6 @@ mod helpers;
|
||||
mod icb;
|
||||
mod lane;
|
||||
mod library;
|
||||
pub(crate) use library::whole_key as whole_library_key;
|
||||
mod managed;
|
||||
mod pipeline_key;
|
||||
pub(crate) mod prepass;
|
||||
@@ -265,7 +264,6 @@ pub(crate) use library::verified_key as test_key;
|
||||
#[cfg(test)]
|
||||
pub(crate) use library::whole_key as test_whole_key;
|
||||
use library::{Libraries, LibraryRef};
|
||||
pub(crate) use library::LibraryKey;
|
||||
pub(crate) use library::{LibraryJob, LibraryStart, MadeLibrary, complete, make_library};
|
||||
use managed::{STORAGE_MODE_MANAGED, storage_mode};
|
||||
pub(crate) use pipeline_key::PipelineKey;
|
||||
@@ -610,16 +608,6 @@ fn new_sampler<P: Platform>(
|
||||
/// A host handle for one guest object, by kind. Later increments read these to
|
||||
/// bind resources into command buffers; this slice only inserts them on a create
|
||||
/// and drops them on a destroy.
|
||||
/// Live dynamic values captured from active GPU objects during a snapshot.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct LiveValues {
|
||||
pub(crate) events: Vec<(u64, u64)>,
|
||||
pub(crate) shared_events: Vec<(u64, u64)>,
|
||||
pub(crate) buffers: Vec<(u64, Vec<u8>)>,
|
||||
pub(crate) textures: Vec<(u64, Vec<u8>)>,
|
||||
pub(crate) surface_caches: Vec<(u64, Vec<u8>)>,
|
||||
}
|
||||
|
||||
enum ObjHandle<P: Platform> {
|
||||
Event(P::Event),
|
||||
Fence(P::Fence),
|
||||
@@ -3550,285 +3538,6 @@ impl<P: Platform> GraphicsDecoder<P> {
|
||||
}
|
||||
|
||||
/// The objects the tables hold (for the tests).
|
||||
/// Flushes all background decoder workers (surface, let-go, close, video) for quiesce.
|
||||
pub(crate) fn flush_workers(&self) {
|
||||
self.shared.surface_worker.flush();
|
||||
self.shared.close_worker.flush();
|
||||
self.shared.let_go_worker.flush();
|
||||
self.shared.video_worker.flush();
|
||||
}
|
||||
|
||||
/// Synchronously downloads every live device-cached IOSurface back to Guest RAM.
|
||||
pub(crate) fn flush_all_surface_caches(&self, device: &P::Device) {
|
||||
use reims_vgpu_vulkan::core::sync::Condvar;
|
||||
let blocks = self.surface_caches.attached_live_blocks();
|
||||
for block in blocks {
|
||||
let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
||||
let p_done = Arc::clone(&pair);
|
||||
let p_fail = Arc::clone(&pair);
|
||||
self.surface_download(
|
||||
device,
|
||||
block,
|
||||
Box::new(move || {
|
||||
*p_done.0.lock() = true;
|
||||
p_done.1.notify_all();
|
||||
}),
|
||||
Box::new(move |_| {
|
||||
*p_fail.0.lock() = true;
|
||||
p_fail.1.notify_all();
|
||||
}),
|
||||
);
|
||||
let mut done = pair.0.lock();
|
||||
while !*done {
|
||||
pair.1.wait(&mut done);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports the resource-ID small-chunk grant table (0 = ungranted, ctx + 1 = granted to ctx).
|
||||
pub(crate) fn export_id_chunks(&self) -> Vec<u32> {
|
||||
self.shared
|
||||
.id_chunks
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|c| c.map_or(0, |ctx| ctx.wrapping_add(1)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Restores the resource-ID small-chunk grant table.
|
||||
pub(crate) fn import_id_chunks(&self, chunks: &[u32]) {
|
||||
let mut guard = self.shared.id_chunks.lock();
|
||||
let n = guard.len().min(chunks.len());
|
||||
for i in 0..n {
|
||||
guard[i] = if chunks[i] == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(chunks[i].wrapping_sub(1))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Replays a `SURFACE_PAGES` registration synchronously without sending a wire reply.
|
||||
/// Restores pre-suspend seqno watermarks for a restored command queue.
|
||||
pub(crate) fn restore_queue_watermark(&self, queue: u64, seqno: u64) {
|
||||
self.shared
|
||||
.surface_order
|
||||
.lock()
|
||||
.restore_queue_watermark(queue, seqno);
|
||||
}
|
||||
|
||||
pub(crate) fn replay_surface_pages(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
pages: &reims_vgpu_graphics::wire::RgfxSurfacePages,
|
||||
runs: &[reims_vgpu_graphics::wire::RgfxPageRun],
|
||||
flags: u32,
|
||||
layout: Option<reims_vgpu_graphics::wire::RgfxSurfacePagesLayout>,
|
||||
) -> Result<(), &'static str> {
|
||||
let settle = self.begin_surface_pages(pages.block_offset);
|
||||
let status = self.carry_out_surface_pages(device, pages, runs, flags, layout, &settle);
|
||||
drop(settle);
|
||||
match status {
|
||||
Some(RGFX_STATUS_OK | RGFX_STATUS_CACHE) => Ok(()),
|
||||
other => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot replay: SURFACE_PAGES block {:#x} failed with status={other:?}",
|
||||
pages.block_offset
|
||||
);
|
||||
Err("surface_pages replay failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports live GPU values (Events, SharedEvents, standalone Buffers & Textures) while quiesced.
|
||||
pub(crate) fn export_live_values(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
known_ranges: &[(u64, u64)],
|
||||
standalone_tex_ids: &std::collections::HashSet<u64>,
|
||||
) -> Result<LiveValues, &'static str> {
|
||||
let mut values = LiveValues::default();
|
||||
let mut first_err: Option<&'static str> = None;
|
||||
let mut contexts: Vec<Arc<Context<P>>> =
|
||||
self.shared.contexts.lock().values().cloned().collect();
|
||||
contexts.sort_by_key(|c| c.id);
|
||||
let in_known = |addr: u64| -> bool {
|
||||
addr != 0
|
||||
&& known_ranges
|
||||
.iter()
|
||||
.any(|&(base, len)| addr >= base && addr < base.saturating_add(len))
|
||||
};
|
||||
for ctx in contexts {
|
||||
ctx.for_each_live(|id, entry| {
|
||||
if first_err.is_some() {
|
||||
return;
|
||||
}
|
||||
match &entry.handle {
|
||||
ObjHandle::Event(ev) => {
|
||||
let val = device.event_signaled_value(ev);
|
||||
if val > 0 {
|
||||
values.events.push((id, val));
|
||||
}
|
||||
}
|
||||
ObjHandle::SharedEvent(se) => {
|
||||
let val = se.signaled_value();
|
||||
if val > 0 {
|
||||
values.shared_events.push((id, val));
|
||||
}
|
||||
}
|
||||
ObjHandle::Buffer(buf) => {
|
||||
if entry.span.is_none()
|
||||
&& entry.ram.is_none()
|
||||
&& !entry.over_cache
|
||||
&& !entry.over_view
|
||||
&& !in_known(buf.gpu_address())
|
||||
{
|
||||
match device.read_standalone_buffer(buf) {
|
||||
Ok(Some(bytes)) => values.buffers.push((id, bytes)),
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_save: buffer {id:#x} readback failed: {e}"
|
||||
);
|
||||
first_err = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ObjHandle::Texture(tex) => {
|
||||
let is_deferred_cache = (entry.over_cache || entry.shape.is_some())
|
||||
&& !entry.over_view
|
||||
&& entry
|
||||
.span
|
||||
.is_some_and(|(at, _)| self.surface_caches.lock().has(at));
|
||||
let is_standalone = standalone_tex_ids.contains(&id)
|
||||
&& !entry.over_cache
|
||||
&& !entry.over_view;
|
||||
if is_standalone || is_deferred_cache {
|
||||
match device.read_standalone_texture(tex) {
|
||||
Ok(Some(bytes)) => values.textures.push((id, bytes)),
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_save: texture {id:#x} readback failed: {e}"
|
||||
);
|
||||
first_err = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
if let Some(e) = first_err {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
values.surface_caches = self.surface_caches.export_unattached(device)?;
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
/// Restores live GPU values onto objects previously replayed into the decoder tables.
|
||||
pub(crate) fn import_live_values(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
values: &LiveValues,
|
||||
) -> Result<(), &'static str> {
|
||||
for &(id, val) in &values.events {
|
||||
let ctx = self
|
||||
.context_state(context_of(id))
|
||||
.ok_or("snapshot_load: missing context for event")?;
|
||||
let ok = ctx
|
||||
.with_live(id, |entry| match &entry.handle {
|
||||
ObjHandle::Event(ev) => device.event_restore_signaled_value(ev, val),
|
||||
_ => false,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_load: failed to restore event {id:#x} value={val}"
|
||||
);
|
||||
return Err("snapshot_load: event value restore failed");
|
||||
}
|
||||
}
|
||||
for &(id, val) in &values.shared_events {
|
||||
let ctx = self
|
||||
.context_state(context_of(id))
|
||||
.ok_or("snapshot_load: missing context for shared event")?;
|
||||
let ok = ctx
|
||||
.with_live(id, |entry| match &entry.handle {
|
||||
ObjHandle::SharedEvent(se) => se.set_signaled_value(val).is_ok(),
|
||||
_ => false,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_load: failed to restore shared event {id:#x} value={val}"
|
||||
);
|
||||
return Err("snapshot_load: shared event value restore failed");
|
||||
}
|
||||
}
|
||||
for (id, bytes) in &values.buffers {
|
||||
let ctx = self
|
||||
.context_state(context_of(*id))
|
||||
.ok_or("snapshot_load: missing context for buffer")?;
|
||||
let ok = ctx
|
||||
.with_live(*id, |entry| match &entry.handle {
|
||||
ObjHandle::Buffer(buf) => device.write_standalone_buffer(buf, bytes),
|
||||
_ => false,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_load: failed to restore buffer {id:#x} ({} bytes)",
|
||||
bytes.len()
|
||||
);
|
||||
return Err("snapshot_load: buffer upload failed");
|
||||
}
|
||||
}
|
||||
self.surface_caches
|
||||
.import_unattached(device, &values.surface_caches)?;
|
||||
for (id, bytes) in &values.textures {
|
||||
let ctx = self
|
||||
.context_state(context_of(*id))
|
||||
.ok_or("snapshot_load: missing context for texture")?;
|
||||
let ok = ctx
|
||||
.with_live(*id, |entry| match &entry.handle {
|
||||
ObjHandle::Texture(tex) => {
|
||||
if !device.write_standalone_texture(tex, bytes) {
|
||||
return false;
|
||||
}
|
||||
if let Some((block, _)) = entry.span
|
||||
&& (entry.over_cache || entry.shape.is_some())
|
||||
{
|
||||
let shape_id = entry.shape.as_ref().map(|s| s.reference.id());
|
||||
self.surface_caches
|
||||
.lock()
|
||||
.mark_restored_texture(block, shape_id);
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_load: failed to restore texture {id:#x} ({} bytes)",
|
||||
bytes.len()
|
||||
);
|
||||
return Err("snapshot_load: texture upload failed");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub fn object_count(&self) -> usize {
|
||||
let contexts: Vec<Arc<Context<P>>> =
|
||||
@@ -6830,11 +6539,6 @@ impl<P: Platform> CompiledPipeline<P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether compilation produced a live pipeline handle (not refused).
|
||||
pub(crate) fn is_made(&self) -> bool {
|
||||
self.handle.is_some()
|
||||
}
|
||||
|
||||
/// A made pipeline and its reflection.
|
||||
fn made(obj_id: u64, handle: ObjHandle<P>, reflection: RgfxPipelineReflection) -> Self {
|
||||
CompiledPipeline {
|
||||
|
||||
@@ -529,7 +529,7 @@ use reims_vgpu_vulkan::core::platform::os::clock::MonoTime;
|
||||
#[cfg(unix)]
|
||||
use reims_vgpu_vulkan::core::platform::resource::SurfaceHandle;
|
||||
use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, MemoryFor};
|
||||
use reims_vgpu_vulkan::core::platform::types::{CommandBufferStatus, NsRange};
|
||||
use reims_vgpu_vulkan::core::platform::types::NsRange;
|
||||
use reims_vgpu_vulkan::core::platform::values::{PagesPlane, TextureDesc};
|
||||
use reims_vgpu_vulkan::core::platform::{Handle, Platform};
|
||||
use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult, refusals};
|
||||
@@ -3589,18 +3589,6 @@ impl<P: Platform> SurfaceCaches<P> {
|
||||
.map(|c| c.length)
|
||||
}
|
||||
|
||||
/// Marks a deferred cache (and optional shape) as populated after snapshot texture restore.
|
||||
pub(crate) fn mark_restored_texture(&mut self, block: u64, shape_id: Option<u64>) {
|
||||
if let Some(cache) = self.by_block.get_mut(&block) {
|
||||
cache.written = true;
|
||||
cache.first_fill = None;
|
||||
cache.zeros = false;
|
||||
if let Some(id) = shape_id {
|
||||
cache.shapes.mark_restored(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache of the block `m` names where the block has no view: a deferred block's while its
|
||||
/// pages are not named, or where they are copied, and a cache made with its pages copied
|
||||
/// ([`Caches::make_copied`]); where the block's size holds the `m.block_size` bytes `m` names
|
||||
@@ -8349,227 +8337,6 @@ impl<P: Platform> Caches<P> {
|
||||
/// `trace`: `done` once the pages hold the cache, or `failed` where the platform raised at
|
||||
/// the copy.
|
||||
#[allow(clippy::too_many_arguments)] // the download's, and its trace
|
||||
/// Returns all currently tracked surface cache block offsets for pre-snapshot flushing.
|
||||
pub(crate) fn attached_live_blocks(&self) -> Vec<u64> {
|
||||
self.lock()
|
||||
.by_block
|
||||
.iter()
|
||||
.filter(|(_, c)| c.pages.is_some())
|
||||
.map(|(&block, _)| block)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Exports GPU buffer contents for deferred IOSurface device caches whose guest pages
|
||||
/// are not named (`pages.is_none()`), flushing any dirty per-shape textures into the
|
||||
/// cache's backing buffer first so VA-API decoded video frames and unattached WindowServer
|
||||
/// surfaces survive suspend/resume intact.
|
||||
pub(crate) fn export_unattached(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
|
||||
self.export_unattached_with(
|
||||
device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| device.wait_idle(),
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|buffer| device.read_standalone_buffer(buffer),
|
||||
)
|
||||
}
|
||||
|
||||
fn export_unattached_with(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
mut command_buffer: impl FnMut(&P::CommandQueue) -> RaiseResult<Option<P::CommandBuffer>>,
|
||||
mut commit: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
|
||||
mut wait_idle: impl FnMut(),
|
||||
mut wait_completed: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
|
||||
mut read_buffer: impl FnMut(&P::Buffer) -> Result<Option<Vec<u8>>, &'static str>,
|
||||
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
|
||||
let need_mem: Vec<P::Buffer> = {
|
||||
let state = self.lock();
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.filter(|c| {
|
||||
c.pages.is_none() && !c.device.memory_made() && c.shapes.iter().any(|s| s.dirty)
|
||||
})
|
||||
.map(|c| c.device.clone_ref())
|
||||
.collect()
|
||||
};
|
||||
self.make_memory(need_mem, MemoryFor::WriteBack);
|
||||
|
||||
let (dirty_blocks, queue) = {
|
||||
let mut state = self.lock();
|
||||
let dirty_blocks: Vec<u64> = state
|
||||
.by_block
|
||||
.iter()
|
||||
.filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty))
|
||||
.map(|(&b, _)| b)
|
||||
.collect();
|
||||
let queue = if dirty_blocks.is_empty() {
|
||||
None
|
||||
} else {
|
||||
if !state
|
||||
.make_transfer(device)
|
||||
.map_err(|_| "snapshot_save: surface cache transfer init failed")?
|
||||
{
|
||||
return Err("snapshot_save: surface cache transfer queue unavailable");
|
||||
}
|
||||
state
|
||||
.transfer
|
||||
.as_ref()
|
||||
.map(|transfer| transfer.queue.clone_ref())
|
||||
};
|
||||
(dirty_blocks, queue)
|
||||
};
|
||||
if let Some(queue) = queue {
|
||||
let mut submitted = Vec::new();
|
||||
let flushed = (|| {
|
||||
for block in dirty_blocks {
|
||||
let cb = command_buffer(&queue)
|
||||
.map_err(|_| "snapshot_save: surface cache command buffer failed")?
|
||||
.ok_or("snapshot_save: surface cache command buffer unavailable")?;
|
||||
let mut state = self.lock();
|
||||
let Some(cache) = state.by_block.get_mut(&block).filter(|cache| {
|
||||
cache.pages.is_none() && cache.shapes.iter().any(|s| s.dirty)
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
if !cache.copy_through(MemoryFor::WriteBack) {
|
||||
return Err("snapshot_save: deferred surface cache allocation failed");
|
||||
}
|
||||
let back =
|
||||
shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| s.dirty)
|
||||
.map_err(|_| "snapshot_save: surface cache shape write_back failed")?;
|
||||
if back.is_empty() {
|
||||
return Err("snapshot_save: surface cache blit encoder unavailable");
|
||||
}
|
||||
// Retirement frees the queue slot even while we keep the handle for status.
|
||||
let commit_failed = "snapshot_save: surface cache command buffer commit failed";
|
||||
state.unlocked(|| commit(&cb)).map_err(|_| commit_failed)?;
|
||||
let status = cb.status();
|
||||
if status.raw() < CommandBufferStatus::COMMITTED.raw()
|
||||
|| status == CommandBufferStatus::ERROR
|
||||
{
|
||||
return Err(commit_failed);
|
||||
}
|
||||
drop(state);
|
||||
submitted.push((block, back, cb));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let mut wait_failed = false;
|
||||
if !submitted.is_empty() {
|
||||
wait_idle();
|
||||
for (_, _, cb) in &submitted {
|
||||
if wait_completed(cb).is_err() {
|
||||
wait_failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
flushed?;
|
||||
if wait_failed
|
||||
|| submitted
|
||||
.iter()
|
||||
.any(|(_, _, cb)| cb.status() != CommandBufferStatus::COMPLETED)
|
||||
{
|
||||
return Err(
|
||||
"snapshot_save: surface cache command buffer did not complete successfully",
|
||||
);
|
||||
}
|
||||
let mut state = self.lock();
|
||||
let state = &mut *state;
|
||||
for (block, back, _) in &submitted {
|
||||
if let Some(cache) = state.by_block.get_mut(block) {
|
||||
cache.wrote_shapes(back);
|
||||
cache.shapes.written_back(back, &mut state.counts.shapes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut to_read: Vec<(u64, P::Buffer)> = {
|
||||
let state = self.lock();
|
||||
state
|
||||
.by_block
|
||||
.iter()
|
||||
.filter(|(_, c)| c.pages.is_none() && c.device.memory_made())
|
||||
.map(|(&block, c)| (block, c.device.clone_ref()))
|
||||
.collect()
|
||||
};
|
||||
to_read.sort_by_key(|(block, _)| *block);
|
||||
|
||||
let mut out = Vec::with_capacity(to_read.len());
|
||||
for (block, buf) in to_read {
|
||||
match read_buffer(&buf)? {
|
||||
Some(bytes) => out.push((block, bytes)),
|
||||
None => return Err("snapshot_save: unattached surface cache buffer unreadable"),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Restores GPU buffer contents for deferred unattached IOSurface device caches.
|
||||
pub(crate) fn import_unattached(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
entries: &[(u64, Vec<u8>)],
|
||||
) -> Result<(), &'static str> {
|
||||
if entries.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let targets: Vec<(u64, P::Buffer)> = {
|
||||
let state = self.lock();
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for (block, _) in entries {
|
||||
let cache = state
|
||||
.by_block
|
||||
.get(block)
|
||||
.ok_or("snapshot_load: missing unattached surface cache")?;
|
||||
out.push((*block, cache.device.clone_ref()));
|
||||
}
|
||||
out
|
||||
};
|
||||
let need_mem: Vec<P::Buffer> = targets
|
||||
.iter()
|
||||
.filter(|(_, b)| !b.memory_made())
|
||||
.map(|(_, b)| b.clone_ref())
|
||||
.collect();
|
||||
self.make_memory(need_mem, MemoryFor::Fill);
|
||||
|
||||
for ((block, buf), (_, bytes)) in targets.iter().zip(entries.iter()) {
|
||||
if !buf.memory_made() {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_load: failed to allocate memory for unattached surface cache {block:#x}"
|
||||
);
|
||||
return Err("snapshot_load: surface cache memory allocation failed");
|
||||
}
|
||||
if !device.write_standalone_buffer(buf, bytes) {
|
||||
log::error!(
|
||||
target: "reims_vgpu::graphics",
|
||||
"snapshot_load: failed to upload unattached surface cache {block:#x} ({} bytes)",
|
||||
bytes.len()
|
||||
);
|
||||
return Err("snapshot_load: surface cache upload failed");
|
||||
}
|
||||
}
|
||||
|
||||
let mut state = self.lock();
|
||||
for (block, _) in entries {
|
||||
if let Some(cache) = state.by_block.get_mut(block) {
|
||||
let _ = cache.copy_through(MemoryFor::Fill);
|
||||
cache.written = true;
|
||||
cache.first_fill = None;
|
||||
cache.zeros = false;
|
||||
cache.lacks = false;
|
||||
cache.changed = Changed::All;
|
||||
cache.shapes.mark_owed_all();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn download(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
@@ -16441,325 +16208,6 @@ pub(super) mod tests {
|
||||
r.pages_flagged(block, 0, &[], length, flags)
|
||||
}
|
||||
|
||||
const SNAPSHOT_CACHE_LENGTH: u64 = 0x1000;
|
||||
|
||||
fn snapshot_rig(blocks: u64) -> Rig {
|
||||
let r = rig(8);
|
||||
r.dec.set_deferred_budget(blocks * SNAPSHOT_CACHE_LENGTH);
|
||||
r.dec.caches().shaped = true;
|
||||
r
|
||||
}
|
||||
|
||||
fn dirty_unattached_cache(r: &mut Rig, block: u64) -> reims_vgpu_vulkan::core::platform::ObjId {
|
||||
assert_eq!(defer(r, block, SNAPSHOT_CACHE_LENGTH), RGFX_STATUS_OK);
|
||||
let key = ShapeKey {
|
||||
plane: 0,
|
||||
offset: 128,
|
||||
bytes_per_row: 128,
|
||||
width: 16,
|
||||
height: 2,
|
||||
texel_bytes: 4,
|
||||
storage: false,
|
||||
};
|
||||
let desc = r.p.texture_descriptor(&TextureDesc {
|
||||
pixel_format: 80,
|
||||
width: key.width,
|
||||
height: key.height,
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let image = r.device.new_texture(ON, &desc).unwrap().unwrap();
|
||||
let id = image.id();
|
||||
let mut state = r.dec.caches();
|
||||
let cache = state.by_block.get_mut(&block).unwrap();
|
||||
assert!(cache.pages.is_none());
|
||||
assert!(!cache.device.memory_made());
|
||||
let (reference, _) = cache.shapes.insert(key, image, false, 0);
|
||||
assert!(cache.shapes.mark_dirty(reference.id()));
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_exports_more_dirty_unattached_caches_than_the_transfer_queue_holds() {
|
||||
use reims_vgpu_vulkan::core::platform::types::MtlSize;
|
||||
|
||||
const BLOCKS: u64 = 80;
|
||||
const CAPACITY: usize = 64;
|
||||
let mut r = snapshot_rig(BLOCKS + 1);
|
||||
let mut textures = HashMap::default();
|
||||
let mut expected = Vec::new();
|
||||
for i in 0..BLOCKS {
|
||||
let block = BLOCK + i * 0x2000;
|
||||
let texture = dirty_unattached_cache(&mut r, block);
|
||||
let texels = [[i as u8; 64], [255 - i as u8; 64]];
|
||||
let mut bytes = vec![0; SNAPSHOT_CACHE_LENGTH.to_usize()];
|
||||
for (row, texels) in bytes[128..].chunks_mut(128).zip(&texels) {
|
||||
row[..64].copy_from_slice(texels);
|
||||
}
|
||||
textures.insert(texture, texels);
|
||||
expected.push((block, bytes));
|
||||
}
|
||||
assert_eq!(
|
||||
defer(&mut r, BLOCK + BLOCKS * 0x2000, SNAPSHOT_CACHE_LENGTH),
|
||||
RGFX_STATUS_OK
|
||||
);
|
||||
|
||||
let mark = r.p.call_log().mark();
|
||||
let world = r.p.world();
|
||||
let mut acquired = 0;
|
||||
let retired = Cell::new(0);
|
||||
let caches = &r.dec.surface_caches;
|
||||
let exported = caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| {
|
||||
assert!(
|
||||
caches.try_lock().is_some(),
|
||||
"queue acquisition holds the cache lock"
|
||||
);
|
||||
let in_flight = world.committed().len();
|
||||
assert_eq!(
|
||||
world.live("MTLCommandBuffer").len(),
|
||||
in_flight + retired.get(),
|
||||
"a previous buffer is uncommitted"
|
||||
);
|
||||
if in_flight == CAPACITY {
|
||||
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
|
||||
}
|
||||
assert!(world.committed().len() < CAPACITY);
|
||||
acquired += 1;
|
||||
queue.command_buffer(ON)
|
||||
},
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
assert_eq!(caches.try_lock().unwrap().counts.shapes.written_back, 0);
|
||||
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
|
||||
},
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|buffer| {
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
// The fake logs blits without executing them. Reproduce each logged GPU copy.
|
||||
let calls = r.p.call_log().since(mark);
|
||||
let mut copies = calls.iter().filter(|call| {
|
||||
call.sel.starts_with("copyFromTexture:")
|
||||
&& call.args[5].as_obj() == Some(buffer.id())
|
||||
});
|
||||
let copy = copies.next().expect("a copy into this cache");
|
||||
assert!(copies.next().is_none());
|
||||
assert_eq!(copy.args[4], Arg::val(&MtlSize::new(16, 2, 1)));
|
||||
let source = &textures[©.args[0].as_obj().unwrap()];
|
||||
let offset = copy.args[6].as_u64().unwrap().to_usize();
|
||||
let pitch = copy.args[7].as_u64().unwrap().to_usize();
|
||||
let mut bytes = vec![0; buffer.length().to_usize()];
|
||||
for (row, texels) in source.iter().enumerate() {
|
||||
let at = offset + row * pitch;
|
||||
bytes[at..at + 64].copy_from_slice(texels);
|
||||
}
|
||||
Ok(Some(bytes))
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(acquired, BLOCKS);
|
||||
assert_eq!(retired.get(), BLOCKS.to_usize());
|
||||
assert_eq!(exported.unwrap(), expected);
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, BLOCKS);
|
||||
assert!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.all(|cache| cache.shapes.iter().all(|s| !s.dirty))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_drops_uncommitted_unattached_writebacks_on_error() {
|
||||
use reims_vgpu_vulkan::core::testkit::Step;
|
||||
use reims_vgpu_vulkan::core::testkit::impls::resource::MAKE_MEMORY;
|
||||
|
||||
for (selector, steps, error) in [
|
||||
(
|
||||
"commandBuffer",
|
||||
vec![Step::Nil],
|
||||
"snapshot_save: surface cache command buffer unavailable",
|
||||
),
|
||||
(
|
||||
MAKE_MEMORY,
|
||||
vec![Step::value(false); 2],
|
||||
"snapshot_save: deferred surface cache allocation failed",
|
||||
),
|
||||
(
|
||||
"blitCommandEncoder",
|
||||
vec![Step::Nil],
|
||||
"snapshot_save: surface cache blit encoder unavailable",
|
||||
),
|
||||
(
|
||||
"endEncoding",
|
||||
vec![Step::unrecognized("endEncoding")],
|
||||
"snapshot_save: surface cache shape write_back failed",
|
||||
),
|
||||
(
|
||||
"commit",
|
||||
vec![Step::unrecognized("commit")],
|
||||
"snapshot_save: surface cache command buffer commit failed",
|
||||
),
|
||||
] {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
for step in steps {
|
||||
r.p.script().push(selector, step);
|
||||
}
|
||||
let caches = &r.dec.surface_caches;
|
||||
assert_eq!(caches.export_unattached(&r.device), Err(error));
|
||||
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
|
||||
assert!(
|
||||
r.dec.caches().by_block[&BLOCK]
|
||||
.shapes
|
||||
.iter()
|
||||
.all(|s| s.dirty)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_stops_before_readback_if_a_later_writeback_fails() {
|
||||
let mut r = snapshot_rig(2);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
|
||||
r.p.faults()
|
||||
.at("MTLCommandQueue", "commandBuffer", 1, Fault::Nil);
|
||||
|
||||
let caches = &r.dec.surface_caches;
|
||||
let world = r.p.world();
|
||||
let mut retired = 0;
|
||||
let exported = caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| retired += world.complete_all(CompleteOn::Caller),
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|_| panic!("a failed writeback must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer unavailable")
|
||||
);
|
||||
assert_eq!(retired, 1);
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert_eq!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.filter(|c| c.shapes.iter().any(|s| s.dirty))
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_preserves_dirty_shapes_if_writeback_commit_is_silently_refused() {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|_| Ok(()),
|
||||
|| panic!("a refused commit leaves no submitted work to wait for"),
|
||||
|_| panic!("a refused commit leaves no submitted work to wait for"),
|
||||
|_| panic!("a refused commit must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer commit failed")
|
||||
);
|
||||
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| s.dirty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_preserves_dirty_shapes_if_a_submitted_writeback_fails() {
|
||||
let mut r = snapshot_rig(2);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
|
||||
|
||||
let world = r.p.world();
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
let [first, second] = world.committed().try_into().unwrap();
|
||||
assert!(world.complete(
|
||||
first,
|
||||
CommandBufferStatus::COMPLETED,
|
||||
None,
|
||||
CompleteOn::Caller
|
||||
));
|
||||
assert!(world.complete(
|
||||
second,
|
||||
CommandBufferStatus::ERROR,
|
||||
None,
|
||||
CompleteOn::Caller
|
||||
));
|
||||
},
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|_| panic!("a failed writeback must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer did not complete successfully")
|
||||
);
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.all(|cache| cache.shapes.iter().all(|s| s.dirty))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_waits_for_each_submitted_writeback_status_after_wait_idle() {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
|
||||
let world = r.p.world();
|
||||
let mut waited_completed = 0;
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
// Simulate wait_idle returning before the completion worker has
|
||||
// published the command buffer's final COMPLETED status.
|
||||
assert_eq!(world.committed().len(), 1);
|
||||
},
|
||||
|cb| {
|
||||
waited_completed += 1;
|
||||
assert_eq!(cb.status(), CommandBufferStatus::SCHEDULED);
|
||||
assert_eq!(world.complete_all(CompleteOn::Caller), 1);
|
||||
cb.wait_until_completed(ON)
|
||||
},
|
||||
|buffer| {
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
Ok(Some(vec![0xAB; buffer.length().to_usize()]))
|
||||
},
|
||||
);
|
||||
assert_eq!(waited_completed, 1);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Ok(vec![(BLOCK, vec![0xAB; SNAPSHOT_CACHE_LENGTH.to_usize()])])
|
||||
);
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 1);
|
||||
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| !s.dirty));
|
||||
}
|
||||
|
||||
/// A `SURFACE_PAGES` naming the pages of the deferred block at `block`, `runs` as
|
||||
/// [`Rig::pages`]'s, from context `context`; its answer.
|
||||
fn attach(r: &mut Rig, block: u64, context: u32, runs: &[(u64, u64)], length: u64) -> u32 {
|
||||
|
||||
@@ -914,23 +914,6 @@ impl<T> ShapeTable<T> {
|
||||
shape.map(|s| s.dirty = true).is_some()
|
||||
}
|
||||
|
||||
/// Marks a shape whose pixels were directly uploaded during snapshot restore as valid & dirty.
|
||||
pub(crate) fn mark_restored(&mut self, id: u64) {
|
||||
if let Some(s) = self.shapes.iter_mut().find(|s| s.id() == id) {
|
||||
s.owed = false;
|
||||
s.dirty = true;
|
||||
s.cleared = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_owed_all(&mut self) {
|
||||
for s in &mut self.shapes {
|
||||
s.owed = true;
|
||||
s.cleared = false;
|
||||
s.clean();
|
||||
}
|
||||
}
|
||||
|
||||
/// A video command buffer wrote the buffer, its decodes' pictures, not the images: every
|
||||
/// shape owes a fill from it, its own write before the buffer's lost (the decode writes its
|
||||
/// planes whole, and a write it does not cover was copied into the buffer before it ran);
|
||||
|
||||
@@ -292,17 +292,6 @@ impl Marks {
|
||||
self.done.load(Ordering::Acquire),
|
||||
)
|
||||
}
|
||||
|
||||
/// Advances all per-queue watermarks to `seqno` after snapshot restore (all pre-suspend work
|
||||
/// finished during quiesce).
|
||||
pub(crate) fn restore_watermark(&self, seqno: u64) {
|
||||
self.taken.fetch_max(seqno, Ordering::SeqCst);
|
||||
self.signalled.fetch_max(seqno, Ordering::SeqCst);
|
||||
self.committed.fetch_max(seqno, Ordering::SeqCst);
|
||||
self.done.fetch_max(seqno, Ordering::SeqCst);
|
||||
self.commit.begin(seqno);
|
||||
self.commit.raise(seqno);
|
||||
}
|
||||
}
|
||||
|
||||
/// A signal a command buffer carries: its queue's `done` rises to `seqno` once it finishes.
|
||||
@@ -873,19 +862,6 @@ impl<P: Platform> SurfaceOrder<P> {
|
||||
q.buffers = Some(buffers);
|
||||
}
|
||||
|
||||
/// Restores a queue's commit/surface-order watermarks and timeline event value after snapshot load.
|
||||
pub(crate) fn restore_queue_watermark(&mut self, queue: u64, seqno: u64) {
|
||||
if seqno == 0 {
|
||||
return;
|
||||
}
|
||||
if let Some(q) = self.queues.get(&queue) {
|
||||
q.marks.restore_watermark(seqno);
|
||||
if let Some(ev) = &q.event {
|
||||
let _ = ev.set_signaled_value(seqno);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a removal from context `context`'s table waits for before its entry is let go of
|
||||
/// ([`super::tables`], "After the buffers posted before it"): each queue of the context the
|
||||
/// decoder made and that has not ended, whose ring published a command buffer its commit mark
|
||||
|
||||
@@ -272,16 +272,6 @@ impl<P: Platform> PresentQueue<P> {
|
||||
self.state.lock().queues.insert(queue, poster);
|
||||
}
|
||||
|
||||
/// Advances the finished watermark for a restored queue so pre-suspend surface writers never stall.
|
||||
pub(crate) fn restore_finished(&self, queue: u64, seqno: u64) {
|
||||
if seqno == 0 {
|
||||
return;
|
||||
}
|
||||
let mut st = self.state.lock();
|
||||
let done = st.finished.entry(queue).or_insert(0);
|
||||
*done = (*done).max(seqno);
|
||||
}
|
||||
|
||||
/// Shows IOSurface `id`'s `texture` (`None`: the scanout) on display `display`, with the
|
||||
/// colour stages `color` sets, once each command buffer in `writers` has finished, and
|
||||
/// `fill`, its surface's device cache's fill, where it has one, and every present of the
|
||||
|
||||
@@ -239,8 +239,6 @@ pub(crate) struct ScanoutDraw<P: Platform> {
|
||||
ramps: Mutex<Vec<(u64, P::Texture)>>,
|
||||
/// The scanout's ramp, made at its first use; `None` inside where the platform refused it.
|
||||
scanout_ramp: Kept<ScanoutRead<P>>,
|
||||
/// Staging texture used to GPU-scale a raw scanout whose size differs from the window's image.
|
||||
scanout_stage: Mutex<Option<P::Texture>>,
|
||||
/// What draws the guest's cursor where the window draws it (`cursor`): its pipelines and its
|
||||
/// glyph's texture, made at their first use.
|
||||
cursor: Mutex<CursorPass<P>>,
|
||||
@@ -570,7 +568,6 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
color_table: Mutex::new(None),
|
||||
ramps: Mutex::default(),
|
||||
scanout_ramp: Kept::new(),
|
||||
scanout_stage: Mutex::new(None),
|
||||
cursor: Mutex::new(CursorPass::cursor()),
|
||||
overlay: Mutex::new(CursorPass::overlay()),
|
||||
#[cfg(test)]
|
||||
@@ -610,7 +607,6 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
*self.color_table.lock() = None;
|
||||
self.ramps.lock().clear();
|
||||
self.scanout_ramp.forget();
|
||||
*self.scanout_stage.lock() = None;
|
||||
*self.cursor.lock() = CursorPass::cursor();
|
||||
*self.overlay.lock() = CursorPass::overlay();
|
||||
}
|
||||
@@ -904,8 +900,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
if let Some((surface, view, hold)) = self.presented.shown() {
|
||||
let (from, to) = (surface.pixel_format(), texture.pixel_format());
|
||||
self.presented.seen_format(from, to);
|
||||
let same_size = surface.width() == region.width && surface.height() == region.height;
|
||||
let copied = same_size && BGRA8_FORMATS.contains(&from) && BGRA8_FORMATS.contains(&to);
|
||||
let copied = BGRA8_FORMATS.contains(&from) && BGRA8_FORMATS.contains(&to);
|
||||
let drawn = if color.is_none() && copied {
|
||||
self.encode_surface(&surface, texture, region)
|
||||
} else {
|
||||
@@ -1468,15 +1463,6 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
fn encode_scanout(&self, texture: &P::Texture, region: PixelRect) -> Option<P::CommandBuffer> {
|
||||
let scanout = (*self.shown.scanout.lock())?;
|
||||
let (buffer, source_offset) = self.scanout_buffer(&scanout)?;
|
||||
let (sw, sh) = (u64::from(scanout.width), u64::from(scanout.height));
|
||||
if sw > 0
|
||||
&& sh > 0
|
||||
&& (sw != region.width || sh != region.height)
|
||||
&& let Some(cb) =
|
||||
self.encode_scanout_scaled(&scanout, &buffer, source_offset, texture, region)
|
||||
{
|
||||
return Some(cb);
|
||||
}
|
||||
let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?;
|
||||
let (texture_width, texture_height) = (texture.width(), texture.height());
|
||||
let x = region.x.min(texture_width);
|
||||
@@ -1583,62 +1569,6 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Stages `scanout` into a `BGRA8Unorm` texture and scales it into `texture` at `region` via
|
||||
/// the linear-filtered display present shader (used when guest mode != window pixels, e.g.
|
||||
/// `REIMS_VGPU_WINDOW_FIXED_MODE=1` during boot/Recovery).
|
||||
fn encode_scanout_scaled(
|
||||
&self,
|
||||
scanout: &Scanout,
|
||||
buffer: &P::Buffer,
|
||||
source_offset: u64,
|
||||
texture: &P::Texture,
|
||||
region: PixelRect,
|
||||
) -> Option<P::CommandBuffer> {
|
||||
let (sw, sh) = (u64::from(scanout.width), u64::from(scanout.height));
|
||||
let stage = {
|
||||
let mut slot = self.scanout_stage.lock();
|
||||
let reuse = slot
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.width() == sw && t.height() == sh);
|
||||
if !reuse {
|
||||
let desc = self.platform.texture_descriptor(&TextureDesc {
|
||||
pixel_format: 80,
|
||||
width: sw,
|
||||
height: sh,
|
||||
usage: RAMP_USAGE,
|
||||
resource_options: Some(PRIVATE),
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let made = no_catch(self.device.new_texture(OnFault::Die, &desc))?;
|
||||
*slot = Some(made);
|
||||
}
|
||||
slot.as_ref()?.clone_ref()
|
||||
};
|
||||
let command_buffer = no_catch(self.queue.command_buffer(OnFault::Die))?;
|
||||
let blit = Open::new(
|
||||
no_catch(command_buffer.blit_encoder(OnFault::Die))?,
|
||||
end_blit::<P>,
|
||||
);
|
||||
let stride = u64::from(scanout.stride);
|
||||
no_catch(blit.get().encode(
|
||||
OnFault::Die,
|
||||
BlitCmd::CopyBufferToTexture {
|
||||
source_buffer: buffer,
|
||||
source_offset,
|
||||
source_bytes_per_row: stride,
|
||||
source_bytes_per_image: stride * sh,
|
||||
source_size: MtlSize::new(sw, sh, 1),
|
||||
destination_texture: &stage,
|
||||
destination_slice: 0,
|
||||
destination_level: 0,
|
||||
destination_origin: MtlOrigin::new(0, 0, 0),
|
||||
},
|
||||
));
|
||||
blit.end();
|
||||
self.encode_converted_into(&command_buffer, &stage, texture, region)?;
|
||||
Some(command_buffer)
|
||||
}
|
||||
|
||||
/// A command buffer of the sink's queue with the presented `surface` drawn into `texture` at
|
||||
/// `region` by the display's present shaders, which convert its format to the drawable's,
|
||||
/// after a clear of the drawable to black where `region` does not cover it ([`pass_load`]);
|
||||
@@ -1650,25 +1580,12 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
texture: &P::Texture,
|
||||
region: PixelRect,
|
||||
) -> Option<P::CommandBuffer> {
|
||||
let command_buffer = self.surface_command_buffer()?;
|
||||
self.encode_converted_into(&command_buffer, surface, texture, region)?;
|
||||
Some(command_buffer)
|
||||
}
|
||||
|
||||
/// Encodes the linear-filtered display present shader drawing `surface` into `texture` at
|
||||
/// `region` on `command_buffer`.
|
||||
fn encode_converted_into(
|
||||
&self,
|
||||
command_buffer: &P::CommandBuffer,
|
||||
surface: &P::Texture,
|
||||
texture: &P::Texture,
|
||||
region: PixelRect,
|
||||
) -> Option<()> {
|
||||
let converter = self.converter()?;
|
||||
let pipeline = converter.pipelines.pipeline_for(PipelineKey {
|
||||
format: texture.pixel_format(),
|
||||
gamma: false,
|
||||
})?;
|
||||
let command_buffer = self.surface_command_buffer()?;
|
||||
let (texture_width, texture_height) = (texture.width(), texture.height());
|
||||
let x = region.x.min(texture_width);
|
||||
let y = region.y.min(texture_height);
|
||||
@@ -1740,7 +1657,7 @@ impl<P: ApiPlatform> ScanoutDraw<P> {
|
||||
}
|
||||
}
|
||||
encoder.end();
|
||||
Some(())
|
||||
Some(command_buffer)
|
||||
}
|
||||
|
||||
/// Clears all of `texture` to opaque black, in a render pass of `command_buffer` with no
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -85,7 +85,6 @@
|
||||
mod addresses;
|
||||
mod host_blocks;
|
||||
mod private_blocks;
|
||||
pub(crate) use private_blocks::{PrivateBlockSnapshot, PrivateBlocksSnapshot};
|
||||
mod rt_blocks;
|
||||
mod takes;
|
||||
|
||||
@@ -310,47 +309,6 @@ pub enum BlockError {
|
||||
|
||||
/// Where the pool's blocks come from (metal2vulkan-runtime's `Device::take_block` and
|
||||
/// `release_block`).
|
||||
/// Capture/replay address metadata for a pool or private block.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BlockCapture {
|
||||
pub class: MemoryClass,
|
||||
pub alloc_len: u64,
|
||||
pub offset: u64,
|
||||
pub len: u64,
|
||||
pub gpu_address: u64,
|
||||
pub opaque_buffer_address: u64,
|
||||
pub opaque_memory_address: u64,
|
||||
}
|
||||
|
||||
/// Snapshot of a single live Shared Pool piece mapped into Guest GPA.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PoolPieceSnapshot {
|
||||
pub gpa: u64,
|
||||
pub len: u64,
|
||||
pub gpu_address: u64,
|
||||
pub capture: Option<BlockCapture>,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Snapshot of a context's carved sub-block inside a Shared Pool piece.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PoolCarveSnapshot {
|
||||
pub gpa: u64,
|
||||
pub context: u32,
|
||||
pub len: u64,
|
||||
pub serial: u64,
|
||||
pub gpu_address: u64,
|
||||
pub picked_address: bool,
|
||||
}
|
||||
|
||||
/// Complete snapshot of the Shared Pool.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PoolSnapshot {
|
||||
pub serial: u64,
|
||||
pub pieces: Vec<PoolPieceSnapshot>,
|
||||
pub carves: Vec<PoolCarveSnapshot>,
|
||||
}
|
||||
|
||||
pub trait BlockSource: Send + Sync {
|
||||
/// A block of `class` at least `len` long ([`BlockInfo::len`]). Waits only when no block is
|
||||
/// ready.
|
||||
@@ -359,27 +317,6 @@ pub trait BlockSource: Send + Sync {
|
||||
/// any more: it goes back to the ready set, with its id, address and host mapping, or is
|
||||
/// freed.
|
||||
fn release_block(&self, block: BlockId) -> Result<(), BlockError>;
|
||||
|
||||
/// Returns capture/replay metadata for a live block, if supported.
|
||||
fn capture_block(&self, _block: BlockId) -> Option<BlockCapture> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Replays a previously captured block at its exact Vulkan device address.
|
||||
fn take_block_replayed(&self, _cap: BlockCapture) -> Result<BlockInfo, BlockError> {
|
||||
Err(BlockError::OutOfMemory)
|
||||
}
|
||||
|
||||
/// Reads back raw VRAM bytes of a Private block (via GPU staging blit).
|
||||
/// Returns `Ok(None)` when the source has no GPU-backed VRAM (unit-test fakes).
|
||||
fn read_private_block(&self, _block: BlockId) -> Result<Option<Vec<u8>>, BlockError> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Uploads raw VRAM bytes into a Private block (via GPU staging blit).
|
||||
fn write_private_block(&self, _block: BlockId, _data: &[u8]) -> Result<(), BlockError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest physical range the host reserved for the pool, with no RAM under it.
|
||||
@@ -1150,146 +1087,6 @@ impl Pool {
|
||||
dead_code,
|
||||
reason = "the guest's side of the pool (its ring messages) calls it once it lands"
|
||||
)]
|
||||
/// Waits until in-flight pool take workers and zeroer are idle.
|
||||
pub(crate) fn quiesce(&self) {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let busy = {
|
||||
let st = self.shared.state.lock();
|
||||
st.workers > 0 || st.zeroer || st.serving > 0 || !st.asks.is_empty()
|
||||
};
|
||||
if !busy || std::time::Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports all live Shared Pool pieces (with raw bytes & BDA capture metadata) and carves.
|
||||
pub(crate) fn export_snapshot(&self) -> Result<PoolSnapshot, Error> {
|
||||
self.quiesce();
|
||||
let st = self.shared.state.lock();
|
||||
let source = st.source.clone();
|
||||
let mut pieces = Vec::new();
|
||||
for (&gpa, p) in &st.pieces {
|
||||
if !matches!(p.mapped, Mapped::Live | Mapped::Adding) {
|
||||
continue;
|
||||
}
|
||||
let cap = source.as_ref().and_then(|s| s.capture_block(p.block.id));
|
||||
let ptr = p.block.contents.ok_or(Error::HostResources)?;
|
||||
let bytes = unsafe {
|
||||
std::slice::from_raw_parts(ptr.as_ptr(), p.block.len as usize).to_vec()
|
||||
};
|
||||
pieces.push(PoolPieceSnapshot {
|
||||
gpa,
|
||||
len: p.block.len,
|
||||
gpu_address: p.block.gpu_address,
|
||||
capture: cap,
|
||||
bytes,
|
||||
});
|
||||
}
|
||||
let carves = takes::export_carves(&st.carves);
|
||||
Ok(PoolSnapshot {
|
||||
serial: st.serial,
|
||||
pieces,
|
||||
carves,
|
||||
})
|
||||
}
|
||||
|
||||
/// Restores Shared Pool pieces at their exact GPAs and Vulkan BDAs, and asks host to map them.
|
||||
pub(crate) fn import_snapshot(&self, snap: &PoolSnapshot) -> Result<(), Error> {
|
||||
self.quiesce();
|
||||
let source = {
|
||||
let st = self.shared.state.lock();
|
||||
st.source.clone()
|
||||
};
|
||||
let Some(source) = source else {
|
||||
return if snap.pieces.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::HostResources)
|
||||
};
|
||||
};
|
||||
// First release any pre-existing empty pieces if any (fresh device has none).
|
||||
let mut restored_pieces: Vec<(u64, BlockInfo)> = Vec::with_capacity(snap.pieces.len());
|
||||
for ps in &snap.pieces {
|
||||
let blk = if let Some(cap) = ps.capture {
|
||||
source
|
||||
.take_block_replayed(cap)
|
||||
.map_err(|_| Error::HostResources)?
|
||||
} else {
|
||||
source
|
||||
.take_block(MemoryClass::Shared, ps.len)
|
||||
.map_err(|_| Error::HostResources)?
|
||||
};
|
||||
let ptr = blk.contents.ok_or(Error::HostResources)?;
|
||||
if ps.bytes.len() as u64 != blk.len {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len());
|
||||
}
|
||||
restored_pieces.push((ps.gpa, blk));
|
||||
}
|
||||
{
|
||||
let mut st = self.shared.state.lock();
|
||||
st.serial = st.serial.max(snap.serial);
|
||||
for (gpa, blk) in &restored_pieces {
|
||||
let piece_carves = snap
|
||||
.carves
|
||||
.iter()
|
||||
.filter(|c| c.gpa >= *gpa && c.gpa < *gpa + blk.len)
|
||||
.count() as u64;
|
||||
st.by_block.insert(blk.id, *gpa);
|
||||
st.pieces.insert(
|
||||
*gpa,
|
||||
Piece {
|
||||
block: *blk,
|
||||
mapped: Mapped::Adding,
|
||||
empty_since: if piece_carves == 0 {
|
||||
Some((self.shared.now)())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
holds: 0,
|
||||
kept: Arc::new(()),
|
||||
carves: piece_carves,
|
||||
zeros: takes::Ranges::new(),
|
||||
zero_pending: false,
|
||||
going: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
let state = &mut *st;
|
||||
takes::import_carves(&mut state.carves, &mut state.addresses, &snap.carves);
|
||||
}
|
||||
for (gpa, blk) in &restored_pieces {
|
||||
if let Some(ptr) = blk.contents {
|
||||
(self.shared.host.add)(*gpa, ptr.as_ptr(), blk.len);
|
||||
}
|
||||
}
|
||||
self.shared.wake();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-copies snapshotted Shared Pool piece bytes after LiveLog replay (so any `new_buffer`
|
||||
/// zero-initialization during replay cannot clobber saved guest/GPU contents).
|
||||
pub(crate) fn restore_bytes(&self, snap: &PoolSnapshot) -> Result<(), Error> {
|
||||
let st = self.shared.state.lock();
|
||||
for ps in &snap.pieces {
|
||||
let piece = st.pieces.get(&ps.gpa).ok_or(Error::HostResources)?;
|
||||
let ptr = piece.block.contents.ok_or(Error::HostResources)?;
|
||||
if ps.bytes.len() as u64 != piece.block.len {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(ps.bytes.as_ptr(), ptr.as_ptr(), ps.bytes.len());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub fn live(&self) -> Vec<(u64, u64)> {
|
||||
let st = self.shared.state.lock();
|
||||
(st.pieces.iter())
|
||||
|
||||
@@ -139,24 +139,6 @@ pub(crate) struct HeldRef {
|
||||
}
|
||||
|
||||
/// A context's block.
|
||||
/// Serializable snapshot of a single Private GPU-address block and its VRAM contents.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct PrivateBlockSnapshot {
|
||||
pub(crate) gpu_address: u64,
|
||||
pub(crate) context: u32,
|
||||
pub(crate) len: u64,
|
||||
pub(crate) serial: u64,
|
||||
pub(crate) capture: Option<super::BlockCapture>,
|
||||
pub(crate) bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Complete snapshot of all contexts' Private blocks.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct PrivateBlocksSnapshot {
|
||||
pub(crate) serial: u64,
|
||||
pub(crate) blocks: Vec<PrivateBlockSnapshot>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Held {
|
||||
context: u32,
|
||||
@@ -455,128 +437,6 @@ impl PrivateBlocks {
|
||||
|
||||
/// The device's reset: every take not yet answered ends unanswered, and every block is freed
|
||||
/// at once, its objects already dropped.
|
||||
/// Waits until in-flight private take workers are idle, then exports all held Private blocks + VRAM.
|
||||
pub(crate) fn export_snapshot(&self) -> Result<PrivateBlocksSnapshot, super::Error> {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let busy = {
|
||||
let st = self.inner.state.lock();
|
||||
st.takers.values().any(|t| t.busy || !t.jobs.is_empty())
|
||||
};
|
||||
if !busy {
|
||||
break;
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return Err(super::Error::HostResources);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
let entries: Vec<(u64, u32, u64, u64, Option<BlockId>)> = {
|
||||
let st = self.inner.state.lock();
|
||||
st.held
|
||||
.iter()
|
||||
.filter(|(_, h)| !h.going)
|
||||
.map(|(&addr, h)| (addr, h.context, h.len, h.serial, h.block))
|
||||
.collect()
|
||||
};
|
||||
let serial = self.inner.state.lock().serial;
|
||||
let mut blocks = Vec::with_capacity(entries.len());
|
||||
for (gpu_address, context, len, bserial, block_id) in entries {
|
||||
let (capture, bytes) = match (&self.inner.source, block_id) {
|
||||
(Some(src), Some(bid)) => {
|
||||
let cap = src.capture_block(bid);
|
||||
let raw = src
|
||||
.read_private_block(bid)
|
||||
.map_err(|_| super::Error::HostResources)?
|
||||
.unwrap_or_default();
|
||||
(cap, raw)
|
||||
}
|
||||
(Some(_), None) => return Err(super::Error::HostResources),
|
||||
(None, _) => (None, Vec::new()),
|
||||
};
|
||||
blocks.push(PrivateBlockSnapshot {
|
||||
gpu_address,
|
||||
context,
|
||||
len,
|
||||
serial: bserial,
|
||||
capture,
|
||||
bytes,
|
||||
});
|
||||
}
|
||||
Ok(PrivateBlocksSnapshot { serial, blocks })
|
||||
}
|
||||
|
||||
/// Restores Private blocks at their exact Vulkan BDAs and uploads saved VRAM contents.
|
||||
pub(crate) fn import_snapshot(&self, snap: &PrivateBlocksSnapshot) -> Result<(), super::Error> {
|
||||
let mut restored = Vec::with_capacity(snap.blocks.len());
|
||||
for b in &snap.blocks {
|
||||
let block_id = if let Some(src) = &self.inner.source {
|
||||
let info = if let Some(cap) = b.capture {
|
||||
src.take_block_replayed(cap)
|
||||
.map_err(|_| super::Error::HostResources)?
|
||||
} else {
|
||||
src.take_block(MemoryClass::Private, b.len)
|
||||
.map_err(|_| super::Error::HostResources)?
|
||||
};
|
||||
Some(info.id)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
restored.push((b, block_id));
|
||||
}
|
||||
let mut st = self.inner.state.lock();
|
||||
st.serial = st.serial.max(snap.serial);
|
||||
st.held.clear();
|
||||
for (b, block_id) in restored {
|
||||
st.held.insert(
|
||||
b.gpu_address,
|
||||
Held {
|
||||
context: b.context,
|
||||
len: b.len,
|
||||
serial: b.serial,
|
||||
going: false,
|
||||
block: block_id,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Uploads snapshotted Private Block VRAM bytes after LiveLog object replay (so `new_buffer`
|
||||
/// zeroing during replay never clobbers restored Private VRAM).
|
||||
pub(crate) fn restore_bytes(&self, snap: &PrivateBlocksSnapshot) -> Result<(), super::Error> {
|
||||
let Some(src) = &self.inner.source else {
|
||||
if snap.blocks.iter().any(|b| !b.bytes.is_empty()) {
|
||||
return Err(super::Error::HostResources);
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
let ids: Vec<(BlockId, &[u8])> = {
|
||||
let st = self.inner.state.lock();
|
||||
let mut out = Vec::with_capacity(snap.blocks.len());
|
||||
for b in &snap.blocks {
|
||||
if b.bytes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let held = st
|
||||
.held
|
||||
.get(&b.gpu_address)
|
||||
.ok_or(super::Error::HostResources)?;
|
||||
if b.bytes.len() as u64 != held.len {
|
||||
return Err(super::Error::InvalidArgument);
|
||||
}
|
||||
let id = held.block.ok_or(super::Error::HostResources)?;
|
||||
out.push((id, b.bytes.as_slice()));
|
||||
}
|
||||
out
|
||||
};
|
||||
for (id, bytes) in ids {
|
||||
src.write_private_block(id, bytes)
|
||||
.map_err(|_| super::Error::HostResources)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&self) {
|
||||
let (released, ended) = {
|
||||
let mut state = self.inner.state.lock();
|
||||
|
||||
@@ -42,7 +42,7 @@ use parking_lot::Mutex;
|
||||
use reims_vgpu_vulkan::core::trace;
|
||||
use reims_vgpu_vulkan::rt_platform::{RtDevice, RtObj};
|
||||
|
||||
use super::{BlockCapture, BlockError, BlockId, BlockInfo, BlockSource, MemoryClass};
|
||||
use super::{BlockError, BlockId, BlockInfo, BlockSource, MemoryClass};
|
||||
|
||||
/// The pool's blocks from an rt device, with the handle of each one handed out.
|
||||
pub(crate) struct RtBlocks {
|
||||
@@ -144,153 +144,6 @@ impl BlockSource for RtBlocks {
|
||||
// be; rt drops the handle all the same.
|
||||
(self.device.rt().release_block(handle)).map_err(|_| BlockError::NotHeld)
|
||||
}
|
||||
|
||||
fn capture_block(&self, block: BlockId) -> Option<BlockCapture> {
|
||||
let held = self.held.lock();
|
||||
let h = held.get(&block)?;
|
||||
let cap = h.capture_info()?;
|
||||
Some(BlockCapture {
|
||||
class: match cap.class {
|
||||
rt::MemoryClass::Private => MemoryClass::Private,
|
||||
rt::MemoryClass::Shared => MemoryClass::Shared,
|
||||
},
|
||||
alloc_len: cap.alloc_len,
|
||||
offset: cap.offset,
|
||||
len: cap.len,
|
||||
gpu_address: cap.gpu_address,
|
||||
opaque_buffer_address: cap.opaque_buffer_address,
|
||||
opaque_memory_address: cap.opaque_memory_address,
|
||||
})
|
||||
}
|
||||
|
||||
fn take_block_replayed(&self, cap: BlockCapture) -> Result<BlockInfo, BlockError> {
|
||||
let rt_cap = rt::BlockCaptureInfo {
|
||||
class: match cap.class {
|
||||
MemoryClass::Private => rt::MemoryClass::Private,
|
||||
MemoryClass::Shared => rt::MemoryClass::Shared,
|
||||
},
|
||||
alloc_len: cap.alloc_len,
|
||||
offset: cap.offset,
|
||||
len: cap.len,
|
||||
gpu_address: cap.gpu_address,
|
||||
opaque_buffer_address: cap.opaque_buffer_address,
|
||||
opaque_memory_address: cap.opaque_memory_address,
|
||||
};
|
||||
let block = self
|
||||
.device
|
||||
.rt()
|
||||
.take_block_replayed(rt_cap)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let Some(gpu_address) = block.gpu_address else {
|
||||
let _ = self.device.rt().release_block(block);
|
||||
return Err(BlockError::OutOfMemory);
|
||||
};
|
||||
let info = BlockInfo {
|
||||
id: BlockId(block.id.get()),
|
||||
class: cap.class,
|
||||
len: block.len,
|
||||
gpu_address,
|
||||
contents: block.contents,
|
||||
};
|
||||
self.known.know(block.clone());
|
||||
self.held.lock().insert(info.id, block);
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn read_private_block(&self, block: BlockId) -> Result<Option<Vec<u8>>, BlockError> {
|
||||
let handle = self
|
||||
.held
|
||||
.lock()
|
||||
.get(&block)
|
||||
.cloned()
|
||||
.ok_or(BlockError::NotHeld)?;
|
||||
let len = handle.len;
|
||||
if len == 0 {
|
||||
return Ok(Some(Vec::new()));
|
||||
}
|
||||
let rt = self.device.rt();
|
||||
let stage = rt
|
||||
.take_block(rt::MemoryClass::Shared, len)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let res = (|| -> Result<Vec<u8>, BlockError> {
|
||||
let src_buf = rt
|
||||
.new_buffer(handle.id, 0, len, None)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let dst_buf = rt
|
||||
.new_buffer(stage.id, 0, len, None)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let q = rt
|
||||
.new_command_queue(4)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let cb = q.command_buffer().map_err(|_| BlockError::OutOfMemory)?;
|
||||
let mut blit = cb
|
||||
.blit_command_encoder()
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
blit.copy_from_buffer_to_buffer(&src_buf, 0, &dst_buf, 0, len)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
blit.end_encoding();
|
||||
cb.commit().map_err(|_| BlockError::OutOfMemory)?;
|
||||
cb.wait_until_completed()
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let ptr = stage.contents.ok_or(BlockError::OutOfMemory)?;
|
||||
let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), len as usize).to_vec() };
|
||||
drop(dst_buf);
|
||||
drop(src_buf);
|
||||
Ok(bytes)
|
||||
})();
|
||||
let _ = rt.release_block(stage);
|
||||
res.map(Some)
|
||||
}
|
||||
|
||||
fn write_private_block(&self, block: BlockId, data: &[u8]) -> Result<(), BlockError> {
|
||||
let handle = self
|
||||
.held
|
||||
.lock()
|
||||
.get(&block)
|
||||
.cloned()
|
||||
.ok_or(BlockError::NotHeld)?;
|
||||
let len = handle.len;
|
||||
if data.len() as u64 != len {
|
||||
return Err(BlockError::OutOfMemory);
|
||||
}
|
||||
if len == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let rt = self.device.rt();
|
||||
let stage = rt
|
||||
.take_block(rt::MemoryClass::Shared, len)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let res = (|| -> Result<(), BlockError> {
|
||||
let ptr = stage.contents.ok_or(BlockError::OutOfMemory)?;
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.as_ptr(), len as usize);
|
||||
}
|
||||
let src_buf = rt
|
||||
.new_buffer(stage.id, 0, len, None)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let dst_buf = rt
|
||||
.new_buffer(handle.id, 0, len, None)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let q = rt
|
||||
.new_command_queue(4)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
let cb = q.command_buffer().map_err(|_| BlockError::OutOfMemory)?;
|
||||
let mut blit = cb
|
||||
.blit_command_encoder()
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
blit.copy_from_buffer_to_buffer(&src_buf, 0, &dst_buf, 0, len)
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
blit.end_encoding();
|
||||
cb.commit().map_err(|_| BlockError::OutOfMemory)?;
|
||||
cb.wait_until_completed()
|
||||
.map_err(|_| BlockError::OutOfMemory)?;
|
||||
drop(dst_buf);
|
||||
drop(src_buf);
|
||||
Ok(())
|
||||
})();
|
||||
let _ = rt.release_block(stage);
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RtBlocks {
|
||||
|
||||
@@ -191,47 +191,6 @@ enum GpuAddress {
|
||||
Picked(u64),
|
||||
}
|
||||
|
||||
pub(super) fn export_carves(carves: &BTreeMap<u64, Carve>) -> Vec<super::PoolCarveSnapshot> {
|
||||
carves
|
||||
.iter()
|
||||
.filter(|(_, c)| matches!(c.state, Carving::Held))
|
||||
.map(|(&gpa, c)| super::PoolCarveSnapshot {
|
||||
gpa,
|
||||
context: c.context,
|
||||
len: c.len,
|
||||
serial: c.serial,
|
||||
gpu_address: c.gpu_address.get(),
|
||||
picked_address: matches!(c.gpu_address, GpuAddress::Picked(_)),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn import_carves(
|
||||
carves: &mut BTreeMap<u64, Carve>,
|
||||
_addresses: &mut super::addresses::HostAddresses,
|
||||
snap: &[super::PoolCarveSnapshot],
|
||||
) {
|
||||
carves.clear();
|
||||
for c in snap {
|
||||
let gpu_address = if c.picked_address {
|
||||
GpuAddress::Picked(c.gpu_address)
|
||||
} else {
|
||||
GpuAddress::OfBlock(c.gpu_address)
|
||||
};
|
||||
carves.insert(
|
||||
c.gpa,
|
||||
Carve {
|
||||
context: c.context,
|
||||
len: c.len,
|
||||
serial: c.serial,
|
||||
state: Carving::Held,
|
||||
gpu_address,
|
||||
zero: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuAddress {
|
||||
fn get(self) -> u64 {
|
||||
match self {
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
* moved the cursor yet: the latest is where the host's pointer is.
|
||||
*
|
||||
* Where the point lies, and the rectangles the host is told:
|
||||
* - on x86-64, each framebuffer holds its display's virtual desktop rectangle as WindowServer
|
||||
* placed it (getBoundingRect), and a move of the cursor on any display tells the host each
|
||||
* virtual rectangle that changed (tellBounds);
|
||||
* - on x86-64, each framebuffer holds its display's rectangle as WindowServer placed it
|
||||
* (getBoundingRect), and a move of the cursor on any display tells the host each display's
|
||||
* that changed (tellBounds);
|
||||
* - on arm64, WindowServer tells the displays nothing of where it placed them, so the kext
|
||||
* learns it from its own posts: a crossing posts at the display's pixel of the rectangle held
|
||||
* for it, and again beside the other displays where the cursor did not reach it, at most
|
||||
@@ -185,7 +185,7 @@ void ReimsGraphics::movePointer(thread_call_param_t self, thread_call_param_t)
|
||||
IOSimpleLockUnlock(me->interruptLock);
|
||||
if (!me->hasStarted())
|
||||
return;
|
||||
// The display's scanout size and its virtual desktop rectangle.
|
||||
// The display's mode and its rectangle in the global space.
|
||||
ReimsGraphics *fb = me->copyDisplay(me->drivenIndex(at.display));
|
||||
if (!fb)
|
||||
return;
|
||||
@@ -221,7 +221,7 @@ void ReimsGraphics::movePointer(thread_call_param_t self, thread_call_param_t)
|
||||
move == RgfxPointerMove::moved ? "moves" : "is dragged", globalX, globalY, posted);
|
||||
}
|
||||
|
||||
// The virtual rectangles used for both IOHIDSystem posts and DISPLAY_BOUNDS.
|
||||
// Each framebuffer holds its display's rectangle as WindowServer placed it (getBoundingRect).
|
||||
void ReimsGraphics::displayPlaces(RgfxGlobalRect *rects, bool *placed)
|
||||
{
|
||||
ReimsGraphics *fbs[RGFX_DISPLAYS_MAX];
|
||||
@@ -232,7 +232,7 @@ void ReimsGraphics::displayPlaces(RgfxGlobalRect *rects, bool *placed)
|
||||
fbs[i]->getBoundingRect(&bounds);
|
||||
if (!bounds || display >= RGFX_DISPLAYS_MAX)
|
||||
continue;
|
||||
rects[display] = rgfxFramebufferDesktopBounds(bounds);
|
||||
rects[display] = {bounds->minx, bounds->miny, bounds->maxx, bounds->maxy};
|
||||
placed[display] = true;
|
||||
}
|
||||
releaseDisplays(fbs, n);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// RgfxDisplayBounds: which displays' rectangles the kext tells the host in DISPLAY_BOUNDS
|
||||
// (design.md, "Multiple displays", "A drag across displays"). On x86-64 each framebuffer holds its
|
||||
// display's virtual desktop rectangle as WindowServer placed it (IOFBSetBounds, which
|
||||
// IOFramebuffer::getBoundingRect reads; RgfxPointerOver.hpp), and on arm64 the kext holds
|
||||
// display's rectangle in WindowServer's global space as WindowServer placed it (IOFBSetBounds,
|
||||
// which IOFramebuffer::getBoundingRect reads; RgfxPointerOver.hpp), and on arm64 the kext holds
|
||||
// each one a landing of its own moves of the cursor confirmed (RgfxDisplayPlaces.hpp); the host
|
||||
// carries its captured pointer past one display's edge onto the display whose rectangle meets it
|
||||
// there. Each move of the cursor, on any display, tells the host every display's rectangle that
|
||||
@@ -21,15 +21,6 @@
|
||||
#include "RgfxPointerOver.hpp"
|
||||
#include "reims_graphics_wire.h"
|
||||
|
||||
// IOFramebuffer's getBoundingRect returns its physical and virtual rectangles in order.
|
||||
// IOFBSetBounds supplies both, or IOFramebuffer uses the sole rectangle for both.
|
||||
template <class Bounds>
|
||||
inline RgfxGlobalRect rgfxFramebufferDesktopBounds(const Bounds *bounds)
|
||||
{
|
||||
const Bounds &rect = bounds[1];
|
||||
return {rect.minx, rect.miny, rect.maxx, rect.maxy};
|
||||
}
|
||||
|
||||
// The rectangle the host was last told of each display, by id, where it was told one.
|
||||
struct RgfxBoundsTold {
|
||||
RgfxGlobalRect rects[RGFX_DISPLAYS_MAX];
|
||||
|
||||
@@ -4,12 +4,16 @@
|
||||
// the display its cursor is on, so the kext moves the cursor onto that display, at that point,
|
||||
// before the tablet's next position comes (ReimsGraphicsPointer.cpp).
|
||||
//
|
||||
// IOHIDSystem's post takes a point in WindowServer's virtual desktop. On x86-64 the framebuffer
|
||||
// holds the virtual rectangle WindowServer gave it (IOFBSetBounds); on arm64 the kext learns
|
||||
// each rectangle from its own moves (RgfxDisplayPlaces.hpp). Scale the scanout pixels into that
|
||||
// rectangle. Measured on x86-64 macOS 11.7.11, 15.8.2 and 26.7.2 with two 1920 x 1080 displays
|
||||
// side by side: a mouse-moved posted at a point in display 1's CGDisplayBounds puts the cursor
|
||||
// there (lane ptrcross, potluck jobs m3-max-34583 to 34585).
|
||||
// The point is in WindowServer's global space, in which it placed each display: on x86-64 each
|
||||
// framebuffer holds its display's rectangle there as WindowServer gave it (IOFBSetBounds, which
|
||||
// IOFramebuffer::getBoundingRect reads), the space the cursor's moves arrive in
|
||||
// (IOFramebuffer::extSetCursorPosition); on arm64 the kext learns each one from its own moves
|
||||
// (RgfxDisplayPlaces.hpp). The display's pixel lies in that rectangle as the pixel
|
||||
// lies in the display's mode, scaled from the mode's pixels to the rectangle's size. Measured on
|
||||
// x86-64 macOS 11.7.11, 15.8.2 and 26.7.2 with two 1920 x 1080 displays side by side: each
|
||||
// framebuffer's rectangle is the display's CGDisplayBounds, and IOHIDSystem's mouse-moved posted
|
||||
// at a point of display 1's rectangle puts the cursor there (lane ptrcross, potluck jobs
|
||||
// m3-max-34583 to 34585).
|
||||
//
|
||||
// The move is a mouse-moved where no button is held, and the drag of the button held where one is,
|
||||
// as IOHIDSystem's own moves are (the left button's before the right's, the right's before any
|
||||
|
||||
@@ -19,38 +19,10 @@ void check(bool ok, const char *what)
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
void mixedScaleDesktop()
|
||||
{
|
||||
// IOFramebuffer keeps the physical and virtual desktop rectangles, in that order.
|
||||
const RgfxGlobalRect framebuffers[2][2] = {
|
||||
{{0, 0, 3840, 2160}, {0, 0, 1920, 1080}},
|
||||
{{3840, 0, 6400, 1440}, {1920, 0, 4480, 1440}},
|
||||
};
|
||||
const RgfxGlobalRect left = rgfxFramebufferDesktopBounds(framebuffers[0]);
|
||||
const RgfxGlobalRect right = rgfxFramebufferDesktopBounds(framebuffers[1]);
|
||||
int32_t x = 0, y = 0;
|
||||
check(rgfxPointerGlobal(right, 2560, 1440, 2, 653, &x, &y) && x == 1922 && y == 653,
|
||||
"crossing onto the native display uses its virtual origin");
|
||||
check(rgfxPointerGlobal(left, 3840, 2160, 3834, 943, &x, &y) && x == 1917 && y == 471,
|
||||
"crossing back scales scanout pixels into the HiDPI desktop rectangle");
|
||||
|
||||
// Both displays were native before the switch. Their physical rectangles stay the same.
|
||||
RgfxBoundsTold told = {};
|
||||
rgfxBoundsWereTold(&told, 0, framebuffers[0][0]);
|
||||
rgfxBoundsWereTold(&told, 1, framebuffers[1][0]);
|
||||
check(rgfxBoundsToTell(told, 0, left) && rgfxBoundsToTell(told, 1, right),
|
||||
"a HiDPI switch reports the resized display and the moved neighbor");
|
||||
const RgfxDisplayBounds command = rgfxBoundsCommand(1, right);
|
||||
check(command.min_x == 1920 && command.max_x == 4480 && command.max_y == 1440,
|
||||
"DISPLAY_BOUNDS uses the same desktop rectangle as the pointer post");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
mixedScaleDesktop();
|
||||
|
||||
// The wire's command: 40 bytes, the display then the rectangle past the 16-byte header.
|
||||
check(sizeof(RgfxDisplayBounds) == 40 && RGFX_CMD_DISPLAY_BOUNDS == 9, "the wire's");
|
||||
check(offsetof(RgfxDisplayBounds, display) == 16 && offsetof(RgfxDisplayBounds, min_x) == 20 &&
|
||||
|
||||
Binary file not shown.
@@ -34,4 +34,4 @@ Arch = "arm64e"
|
||||
MinKernel = "23.0.0"
|
||||
MaxKernel = ""
|
||||
Comment = "Installs the reims-graphics Metal bundle and admits it"
|
||||
sha256 = "969de78746515a49078709af17268af29ee398262dd45911e897c8ce2e806792"
|
||||
sha256 = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
|
||||
@@ -331,7 +331,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/ReimsGraphics.cpp" = "7ea4b22d26781eb7f673968cf77e33b65cd09042f4a949f600d27d1f9024ebec"
|
||||
"guest/kext/src/ReimsGraphics.hpp" = "e4162466ced71dd89ca50a38dcdf26c874765aab471bd96375fcb99f0766f20d"
|
||||
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
|
||||
"guest/kext/src/ReimsGraphicsPointer.cpp" = "7b3482545b8e5e459327ab31648e32d83fd8317587b453b4133a5974fa44e35d"
|
||||
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
|
||||
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
|
||||
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
|
||||
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
|
||||
@@ -359,7 +359,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
|
||||
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
|
||||
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
|
||||
"guest/kext/src/RgfxDisplayBounds.hpp" = "7aafbc6d1c2bb28e50c973f77d21c1aa00b322fb5fc934d4b1238b50f3aa89db"
|
||||
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
|
||||
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
|
||||
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
|
||||
"guest/kext/src/RgfxDisplayPipeUserClient.cpp" = "460c7d61a305d7d145b3318bb4fbe940c0d2d48d63afbbfeb6f273cd929aa3af"
|
||||
@@ -397,7 +397,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/RgfxPointerDevice.cpp" = "a4f88cc9b272259c3a85325b2295feea6a22221f52035fc5130d72f52cb88891"
|
||||
"guest/kext/src/RgfxPointerDevice.hpp" = "a393c90bed65528495868778e4130851e98aeafcb11401aef05d2d41d5b90d3f"
|
||||
"guest/kext/src/RgfxPointerMotion.hpp" = "d5cbe1a09db996980319d0b907782675fa82b5a03fd84a51f7c7d12c5dada926"
|
||||
"guest/kext/src/RgfxPointerOver.hpp" = "757946b2332ba278201f4c2f44ec1ee2bb21ca10b017a7c7933f696d8ee8f10c"
|
||||
"guest/kext/src/RgfxPointerOver.hpp" = "c2c38dbd101b1f59400bb159bd8cb44ed8c937bf25b93e9d62a03d6c2fd9ae50"
|
||||
"guest/kext/src/RgfxPointerReporting.cpp" = "c9f33023f3acea2e638353e8943c65f28f8befa984989ae88e7abc24858b961e"
|
||||
"guest/kext/src/RgfxPoolBlocks.hpp" = "a657b67922b04b75ccef6f12e10d775867f4037e50b89a8cf0d4972af43747fe"
|
||||
"guest/kext/src/RgfxQueueLimits.hpp" = "13f8ecd60e8d19f438b8ddc1cf3a0273fba1028bc049110776b637fa2097173c"
|
||||
@@ -466,5 +466,5 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"ReimsGraphics.kext/Contents/Info.plist" = "9683153587659c4bd4d5c52167eff1f3d2ae51dae575f60c15a27d89240f46c5"
|
||||
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "33a086b90fa116b3cf0c6bb826c27f8a55cd83f15522ee794e20186d469bdbc7"
|
||||
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
|
||||
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "969de78746515a49078709af17268af29ee398262dd45911e897c8ce2e806792"
|
||||
"set.toml" = "934935a19dea7d19f09c411552120e3290f2f534bf12d97c8b4900e140aa4140"
|
||||
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
|
||||
"set.toml" = "a4da2409f25dd7bf12260de752c38c474b60d4b2d993810a44de0f4b07cb6dfd"
|
||||
Binary file not shown.
Binary file not shown.
@@ -24,7 +24,7 @@ Arch = "x86_64"
|
||||
MinKernel = "20.0.0"
|
||||
MaxKernel = ""
|
||||
Comment = "The reims-graphics display, accelerator and device control"
|
||||
sha256 = "2f15b6a13b44e98d4af81240c44720c0004f3c7d5c9dfecfde3b39f069930349"
|
||||
sha256 = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
|
||||
|
||||
[[kext]]
|
||||
BundlePath = "RgfxGate.kext"
|
||||
@@ -34,4 +34,4 @@ Arch = "x86_64"
|
||||
MinKernel = "20.0.0"
|
||||
MaxKernel = ""
|
||||
Comment = "Installs the reims-graphics Metal bundle and admits it"
|
||||
sha256 = "534ab7e2f0b39ce9f6403b8988e89419889893b68ea91687b5aaeff38f5a9be6"
|
||||
sha256 = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
|
||||
@@ -331,7 +331,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/ReimsGraphics.cpp" = "7ea4b22d26781eb7f673968cf77e33b65cd09042f4a949f600d27d1f9024ebec"
|
||||
"guest/kext/src/ReimsGraphics.hpp" = "e4162466ced71dd89ca50a38dcdf26c874765aab471bd96375fcb99f0766f20d"
|
||||
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
|
||||
"guest/kext/src/ReimsGraphicsPointer.cpp" = "7b3482545b8e5e459327ab31648e32d83fd8317587b453b4133a5974fa44e35d"
|
||||
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
|
||||
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
|
||||
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
|
||||
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
|
||||
@@ -359,7 +359,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
|
||||
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
|
||||
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
|
||||
"guest/kext/src/RgfxDisplayBounds.hpp" = "7aafbc6d1c2bb28e50c973f77d21c1aa00b322fb5fc934d4b1238b50f3aa89db"
|
||||
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
|
||||
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
|
||||
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
|
||||
"guest/kext/src/RgfxDisplayPipeUserClient.cpp" = "460c7d61a305d7d145b3318bb4fbe940c0d2d48d63afbbfeb6f273cd929aa3af"
|
||||
@@ -397,7 +397,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/RgfxPointerDevice.cpp" = "a4f88cc9b272259c3a85325b2295feea6a22221f52035fc5130d72f52cb88891"
|
||||
"guest/kext/src/RgfxPointerDevice.hpp" = "a393c90bed65528495868778e4130851e98aeafcb11401aef05d2d41d5b90d3f"
|
||||
"guest/kext/src/RgfxPointerMotion.hpp" = "d5cbe1a09db996980319d0b907782675fa82b5a03fd84a51f7c7d12c5dada926"
|
||||
"guest/kext/src/RgfxPointerOver.hpp" = "757946b2332ba278201f4c2f44ec1ee2bb21ca10b017a7c7933f696d8ee8f10c"
|
||||
"guest/kext/src/RgfxPointerOver.hpp" = "c2c38dbd101b1f59400bb159bd8cb44ed8c937bf25b93e9d62a03d6c2fd9ae50"
|
||||
"guest/kext/src/RgfxPointerReporting.cpp" = "c9f33023f3acea2e638353e8943c65f28f8befa984989ae88e7abc24858b961e"
|
||||
"guest/kext/src/RgfxPoolBlocks.hpp" = "a657b67922b04b75ccef6f12e10d775867f4037e50b89a8cf0d4972af43747fe"
|
||||
"guest/kext/src/RgfxQueueLimits.hpp" = "13f8ecd60e8d19f438b8ddc1cf3a0273fba1028bc049110776b637fa2097173c"
|
||||
@@ -464,7 +464,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"Graft.kext/Contents/Info.plist" = "fa8533d5ec06430f3ede502e6f9e739e9c8c3f6b6909c46d854effe6028cbc7f"
|
||||
"Graft.kext/Contents/MacOS/Graft" = "04a1d44c0c80c20a71f3a662c46b56a1732b8134f095fb2ac57ec790f72baf72"
|
||||
"ReimsGraphics.kext/Contents/Info.plist" = "ae0dafd3b6c36c24d1c92467d8203d76360eb6e4f6ad5c496167a21033b2c209"
|
||||
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "2f15b6a13b44e98d4af81240c44720c0004f3c7d5c9dfecfde3b39f069930349"
|
||||
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
|
||||
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
|
||||
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "534ab7e2f0b39ce9f6403b8988e89419889893b68ea91687b5aaeff38f5a9be6"
|
||||
"set.toml" = "c2f6659892f049da4bc81ec2854915cdb5cd1c4de8b15728582264b64f166131"
|
||||
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
|
||||
"set.toml" = "49182c19c3d961b251901e19a09016df684f1f102527a0d3274697eaaf3dbab5"
|
||||
@@ -0,0 +1 @@
|
||||
patches/*.patch -text
|
||||
@@ -0,0 +1,200 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate acts) or agreed
|
||||
to in writing, shall any Contributor be liable to You for damages,
|
||||
including any direct, indirect, special, incidental, or consequential
|
||||
damages of any character arising as a result of this License or out of
|
||||
the use or inability to use the Work (including but not limited to damages
|
||||
for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Reims-Go contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Third-Party Notices
|
||||
|
||||
The build and packaging scripts were migrated from Reims-Go and are licensed
|
||||
under the Apache License, Version 2.0 (see `LICENSE` alongside the scripts).
|
||||
Local compatibility patches under `patches/` use terms compatible with their
|
||||
target upstream projects (see `patches/LICENSE`).
|
||||
|
||||
The portable runtime bundle (`reims-runtime-win-x64-<commit>.tar.zst`) contains
|
||||
precompiled binaries built from the following upstream open-source projects.
|
||||
Each runtime release ships the matching source package, `NOTICE.md`, and
|
||||
`licenses/`:
|
||||
|
||||
1. **reims-vgpu / reims-ctl**
|
||||
- Upstream: https://github.com/steelbrain/reims-vgpu
|
||||
- License: `GPL-2.0-or-later OR LGPL-3.0-or-later`
|
||||
2. **metal2vulkan / metal2vulkan-runtime**
|
||||
- Upstream: https://github.com/steelbrain/metal2vulkan
|
||||
- License: `GPL-2.0-or-later OR LGPL-3.0-or-later`
|
||||
3. **reims-util**
|
||||
- Upstream: https://github.com/steelbrain/reims-util
|
||||
- License: `GPL-2.0-or-later OR LGPL-3.0-or-later`
|
||||
4. **QEMU (qemu-reims-vgpu fork)**
|
||||
- Upstream: https://github.com/steelbrain/qemu-reims-vgpu
|
||||
- License: `GPL-2.0-only` / `GPL-2.0-or-later` (and component licenses in QEMU)
|
||||
5. **MSYS2 CLANG64 runtime libraries, libva, Mesa vaon12**
|
||||
- Upstream: https://github.com/msys2/MINGW-packages
|
||||
- License: Respective open-source licenses of each packaged DLL (bundled under `licenses/msys2/` in the runtime archive)
|
||||
|
||||
No Apple proprietary files, macOS installers, recovery images, or SMC keys are
|
||||
included in this repository or in any runtime bundle.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Licensing for `patches/`
|
||||
|
||||
Unlike the rest of the Reims-Go repository (which is licensed under the Apache
|
||||
License, Version 2.0), patch files in this directory are intended to be applied
|
||||
to and contributed back to their respective upstream repositories. To maintain
|
||||
strict license compatibility with each target codebase:
|
||||
|
||||
- `qemu-*.patch` (targeting `vendor/qemu` / QEMU) are licensed under
|
||||
**GPL-2.0-or-later**.
|
||||
- `reims-*.patch` (targeting `steelbrain/reims-vgpu` or `steelbrain/reims-util`) are
|
||||
dual-licensed under **GPL-2.0-or-later OR LGPL-3.0-or-later**.
|
||||
@@ -0,0 +1,44 @@
|
||||
# 运行时源码与依赖补丁
|
||||
|
||||
便携运行时由本仓库的 [Preview CI](../../../.github/workflows/runtime-preview.yml) 构建,使用以下源码分支。
|
||||
|
||||
| 组件 | 源码 | 维护范围 |
|
||||
| :--- | :--- | :--- |
|
||||
| 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 提交,用 `Cargo.toml` 和 `Cargo.lock` 固定 metal2vulkan,用 `crates/reims-ctl/src/reims_util.rs` 固定 reims-util。CI 根据这些固定值检出依赖,在运行时清单和对应源码包中记录四个组件的仓库及实际提交。
|
||||
|
||||
Alpha 编号与挂起兼容判定见 [Alpha 运行时编号与挂起兼容性规范](../versioning.md)。
|
||||
|
||||
## 构建时应用的依赖补丁
|
||||
|
||||
[`series.txt`](series.txt) 目前为空。临时补丁按清单顺序应用,冲突会停止构建。客户端的运行时包格式见[便携运行时规范](https://github.com/Nwflower/Reims-Go/blob/main/docs/portable-runtime-spec.md)。
|
||||
|
||||
---
|
||||
|
||||
## 关注中的上游 PR 与演进
|
||||
|
||||
跟踪仓库:[`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 与 [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。
|
||||
|
||||
| 上游方向 / PR | 价值与影响 | 合入后的跟进动作 |
|
||||
| :--- | :--- | :--- |
|
||||
| `#153` 图形呈现 | Windows NVIDIA MAILBOX/FIFO 首帧优化,改善高帧率与首帧延迟 | 随每日 `alpha` 构建进入冒烟验证 |
|
||||
| `#152` 平台层 | 原生 Windows Vulkan 后端,降低图形适配开销 | 升级运行时并对比帧率与稳定性 |
|
||||
| `#107` 图形内存 | 采样纹理回读就地消费,减少内存拷贝 | 随运行时升级纳入 |
|
||||
| `#123` 窗口体验 | `Ctrl+Alt+Enter` 运行中热切全屏 | 同步界面快捷键提示 |
|
||||
| `#172` 窗口体验 | Windows 拖动窗口动态贴合,消除缩放黑边 | 验证多显示器与高 DPI 缩放 |
|
||||
| `Win → Command` | 自由指针模式下 Windows 键映射 macOS Command | 合入后移除前端相关提示 |
|
||||
| `reims-util` 语言参数 | 支持 `opencore --lang` 并在重建 OpenCore 时保留 `prev-lang:kbd` | 合入后可逐步简化本仓 `internal/opencore` 补丁重写 |
|
||||
|
||||
---
|
||||
|
||||
## 补丁退役检查表
|
||||
|
||||
每日构建会跳过已合入的等价补丁,并在日志中报告。确认后按以下步骤清理。
|
||||
|
||||
1. 删除 `patches/` 下对应的 `.patch` 文件,并同步更新 [`series.txt`](series.txt) 与本文件。
|
||||
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`。
|
||||
@@ -0,0 +1,6 @@
|
||||
# Patch queue, in the order the patches are applied (see patches/README.md).
|
||||
# One patch per line: <target> <file>.
|
||||
# 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.
|
||||
@@ -0,0 +1,102 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Apply the patch queue in patches/series.txt to the checked-out upstream sources.
|
||||
|
||||
.DESCRIPTION
|
||||
For each patch, in series order:
|
||||
- applies cleanly -> apply it;
|
||||
- already in the tree -> skip it (git apply --reverse --check passes: on a
|
||||
fresh upstream clone this means merged upstream);
|
||||
- neither -> stop with an error. Patches are never edited
|
||||
automatically (AGENTS.md rule 4).
|
||||
|
||||
Writes the result as JSON to -ResultFile:
|
||||
{ "applied": ["a.patch", ...], "merged": ["b.patch", ...], "conflict": "c.patch" | null }
|
||||
so CI can pass the applied list to pack-runtime.ps1 (manifest states only what
|
||||
was really applied, AGENTS.md rule 5) and report merged or conflicting patches.
|
||||
|
||||
.EXAMPLE
|
||||
pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -Metal2VulkanRepo $env:RUNNER_TEMP\metal2vulkan -ResultFile patches.json
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$ReimsRepo,
|
||||
[string]$ResultFile = '',
|
||||
[string]$UtilRepo = '',
|
||||
[string]$Metal2VulkanRepo = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$patchesDir = Join-Path $repoRoot 'patches'
|
||||
$repositories = @{
|
||||
'reims-vgpu' = $ReimsRepo
|
||||
'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu'
|
||||
'reims-util' = $UtilRepo
|
||||
'metal2vulkan' = $Metal2VulkanRepo
|
||||
}
|
||||
|
||||
function Read-PatchSeries {
|
||||
$series = Join-Path $patchesDir 'series.txt'
|
||||
foreach ($line in Get-Content -LiteralPath $series) {
|
||||
$t = $line.Trim()
|
||||
if (-not $t -or $t.StartsWith('#')) { continue }
|
||||
$parts = $t -split '\s+'
|
||||
if ($parts.Count -ne 2 -or -not $repositories.ContainsKey($parts[0])) {
|
||||
throw "Bad line in patches/series.txt: '$line'"
|
||||
}
|
||||
[pscustomobject]@{ Target = $parts[0]; Name = $parts[1] }
|
||||
}
|
||||
}
|
||||
|
||||
$result = [ordered]@{ applied = @(); merged = @(); conflict = $null }
|
||||
function Save-Result {
|
||||
if ($ResultFile) {
|
||||
[IO.File]::WriteAllText($ResultFile, ($result | ConvertTo-Json -Depth 3), [Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
}
|
||||
|
||||
$series = @(Read-PatchSeries)
|
||||
if (-not $UtilRepo -and $series.Target -contains 'reims-util') {
|
||||
throw 'Pass -UtilRepo with a checkout at the reims-util revision pinned by reims-ctl.'
|
||||
}
|
||||
if (-not $Metal2VulkanRepo -and $series.Target -contains 'metal2vulkan') {
|
||||
throw 'Pass -Metal2VulkanRepo with a checkout at the metal2vulkan revision pinned by reims-vgpu.'
|
||||
}
|
||||
|
||||
foreach ($p in $series) {
|
||||
$file = Join-Path $patchesDir $p.Name
|
||||
if (-not (Test-Path -LiteralPath $file)) { throw "Patch listed in series.txt is missing: $file" }
|
||||
$dir = $repositories[$p.Target]
|
||||
# git -C into a missing or uninitialised submodule falls back to the outer
|
||||
# repository, where "git apply" silently skips paths outside the current
|
||||
# directory and reports success. Require $dir to be its own work tree.
|
||||
$top = (& git -C $dir rev-parse --show-toplevel 2>$null)
|
||||
if ($LASTEXITCODE -ne 0 -or -not $top -or
|
||||
[IO.Path]::GetFullPath($top.Trim()).TrimEnd([char[]]'\/') -ne [IO.Path]::GetFullPath($dir).TrimEnd([char[]]'\/')) {
|
||||
throw "$dir is not a checked-out git work tree for $($p.Target)"
|
||||
}
|
||||
|
||||
& git -C $dir apply --check $file 2>$null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
& git -C $dir apply $file
|
||||
if ($LASTEXITCODE -ne 0) { throw "git apply $($p.Name) failed after a clean --check" }
|
||||
Write-Host "applied $($p.Target) $($p.Name)"
|
||||
$result.applied += $p.Name
|
||||
continue
|
||||
}
|
||||
& git -C $dir apply --reverse --check $file 2>$null
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-Host "merged $($p.Target) $($p.Name) (already in the tree: merged upstream? retire it per spec section 5 rule 4)"
|
||||
$result.merged += $p.Name
|
||||
continue
|
||||
}
|
||||
$result.conflict = $p.Name
|
||||
Save-Result
|
||||
# Show git's own reason in the log.
|
||||
& git -C $dir apply --check $file
|
||||
throw "$($p.Name) neither applies nor is already upstream in $dir. Stop: don't edit patches automatically (AGENTS.md rule 4)."
|
||||
}
|
||||
$global:LASTEXITCODE = 0
|
||||
Save-Result
|
||||
@@ -0,0 +1,161 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Entry gate for the alpha channel (portable-runtime-spec.md section 6), run by
|
||||
CI on the packed release files before anything is published.
|
||||
|
||||
.DESCRIPTION
|
||||
Fails unless all of these hold:
|
||||
1. The runtime, both source packages and SHA256SUMS.txt exist. Slim
|
||||
releases also require the matching detached symbols archive.
|
||||
2. SHA256SUMS.txt lists all release archives and every hash matches.
|
||||
3. manifest.json in the runtime names -Commit, channel "alpha", the source
|
||||
package, and exactly the patches in -AppliedPatches.
|
||||
4. The runtime's own qemu-system-x86_64.exe, run with a PATH holding only
|
||||
the runtime and Windows (no MSYS2), lists reims-graphics-pci in
|
||||
"-device help".
|
||||
|
||||
This is not the stable gate: promotion to stable still needs the real-host
|
||||
smoke test (scripts/smoke-runtime.ps1) and a person's approval.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$OutDir,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Commit,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[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',
|
||||
[string]$TempRoot = $env:RUNNER_TEMP
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$AppliedPatches = @($AppliedPatches | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||
|
||||
$names = @{
|
||||
runtime = "reims-runtime-win-x64-$Commit.tar.zst"
|
||||
source = "reims-runtime-src-$Commit.tar.zst"
|
||||
msys2 = "reims-runtime-msys2-src-$Commit.tar.zst"
|
||||
sums = 'SHA256SUMS.txt'
|
||||
}
|
||||
|
||||
$symbolsName = "reims-runtime-symbols-$Commit"
|
||||
if ($RequireSlim -or (Test-Path -LiteralPath (Join-Path $OutDir "$symbolsName.tar.zst"))) {
|
||||
$names.symbols = "$symbolsName.tar.zst"
|
||||
}
|
||||
# 1. All assets for this layout.
|
||||
foreach ($k in $names.Keys) {
|
||||
$p = Join-Path $OutDir $names[$k]
|
||||
if (-not (Test-Path -LiteralPath $p)) { throw "Missing release asset: $($names[$k])" }
|
||||
}
|
||||
Write-Host "PASS $($names.Count) release assets present"
|
||||
|
||||
# 2. Sums cover the archives and match.
|
||||
$sums = @{}
|
||||
foreach ($line in Get-Content -LiteralPath (Join-Path $OutDir $names.sums)) {
|
||||
if ($line -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') { $sums[$Matches[2].Trim()] = $Matches[1].ToLowerInvariant() }
|
||||
}
|
||||
foreach ($k in ($names.Keys | Where-Object { $_ -ne 'sums' })) {
|
||||
$n = $names[$k]
|
||||
if (-not $sums.ContainsKey($n)) { throw "SHA256SUMS.txt has no entry for $n" }
|
||||
$got = (Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $OutDir $n)).Hash.ToLowerInvariant()
|
||||
if ($got -ne $sums[$n]) { throw "SHA256 mismatch for ${n}: listed $($sums[$n]), actual $got" }
|
||||
}
|
||||
Write-Host 'PASS SHA256SUMS.txt covers and matches all archives'
|
||||
|
||||
# Extract the runtime.
|
||||
$work = Join-Path $TempRoot ("alpha-gate-" + [guid]::NewGuid())
|
||||
New-Item -ItemType Directory -Force -Path $work | Out-Null
|
||||
try {
|
||||
$tar = Join-Path $work 'runtime.tar'
|
||||
& $Zstd -d -q -f (Join-Path $OutDir $names.runtime) -o $tar
|
||||
if ($LASTEXITCODE -ne 0) { throw "zstd failed ($LASTEXITCODE)" }
|
||||
# Windows' own bsdtar: GNU tar from Git/MSYS2 reads "D:" as a remote host.
|
||||
& (Join-Path $env:SystemRoot 'System32\tar.exe') -xf $tar -C $work
|
||||
if ($LASTEXITCODE -ne 0) { throw "tar failed ($LASTEXITCODE)" }
|
||||
Remove-Item -LiteralPath $tar -Force
|
||||
$root = Join-Path $work "reims-runtime-win-x64-$Commit"
|
||||
|
||||
# 3. Manifest states what was really built.
|
||||
$m = Get-Content -Raw -LiteralPath (Join-Path $root 'manifest.json') | ConvertFrom-Json
|
||||
if ($m.commit -ne $Commit) { throw "manifest commit is $($m.commit), expected $Commit" }
|
||||
if ($m.channel -ne $ExpectChannel) { throw "manifest channel is $($m.channel), expected $ExpectChannel" }
|
||||
if ($m.source_package -ne $names.source) { throw "manifest source_package is $($m.source_package), expected $($names.source)" }
|
||||
if ($RequiredCapability -and $RequiredCapability -notin $m.capabilities) { throw "manifest lacks capability $RequiredCapability" }
|
||||
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)
|
||||
if ($m.raw_bytes -ne $rawBytes) { throw "manifest raw_bytes is $($m.raw_bytes), actual $rawBytes" }
|
||||
$declared = @($m.patches | ForEach-Object { $_.name })
|
||||
if (($declared -join ',') -ne ($AppliedPatches -join ',')) {
|
||||
throw "manifest patches [$($declared -join ', ')] differ from those applied [$($AppliedPatches -join ', ')]"
|
||||
}
|
||||
Write-Host "PASS manifest: commit $Commit, channel $($m.channel), patches [$($declared -join ', ')]"
|
||||
|
||||
if ($m.symbols_package -or $names.symbols) {
|
||||
if (!$names.symbols -or $m.symbols_package -ne $names.symbols) { throw 'Missing or mismatched symbols package' }
|
||||
$symTar = Join-Path $work 'symbols.tar'
|
||||
& $Zstd -d -q -f (Join-Path $OutDir $names.symbols) -o $symTar
|
||||
if ($LASTEXITCODE) { throw 'Cannot decompress symbols package' }
|
||||
$members = & (Join-Path $env:SystemRoot 'System32\tar.exe') -tf $symTar
|
||||
if ($LASTEXITCODE) { throw 'Cannot list symbols package' }
|
||||
foreach ($rel in 'bin/reims-ctl.exe','bin/reims-util.exe','qemu/bin/qemu-system-x86_64.exe','qemu/bin/qemu-img.exe','qemu/bin/reims-vgpu-compile.exe') {
|
||||
$hash = (Get-FileHash -LiteralPath (Join-Path $root $rel) -Algorithm SHA256).Hash
|
||||
if ($hash -ne $m.sha256.$rel) { throw "Manifest hash mismatch for $rel" }
|
||||
if ("$symbolsName/$rel.debug" -notin $members) { throw "Missing debug file for $rel" }
|
||||
}
|
||||
foreach ($rel in 'qemu/bin/libva.dll','qemu/bin/libva_win32.dll','qemu/bin/vaon12_drv_video.dll','NOTICE.md','MSYS2-PACKAGES.txt') {
|
||||
if (!(Test-Path -LiteralPath (Join-Path $root $rel) -PathType Leaf)) { throw "Missing runtime dependency: $rel" }
|
||||
}
|
||||
Write-Host 'PASS stripped executable hashes, detached debug members and video driver files'
|
||||
}
|
||||
|
||||
# 4. QEMU runs from the bundle alone and has the reims device.
|
||||
$qemuBin = Join-Path $root 'qemu\bin'
|
||||
$psi = [Diagnostics.ProcessStartInfo]::new((Join-Path $qemuBin 'qemu-system-x86_64.exe'), '-device help')
|
||||
$psi.UseShellExecute = $false
|
||||
$psi.RedirectStandardOutput = $true
|
||||
$psi.RedirectStandardError = $true
|
||||
$psi.WorkingDirectory = $qemuBin
|
||||
$psi.Environment['PATH'] = "$qemuBin;$env:SystemRoot\System32;$env:SystemRoot"
|
||||
$proc = [Diagnostics.Process]::Start($psi)
|
||||
$errTask = $proc.StandardError.ReadToEndAsync()
|
||||
$out = $proc.StandardOutput.ReadToEnd()
|
||||
if (-not $proc.WaitForExit(120000)) { $proc.Kill(); throw 'qemu -device help timed out' }
|
||||
$err = $errTask.Result
|
||||
if ($proc.ExitCode -ne 0) { throw "qemu -device help exited $($proc.ExitCode): $err" }
|
||||
if ($out -notmatch 'reims-graphics-pci') { throw "qemu -device help does not list reims-graphics-pci`n$out`n$err" }
|
||||
Write-Host 'PASS qemu-system-x86_64 -device help lists reims-graphics-pci (no MSYS2 on PATH)'
|
||||
if ($names.symbols) {
|
||||
$oldPath = $env:PATH
|
||||
$img = Join-Path $qemuBin 'qemu-img.exe'
|
||||
try {
|
||||
$env:PATH = $psi.Environment['PATH']
|
||||
foreach ($exe in 'reims-ctl.exe','reims-util.exe') {
|
||||
& (Join-Path $root "bin/$exe") --version
|
||||
if ($LASTEXITCODE) { throw "$exe --version failed ($LASTEXITCODE)" }
|
||||
}
|
||||
$disk = Join-Path $work 'test.qcow2'
|
||||
& $img create -f qcow2 $disk 32M
|
||||
if ($LASTEXITCODE) { throw "qemu-img create failed ($LASTEXITCODE)" }
|
||||
$info = & $img info --output=json $disk
|
||||
if ($LASTEXITCODE -or (($info -join "`n" | ConvertFrom-Json).'virtual-size' -ne 32MB)) { throw 'qemu-img info failed' }
|
||||
} finally { $env:PATH = $oldPath }
|
||||
Write-Host 'PASS CLI versions and qcow2 creation / inspection (no MSYS2 on PATH)'
|
||||
}
|
||||
} finally {
|
||||
Remove-Item -Recurse -Force -LiteralPath $work -ErrorAction SilentlyContinue
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Pack the sources of the copyleft MSYS2 packages whose DLLs a runtime bundles,
|
||||
as a separate release asset.
|
||||
|
||||
.DESCRIPTION
|
||||
Reads the "# Packages" list from a runtime's MSYS2-PACKAGES.txt, looks up each
|
||||
package's source name (%BASE%) and licenses in the local pacman database, and
|
||||
keeps the packages whose license requires source (GPL / LGPL / MPL) unless an
|
||||
alternative licence without those can be chosen (for example "GPL OR FTL").
|
||||
|
||||
For each kept package it downloads <base>-<version>.src.tar.zst and its .sig
|
||||
from repo.msys2.org (cached in -CacheDir), checks the signature against the
|
||||
MSYS2 keyring with gpgv, and packs them into
|
||||
reims-runtime-msys2-src-<commit>.tar.zst in -OutDir. The archive's hash is
|
||||
added to -OutDir\SHA256SUMS.txt (an existing line for it is replaced).
|
||||
|
||||
Published in the same GitHub Release as the runtime, so the sources are
|
||||
offered from the same place as the binaries (GPLv2 §3, LGPL-2.1 §6).
|
||||
|
||||
.EXAMPLE
|
||||
pwsh -File scripts/pack-msys2-sources.ps1 -PackagesFile MSYS2-PACKAGES.txt -Commit 3731afd -OutDir D:\Data\reims-go\releases\3731afd-candidate
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)] [string]$PackagesFile,
|
||||
[Parameter(Mandatory)] [string]$Commit,
|
||||
[Parameter(Mandatory)] [string]$OutDir,
|
||||
[string]$Msys2 = 'D:\DevTools\msys64',
|
||||
[string]$CacheDir = 'D:\Data\reims-go\releases\msys2-sources-cache',
|
||||
[string]$TempRoot = 'D:\Build\Temp',
|
||||
[string]$Mirror = 'https://repo.msys2.org/mingw/sources'
|
||||
)
|
||||
|
||||
$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 = Resolve-Zstd -Msys2 $Msys2
|
||||
|
||||
function Write-Utf8([string]$path, [string]$text) {
|
||||
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
|
||||
function Read-Desc([string]$name, [string]$version) {
|
||||
$file = Join-Path $localDb "$name-$version\desc"
|
||||
if (-not (Test-Path -LiteralPath $file)) {
|
||||
throw "$name $version is not in the local pacman database ($file): was MSYS2 updated after the runtime was built?"
|
||||
}
|
||||
$fields = @{}
|
||||
$key = $null
|
||||
foreach ($line in Get-Content -LiteralPath $file) {
|
||||
if ($line -match '^%(\w+)%$') { $key = $Matches[1]; $fields[$key] = @(); continue }
|
||||
if ($key -and $line -ne '') { $fields[$key] += $line }
|
||||
}
|
||||
return $fields
|
||||
}
|
||||
|
||||
# A licence entry needs source unless one OR-alternative is free of copyleft.
|
||||
# Entries prefixed "documentation:" cover only docs, which aren't shipped.
|
||||
function Test-NeedsSource([string[]]$licenses) {
|
||||
foreach ($entry in $licenses) {
|
||||
if ($entry -like 'documentation:*') { continue }
|
||||
$expr = $entry -replace '^spdx:', ''
|
||||
$alternatives = $expr -split '\s+OR\s+'
|
||||
$allCopyleft = $true
|
||||
foreach ($alt in $alternatives) {
|
||||
if ($alt -notmatch 'GPL|MPL') { $allCopyleft = $false }
|
||||
}
|
||||
if ($allCopyleft) { return $true }
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
function To-MsysPath([string]$winPath) {
|
||||
$p = $winPath -replace '\\', '/'
|
||||
if ($p -match '^([A-Za-z]):(.*)$') { return '/' + $Matches[1].ToLower() + $Matches[2] }
|
||||
return $p
|
||||
}
|
||||
|
||||
# ── 1. Which packages need source ────────────────────────────
|
||||
$text = Get-Content -Raw -LiteralPath $PackagesFile
|
||||
$section = ($text -split '# Packages[^\n]*\n', 2)[1]
|
||||
if (-not $section) { throw "No '# Packages' section in $PackagesFile" }
|
||||
$packages = $section -split "`n" | Where-Object { $_ -match '^\S+ \S+$' } | ForEach-Object {
|
||||
$n, $v = $_ -split ' '
|
||||
$d = Read-Desc $n $v
|
||||
[pscustomobject]@{
|
||||
Name = $n
|
||||
Version = $v
|
||||
Base = $d['BASE'][0]
|
||||
Licenses = $d['LICENSE']
|
||||
Needs = (Test-NeedsSource $d['LICENSE'])
|
||||
}
|
||||
}
|
||||
$needed = @($packages | Where-Object Needs | Sort-Object Base, Version -Unique)
|
||||
Write-Host ("==> {0} of {1} packages need source; {2} source archives" -f @($packages | Where-Object Needs).Count, $packages.Count, $needed.Count)
|
||||
|
||||
# ── 2. Download and verify ───────────────────────────────────
|
||||
New-Item -ItemType Directory -Force -Path $CacheDir, $OutDir | Out-Null
|
||||
foreach ($p in $needed) {
|
||||
$file = "$($p.Base)-$($p.Version).src.tar.zst"
|
||||
foreach ($f in @($file, "$file.sig")) {
|
||||
$dest = Join-Path $CacheDir $f
|
||||
if (-not (Test-Path -LiteralPath $dest)) {
|
||||
Write-Host " downloading $f"
|
||||
Invoke-WebRequest -Uri "$Mirror/$f" -OutFile "$dest.part" -UserAgent 'reims-go-packager'
|
||||
Move-Item -LiteralPath "$dest.part" -Destination $dest -Force
|
||||
}
|
||||
}
|
||||
$cache = To-MsysPath $CacheDir
|
||||
$out = & $bash -lc "LC_ALL=C gpgv --keyring /etc/pacman.d/gnupg/pubring.gpg '$cache/$file.sig' '$cache/$file' 2>&1"
|
||||
if ($LASTEXITCODE -ne 0) { throw "Signature check failed for ${file}:`n$out" }
|
||||
$signer = ($out | Select-String 'Good signature from "([^"]+)"').Matches.Groups[1].Value
|
||||
$p | Add-Member -NotePropertyName File -NotePropertyValue $file
|
||||
$p | Add-Member -NotePropertyName Signer -NotePropertyValue $signer
|
||||
}
|
||||
|
||||
# ── 3. Pack ──────────────────────────────────────────────────
|
||||
$name = "reims-runtime-msys2-src-$Commit"
|
||||
$stage = Join-Path $TempRoot "pack-$name"
|
||||
if (Test-Path -LiteralPath $stage) { Remove-Item -Recurse -Force -LiteralPath $stage }
|
||||
$dir = Join-Path $stage $name
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $dir 'sources') | Out-Null
|
||||
foreach ($p in $needed) {
|
||||
Copy-Item -LiteralPath (Join-Path $CacheDir $p.File) -Destination (Join-Path $dir 'sources')
|
||||
Copy-Item -LiteralPath (Join-Path $CacheDir "$($p.File).sig") -Destination (Join-Path $dir 'sources')
|
||||
}
|
||||
|
||||
$rows = foreach ($p in ($packages | Sort-Object Name)) {
|
||||
$lic = ($p.Licenses -join '; ') -replace '\|', '/'
|
||||
$src = if ($p.Needs) { "``sources/$("$($p.Base)-$($p.Version).src.tar.zst")``" } else { '— (permissive licence; text in the runtime''s licenses/)' }
|
||||
"| ``$($p.Name -replace '^mingw-w64-clang-x86_64-', '')`` | $($p.Version) | $lic | $src |"
|
||||
}
|
||||
Write-Utf8 (Join-Path $dir 'README.md') @"
|
||||
# MSYS2 package sources for reims-runtime-win-x64-$Commit
|
||||
|
||||
The runtime's ``qemu/bin`` bundles DLLs from MSYS2 CLANG64 packages. This archive
|
||||
holds, unmodified, the source packages of every one whose licence requires source
|
||||
(GPL, LGPL or MPL with no permissive alternative), exactly as MSYS2 publishes them
|
||||
at $Mirror, each with its detached signature (``.sig``), checked with gpgv
|
||||
against the MSYS2 keyring when this archive was made.
|
||||
|
||||
A ``.src.tar.zst`` contains the PKGBUILD, the upstream source tarball and MSYS2's
|
||||
patches: ``makepkg-mingw`` in an MSYS2 shell rebuilds the package.
|
||||
|
||||
| Package | Version | Licence | Source |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
$($rows -join "`n")
|
||||
"@
|
||||
|
||||
$tar = Join-Path $TempRoot "$name.tar"
|
||||
& tar.exe -cf $tar -C $stage $name
|
||||
if ($LASTEXITCODE -ne 0) { throw 'tar failed' }
|
||||
$archive = Join-Path $OutDir "$name.tar.zst"
|
||||
& $zstd -T0 -3 -q -f $tar -o $archive # contents are already compressed
|
||||
if ($LASTEXITCODE -ne 0) { throw 'zstd failed' }
|
||||
Remove-Item -LiteralPath $tar -Force
|
||||
Remove-Item -Recurse -Force -LiteralPath $stage
|
||||
|
||||
# ── 4. SHA256SUMS.txt ────────────────────────────────────────
|
||||
$hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $archive).Hash.ToLowerInvariant()
|
||||
$sums = Join-Path $OutDir 'SHA256SUMS.txt'
|
||||
$lines = @()
|
||||
if (Test-Path -LiteralPath $sums) {
|
||||
$lines = @(Get-Content -LiteralPath $sums | Where-Object { $_ -and $_ -notmatch " $([regex]::Escape("$name.tar.zst"))$" })
|
||||
}
|
||||
$lines += "$hash $name.tar.zst"
|
||||
Write-Utf8 $sums (($lines -join "`n") + "`n")
|
||||
|
||||
Write-Host '==> Done' -ForegroundColor Green
|
||||
'{0} {1:N1} MB ({2} source archives, all signatures good)' -f $archive, ((Get-Item $archive).Length / 1MB), $needed.Count
|
||||
@@ -0,0 +1,587 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Pack a portable reims-vgpu runtime for Windows x64, its matching source
|
||||
package, and SHA256SUMS.txt, ready to publish as a GitHub Release.
|
||||
|
||||
.DESCRIPTION
|
||||
Outputs, in -OutDir (all five are assets of one GitHub Release):
|
||||
reims-runtime-win-x64-<commit>.tar.zst runtime (bin/, qemu/, manifest.json,
|
||||
NOTICE.md, licenses/, patches/,
|
||||
MSYS2-PACKAGES.txt)
|
||||
reims-runtime-src-<commit>.tar.zst corresponding source: pristine upstream
|
||||
trees at the built commits + patches/
|
||||
reims-runtime-msys2-src-<commit>.tar.zst sources of the copyleft MSYS2 packages
|
||||
whose DLLs are bundled (pack-msys2-sources.ps1)
|
||||
reims-runtime-symbols-<commit>.tar.zst detached debug files for the five programs
|
||||
SHA256SUMS.txt all four archives
|
||||
|
||||
manifest.json (schema 2) states what the package was really built from:
|
||||
upstream commit, vendor/qemu commit, reims-util and metal2vulkan commits,
|
||||
every local patch with its SHA256, and the channel. A package built with
|
||||
patches is never described as pure upstream (AGENTS.md rule 5).
|
||||
|
||||
The patches come from patches/series.txt (in that order). -Patches narrows
|
||||
them to the ones really applied to the build tree (CI passes the list from
|
||||
apply-patch-series.ps1, which skips patches already merged upstream).
|
||||
Before packing, the build tree's diff must equal the declared patches, so
|
||||
the source package matches the binaries, and any other change in the
|
||||
build trees is refused. A mismatch stops the script.
|
||||
|
||||
.EXAMPLE
|
||||
pwsh -File scripts/pack-runtime.ps1 -Channel alpha
|
||||
pwsh -File scripts/pack-runtime.ps1 -Patches reims-util-parallel-offline-download.patch,metal2vulkan-snapshot-replay.patch
|
||||
#>
|
||||
[CmdletBinding(PositionalBinding = $false)]
|
||||
param(
|
||||
[string]$ReimsRepo = 'D:\DevTools\reims-vgpu',
|
||||
[string]$UtilRepo = '',
|
||||
[string]$Metal2VulkanRepo = '',
|
||||
[string]$CargoHome = 'D:\DevTools\cargo',
|
||||
[string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current',
|
||||
[string]$Msys2 = 'D:\DevTools\msys64',
|
||||
[string]$OutDir = 'D:\Data\reims-go\releases',
|
||||
[string]$TempRoot = 'D:\Build\Temp',
|
||||
# Channel at build time. A runtime is promoted to stable by turning its
|
||||
# GitHub prerelease into a release, never by repacking (spec section 6).
|
||||
[ValidateSet('alpha', 'stable')]
|
||||
[string]$Channel = 'alpha',
|
||||
[int]$ZstdLevel = 15,
|
||||
# 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'
|
||||
|
||||
function Invoke-Native([string]$exe, [string[]]$argv) {
|
||||
& $exe @argv
|
||||
if ($LASTEXITCODE -ne 0) { throw "$exe $($argv -join ' ') failed ($LASTEXITCODE)" }
|
||||
}
|
||||
|
||||
function Invoke-GitApply([string]$repo, [string]$patchText, [switch]$Check) {
|
||||
$psi = [Diagnostics.ProcessStartInfo]::new()
|
||||
$psi.FileName = (Get-Command git).Source
|
||||
$psi.WorkingDirectory = $repo
|
||||
$psi.UseShellExecute = $false
|
||||
$psi.RedirectStandardInput = $true
|
||||
$psi.RedirectStandardOutput = $true
|
||||
$psi.RedirectStandardError = $true
|
||||
$psi.ArgumentList.Add('apply')
|
||||
if ($Check) { $psi.ArgumentList.Add('--check') }
|
||||
$psi.ArgumentList.Add('-')
|
||||
$proc = [Diagnostics.Process]::Start($psi)
|
||||
$proc.StandardInput.NewLine = "`n"
|
||||
$proc.StandardInput.Write($patchText)
|
||||
$proc.StandardInput.Close()
|
||||
$stdout = $proc.StandardOutput.ReadToEnd()
|
||||
$stderr = $proc.StandardError.ReadToEnd()
|
||||
$proc.WaitForExit()
|
||||
if ($proc.ExitCode) { throw "git apply failed in $repo ($($proc.ExitCode)): $stdout$stderr" }
|
||||
}
|
||||
|
||||
function Get-Sha256([string]$path) {
|
||||
(Get-FileHash -Algorithm SHA256 -LiteralPath $path).Hash.ToLowerInvariant()
|
||||
}
|
||||
|
||||
function Write-Utf8([string]$path, [string]$text) {
|
||||
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
|
||||
function New-TarZst([string]$parent, [string]$name, [string]$archive) {
|
||||
$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)
|
||||
Remove-Item -LiteralPath $tar -Force
|
||||
}
|
||||
|
||||
# ── 1. Inputs and provenance ─────────────────────────────────
|
||||
function Get-GitHubSource([string]$Url, [string]$Fallback) {
|
||||
if ($Url -match '^(?:https://(?:[^/@]+@)?github\.com/|git@github\.com:)([\w.-]+/[\w.-]+?)(?:\.git)?/?$') {
|
||||
return "https://github.com/$($Matches[1])"
|
||||
}
|
||||
return "https://github.com/$Fallback"
|
||||
}
|
||||
|
||||
$ctlExe = Join-Path $CargoBin 'reims-ctl.exe'
|
||||
$utilExe = Join-Path $CargoBin 'reims-util.exe'
|
||||
$qemuExe = Join-Path $QemuDir 'bin\qemu-system-x86_64.exe'
|
||||
foreach ($p in @($ctlExe, $utilExe, $qemuExe)) {
|
||||
if (-not (Test-Path -LiteralPath $p)) { throw "Required runtime binary not found: $p" }
|
||||
}
|
||||
|
||||
$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
|
||||
$qemuOrigin = git -C $ReimsRepo config --file .gitmodules --get submodule.vendor/qemu.url
|
||||
$reimsSource = Get-GitHubSource $reimsOrigin 'steelbrain/reims-vgpu'
|
||||
$qemuSource = Get-GitHubSource $qemuOrigin 'steelbrain/qemu-reims-vgpu'
|
||||
$capabilities = @()
|
||||
$runtimeFeatures = Join-Path $ReimsRepo 'reims-go-runtime.json'
|
||||
if (Test-Path -LiteralPath $runtimeFeatures) {
|
||||
$capabilities = @((Get-Content -Raw -LiteralPath $runtimeFeatures | ConvertFrom-Json).capabilities)
|
||||
}
|
||||
|
||||
$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
|
||||
} else {
|
||||
Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' |
|
||||
ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } |
|
||||
Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
|
||||
}
|
||||
if (-not $utilTree) { throw "reims-util source at $utilCommit not found" }
|
||||
$actualUtil = git -C $utilTree rev-parse HEAD
|
||||
if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" }
|
||||
|
||||
$m2vTree = if ($Metal2VulkanRepo) {
|
||||
(Resolve-Path -LiteralPath $Metal2VulkanRepo).Path
|
||||
} else {
|
||||
Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' -ErrorAction SilentlyContinue |
|
||||
ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } |
|
||||
Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
|
||||
}
|
||||
if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found (pass -Metal2VulkanRepo or check $checkouts)" }
|
||||
$actualM2v = (git -C $m2vTree rev-parse HEAD).Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or $actualM2v -ne $m2vCommit) { throw "metal2vulkan checkout must be at $m2vCommit (got $actualM2v)" }
|
||||
|
||||
$qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim()
|
||||
$utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim()
|
||||
|
||||
# ── 2. Patches must equal the build tree's diffs ─────────────
|
||||
$repositories = @{
|
||||
'reims-vgpu' = $ReimsRepo
|
||||
'vendor/qemu' = $qemuRepo
|
||||
'reims-util' = $utilTree
|
||||
'metal2vulkan' = $m2vTree
|
||||
}
|
||||
$series = @(foreach ($line in Get-Content -LiteralPath (Join-Path $patchesDir 'series.txt')) {
|
||||
$t = $line.Trim()
|
||||
if (-not $t -or $t.StartsWith('#')) { continue }
|
||||
$parts = $t -split '\s+'
|
||||
if ($parts.Count -ne 2 -or -not $repositories.ContainsKey($parts[0])) { throw "Bad line in patches/series.txt: '$line'" }
|
||||
[pscustomobject]@{ Target = $parts[0]; Name = $parts[1] }
|
||||
})
|
||||
# PowerShell -File passes "a,b" as one string: accept both forms.
|
||||
$Patches = @($Patches | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||
foreach ($n in $Patches) {
|
||||
if ($n -notin $series.Name) { throw "-Patches names $n, which is not in patches/series.txt" }
|
||||
}
|
||||
$patchSpecs = @()
|
||||
$usePatchList = $PSBoundParameters.ContainsKey('Patches')
|
||||
foreach ($e in $series) {
|
||||
if ($usePatchList -and $e.Name -notin $Patches) { continue }
|
||||
$file = Join-Path $patchesDir $e.Name
|
||||
if (-not (Test-Path -LiteralPath $file)) { throw "Patch missing: $file" }
|
||||
# Files the patch touches ("--- a/x" / "+++ b/x", and each "diff --git a/x b/y" header, which a
|
||||
# binary patch has alone), to scope the diff checks.
|
||||
$paths = @(Get-Content -LiteralPath $file | ForEach-Object {
|
||||
if ($_ -match '^(?:---|\+\+\+) [ab]/(.+?)\s*$') { $Matches[1] }
|
||||
elseif ($_ -match '^diff --git a/(.+?) b/(.+?)\s*$') { $Matches[1]; $Matches[2] }
|
||||
} | Select-Object -Unique)
|
||||
$patchSpecs += @{
|
||||
Name = $e.Name
|
||||
Target = $e.Target
|
||||
Repo = $repositories[$e.Target]
|
||||
Paths = $paths
|
||||
}
|
||||
}
|
||||
# Avoid colliding with the [string[]]$Patches parameter (PowerShell variable
|
||||
# names are case-insensitive; reusing $patches coerces every entry to a string).
|
||||
$patchEntries = @()
|
||||
# Group patches by repo so multi-patch stacks (e.g. 2-3 QEMU WHPX patches) are
|
||||
# verified together against a clean HEAD export with zero undeclared diff.
|
||||
$byTarget = [ordered]@{}
|
||||
foreach ($ps in $patchSpecs) {
|
||||
$file = Join-Path $patchesDir $ps.Name
|
||||
if (-not (Test-Path -LiteralPath $file)) { throw "Patch missing: $file" }
|
||||
if (-not $byTarget.Contains($ps.Target)) {
|
||||
$byTarget[$ps.Target] = [Collections.Generic.List[hashtable]]::new()
|
||||
}
|
||||
$byTarget[$ps.Target].Add($ps)
|
||||
$patchEntries += [ordered]@{ name = $ps.Name; target = $ps.Target; sha256 = (Get-Sha256 $file) }
|
||||
}
|
||||
foreach ($targetName in $byTarget.Keys) {
|
||||
$group = $byTarget[$targetName]
|
||||
$repo = $group[0].Repo
|
||||
$paths = @($group | ForEach-Object { $_.Paths } | Where-Object { $_ } | Select-Object -Unique)
|
||||
# Use --full-index so blob hash abbreviation lengths match regardless of
|
||||
# object count between the upstream clone and the single-commit verify repo.
|
||||
$diffArgs = @('-C', $repo, '-c', 'core.autocrlf=false', 'diff', '--full-index')
|
||||
if ($paths.Count) { $diffArgs += '--'; $diffArgs += $paths }
|
||||
# The mode on an "index" line is the file's, not the change's: the verify tree is extracted by
|
||||
# tar on Windows, which keeps no executable bit, so a changed executable (a prebuilt kext) reads
|
||||
# 100644 there and 100755 here. A change of mode has its own "old mode"/"new mode" lines, which
|
||||
# stay compared.
|
||||
$indexMode = '(?m)^(index [0-9a-f]+\.\.[0-9a-f]+) [0-7]{6}$'
|
||||
$treeDiff = ((& git @diffArgs | Out-String).Replace("`r`n", "`n") -replace $indexMode, '$1').TrimEnd()
|
||||
|
||||
# Apply the declared patch stack to a clean temporary clone of HEAD and compare diffs byte-for-byte.
|
||||
$verifyDir = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid())
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path $verifyDir | Out-Null
|
||||
$headRev = (git -C $repo rev-parse HEAD).Trim()
|
||||
Invoke-Native 'git' @('init', '-q', $verifyDir)
|
||||
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.autocrlf', 'false')
|
||||
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.eol', 'lf')
|
||||
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.filemode', 'false')
|
||||
Write-Utf8 (Join-Path $verifyDir '.gitattributes') '* text eol=lf`n'
|
||||
$tar = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid() + '.tar')
|
||||
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $headRev)
|
||||
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $verifyDir)
|
||||
Remove-Item -LiteralPath $tar -Force
|
||||
# bsdtar expands the upstream LF bytes, but Windows text tools used
|
||||
# during extraction must not decide the comparison's line endings.
|
||||
foreach ($file in Get-ChildItem -LiteralPath $verifyDir -Recurse -File) {
|
||||
if ($file.LinkType) { continue }
|
||||
$bytes = [IO.File]::ReadAllBytes($file.FullName)
|
||||
$text = [Text.Encoding]::UTF8.GetString($bytes)
|
||||
if ($text.Contains([char]0)) { continue }
|
||||
$lf = $text.Replace("`r`n", "`n")
|
||||
if ($lf -cne $text) {
|
||||
[IO.File]::WriteAllText($file.FullName, $lf, [Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
}
|
||||
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'add', '-A')
|
||||
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '-m', 'base')
|
||||
Invoke-Native 'git' @('-C', $verifyDir, 'add', '--renormalize', '.')
|
||||
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '--allow-empty', '-m', 'normalize-lf')
|
||||
foreach ($ps in $group) {
|
||||
$pf = Join-Path $patchesDir $ps.Name
|
||||
# .patch files may be checked out with CRLF on Windows. Keep the
|
||||
# authoritative file intact while comparing its LF representation
|
||||
# with a Git tree archived and indexed with LF line endings.
|
||||
$patchLf = Join-Path $TempRoot ("patch-lf-" + [guid]::NewGuid() + '.patch')
|
||||
$patchText = [IO.File]::ReadAllText($pf).Replace("`r`n", "`n")
|
||||
[IO.File]::WriteAllText($patchLf, $patchText, [Text.UTF8Encoding]::new($false))
|
||||
Invoke-GitApply $verifyDir $patchText -Check
|
||||
Invoke-GitApply $verifyDir $patchText
|
||||
Remove-Item -LiteralPath $patchLf -Force
|
||||
}
|
||||
$expectedDiff = ((& git -C $verifyDir -c core.autocrlf=false diff --full-index | Out-String).Replace("`r`n", "`n") -replace $indexMode, '$1').TrimEnd()
|
||||
if ($treeDiff -ne $expectedDiff) {
|
||||
$treeStat = (& git -C $repo diff --stat -- @paths | Out-String).Trim()
|
||||
$expStat = (& git -C $verifyDir diff --stat | Out-String).Trim()
|
||||
Write-Host "Build tree diff --stat:`n$treeStat"
|
||||
Write-Host "Expected patch stack diff --stat:`n$expStat"
|
||||
throw "Patch stack ($(($group | ForEach-Object { $_.Name }) -join ', ')) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)."
|
||||
}
|
||||
# Also verify newly created (untracked) files added by patches byte-for-byte.
|
||||
$addedFiles = @(& git -C $verifyDir ls-files --others --exclude-standard | Where-Object { $_ })
|
||||
foreach ($rel in $addedFiles) {
|
||||
$expPath = Join-Path $verifyDir ($rel -replace '/', '\')
|
||||
$treePath = Join-Path $repo ($rel -replace '/', '\')
|
||||
if (-not (Test-Path -LiteralPath $treePath -PathType Leaf)) {
|
||||
throw "Patch stack expected new file $rel in $repo, but it is missing."
|
||||
}
|
||||
$expText = [IO.File]::ReadAllText($expPath).Replace("`r`n", "`n")
|
||||
$treeText = [IO.File]::ReadAllText($treePath).Replace("`r`n", "`n")
|
||||
if ($treeText -cne $expText) {
|
||||
throw "New file $rel in $repo does not match the declared patch stack. Stop: don't edit patches automatically (AGENTS.md rule 4)."
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $verifyDir) { Remove-Item -Recurse -Force -LiteralPath $verifyDir }
|
||||
}
|
||||
}
|
||||
# Anything else changed in the build trees is undeclared: refuse.
|
||||
function Get-Undeclared([string]$repo, [string]$target, [string[]]$statusArgs) {
|
||||
$declared = @($patchSpecs | Where-Object { $_.Target -eq $target } | ForEach-Object { $_.Paths })
|
||||
@(& git -C $repo status --porcelain @statusArgs | Where-Object {
|
||||
$path = $_.Substring(3).Trim('"')
|
||||
$path -notin $declared
|
||||
})
|
||||
}
|
||||
$otherCtl = Get-Undeclared $ReimsRepo 'reims-vgpu' @('--ignore-submodules=all')
|
||||
$otherQemu = Get-Undeclared $qemuRepo 'vendor/qemu' @('--untracked-files=no')
|
||||
$utilStatusArgs = if ($UtilRepo) { '--untracked-files=all' } else { '--untracked-files=no' }
|
||||
$otherUtil = Get-Undeclared $utilTree 'reims-util' @($utilStatusArgs)
|
||||
$m2vStatusArgs = if ($Metal2VulkanRepo) { '--untracked-files=all' } else { '--untracked-files=no' }
|
||||
$otherM2v = Get-Undeclared $m2vTree 'metal2vulkan' @($m2vStatusArgs)
|
||||
if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count -or $otherM2v.Count) {
|
||||
throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil + $otherM2v -join "`n")"
|
||||
}
|
||||
|
||||
$bundleName = "reims-runtime-win-x64-$id"
|
||||
$srcName = "reims-runtime-src-$id"
|
||||
$symbolsName = "reims-runtime-symbols-$id"
|
||||
$stageRoot = Join-Path $TempRoot "pack-$id"
|
||||
$bundleDir = Join-Path $stageRoot $bundleName
|
||||
$srcDir = Join-Path $stageRoot $srcName
|
||||
if (Test-Path -LiteralPath $stageRoot) { Remove-Item -Recurse -Force -LiteralPath $stageRoot }
|
||||
New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "$bundleDir\licenses", "$bundleDir\patches", $srcDir, $OutDir | Out-Null
|
||||
|
||||
# ── 3. Runtime bundle ────────────────────────────────────────
|
||||
Write-Host "==> Staging $bundleName ($Channel)"
|
||||
$resolvedQemu = (Get-Item -LiteralPath $QemuDir).Target
|
||||
if (-not $resolvedQemu) { $resolvedQemu = $QemuDir }
|
||||
$keyFiles = @(& (Join-Path $PSScriptRoot 'stage-runtime-binaries.ps1') -CargoBin $CargoBin -QemuDir $resolvedQemu `
|
||||
-BundleDir $bundleDir -SymbolsDir (Join-Path $stageRoot $symbolsName) -Objcopy (Join-Path $Msys2 'clang64/bin/llvm-objcopy.exe') | ForEach-Object { $_ })
|
||||
$expectedKeyFiles = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe',
|
||||
'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
|
||||
if ($keyFiles.Count -ne 5 -or (Compare-Object $expectedKeyFiles $keyFiles)) {
|
||||
$keyFiles | ForEach-Object { Write-Host "Unexpected stager output [$($_.GetType().FullName)]: $_" }
|
||||
throw 'Binary stager did not return exactly the five expected executable paths'
|
||||
}
|
||||
|
||||
Copy-Item -LiteralPath (Join-Path $repoRoot 'NOTICE.md') -Destination "$bundleDir\NOTICE.md"
|
||||
foreach ($ps in $patchSpecs) { Copy-Item -LiteralPath (Join-Path $patchesDir $ps.Name) -Destination "$bundleDir\patches\" }
|
||||
Copy-Item -LiteralPath (Join-Path $patchesDir 'README.md') -Destination "$bundleDir\patches\README.md"
|
||||
if (Test-Path -LiteralPath (Join-Path $patchesDir 'LICENSE')) {
|
||||
Copy-Item -LiteralPath (Join-Path $patchesDir 'LICENSE') -Destination "$bundleDir\patches\LICENSE"
|
||||
}
|
||||
# The order the patches above were applied in (only those really applied).
|
||||
Write-Utf8 "$bundleDir\patches\series.txt" ((($patchSpecs | ForEach-Object { '{0,-12} {1}' -f $_.Target, $_.Name }) -join "`n") + "`n")
|
||||
$licenses = @{
|
||||
'reims-vgpu-LICENSE.txt' = (Join-Path $ReimsRepo 'LICENSE')
|
||||
'qemu-COPYING.txt' = (Join-Path $qemuRepo 'COPYING')
|
||||
'qemu-COPYING.LIB.txt' = (Join-Path $qemuRepo 'COPYING.LIB')
|
||||
}
|
||||
foreach ($k in $licenses.Keys) {
|
||||
if (Test-Path -LiteralPath $licenses[$k]) { Copy-Item -LiteralPath $licenses[$k] -Destination (Join-Path "$bundleDir\licenses" $k) }
|
||||
}
|
||||
if (Test-Path -LiteralPath (Join-Path $ReimsRepo 'LICENSES')) {
|
||||
Copy-Item -Path (Join-Path $ReimsRepo 'LICENSES\*') -Destination "$bundleDir\licenses\" -Recurse -Force
|
||||
}
|
||||
|
||||
# MSYS2 CLANG64 DLLs: owning package and version, and where its source is.
|
||||
Write-Host '==> Listing MSYS2 packages of bundled DLLs'
|
||||
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
|
||||
$dlls = @(Get-ChildItem -LiteralPath "$bundleDir\qemu\bin" -Filter '*.dll' -File | Sort-Object Name)
|
||||
$pkgLines = [Collections.Generic.List[string]]::new()
|
||||
$pkgSet = [ordered]@{}
|
||||
$pkgNames = [ordered]@{}
|
||||
foreach ($d in $dlls) {
|
||||
$owner = (& $bash -lc "LC_ALL=C pacman -Qqo /clang64/bin/$($d.Name) 2>/dev/null" | Select-Object -First 1)
|
||||
if ($owner) {
|
||||
$ver = (& $bash -lc "LC_ALL=C pacman -Q $owner" | Select-Object -First 1).Split(' ')[1]
|
||||
$pkgLines.Add("$($d.Name)`t$owner`t$ver")
|
||||
$pkgSet["$owner $ver"] = $true
|
||||
$pkgNames[$owner] = $true
|
||||
} else {
|
||||
$pkgLines.Add("$($d.Name)`t(not from an MSYS2 package: built with qemu, source in the source package)`t-")
|
||||
}
|
||||
}
|
||||
# Bundle each MSYS2 package's installed license texts under licenses/msys2/.
|
||||
$msysLicRoot = Join-Path $bundleDir 'licenses\msys2'
|
||||
foreach ($owner in $pkgNames.Keys) {
|
||||
$licFiles = @(& $bash -lc "LC_ALL=C pacman -Ql $owner 2>/dev/null" | ForEach-Object {
|
||||
if ($_ -match '^\S+\s+(/clang64/share/licenses/.+)$' -and -not $Matches[1].EndsWith('/')) { $Matches[1] }
|
||||
})
|
||||
foreach ($lf in $licFiles) {
|
||||
$rel = $lf.Substring('/clang64/share/licenses/'.Length)
|
||||
$srcFile = Join-Path $Msys2 ($lf.TrimStart('/') -replace '/', '\')
|
||||
if (Test-Path -LiteralPath $srcFile -PathType Leaf) {
|
||||
$dstFile = Join-Path $msysLicRoot ($rel -replace '/', '\')
|
||||
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dstFile))
|
||||
Copy-Item -LiteralPath $srcFile -Destination $dstFile -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
$msysText = @"
|
||||
# DLLs bundled in qemu/bin and the MSYS2 CLANG64 packages they come from
|
||||
# (pacman -Qo on the build machine, $(Get-Date -Format 'yyyy-MM-dd')).
|
||||
#
|
||||
# Sources: every package whose licence requires source (GPL / LGPL / MPL) is in
|
||||
# reims-runtime-msys2-src-$id.tar.zst, published beside this runtime.
|
||||
# The same files are also at:
|
||||
# https://repo.msys2.org/mingw/sources/ (<package>-<version>.src.tar.zst, by pkgbase)
|
||||
# https://github.com/msys2/MINGW-packages (build recipes)
|
||||
# Licenses: bundled under licenses/msys2/ from each package's /clang64/share/licenses/ in MSYS2.
|
||||
|
||||
DLL`tPACKAGE`tVERSION
|
||||
$($pkgLines -join "`n")
|
||||
|
||||
# Packages ($($pkgSet.Count))
|
||||
$($pkgSet.Keys -join "`n")
|
||||
"@
|
||||
Write-Utf8 "$bundleDir\MSYS2-PACKAGES.txt" $msysText
|
||||
|
||||
# ── 4. Source bundle ─────────────────────────────────────────
|
||||
Write-Host "==> Staging $srcName"
|
||||
function Export-GitTree([string]$repo, [string]$rev, [string]$dest) {
|
||||
New-Item -ItemType Directory -Force -Path $dest | Out-Null
|
||||
$tar = Join-Path $TempRoot ("git-export-" + [guid]::NewGuid() + '.tar')
|
||||
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $rev)
|
||||
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $dest)
|
||||
Remove-Item -LiteralPath $tar -Force
|
||||
}
|
||||
Export-GitTree $ReimsRepo $fullCommit (Join-Path $srcDir "reims-vgpu-$commit")
|
||||
Export-GitTree $qemuRepo $qemuCommit (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu")
|
||||
# QEMU's meson wraps downloaded for this build (dtc, keycodemapdb, ...): part of what was built.
|
||||
Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory |
|
||||
Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } |
|
||||
ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force }
|
||||
|
||||
Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))")
|
||||
Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))")
|
||||
foreach ($extra in @(
|
||||
@{ Name = 'reims-util'; Tree = $utilTree },
|
||||
@{ Name = 'metal2vulkan'; Tree = $m2vTree }
|
||||
)) {
|
||||
foreach ($lf in @('LICENSE', 'LICENSE.txt', 'LICENSE.md', 'COPYING', 'COPYING.LIB')) {
|
||||
$srcLic = Join-Path $extra.Tree $lf
|
||||
if (Test-Path -LiteralPath $srcLic -PathType Leaf) {
|
||||
Copy-Item -LiteralPath $srcLic -Destination (Join-Path "$bundleDir\licenses" "$($extra.Name)-$lf") -Force
|
||||
}
|
||||
}
|
||||
if (Test-Path -LiteralPath (Join-Path $extra.Tree 'LICENSES') -PathType Container) {
|
||||
Copy-Item -Path (Join-Path $extra.Tree 'LICENSES\*') -Destination "$bundleDir\licenses\" -Recurse -Force
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null
|
||||
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')) {
|
||||
$m2vDir = "metal2vulkan-$($m2vCommit.Substring(0, 7))"
|
||||
$m2vApply = ($byTarget['metal2vulkan'] | ForEach-Object { " git -C $m2vDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n"
|
||||
@"
|
||||
|
||||
Before running ``scripts/install-ctl.sh``, apply the ``metal2vulkan`` patches
|
||||
and point Cargo at the patched checkout via ```$CARGO_HOME/config.toml``:
|
||||
|
||||
$m2vApply
|
||||
cat >> "`${CARGO_HOME:-`$HOME/.cargo}/config.toml" <<EOF
|
||||
[patch."$($pins.Metal.Url)"]
|
||||
metal2vulkan = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan" }
|
||||
metal2vulkan-runtime = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan-runtime" }
|
||||
EOF
|
||||
|
||||
"@
|
||||
}
|
||||
$utilBuildSteps = if ($byTarget.Contains('reims-util')) {
|
||||
$utilDir = "reims-util-$($utilCommit.Substring(0, 7))"
|
||||
$utilApply = ($byTarget['reims-util'] | ForEach-Object { " git -C $utilDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n"
|
||||
@"
|
||||
|
||||
After the upstream build, run these commands from the extracted source
|
||||
archive's root in the same MSYS2 CLANG64 shell. They apply the reims-util
|
||||
patches and replace the stock reims-util executable with this build:
|
||||
|
||||
$utilApply
|
||||
cd reims-vgpu-$commit
|
||||
toolchain=`$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)
|
||||
CC=clang CXX=clang++ AR=llvm-ar cargo +"`$toolchain-x86_64-pc-windows-gnullvm" install --locked --force --path ../$utilDir
|
||||
|
||||
"@
|
||||
}
|
||||
$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
|
||||
|
||||
Corresponding source for the binaries in ``$bundleName.tar.zst``.
|
||||
|
||||
| Directory | Source repository | Commit |
|
||||
| :-- | :-- | :-- |
|
||||
| ``reims-vgpu-$commit/`` | $reimsSource | ``$fullCommit`` |
|
||||
| ``reims-vgpu-$commit/vendor/qemu/`` | $qemuSource | ``$qemuCommit`` |
|
||||
| ``reims-util-$($utilCommit.Substring(0, 7))/`` | $($pins.Util.Url) | ``$utilCommit`` |
|
||||
| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | $($pins.Metal.Url) | ``$m2vCommit`` |
|
||||
|
||||
$(
|
||||
if ($applyRuntimePatches) {
|
||||
"Apply the runtime patches from the archive root.`n`n" + ($applyRuntimePatches -join "`n")
|
||||
}
|
||||
)
|
||||
|
||||
$m2vBuildSteps
|
||||
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
|
||||
"@
|
||||
|
||||
# ── 5. Manifest (schema 2) ───────────────────────────────────
|
||||
$hashes = [ordered]@{}
|
||||
foreach ($rel in $keyFiles) {
|
||||
$fp = Join-Path $bundleDir ($rel -replace '/', '\')
|
||||
$hashes[$rel] = Get-Sha256 $fp
|
||||
}
|
||||
$manifest = [ordered]@{
|
||||
schema_version = 2
|
||||
name = $bundleName
|
||||
platform = 'windows-x86_64'
|
||||
upstream_repo = $reimsSource
|
||||
commit = $id
|
||||
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
|
||||
channel = $Channel
|
||||
source_package = "$srcName.tar.zst"
|
||||
symbols_package = "$symbolsName.tar.zst"
|
||||
qemu_version = $qemuVersionLine
|
||||
util_version = $utilVersionLine
|
||||
built_at = (Get-Date).ToString('o')
|
||||
file_count = (Get-ChildItem -LiteralPath $bundleDir -Recurse -File).Count + 1
|
||||
dll_count = $dlls.Count
|
||||
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
|
||||
Write-Host '==> Compressing sources'
|
||||
$srcArchive = Join-Path $OutDir "$srcName.tar.zst"
|
||||
New-TarZst $stageRoot $srcName $srcArchive
|
||||
$symbolsArchive = Join-Path $OutDir "$symbolsName.tar.zst"
|
||||
New-TarZst $stageRoot $symbolsName $symbolsArchive
|
||||
|
||||
$rtHash = Get-Sha256 $runtimeArchive
|
||||
$srcHash = Get-Sha256 $srcArchive
|
||||
Write-Utf8 "$runtimeArchive.sha256" "$rtHash $bundleName.tar.zst`n"
|
||||
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') "$rtHash $bundleName.tar.zst`n$srcHash $srcName.tar.zst`n$(Get-Sha256 $symbolsArchive) $symbolsName.tar.zst`n"
|
||||
|
||||
# Sources of the copyleft MSYS2 packages, as their own asset (adds a line to SHA256SUMS.txt).
|
||||
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $id -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
|
||||
|
||||
Remove-Item -Recurse -Force -LiteralPath $stageRoot
|
||||
|
||||
Write-Host ''
|
||||
Write-Host '==> Done' -ForegroundColor Green
|
||||
'{0,-10} {1} {2:N1} MB' -f 'runtime', $runtimeArchive, ((Get-Item $runtimeArchive).Length / 1MB)
|
||||
'{0,-10} {1} {2:N1} MB' -f 'source', $srcArchive, ((Get-Item $srcArchive).Length / 1MB)
|
||||
"channel $Channel; patches: $(($patchEntries | ForEach-Object { $_.name }) -join ', '); DLLs: $($dlls.Count)"
|
||||
@@ -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,191 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Real-host smoke test for an alpha portable reims-vgpu runtime archive.
|
||||
|
||||
.DESCRIPTION
|
||||
Implements docs/portable-runtime-spec.md section 6 (alpha -> stable gate):
|
||||
1. Verifies SHA256 against SHA256SUMS.txt (when provided).
|
||||
2. Extracts the runtime into an isolated directory under -TempRoot (never C:).
|
||||
3. Verifies manifest.json provenance, NOTICE.md, licenses/, and core binaries.
|
||||
4. Runs `reims-ctl doctor` and `reims-ctl list --json` in a clean environment
|
||||
stripped of MSYS2 / Cargo paths to prove true portability.
|
||||
5. Writes a Markdown report for human review before promoting to `stable`.
|
||||
|
||||
.EXAMPLE
|
||||
powershell -ExecutionPolicy Bypass -File scripts/smoke-runtime.ps1 `
|
||||
-ArchivePath D:\Data\reims-go\releases\reims-runtime-win-x64-3731afd.tar.zst `
|
||||
-Sha256File D:\Data\reims-go\releases\SHA256SUMS.txt
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$ArchivePath,
|
||||
[string]$Sha256File = '',
|
||||
[string]$TempRoot = 'D:\Build\Temp',
|
||||
[string]$ReportOut = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
if (-not (Test-Path -LiteralPath $ArchivePath)) {
|
||||
throw "Archive not found: $ArchivePath"
|
||||
}
|
||||
|
||||
$archiveFile = Get-Item -LiteralPath $ArchivePath
|
||||
$actualHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $ArchivePath).Hash.ToLowerInvariant()
|
||||
$hashStatus = 'skipped (no -Sha256File provided)'
|
||||
if ($Sha256File -ne '') {
|
||||
if (-not (Test-Path -LiteralPath $Sha256File)) {
|
||||
throw "SHA256SUMS file not found: $Sha256File"
|
||||
}
|
||||
$matched = $false
|
||||
foreach ($line in (Get-Content -LiteralPath $Sha256File)) {
|
||||
if ($line -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') {
|
||||
$h = $Matches[1].ToLowerInvariant()
|
||||
$n = $Matches[2].Trim()
|
||||
if ($n -eq $archiveFile.Name) {
|
||||
if ($h -ne $actualHash) {
|
||||
throw "SHA256 mismatch for $($archiveFile.Name): expected $h, got $actualHash"
|
||||
}
|
||||
$matched = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (-not $matched) {
|
||||
throw "Entry for $($archiveFile.Name) not found in $Sha256File"
|
||||
}
|
||||
$hashStatus = "PASS ($actualHash)"
|
||||
}
|
||||
|
||||
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
|
||||
$smokeDir = Join-Path $TempRoot "smoke-$stamp"
|
||||
$extractDir = Join-Path $smokeDir 'runtime'
|
||||
$dataDir = Join-Path $smokeDir 'data'
|
||||
New-Item -ItemType Directory -Force -Path $extractDir, $dataDir | Out-Null
|
||||
|
||||
function Resolve-Zstd {
|
||||
@(
|
||||
(Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
|
||||
'D:\DevTools\msys64\usr\bin\zstd.exe',
|
||||
'C:\msys64\usr\bin\zstd.exe'
|
||||
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
|
||||
}
|
||||
|
||||
try {
|
||||
Write-Host "[1/5] Extracting $($archiveFile.Name) into $extractDir..."
|
||||
if ($archiveFile.Name.EndsWith('.tar.zst')) {
|
||||
$zstd = Resolve-Zstd
|
||||
if (-not $zstd) { throw 'zstd.exe not found to extract .tar.zst' }
|
||||
$tarPath = Join-Path $smokeDir 'runtime.tar'
|
||||
& $zstd -d -f -q $ArchivePath -o $tarPath
|
||||
if ($LASTEXITCODE -ne 0) { throw "zstd decompress failed ($LASTEXITCODE)" }
|
||||
& tar.exe -xf $tarPath -C $extractDir
|
||||
if ($LASTEXITCODE -ne 0) { throw "tar extract failed ($LASTEXITCODE)" }
|
||||
Remove-Item -LiteralPath $tarPath -Force
|
||||
} elseif ($archiveFile.Name.EndsWith('.zip')) {
|
||||
Expand-Archive -LiteralPath $ArchivePath -DestinationPath $extractDir -Force
|
||||
} else {
|
||||
throw "Unsupported archive format: $($archiveFile.Name)"
|
||||
}
|
||||
|
||||
# Handle single top-level folder inside archive.
|
||||
$rootDir = $extractDir
|
||||
$children = @(Get-ChildItem -LiteralPath $extractDir)
|
||||
if ($children.Count -eq 1 -and $children[0].PSIsContainer) {
|
||||
$rootDir = $children[0].FullName
|
||||
}
|
||||
|
||||
Write-Host "[2/5] Checking manifest.json, compliance files, and core binaries..."
|
||||
$required = @(
|
||||
'manifest.json',
|
||||
'NOTICE.md',
|
||||
'licenses',
|
||||
'bin\reims-ctl.exe',
|
||||
'bin\reims-util.exe',
|
||||
'qemu\bin\qemu-system-x86_64.exe',
|
||||
'qemu\bin\qemu-img.exe'
|
||||
)
|
||||
foreach ($rel in $required) {
|
||||
$p = Join-Path $rootDir $rel
|
||||
if (-not (Test-Path -LiteralPath $p)) {
|
||||
throw "Missing required runtime asset: $rel"
|
||||
}
|
||||
}
|
||||
$manifest = Get-Content -Raw -LiteralPath (Join-Path $rootDir 'manifest.json') | ConvertFrom-Json
|
||||
$patchList = @()
|
||||
if ($manifest.patches) {
|
||||
$patchList = @($manifest.patches | ForEach-Object { $_.name })
|
||||
}
|
||||
|
||||
Write-Host "[3/5] Running reims-ctl doctor in a clean MSYS2-free environment..."
|
||||
$cleanEnv = @{
|
||||
'XDG_CONFIG_HOME' = (Join-Path $dataDir 'config')
|
||||
'XDG_DATA_HOME' = (Join-Path $dataDir 'data')
|
||||
'XDG_CACHE_HOME' = (Join-Path $dataDir 'cache')
|
||||
'TEMP' = (Join-Path $dataDir 'tmp')
|
||||
'TMP' = (Join-Path $dataDir 'tmp')
|
||||
'REIMS_CTL_QEMU' = (Join-Path $rootDir 'qemu')
|
||||
'PATH' = "$($env:SystemRoot)\System32;$($env:SystemRoot)"
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $cleanEnv['XDG_CONFIG_HOME'], $cleanEnv['XDG_DATA_HOME'], $cleanEnv['XDG_CACHE_HOME'], $cleanEnv['TEMP'] | Out-Null
|
||||
|
||||
function Invoke-CleanCtl([string[]]$ctlArgs) {
|
||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||||
$psi.FileName = (Join-Path $rootDir 'bin\reims-ctl.exe')
|
||||
$psi.Arguments = ($ctlArgs -join ' ')
|
||||
$psi.UseShellExecute = $false
|
||||
$psi.RedirectStandardOutput = $true
|
||||
$psi.RedirectStandardError = $true
|
||||
$psi.CreateNoWindow = $true
|
||||
foreach ($k in $cleanEnv.Keys) {
|
||||
$psi.EnvironmentVariables[$k] = $cleanEnv[$k]
|
||||
}
|
||||
$proc = [System.Diagnostics.Process]::Start($psi)
|
||||
$stdout = $proc.StandardOutput.ReadToEnd()
|
||||
$stderr = $proc.StandardError.ReadToEnd()
|
||||
$proc.WaitForExit()
|
||||
return @{ Code = $proc.ExitCode; Stdout = $stdout; Stderr = $stderr }
|
||||
}
|
||||
|
||||
$doctorRes = Invoke-CleanCtl @('doctor')
|
||||
Write-Host "[4/5] Running reims-ctl list --json..."
|
||||
$listRes = Invoke-CleanCtl @('list', '--json')
|
||||
if ($listRes.Code -ne 0) {
|
||||
throw "reims-ctl list --json failed ($($listRes.Code)): $($listRes.Stderr)"
|
||||
}
|
||||
|
||||
Write-Host "[5/5] Generating smoke report..."
|
||||
$reportLines = @(
|
||||
"# Runtime Smoke Test Report",
|
||||
"",
|
||||
"- **Tested at**: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz')",
|
||||
"- **Host**: $([Environment]::MachineName) ($([Environment]::OSVersion.VersionString))",
|
||||
"- **Archive**: $($archiveFile.Name) ($([math]::Round($archiveFile.Length / 1MB, 1)) MB)",
|
||||
"- **SHA256 check**: $hashStatus",
|
||||
"- **Upstream commit**: $($manifest.commit) (channel: $($manifest.channel))",
|
||||
"- **vendor/qemu commit**: $($manifest.vendor_qemu_commit)",
|
||||
"- **Patches**: $(if ($patchList.Count -gt 0) { $patchList -join ', ' } else { 'none (pure upstream)' })",
|
||||
"- **Source package declared**: $($manifest.source_package)",
|
||||
"- **reims-ctl list --json**: PASS (exit $($listRes.Code))",
|
||||
"- **reims-ctl doctor exit code**: $($doctorRes.Code)",
|
||||
"",
|
||||
"## reims-ctl doctor output",
|
||||
'```text',
|
||||
$doctorRes.Stdout.TrimEnd(),
|
||||
'```'
|
||||
)
|
||||
$report = $reportLines -join "`n"
|
||||
if ($ReportOut -ne '') {
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $ReportOut) | Out-Null
|
||||
[IO.File]::WriteAllText($ReportOut, $report + "`n", [Text.UTF8Encoding]::new($false))
|
||||
Write-Host "Smoke report written to: $ReportOut"
|
||||
} else {
|
||||
Write-Host "`n$report"
|
||||
}
|
||||
Write-Host "`nSmoke test finished. Human review required before promoting alpha -> stable."
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $smokeDir) {
|
||||
Remove-Item -LiteralPath $smokeDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# Stage the Windows x64 payload and matching GNU debug files. Inputs are read-only.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)] [string]$CargoBin,
|
||||
[Parameter(Mandatory)] [string]$QemuDir,
|
||||
[Parameter(Mandatory)] [string]$BundleDir,
|
||||
[Parameter(Mandatory)] [string]$SymbolsDir,
|
||||
[Parameter(Mandatory)] [string]$Objcopy
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$programs = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe',
|
||||
'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
|
||||
|
||||
# Omit only the paths tested with the x64 launcher. Keep new upstream files,
|
||||
# in particular dynamically loaded video drivers, ROMs, and license notices.
|
||||
$tools = @('bin/qemu-system-x86_64w.exe', 'bin/elf2dmp.exe', 'bin/qemu-edid.exe',
|
||||
'bin/qemu-io.exe', 'bin/qemu-nbd.exe', 'bin/qemu-storage-daemon.exe')
|
||||
foreach ($file in Get-ChildItem -LiteralPath $QemuDir -Recurse -Force -File) {
|
||||
$rel = [IO.Path]::GetRelativePath($QemuDir, $file.FullName).Replace('\', '/')
|
||||
if ($rel -in $tools) { continue }
|
||||
if ($rel -match '^share/edk2-(aarch64|riscv64|loongarch64)-(code|vars)\.fd$' -or
|
||||
$rel -match '^share/firmware/\d+-edk2-(aarch64|riscv64|loongarch64)\.json$') { continue }
|
||||
if ("qemu/$rel" -in $programs) { continue }
|
||||
$dest = Join-Path $BundleDir "qemu/$rel"
|
||||
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
|
||||
Copy-Item -LiteralPath $file.FullName -Destination $dest
|
||||
}
|
||||
|
||||
foreach ($rel in $programs) {
|
||||
$src = if ($rel.StartsWith('qemu/')) { Join-Path $QemuDir $rel.Substring(5) }
|
||||
else { Join-Path $CargoBin (Split-Path -Leaf $rel) }
|
||||
$dest = Join-Path $BundleDir $rel
|
||||
$debug = Join-Path $SymbolsDir "$rel.debug"
|
||||
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
|
||||
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $debug))
|
||||
& $Objcopy --only-keep-debug $src $debug | Out-Null
|
||||
if ($LASTEXITCODE) { throw "Extracting symbols from $src failed ($LASTEXITCODE)" }
|
||||
& $Objcopy --strip-debug "--add-gnu-debuglink=$debug" $src $dest | Out-Null
|
||||
if ($LASTEXITCODE) { throw "Stripping $src failed ($LASTEXITCODE)" }
|
||||
}
|
||||
# The packer hashes these final, stripped bytes for manifest.json.
|
||||
$programs
|
||||
@@ -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,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 按新主编号处理。若运行时提交已发布且本次只是更换打包输入,先提交新的运行时基线,再发布。
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"capabilities": [
|
||||
"client-window-close",
|
||||
"display-fixed-mode",
|
||||
"nested-virt-nonfatal",
|
||||
"vm-suspend",
|
||||
"win10-compat",
|
||||
"win10-startup-ipis",
|
||||
"win32-coroutine-fiber",
|
||||
"win32-unicode-input",
|
||||
"window-file-drop",
|
||||
"window-text-drop"
|
||||
]
|
||||
}
|
||||
Vendored
+1
-1
Submodule vendor/qemu updated: e6d7cb7422...4571bc5fec.
Reference in new issue
Block a user