Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d9be66a68 | ||
|
|
c95335699c | ||
|
|
edd66dcc12 | ||
|
|
ff284bc497 | ||
|
|
e0cb092b03 | ||
|
|
9e0d1bc1a0 | ||
|
|
bcd18d6485 | ||
|
|
6aa417aef6 | ||
|
|
b1e8f45e9e | ||
|
|
53b6af7574 | ||
|
|
c8213cb933 | ||
|
|
d1637583ba |
No files matched your search
+1
-28
@@ -57,14 +57,6 @@ threads-required = "num-test-threads"
|
||||
[test-groups]
|
||||
vulkan-devices = { max-threads = 3 }
|
||||
|
||||
# The NVIDIA legs end a test that runs past five minutes, so a stuck test fails the leg by name
|
||||
# instead of holding it to the job's limit. On an RTX 3090 (driver 620.70.06, 2026-12-02), seven
|
||||
# GPU tests in flight stalled together after 2,033 had passed, and the leg was killed at its
|
||||
# 10-minute limit with six processes that would not die (m3-max-80466). A test that stays inside the
|
||||
# driver may still not die: the timeout bounds the leg, not the driver.
|
||||
[profile.nvidia]
|
||||
slow-timeout = { period = "60s", terminate-after = 5 }
|
||||
|
||||
# The measurements that run alone (above, the same list) stay out of the group, so that what they
|
||||
# wait for is every test in flight rather than the group's three.
|
||||
[[profile.nvidia.overrides]]
|
||||
@@ -84,30 +76,11 @@ filter = '''
|
||||
'''
|
||||
test-group = "@global"
|
||||
|
||||
# The tests that make an rt device: the Vulkan crate's but core's, reims-vgpu's named on_vulkan or
|
||||
# on_rt_, and the C API's. Each of them failed, and no other test did, in a run on Linux with no
|
||||
# Vulkan driver (homelab-um870, 2026-12-03, potluck job m3-max-85816).
|
||||
[[profile.nvidia.overrides]]
|
||||
platform = 'cfg(target_os = "linux")'
|
||||
filter = '''
|
||||
(package(reims-vgpu-vulkan) & !(binary_id(reims-vgpu-vulkan) & test(/^core::/)))
|
||||
| (package(reims-vgpu) & (test(/on_vulkan/) | test(/(^|::)on_rt_/)))
|
||||
| (package(reims-vgpu) & test(/on_vulkan/))
|
||||
| package(reims-vgpu-c)
|
||||
'''
|
||||
test-group = "vulkan-devices"
|
||||
|
||||
# GitHub CI's profile (.github/workflows/ci.yml, docs/development.md "CI"), whose runners have no
|
||||
# GPU: every test but those that make an rt device. They are the tests the nvidia profile's
|
||||
# `vulkan-devices` group holds (above), and reims-vgpu's tests named `on_rt_`, which make one too.
|
||||
# Measured on Linux with no Vulkan driver (homelab-um870, 2026-12-03, at 5cb932953e): 218 of the
|
||||
# 3,439 tests that are not ignored failed, each of them one of these. CI runs these with the
|
||||
# profile's filter turned over (`--profile ci --ignore-default-filter -E 'not default()'`) on
|
||||
# Mesa's lavapipe, in a job of its own.
|
||||
[profile.ci]
|
||||
default-filter = '''
|
||||
not (
|
||||
(package(reims-vgpu-vulkan) & !(binary_id(reims-vgpu-vulkan) & test(/^core::/)))
|
||||
| (package(reims-vgpu) & (test(/on_vulkan/) | test(/(^|::)on_rt_/)))
|
||||
| package(reims-vgpu-c)
|
||||
)
|
||||
'''
|
||||
@@ -1,16 +0,0 @@
|
||||
# The device tests that fail on lavapipe in CI's lavapipe job (.github/workflows/ci.yml), each
|
||||
# under its reason: nextest's binary id and the test's full name, as nextest's FAIL lines print them,
|
||||
# one test a line. The job runs every other device test, which must pass, then each test here alone,
|
||||
# which must fail (.github/lavapipe-tests.sh): a test here that passes, or any other that fails,
|
||||
# fails the job. A test that comes to pass on lavapipe leaves the list in the commit that makes it
|
||||
# pass.
|
||||
|
||||
# A known limit of CPU devices: their device addresses are the host process's own, and lavapipe put
|
||||
# a buffer of the host's in the process's mmap area, inside the contexts' range [2^46, 2^47), in each
|
||||
# of three runs (docs/graphics-kext/design.md, "Contexts").
|
||||
reims-vgpu graphics::decode::cmdbuf::tests::on_vulkan_the_host_s_own_ranges_lie_outside_every_unit
|
||||
|
||||
# The pass and the table one LSB apart in one byte of BGR10A2Unorm (format 94), [255, 255, 1, 255]
|
||||
# against [255, 255, 0, 255], the same in each of three runs: likely lavapipe's rounding, not
|
||||
# confirmed.
|
||||
reims-vgpu graphics::sink::tests::on_vulkan_the_table_draws_what_the_pass_draws
|
||||
@@ -1,54 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# The lavapipe job's device tests (.github/workflows/ci.yml), run in metal2vulkan's lavapipe image:
|
||||
# the tests nextest's `ci` profile leaves out, every one but the expected failures the list names,
|
||||
# which must pass, then each expected failure alone, which must fail.
|
||||
#
|
||||
# lavapipe-tests.sh ARCHIVE WORKSPACE LIST
|
||||
#
|
||||
# ARCHIVE is `cargo nextest archive`'s file, WORKSPACE the checkout it was built in, and LIST
|
||||
# .github/lavapipe-expected-failures: lines of nextest's binary id and a test's full name, with `#`
|
||||
# comments and blank lines. It fails if a test outside the list fails, if a test in the list passes
|
||||
# or is not one device test, or if a line of the list is not a binary id and a test name.
|
||||
set -uo pipefail
|
||||
archive=$1 workspace=$2 list=$3
|
||||
|
||||
expected=()
|
||||
while IFS= read -r line; do
|
||||
case $line in '' | '#'*) continue ;; esac
|
||||
read -r binary test rest <<< "$line"
|
||||
if [ -z "${test:-}" ] || [ -n "${rest:-}" ]; then
|
||||
echo "::error::$list: not a binary id and a test name: $line"
|
||||
exit 1
|
||||
fi
|
||||
expected+=("binary_id(=$binary) & test(=$test)")
|
||||
done < "$list"
|
||||
|
||||
run() {
|
||||
cargo-nextest nextest run --archive-file "$archive" --workspace-remap "$workspace" \
|
||||
--profile ci --ignore-default-filter --no-tests=fail "$@"
|
||||
}
|
||||
|
||||
ulimit -c 0
|
||||
status=0
|
||||
others='not default()'
|
||||
if [ ${#expected[@]} -gt 0 ]; then
|
||||
any=$(printf ' | (%s)' "${expected[@]}")
|
||||
others="not default() & not (${any# | })"
|
||||
fi
|
||||
run --no-fail-fast -E "$others" || status=1
|
||||
# nextest exits 100 when a test failed and 4 when the filter took no test (--no-tests=fail).
|
||||
for e in "${expected[@]}"; do
|
||||
run -E "not default() & ($e)"
|
||||
case $? in
|
||||
100) echo "failed, as the list expects: $e" ;;
|
||||
0)
|
||||
echo "::error::passed, so it leaves the list: $e"
|
||||
status=1
|
||||
;;
|
||||
*)
|
||||
echo "::error::did not run to a test's failure: $e"
|
||||
status=1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
exit $status
|
||||
@@ -1,518 +0,0 @@
|
||||
# CI on GitHub's runners: the checks that need no GPU and no guest, on Linux, macOS and Windows
|
||||
# (docs/development.md, "CI"). The lab's checks (AGENTS.md, "Checking a change") stay the gate for
|
||||
# a merge; this is a check beside them.
|
||||
#
|
||||
# The runners have no GPU, so the tests run under nextest's `ci` profile (.config/nextest.toml):
|
||||
# every test but those that make an rt device, which run in the lavapipe job, on Mesa's lavapipe,
|
||||
# and nowhere else here. The tests `#[ignore]` keeps for a hardware host stay ignored.
|
||||
#
|
||||
# What a job reaches: GitHub (this repository, vendor/qemu's fork at its gitlink, metal2vulkan at
|
||||
# the commit Cargo.toml pins, the actions below by commit, cargo-nextest's release, Homebrew's
|
||||
# bottles), crates.io, Rust's toolchain server for the toolchain rust-toolchain.toml pins, and the
|
||||
# distributions' packages each job names (Ubuntu's, MSYS2's, and in the lavapipe job, Arch Linux's
|
||||
# of the date metal2vulkan's image pins). QEMU's build takes its three meson subprojects from
|
||||
# QEMU's mirrors on GitHub, at the commits their wraps name.
|
||||
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [development, master]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# One run per ref at a time. A new run of a pull request (refs/pull/N/merge) or of any branch but
|
||||
# development and master cancels that ref's run in progress; on those two it waits for the run in
|
||||
# progress to end instead (GitHub keeps one waiting run a ref, the newest).
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/development' && github.ref != 'refs/heads/master' }}
|
||||
|
||||
env:
|
||||
# The tests a runner without a GPU runs, for `cargo xtask check` and every nextest run below.
|
||||
NEXTEST_PROFILE: ci
|
||||
# The features `cargo xtask check` tests with (xtask/src/main.rs, TESTED_FEATURES).
|
||||
TESTED_FEATURES: reims-vgpu-vulkan/testkit,reims-vgpu/testkit,reims-vgpu/vulkan,reims-vgpu-c/vulkan
|
||||
# The cargo-nextest the lab runs.
|
||||
NEXTEST_VERSION: 0.9.151
|
||||
# The cbindgen the committed header is made with (xtask/src/header.rs, CBINDGEN_VERSION).
|
||||
CBINDGEN_VERSION: 0.29.4
|
||||
# Ubuntu's packages a build of the library on Linux needs beyond the image's: SDL3's video, which
|
||||
# the window crate builds from its source (CMake, and the X11, Wayland, xkbcommon and EGL
|
||||
# headers), as scripts/install-ctl.sh installs them.
|
||||
LIBRARY_APT: >-
|
||||
cmake clang libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxfixes-dev
|
||||
libxss-dev libxtst-dev libxkbcommon-dev libwayland-dev libwayland-bin libdecor-0-dev libegl-dev
|
||||
libgl-dev libdrm-dev libgbm-dev libdbus-1-dev libudev-dev
|
||||
# The cache's bound: rust-cache saves on development alone, and a job whose target directories
|
||||
# hold more than this saves cargo's home alone (the last step of each job).
|
||||
CACHE_TARGET_MAX_GIB: 4
|
||||
|
||||
jobs:
|
||||
linux-check:
|
||||
name: Linux, cargo xtask check
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install packages
|
||||
run: |
|
||||
read -ra packages <<< "$LIBRARY_APT"
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends "${packages[@]}"
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
|
||||
with:
|
||||
tool: cargo-nextest@${{ env.NEXTEST_VERSION }}
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
- name: Install cbindgen
|
||||
run: cargo install --locked cbindgen --version "$CBINDGEN_VERSION"
|
||||
# The lab's check: the lints, the records of the prebuilt ROM and kext sets, rustfmt, clippy
|
||||
# (Linux and x86_64-pc-windows-gnullvm), the hooks, the tests and the doc-tests. No core
|
||||
# dumps: the death tests crash on purpose (AGENTS.md, "The video crates' checks").
|
||||
- name: cargo xtask check
|
||||
run: |
|
||||
ulimit -c 0
|
||||
cargo xtask check
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: &bound |
|
||||
kib=$({ du -sk target crates/*/target 2>/dev/null || true; } | awk '{s += $1} END {print s + 0}')
|
||||
echo "target directories: $((kib / 1024)) MiB, bound ${CACHE_TARGET_MAX_GIB} GiB"
|
||||
if [ "$GITHUB_REF" = refs/heads/development ] && [ "$kib" -gt $((CACHE_TARGET_MAX_GIB * 1024 * 1024)) ]; then
|
||||
rm -rf target crates/*/target
|
||||
echo "over the bound: the cache saves cargo's home alone"
|
||||
fi
|
||||
|
||||
linux-ctl:
|
||||
name: Linux, make check-ctl
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# MinGW's gcc and ar, for the C ring's build script compiles in clippy for
|
||||
# x86_64-pc-windows-gnullvm; clang, for the Ambrosia module reims-ctl's build makes.
|
||||
- name: Install packages
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64 clang
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: |
|
||||
crates/reims-ctl -> target
|
||||
crates/reims-restore -> target
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
# rustfmt, clippy, clippy for x86_64-pc-windows-gnullvm and the tests, in each of reims-ctl's
|
||||
# two workspaces.
|
||||
- name: make check-ctl
|
||||
run: make check-ctl
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: *bound
|
||||
|
||||
linux-doc:
|
||||
name: Linux, rustdoc
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
RUSTDOCFLAGS: -D warnings
|
||||
# `cargo xtask check`'s CROSS_CHECK_FEATURES: the tested features, with SDL's sources unbuilt.
|
||||
DOC_FEATURES: reims-vgpu-vulkan/testkit,reims-vgpu/testkit,reims-vgpu/vulkan,reims-vgpu-c/vulkan,reims-vgpu-window/sdl-no-link
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
# The workspace's docs with its private items, warnings denied, for Linux and for Windows.
|
||||
- name: rustdoc for Linux
|
||||
run: cargo doc --workspace --no-deps --document-private-items --keep-going --features "$DOC_FEATURES"
|
||||
- name: rustdoc for x86_64-pc-windows-gnullvm
|
||||
if: ${{ !cancelled() }}
|
||||
run: cargo doc --workspace --no-deps --document-private-items --keep-going --target x86_64-pc-windows-gnullvm --features "$DOC_FEATURES"
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: *bound
|
||||
|
||||
linux-qemu:
|
||||
name: Linux, QEMU and its unit tests
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
# The fork's tests the lab runs for it (forkunit): unit tests under tests/unit, and qtests
|
||||
# under tests/qtest, which run against this build's qemu-system-x86_64.
|
||||
FORK_TESTS: >-
|
||||
unit/test-cutils unit/test-dsound-ring unit/test-audio-rate unit/test-whpx-mmio
|
||||
unit/test-reims-pointer qtest/virtio-pci-caps-test qtest/usb-hcd-xhci-test
|
||||
steps:
|
||||
# vendor/qemu alone, at its gitlink, from the fork's public repository; none of QEMU's own
|
||||
# submodules.
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: true
|
||||
# QEMU's build tools and the libraries it links, as scripts/install-ctl.sh installs them.
|
||||
- name: Install packages
|
||||
run: |
|
||||
read -ra packages <<< "$LIBRARY_APT"
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends "${packages[@]}" \
|
||||
build-essential pkg-config python3 python3-venv ninja-build flex bison bzip2 binutils \
|
||||
libglib2.0-dev libpixman-1-dev libslirp-dev zlib1g-dev libfdt-dev libpipewire-0.3-dev \
|
||||
libpulse-dev libasound2-dev libusb-1.0-0-dev libspice-server-dev libgnutls28-dev \
|
||||
libgtk-3-dev
|
||||
# configure fetches keycodemapdb, berkeley-softfloat-3 and berkeley-testfloat-3, at the
|
||||
# commits their wraps name, from QEMU's mirrors on GitHub, which hold the same commits.
|
||||
- name: Fetch QEMU's subprojects from GitHub
|
||||
run: git config --global url.https://github.com/qemu/.insteadOf https://gitlab.com/qemu-project/
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
# The library's dist tree, then qemu-system-x86_64 with reims-graphics-pci linked on it.
|
||||
- name: make qemu
|
||||
run: make qemu
|
||||
- name: The fork's unit tests and qtests
|
||||
run: |
|
||||
ulimit -c 0
|
||||
cd build/qemu
|
||||
targets=()
|
||||
for t in $FORK_TESTS; do targets+=("tests/$t"); done
|
||||
ninja "${targets[@]}"
|
||||
failed=()
|
||||
for t in $FORK_TESTS; do
|
||||
echo "::group::$t"
|
||||
if [ "${t%%/*}" = qtest ]; then
|
||||
QTEST_QEMU_BINARY=./qemu-system-x86_64 timeout 300 "./tests/$t" --tap -k || failed+=("$t")
|
||||
else
|
||||
timeout 300 "./tests/$t" --tap -k || failed+=("$t")
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
if [ ${#failed[@]} -gt 0 ]; then
|
||||
echo "::error::failed: ${failed[*]}"
|
||||
exit 1
|
||||
fi
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: *bound
|
||||
|
||||
# The device tests, the ones the `ci` profile leaves out, on Mesa's lavapipe in metal2vulkan's
|
||||
# lavapipe image at the commit Cargo.toml pins (its scripts/lavapipe-image: Arch Linux's packages
|
||||
# of one archive date, the bootstrap tarball checked against its sha256). The tests are built on
|
||||
# the runner and run in the image, with no network. The tests .github/lavapipe-expected-failures
|
||||
# names, each under its reason, must fail there, and every other must pass
|
||||
# (.github/lavapipe-tests.sh).
|
||||
linux-lavapipe:
|
||||
name: Linux, device tests on lavapipe
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 150
|
||||
env:
|
||||
# What the job adds to metal2vulkan's image (the step after its build).
|
||||
LAVAPIPE_EXTRAS: gcc git
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install packages
|
||||
run: |
|
||||
read -ra packages <<< "$LIBRARY_APT"
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends "${packages[@]}"
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
|
||||
with:
|
||||
tool: cargo-nextest@${{ env.NEXTEST_VERSION }}
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
# metal2vulkan's checkout at the pinned commit, as cargo fetched it.
|
||||
- name: Find metal2vulkan's lavapipe image
|
||||
id: image
|
||||
run: |
|
||||
manifest=$(cargo metadata --format-version 1 |
|
||||
python3 -I -c 'import json, sys; print(next(p["manifest_path"] for p in json.load(sys.stdin)["packages"] if p["name"] == "metal2vulkan-runtime"))')
|
||||
dir=$(dirname "$(dirname "$(dirname "$manifest")")")/scripts/lavapipe-image
|
||||
[ -f "$dir/lavapipe-image" ] || { echo "::error::no lavapipe image in $dir"; exit 1; }
|
||||
echo "dir=$dir" >> "$GITHUB_OUTPUT"
|
||||
pin=$(sha256sum < "$dir/pin" | cut -c1-16)
|
||||
echo "pin=$pin" >> "$GITHUB_OUTPUT"
|
||||
echo "key=lavapipe-image-$pin-${LAVAPIPE_EXTRAS// /-}" >> "$GITHUB_OUTPUT"
|
||||
# The image's downloads, with the packages the step after its build adds.
|
||||
- name: Restore the image's downloads
|
||||
id: downloads
|
||||
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ~/.cache/m2v-lavapipe-image
|
||||
key: ${{ steps.image.outputs.key }}
|
||||
restore-keys: lavapipe-image-${{ steps.image.outputs.pin }}
|
||||
- name: Build the image
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
IMAGE: ${{ steps.image.outputs.dir }}
|
||||
run: bash "$IMAGE/lavapipe-image" ensure
|
||||
# The C compiler the C API's harness tests run and the git the build stamp's test runs, which
|
||||
# the image's pin names neither of: installed into the image the build made, from the pin's
|
||||
# own archive date, through the build's pacman.conf, package cache and databases, and kept
|
||||
# under the same tag, which the run below uses.
|
||||
- name: Add cc and git to the image
|
||||
env:
|
||||
IMAGE: ${{ steps.image.outputs.dir }}
|
||||
run: |
|
||||
read -ra extras <<< "$LAVAPIPE_EXTRAS"
|
||||
date=$(sed -n 's/^date=//p' "$IMAGE/pin")
|
||||
cache=$HOME/.cache/m2v-lavapipe-image
|
||||
image=$(docker images --format '{{.Repository}}:{{.Tag}}' | sed -n '/^m2v-lavapipe:/p')
|
||||
[ -n "$image" ] && [ "$(wc -l <<< "$image")" = 1 ] || { echo "::error::not one lavapipe image: $image"; exit 1; }
|
||||
# shellcheck disable=SC2016 # the container's bash expands them
|
||||
docker run --name ci-lavapipe-extras \
|
||||
-v "$cache/pkg:/var/cache/pacman/pkg" -v "$cache/sync-$date:/var/lib/pacman/sync" \
|
||||
-v "$cache/pacman.conf:/etc/pacman.conf:ro" "$image" bash -euc '
|
||||
owner=$1
|
||||
shift
|
||||
pacman -S --noconfirm --needed "$@"
|
||||
yes | pacman -Sc >/dev/null
|
||||
chown -R "$owner" /var/cache/pacman/pkg /var/lib/pacman/sync
|
||||
' bash "$(id -u):$(id -g)" "${extras[@]}"
|
||||
docker commit ci-lavapipe-extras "$image" >/dev/null
|
||||
docker rm ci-lavapipe-extras >/dev/null
|
||||
bash "$IMAGE/lavapipe-image" run -- bash -c 'cc --version | head -1 && git --version'
|
||||
- name: Save the image's downloads
|
||||
if: steps.downloads.outputs.cache-hit != 'true' && github.event_name == 'push'
|
||||
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ~/.cache/m2v-lavapipe-image
|
||||
key: ${{ steps.image.outputs.key }}
|
||||
- name: Build the tests
|
||||
run: cargo nextest archive --workspace --features "$TESTED_FEATURES" --archive-file "$RUNNER_TEMP/tests.tar.zst"
|
||||
- name: Run the device tests on lavapipe
|
||||
env:
|
||||
IMAGE: ${{ steps.image.outputs.dir }}
|
||||
run: |
|
||||
bash "$IMAGE/lavapipe-image" run --read "$GITHUB_WORKSPACE" \
|
||||
--read "$RUNNER_TEMP/tests.tar.zst" --env LP_NUM_THREADS=1 -- \
|
||||
bash "$GITHUB_WORKSPACE/.github/lavapipe-tests.sh" "$RUNNER_TEMP/tests.tar.zst" \
|
||||
"$GITHUB_WORKSPACE" "$GITHUB_WORKSPACE/.github/lavapipe-expected-failures"
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: *bound
|
||||
|
||||
# `cargo xtask check` in two jobs, its lints and its tests (`--lints`, `--tests`): the whole
|
||||
# check ran past an hour on the macos-26 runner.
|
||||
macos-check:
|
||||
name: macOS, cargo xtask check --lints
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# The image's Xcode carries its Metal toolchain, which the Vulkan crate's build compiles its
|
||||
# metallibs with on a Mac; nothing of Apple's is fetched here.
|
||||
- name: Xcode's Metal compiler
|
||||
run: xcrun -sdk macosx metal --version
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
- name: Install cbindgen
|
||||
run: cargo install --locked cbindgen --version "$CBINDGEN_VERSION"
|
||||
# The lab's check on a Mac but its tests: also clippy for Linux.
|
||||
- name: cargo xtask check --lints
|
||||
run: cargo xtask check --lints
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: *bound
|
||||
|
||||
macos-test:
|
||||
name: macOS, cargo xtask check --tests
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Xcode's Metal compiler
|
||||
run: xcrun -sdk macosx metal --version
|
||||
# The threads a process and a user may have here: the tests start a few thousand at once.
|
||||
- name: Thread limits
|
||||
run: |
|
||||
sysctl kern.num_taskthreads kern.maxprocperuid hw.ncpu hw.memsize
|
||||
ulimit -u
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
|
||||
with:
|
||||
tool: cargo-nextest@${{ env.NEXTEST_VERSION }}
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
# The lab's tests on a Mac: also core's tests as x86_64-apple-darwin under Rosetta, which
|
||||
# the image installs.
|
||||
- name: cargo xtask check --tests
|
||||
run: cargo xtask check --tests
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: *bound
|
||||
|
||||
macos-ctl:
|
||||
name: macOS, make check-ctl
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
# MinGW's gcc and ar, for the C ring's build script compiles in clippy for
|
||||
# x86_64-pc-windows-gnullvm.
|
||||
- name: Install mingw-w64
|
||||
run: brew install mingw-w64
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: |
|
||||
crates/reims-ctl -> target
|
||||
crates/reims-restore -> target
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
- name: make check-ctl
|
||||
run: make check-ctl
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: *bound
|
||||
|
||||
macos-doc:
|
||||
name: macOS, rustdoc
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
RUSTDOCFLAGS: -D warnings
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install Rust
|
||||
run: rustup toolchain install
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
- name: rustdoc
|
||||
run: cargo doc --workspace --no-deps --all-features --document-private-items
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
run: *bound
|
||||
|
||||
# The guest's kexts, loader and Metal bundle: their own tests, with Xcode and its Metal
|
||||
# compiler, which the image carries. The bundle builds against the macOS 27 SDK (it names its
|
||||
# Metal types, MTLTensorPlaneType among them), so the job runs on the Xcode 27 image, macOS 27,
|
||||
# with Xcode 27.2, the lab's. Rebuilding the prebuilt kext sets stays in the lab.
|
||||
macos-guest:
|
||||
name: macOS, guest tests
|
||||
runs-on: xcode-27
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
DEVELOPER_DIR: /Applications/Xcode_27.2.app/Contents/Developer
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Xcode's Metal compiler
|
||||
run: xcrun -sdk macosx metal --version
|
||||
- name: make -C guest test
|
||||
run: make -C guest test
|
||||
|
||||
# Windows, in MSYS2's CLANG64 with the pinned nightly's x86_64-pc-windows-gnullvm host
|
||||
# toolchain, as scripts/install-ctl.sh builds there.
|
||||
windows:
|
||||
name: Windows, clippy and tests
|
||||
runs-on: windows-2025
|
||||
timeout-minutes: 120
|
||||
defaults:
|
||||
run:
|
||||
shell: msys2 {0}
|
||||
env:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
AR: llvm-ar
|
||||
CC_x86_64_pc_windows_gnullvm: clang
|
||||
CXX_x86_64_pc_windows_gnullvm: clang++
|
||||
AR_x86_64_pc_windows_gnullvm: llvm-ar
|
||||
CMAKE_GENERATOR: Ninja
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: msys2/setup-msys2@3c51bf698df1e37b2261f53cb67797b97761185c # v2.34.0
|
||||
with:
|
||||
msystem: CLANG64
|
||||
path-type: inherit
|
||||
install: >-
|
||||
make diffutils mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-lld
|
||||
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-ninja
|
||||
- name: Install Rust
|
||||
run: |
|
||||
channel=$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)
|
||||
echo "RUSTUP_TOOLCHAIN=$channel-x86_64-pc-windows-gnullvm" >> "$GITHUB_ENV"
|
||||
rustup toolchain install --profile minimal --component clippy,rustfmt "$channel-x86_64-pc-windows-gnullvm"
|
||||
- uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12
|
||||
with:
|
||||
tool: cargo-nextest@${{ env.NEXTEST_VERSION }}
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
# The two clippy runs of `cargo xtask check` on a Windows host.
|
||||
- name: clippy, every feature
|
||||
run: cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||
- name: clippy, the tested features
|
||||
if: ${{ !cancelled() }}
|
||||
run: cargo clippy --workspace --all-targets --no-default-features --features "$TESTED_FEATURES" -- -D warnings
|
||||
# The library's crates and their tested features, as scripts/internal/windows-tests.sh runs
|
||||
# them on the lab's Windows host.
|
||||
- name: Tests
|
||||
if: ${{ !cancelled() }}
|
||||
run: |
|
||||
cargo nextest run --target x86_64-pc-windows-gnullvm --no-fail-fast --features "$TESTED_FEATURES" \
|
||||
-p reims-vgpu-graphics -p reims-vgpu-vulkan -p reims-vgpu-window -p reims-vgpu -p reims-vgpu-c
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
shell: bash
|
||||
run: *bound
|
||||
|
||||
windows-ctl:
|
||||
name: Windows, make check-ctl
|
||||
runs-on: windows-2025
|
||||
timeout-minutes: 120
|
||||
defaults:
|
||||
run:
|
||||
shell: msys2 {0}
|
||||
env:
|
||||
CC: clang
|
||||
CXX: clang++
|
||||
AR: llvm-ar
|
||||
CC_x86_64_pc_windows_gnullvm: clang
|
||||
CXX_x86_64_pc_windows_gnullvm: clang++
|
||||
AR_x86_64_pc_windows_gnullvm: llvm-ar
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: msys2/setup-msys2@3c51bf698df1e37b2261f53cb67797b97761185c # v2.34.0
|
||||
with:
|
||||
msystem: CLANG64
|
||||
path-type: inherit
|
||||
install: >-
|
||||
make diffutils mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-lld
|
||||
- name: Install Rust
|
||||
run: |
|
||||
channel=$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)
|
||||
echo "RUSTUP_TOOLCHAIN=$channel-x86_64-pc-windows-gnullvm" >> "$GITHUB_ENV"
|
||||
rustup toolchain install --profile minimal --component clippy,rustfmt "$channel-x86_64-pc-windows-gnullvm"
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
workspaces: |
|
||||
crates/reims-ctl -> target
|
||||
crates/reims-restore -> target
|
||||
save-if: ${{ github.ref == 'refs/heads/development' }}
|
||||
# rustfmt, clippy (this host's, x86_64-pc-windows-gnullvm) and the tests, in each of
|
||||
# reims-ctl's two workspaces.
|
||||
- name: make check-ctl
|
||||
run: make check-ctl
|
||||
- name: Bound the cache
|
||||
if: ${{ !cancelled() }}
|
||||
shell: bash
|
||||
run: *bound
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
[submodule "vendor/qemu"]
|
||||
path = vendor/qemu
|
||||
url = https://github.com/steelbrain/qemu-reims-vgpu
|
||||
branch = steelbrain/reims-vgpu-rebase-2
|
||||
url = https://github.com/yxc0915/qemu-reims-vgpu.git
|
||||
branch = codex/intel-vm-suspend
|
||||
@@ -70,8 +70,8 @@ The Makefile's header lists every target. README.md lists the requirements.
|
||||
| core: the platform traits, the runtime, raises and deaths, the guest's RAM, the testkit | `crates/reims-vgpu-vulkan/src/core.rs` and `core/`, the Vulkan crate's module `core`; the testkit is its `testkit` feature |
|
||||
| the Vulkan platform's metallibs, which a build off a Mac copies | `crates/reims-vgpu-vulkan/metallibs`, written on a Mac by `cargo xtask metallibs` (README.md, Building) |
|
||||
| a display's own window, and the register of what it does | `crates/reims-vgpu-window`, its `features.md` and its manual walk on macOS, `scripts/internal/walk_window_macos.sh`; the wiring is `crates/reims-vgpu/src/window.rs` |
|
||||
| the reims-graphics device's video on the host, on NVDEC or VA-API, and on a Mac on VideoToolbox | `crates/reims-vgpu-video`, in modules: `core` (what the arms share: their runtime, locks, a guest surface's memory and bounded waits), `codec` (the codecs above the hardware), and on Linux `vaapi` and `nvidia`, on Windows `vaapi` and on macOS `videotoolbox` (the hardware's); its subcrate `conformance` is the test streams' readers and writers; the arms are reims-vgpu's `crates/reims-vgpu/src/graphics/{nvidia,vaapi,videotoolbox,video_choice,video_host}.rs`, on the runtime in `crates/reims-vgpu/src/video/runtime.rs` |
|
||||
| the video docs | [docs/video](docs/video): `devices.md` is what the device answers and what a decode does, `backends.md` the arms, the crate and the conformance suite (`crates/reims-vgpu-video/tools/h264-check.sh` and `hevc-check.sh`), `core.md`, `vaapi.md` and `nvidia.md` its modules, `hand-overs.md` every point where one API writes a picture and another reads it, with its wait and test, `bugs.md` what is wrong or put off |
|
||||
| the reims-graphics device's video on the host, on NVDEC or VA-API | `crates/reims-vgpu-video`, in modules: `core` (what the arms share: their runtime, locks, a guest surface's memory and bounded waits), `codec` (the codecs above the hardware), and on Linux `vaapi` and `nvidia` and on Windows `vaapi` (the hardware's); its subcrate `conformance` is the test streams' readers and writers; the arms are reims-vgpu's `crates/reims-vgpu/src/graphics/{nvidia,vaapi,video_choice,video_host}.rs`, on the runtime in `crates/reims-vgpu/src/video/runtime.rs` |
|
||||
| the video docs | [docs/video](docs/video): `devices.md` is what the device answers and what a decode does, `backends.md` the arms, the crate and the conformance suite (`crates/reims-vgpu-video/tools/h264-check.sh` and `hevc-check.sh`), `core.md`, `vaapi.md` and `nvidia.md` its modules, `bugs.md` what is wrong or put off |
|
||||
| the guest's kexts, loader and Metal bundle | `guest/`, the prebuilt set reims-ctl carries, `guest/prebuilt`, and the arm64e set Ambrosia's config bundle takes, `guest/prebuilt-arm64e` |
|
||||
| the dist tree QEMU links | `xtask/src/dist.rs` (`cargo xtask dist`) |
|
||||
| the option ROM reims-ctl gives the device | `firmware/`, and the prebuilt ROM, `firmware/prebuilt/ReimsGraphics.rom`, described in [docs/architecture.md](docs/architecture.md) section 11.4 |
|
||||
@@ -136,11 +136,11 @@ passes run again alone.
|
||||
| the library (`crates/`), the C API or its header | `cargo xtask check` |
|
||||
| what the Vulkan platform ends the process on, or what device info, GPU families or feature queries answer | the library's checks, and a cold boot of each guest the change can reach before it merges ("A boot is the only check", below) |
|
||||
| a `.metal` source of the Vulkan crate, `shaders.metal` among them | `cargo xtask metallibs` on a Mac, committing the metallibs it writes with the change; then the library's checks |
|
||||
| the video crate (`crates/reims-vgpu-video`), or its arms in `reims-vgpu` | `cargo xtask check` on a Mac; the Linux tests on a VA-API host and on an NVIDIA host; where the `vaapi` module's decoders change, the conformance suite on a VA-API host; and, where the `videotoolbox` module or its arm changes, `crates/reims-vgpu-video/tools/vt-check.sh` on a Mac, its hardware decoders against ffmpeg's MD5s ("The video crates' checks", below) |
|
||||
| the video crate (`crates/reims-vgpu-video`), or its arms in `reims-vgpu` | `cargo xtask check` on a Mac; the Linux tests on a VA-API host and on an NVIDIA host; and, where the `vaapi` module's decoders change, the conformance suite on a VA-API host ("The video crates' checks", below) |
|
||||
| Windows-only code (`cfg(windows)` files) | `cargo xtask check` on the Mac or Linux, which clippy-checks the Windows target; and the crate's tests on homelab-mac-mini-2018, `scripts/internal/windows-tests.sh -p <crate>`: two potluck jobs there, the build, which starts from the mini's kept base build (`MINIBASE=0` builds from nothing), then the tests holding its UHD 630 (`--gpu 8086:3e9b`; the tests' job peaked at 14.7 to 20.7 GiB of commit charge, and reserves 26 GiB) |
|
||||
| `xtask/` | `cargo test -p xtask`, rustfmt and clippy on it |
|
||||
| `crates/reims-ctl` or `crates/reims-restore` | `make check-ctl` on the Mac, which runs `cargo fmt --check`, `cargo clippy --all-targets`, `cargo clippy --all-targets --target x86_64-pc-windows-gnullvm` and `cargo test` in each of the two workspaces, `crates/reims-ctl` and `crates/reims-restore` (with reims-apfs), with `-D warnings` and `--workspace` (`cargo xtask check` reaches neither; the Windows clippy is the one check that sees a break of their Windows build, and needs a MinGW C compiler for ring's build script: on the Mac, Homebrew's `mingw-w64`, which the target gives as `CC_x86_64_pc_windows_gnullvm=x86_64-w64-mingw32-gcc` and `AR_x86_64_pc_windows_gnullvm=x86_64-w64-mingw32-ar`; where `x86_64-w64-mingw32-gcc` is not on the PATH, a Linux host's among them, the target says so and fails); a change to the QEMU command it builds, or to `scripts/install-ctl.sh` or `scripts/install.ps1`, also needs an install and a VM boot on each host it touches |
|
||||
| `guest/` (kext, bundle, rgfxgate, loader) | `make -C guest test` on a Mac, which on Apple silicon also runs the bundle's checks a second time for arm64, natively, in `guest/bundle/build/arm64` (its x86_64 checks run under Rosetta there, and natively on an x86-64 Mac); a change to a source the sets are built from also needs `make -C guest prebuilt` and `make -C guest prebuilt-arm64e`, committing `guest/prebuilt` and `guest/prebuilt-arm64e` with it (`make -C guest prebuilt-check`, which checks both, fails otherwise) |
|
||||
| `crates/reims-ctl` | `cargo test`, `cargo fmt --check`, `cargo clippy --all-targets`, and `cargo clippy --all-targets --target x86_64-pc-windows-gnullvm` on the Mac, in it (`cargo xtask check` does not reach it; the last is the one check that sees a break of its Windows build, and needs a MinGW C compiler for ring's build script: on the Mac, Homebrew's `mingw-w64`, with `CC_x86_64_pc_windows_gnullvm=x86_64-w64-mingw32-gcc` and `AR_x86_64_pc_windows_gnullvm=x86_64-w64-mingw32-ar`; a Linux host without that toolchain fails it); a change to the QEMU command it builds, or to `scripts/install-ctl.sh` or `scripts/install.ps1`, also needs an install and a VM boot on each host it touches |
|
||||
| `guest/` (kext, bundle, rgfxgate, loader) | `make -C guest test` on a Mac; a change to a source the sets are built from also needs `make -C guest prebuilt` and `make -C guest prebuilt-arm64e`, committing `guest/prebuilt` and `guest/prebuilt-arm64e` with it (`make -C guest prebuilt-check`, which checks both, fails otherwise) |
|
||||
| `firmware/`, the option ROM | build it (`make -C firmware`); a change not meant to alter what the guest's firmware sees keeps the ROM's bytes; a change to what `ReimsGraphics.rom` is built from (its sources, the Makefile, `crates/reims-vgpu-graphics/include/reims_graphics_wire.h`) also runs `make -C firmware prebuilt` on a Mac, committing the ROM and record it writes |
|
||||
| `firmware/ambrosia` | build it (`make -C firmware/ambrosia bundle`); a change to what it does with the device also needs an arm64 guest's boot on Ambrosia with the device and the module ([docs/qemu.md](docs/qemu.md), "arm64 guests") |
|
||||
| `vendor/qemu` | build it (`make qemu`) and realize the device paused (`-S`); a change to `hw/display/reims-graphics-pci.c`, or to what QEMU calls, also needs a VM boot ([docs/lessons.md](docs/lessons.md), [docs/qemu.md](docs/qemu.md)) |
|
||||
|
||||
Generated
-1
@@ -419,7 +419,6 @@ dependencies = [
|
||||
"parking_lot",
|
||||
"reims-vgpu-graphics",
|
||||
"reims-vgpu-video",
|
||||
"reims-vgpu-video-conformance",
|
||||
"reims-vgpu-vulkan",
|
||||
"reims-vgpu-window",
|
||||
"sha2 0.10.9",
|
||||
|
||||
+2
-5
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
|
||||
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
|
||||
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
|
||||
# from metal2vulkan's public repository at the commit both name.
|
||||
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "865592b96b791840b26dddb310f33561bfc7d564" }
|
||||
metal2vulkan = { git = "https://github.com/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/steelbrain/metal2vulkan", rev = "865592b96b791840b26dddb310f33561bfc7d564" }
|
||||
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
|
||||
@@ -87,9 +87,6 @@ tikv-jemallocator = "0.7.0"
|
||||
[workspace.lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
missing_docs = "warn"
|
||||
# A result the caller must take is taken: an ignored `#[must_use]` value does not compile, as a
|
||||
# blit command's `Encoded` (whether the platform recorded it) is one every caller answers.
|
||||
unused_must_use = "deny"
|
||||
|
||||
# The workspace's docs are its developers', built with its private items (`cargo doc
|
||||
# --document-private-items`), where a public item's links to the private items its docs name
|
||||
|
||||
@@ -15,12 +15,6 @@
|
||||
# Mesa's KosmicKrisp driver, which the library's rt platform
|
||||
# loads from ../lib of a QEMU in build/qemu or in a directory
|
||||
# beside it (make qemu makes them too); nothing elsewhere
|
||||
# make check-ctl
|
||||
# reims-ctl's checks (AGENTS.md, "Checking a change") in each
|
||||
# of its two workspaces, crates/reims-ctl and crates/reims-restore
|
||||
# (with reims-apfs), which cargo xtask check reaches neither of:
|
||||
# rustfmt, clippy, clippy for x86-64 Windows and the tests; it
|
||||
# stops where x86_64-w64-mingw32-gcc is not on the PATH
|
||||
# make clean remove build/, QEMU's build included
|
||||
#
|
||||
# QEMU_CONFIGURE adds options to QEMU's configure and runs it again.
|
||||
@@ -44,7 +38,7 @@ RUST_DIST := $(RUST_TARGET)/dist-vulkan
|
||||
# (crates/reims-vgpu-vulkan/src/rt_platform/stage.rs).
|
||||
HELPER := reims-vgpu-compile$(if $(filter Windows_NT,$(OS)),.exe)
|
||||
|
||||
.PHONY: all qemu vulkan-links check-ctl clean
|
||||
.PHONY: all qemu vulkan-links clean
|
||||
|
||||
all:
|
||||
CARGO_TARGET_DIR="$(RUST_TARGET)" cargo xtask dist
|
||||
@@ -128,49 +122,5 @@ vulkan-links:
|
||||
fi; \
|
||||
done
|
||||
|
||||
# reims-ctl's checks, run in each of its workspaces by --manifest-path, never
|
||||
# through the library's xtask: reims-ctl and reims-restore are workspaces of
|
||||
# their own, so they build without the metal2vulkan the library's workspace
|
||||
# fetches. The cheapest step first, and the first failure stops it. clippy for
|
||||
# x86_64-pc-windows-gnullvm, the Windows build, is the one check on the Mac or
|
||||
# Linux that sees a break of it (docs/lessons.md): its build scripts compile
|
||||
# C for Windows (ring's, under ureq's rustls) with MinGW's gcc and ar, which
|
||||
# a Mac has from Homebrew's mingw-w64. Where they are missing it says so and
|
||||
# stops, before any step runs. On Windows, where reims-ctl builds for that
|
||||
# target natively (MSYS2's CLANG64), the host's clippy is that check, and it
|
||||
# says so in place of a second run.
|
||||
CTL_WORKSPACES := crates/reims-ctl crates/reims-restore
|
||||
CTL_WINDOWS := x86_64-pc-windows-gnullvm
|
||||
CTL_MINGW := x86_64-w64-mingw32
|
||||
|
||||
check-ctl:
|
||||
ifneq ($(OS),Windows_NT)
|
||||
@for t in gcc ar; do command -v $(CTL_MINGW)-$$t >/dev/null || { \
|
||||
echo "check-ctl: $(CTL_MINGW)-$$t is not on the PATH, and clippy for $(CTL_WINDOWS) needs it for the C its dependencies build (on a Mac: brew install mingw-w64)" >&2; \
|
||||
exit 1; }; done
|
||||
endif
|
||||
@for w in $(CTL_WORKSPACES); do \
|
||||
echo "check-ctl: rustfmt in $$w"; \
|
||||
cargo fmt --manifest-path $$w/Cargo.toml --all --check || exit 1; \
|
||||
done
|
||||
@for w in $(CTL_WORKSPACES); do \
|
||||
echo "check-ctl: clippy in $$w"; \
|
||||
cargo clippy --manifest-path $$w/Cargo.toml --workspace --all-targets -- -D warnings || exit 1; \
|
||||
done
|
||||
ifeq ($(OS),Windows_NT)
|
||||
@echo "check-ctl: clippy for $(CTL_WINDOWS): the clippy above, this host's"
|
||||
else
|
||||
@for w in $(CTL_WORKSPACES); do \
|
||||
echo "check-ctl: clippy for $(CTL_WINDOWS) in $$w"; \
|
||||
CC_x86_64_pc_windows_gnullvm=$(CTL_MINGW)-gcc AR_x86_64_pc_windows_gnullvm=$(CTL_MINGW)-ar \
|
||||
cargo clippy --manifest-path $$w/Cargo.toml --workspace --all-targets --target $(CTL_WINDOWS) -- -D warnings || exit 1; \
|
||||
done
|
||||
endif
|
||||
@for w in $(CTL_WORKSPACES); do \
|
||||
echo "check-ctl: tests in $$w"; \
|
||||
cargo test --manifest-path $$w/Cargo.toml --workspace || exit 1; \
|
||||
done
|
||||
@echo "check-ctl: ok"
|
||||
|
||||
clean:
|
||||
rm -rf "$(BUILD_DIR)"
|
||||
@@ -36,12 +36,9 @@ GPU the wrong pages of the guest's memory, which can overwrite it. `reims-ctl` w
|
||||
an older kernel, and `reims-ctl doctor` shows the kernel it found.
|
||||
|
||||
arm64 macOS 14 to 27 runs on QEMU too, with Ambrosia, our own arm64 firmware, and the same virtual
|
||||
GPU. On an Apple silicon Mac it runs under HVF, macOS's hypervisor, and on arm64 Linux under KVM. An
|
||||
x86-64 Linux host runs arm64 VMs as well, with QEMU emulating the CPU (TCG), which is much slower;
|
||||
we've checked macOS 14, 15 and 26 that way. An x86-64 Windows PC runs them emulated the same way,
|
||||
also much slower. On Windows we have only a contributor's report so far: macOS 27.2.1 restored and
|
||||
booted to its desktop on Windows 11, on a laptop with a 12th-generation Intel Core i7 and an RTX
|
||||
3060 Laptop GPU; we haven't run one there ourselves yet. `reims-ctl` makes an arm64 VM by restoring
|
||||
GPU. On an Apple silicon Mac it runs under HVF, macOS's hypervisor, and on arm64 Linux under KVM.
|
||||
An x86-64 Linux host runs arm64 VMs as well, with QEMU emulating the CPU (TCG), which is much
|
||||
slower; we've checked macOS 14, 15 and 26 that way. `reims-ctl` makes an arm64 VM by restoring
|
||||
macOS from an IPSW, Apple's restore image, onto a new disk, and boots it with Ambrosia, which adds
|
||||
our drivers to the guest as it starts. [docs/qemu.md](docs/qemu.md), "arm64 guests", has the
|
||||
details.
|
||||
@@ -65,10 +62,7 @@ on Mesa's KosmicKrisp, from Homebrew's `mesa`) and QEMU on it, installs QEMU int
|
||||
release, which `reims-ctl` checks against the hash it pins. `vendor/qemu` is
|
||||
fetched from its public repository (`steelbrain/qemu-reims-vgpu`), at the commit this checkout
|
||||
pins, and Cargo fetches metal2vulkan from its public repository, at the commit the workspace's
|
||||
`Cargo.toml` names. On Linux it also writes `~/.local/share/applications/reims-vgpu.desktop`, a
|
||||
hidden app entry for the VMs' windows, so GNOME can remember your answer when it asks whether a
|
||||
window may take its shortcuts; it leaves alone a file there it didn't write.
|
||||
`reims-ctl doctor` checks the host and the install.
|
||||
`Cargo.toml` names. `reims-ctl doctor` checks the host and the install.
|
||||
|
||||
On Windows, open PowerShell and run:
|
||||
|
||||
@@ -84,8 +78,7 @@ restart once before your first VM), clones the repository into your user folder
|
||||
clang, with the Rust toolchain that goes with it: it installs Rust if you don't have it, and adds
|
||||
that toolchain beside yours if your Rust is set up for Visual Studio, so you don't need Visual
|
||||
Studio. It installs `reims-ctl` into `%USERPROFILE%\.cargo\bin`. On an Intel Core i7-8700B a
|
||||
first install took about 20 minutes, and running it again about a minute, measured before the
|
||||
install also built QEMU for arm64 VMs and `reims-restore`. From a clone,
|
||||
first install took about 20 minutes, and running it again about a minute. From a clone,
|
||||
`powershell -ExecutionPolicy Bypass -File scripts\install.ps1` does the same. Windows support is
|
||||
newer than Linux's. The guest's H.264 and HEVC video decodes on your GPU there through Mesa's VA-API
|
||||
driver for Direct3D 12, which the install adds from MSYS2. Encoding doesn't use your GPU on Windows
|
||||
@@ -137,7 +130,7 @@ yet, whichever GPU you have, so the guest encodes video in software there.
|
||||
`--installer` takes an installer of your own.
|
||||
|
||||
An arm64 VM comes from an IPSW instead. On a Mac or arm64 Linux that's what `create` makes; on
|
||||
x86-64 Linux and Windows, `--ipsw` asks for one:
|
||||
x86-64 Linux, `--ipsw` asks for one:
|
||||
|
||||
```sh
|
||||
reims-ctl create mac --ipsw latest --start # downloads the current macOS's IPSW, about 25 GB
|
||||
@@ -146,22 +139,19 @@ yet, whichever GPU you have, so the guest encodes video in software there.
|
||||
|
||||
Apple offers only the current macOS to download, so an older one needs an IPSW you have. The
|
||||
download is kept for your next VM. The VM's first boot makes macOS's Data volume and then
|
||||
resets the VM, which won't start again until you finish it: stop it and run
|
||||
`reims-restore finish-eacs` with the VM's folder. If it says the VM needs one more first boot,
|
||||
start it, and after that boot stop it and finish again. Once it finishes, the next start goes
|
||||
to Setup Assistant.
|
||||
resets the VM, which won't start again until you finish it: stop it, run
|
||||
`reims-restore finish-eacs` with the VM's folder, and the next start goes to Setup Assistant.
|
||||
|
||||
### Day to day
|
||||
|
||||
`reims-ctl` with no command opens its interactive interface: create a VM, start it (each of its
|
||||
displays opens in a window), stop it (the guest shuts down, or is powered off after a timeout),
|
||||
edit its CPUs, memory, displays (up to four), resolution, borderless windows, GPU, audio and
|
||||
logs, change its installer, print the exact QEMU command it runs, and zip its logs with the
|
||||
host's details into Downloads for a bug report.
|
||||
edit its CPUs, memory, displays (up to four), resolution, borderless windows, input capture,
|
||||
GPU, audio and logs, change its installer, print the exact QEMU command it runs, and zip its
|
||||
logs with the host's details into Downloads for a bug report.
|
||||
|
||||
```sh
|
||||
reims-ctl list # the VMs and whether they run
|
||||
reims-ctl resume mac # free space first: a VM pauses when this host's disk fills up
|
||||
reims-ctl set mac --memory 12G --resolution 1920x1080 # applies at the next start
|
||||
reims-ctl command mac # the QEMU command it runs, as a shell script
|
||||
reims-ctl report mac # logs, settings, the host's details and its vulkaninfo, zipped, for a bug report
|
||||
@@ -172,32 +162,31 @@ reims-ctl update --channel development # switch to the development branch firs
|
||||
`reims-ctl help` lists every command; every option takes `--name value` or `--name=value`. A running
|
||||
VM keeps the QEMU it started with across an update.
|
||||
|
||||
### The window takes your keyboard shortcuts
|
||||
### The window takes your keyboard shortcuts and your mouse
|
||||
|
||||
Each of the guest's displays opens in a window the library owns (`crates/reims-vgpu-window`).
|
||||
While the window has the keyboard, your shortcuts go to the guest instead of the host. On Linux
|
||||
the window grabs the whole keyboard (SDL3's window, on Wayland or X11), so the compositor's
|
||||
shortcuts, Super and Alt+Tab among them, reach the guest; on Windows the Windows key, Alt+Tab and
|
||||
Alt+F4 do too. Keys reach the guest by position, so the guest's own layout applies, and the Super
|
||||
key (the Windows key on Windows) is the guest's ⌘. There's nothing to click first, and the mouse
|
||||
is never held: it moves in and out of the window freely, the window resizes as any other does,
|
||||
and a click on another window or the taskbar takes you out. **Ctrl+Alt+Super** together
|
||||
(**Ctrl+Alt+Win** on Windows) gives the host its shortcuts back until you next switch to the
|
||||
window; the title names those keys while the window holds the keyboard.
|
||||
Each of the guest's displays opens in a window the library owns (`crates/reims-vgpu-window`). **Click into the
|
||||
guest's picture to capture the keyboard and the mouse:** shortcuts and system keys then go to the
|
||||
guest instead of the host, and the pointer stays inside the picture until you release it, so you
|
||||
can throw it at the guest's corners and edges without landing on another window. Keys reach the
|
||||
guest by position, so the guest's own layout applies, and the Super key (the Windows key on Windows)
|
||||
is the guest's ⌘. While captured, the window grabs the whole keyboard (SDL3's window, on Wayland or
|
||||
X11), so the compositor's shortcuts, Super and Alt+Tab among them, reach the guest; on Windows, the
|
||||
Windows key and Alt+Tab do too. **Ctrl+Alt+Super** together (**Ctrl+Alt+Win** on Windows) releases
|
||||
it.
|
||||
|
||||
On a Mac, every ⌘ shortcut goes to the guest while its window is in front, ⌘Q among them, so quit
|
||||
the VM from the menu or by closing its window. Some keys never reach the guest, because the system
|
||||
keeps them before any app sees them: Ctrl+Alt+Del and Win+L on Windows, and on a Mac ⌘Space, ⌘Tab,
|
||||
Mission Control and the screenshot keys.
|
||||
The title says when input is captured and how to release it. Losing focus releases capture too,
|
||||
and gives the host back its system keys and its pointer. Losing focus, releasing capture or closing the window sends a key-up for every key
|
||||
still down, so nothing sticks. Closing a window first asks "Turn off the VM?": Turn Off powers the
|
||||
VM off at once, as if its power were cut, and Cancel keeps it running.
|
||||
|
||||
When a game hides the guest's cursor to steer by the mouse, the window holds the pointer still
|
||||
and hands the guest the mouse's motion, while the window has the keyboard and the pointer is over
|
||||
the picture. The title then names the keys that let the pointer go: Ctrl+Alt+Super, Ctrl+Alt+Win
|
||||
on Windows, ⌃⌥⌘ on a Mac.
|
||||
|
||||
Losing focus, those keys or closing the window sends a key-up for every key still down, so
|
||||
nothing sticks. Closing a window first asks "Turn off the VM?": Turn Off powers the VM off at
|
||||
once, as if its power were cut, and Cancel keeps it running.
|
||||
If you'd rather the window never capture anything, turn off **Capture input** in the VM's
|
||||
settings (`e` in `reims-ctl`, or `reims-ctl set <vm> --capture false`; it applies at the VM's
|
||||
next start). The title then ends "— input capture off". Clicks and keys still reach the guest
|
||||
while its window is in front, but nothing is grabbed or held: the pointer moves out of the window
|
||||
freely, and the host keeps its own shortcuts, such as Alt+Tab or ⌘Tab. On a Mac, other ⌘
|
||||
shortcuts go to the guest, ⌘Q among them, so quit the VM from the menu or by closing its window.
|
||||
A game that steers by the mouse's motion gets the plain pointer, which stops at the edge of the
|
||||
guest's picture.
|
||||
|
||||
Fn/Globe does not reach the guest (QEMU's USB keyboard cannot carry it), and there is no HDR output.
|
||||
[`crates/reims-vgpu-window/features.md`](crates/reims-vgpu-window/features.md) lists everything the
|
||||
@@ -211,16 +200,13 @@ reads them once per process, and an unset or unparsable value is the default.
|
||||
| Variable | Effect |
|
||||
|---|---|
|
||||
| `REIMS_VGPU_LOG=info` | the library's log lines to stderr, filtered by a level and `target=level` pairs (`warn,reims_vgpu_graphics=debug`); unset, nowhere. `reims-ctl set <vm> --log-level` sets it |
|
||||
| `REIMS_VGPU_WINDOW=0` | QEMU stays headless under `-display none` (QEMU reads it, not the library). `reims-ctl start <vm> --headless` starts a VM so for that start alone, and `reims-ctl view <vm>` shows its screen |
|
||||
| `REIMS_VGPU_WINDOW=0` | QEMU stays headless under `-display none` (QEMU reads it, not the library) |
|
||||
| `REIMS_VGPU_WINDOW_BORDERLESS=1` | a borderless window that fills its screen |
|
||||
| `REIMS_VGPU_STRICT=1` | end the process when the host runs out of memory, instead of answering the guest the way Metal does then |
|
||||
|
||||
Each window opens at its size of QEMU's `reims-graphics-pci` property `resolution=` (1920x1080 by
|
||||
default), which `reims-ctl`'s resolution setting sets: one size for every display, or one for each
|
||||
display, comma-separated, so `reims-ctl set mac --resolution 2560x1440,1920x1080` gives a VM's two
|
||||
displays a size each. The guest follows each window as you resize it. The guest's Displays settings also list a few smaller sizes of the window's shape: pick
|
||||
one and the window keeps its size, showing the guest's picture scaled up to fill it.
|
||||
[docs/api.md](docs/api.md) section 2 lists every setting and variable.
|
||||
The window opens at the size of QEMU's `reims-graphics-pci` property `resolution=` (1920x1080 by
|
||||
default), which `reims-ctl`'s resolution setting sets, and the guest follows the window as you
|
||||
resize it. [docs/api.md](docs/api.md) section 2 lists every setting and variable.
|
||||
|
||||
## What's here
|
||||
|
||||
@@ -251,7 +237,7 @@ library, which runs it on Vulkan through [`metal2vulkan`](https://github.com/ste
|
||||
and draws the guest's display into a window of its own. On a Mac the library runs on Vulkan too,
|
||||
on Mesa's KosmicKrisp driver rather than on Metal, and the guest's side is built there. x86-64 VMs
|
||||
run on Linux and Windows hosts, and arm64 VMs under HVF on Apple silicon Macs, under KVM on arm64
|
||||
Linux and under TCG on x86-64 Linux and Windows ([docs/qemu.md](docs/qemu.md), "arm64 guests").
|
||||
Linux and under TCG on x86-64 Linux ([docs/qemu.md](docs/qemu.md), "arm64 guests").
|
||||
|
||||
The library's C API (`crates/reims-vgpu-c/include/reims_vgpu.h`, specified in
|
||||
[docs/api.md](docs/api.md)) is its interface to QEMU: `cargo xtask dist` writes the library, the
|
||||
@@ -265,9 +251,7 @@ it needs itself; working on the code needs the following.
|
||||
TCG; on arm64, arm64 VMs under KVM; VMs on our GPU need Linux 7.2 or later), and an Apple silicon Mac for the metallibs and the guest's
|
||||
kexts, where arm64 VMs run under HVF. Every Rust binary built on the Mac is arm64
|
||||
(`aarch64-apple-darwin`): rustc's arm64e target has no pointer authentication, and its binaries
|
||||
crash before `main` (`rust-toolchain.toml`). An x86-64 Windows PC runs x86-64 VMs under WHPX
|
||||
and arm64 VMs under TCG, with the library and QEMU built in MSYS2's CLANG64 shell
|
||||
(`scripts/install.ps1`).
|
||||
crash before `main` (`rust-toolchain.toml`).
|
||||
- The toolchain `rust-toolchain.toml` pins: nightly-2026-11-03 with rustfmt and clippy, for rustc's
|
||||
parallel front end (`-Zthreads`, in `.cargo/config.toml`). rustup installs it on first use.
|
||||
- `cargo-nextest`, which runs the tests in `cargo xtask check`
|
||||
|
||||
Generated
-18
@@ -2013,7 +2013,6 @@ dependencies = [
|
||||
"clap",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"libc",
|
||||
"plist",
|
||||
"png",
|
||||
@@ -2024,7 +2023,6 @@ dependencies = [
|
||||
"sha2 0.11.1",
|
||||
"shlex",
|
||||
"toml",
|
||||
"toml_edit",
|
||||
"ureq",
|
||||
"windows-sys 0.61.2",
|
||||
"zip",
|
||||
@@ -2621,19 +2619,6 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.25.17+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
@@ -3060,9 +3045,6 @@ name = "winnow"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
|
||||
@@ -18,8 +18,6 @@ anyhow = "1.0.104"
|
||||
clap = { version = "4.6.7", features = ["derive", "env", "wrap_help"] }
|
||||
crc32fast = "1.5.2"
|
||||
flate2 = "1.1.10"
|
||||
# A new VM's random MAC (vm.rs), from the OS's random source, as reims-restore takes its nonces.
|
||||
getrandom = "0.4.3"
|
||||
# An x86-64 VM's OpenCore config.plist, for the Mac it presents (opencore.rs).
|
||||
plist = "1.10.1"
|
||||
# The viewer's frames for the kitty and iTerm2 image protocols (view/encode.rs).
|
||||
@@ -34,10 +32,6 @@ serde_json = "1.0.153"
|
||||
sha2 = "0.11.1"
|
||||
shlex = "2.0.1"
|
||||
toml = "1.1.2"
|
||||
# Writes reims-ctl's TOML records (a VM's vm.toml, the registry, the install's and the migrations'
|
||||
# records) over their files as they are, keeping what another build of reims-ctl wrote there in
|
||||
# its place and form (record.rs).
|
||||
toml_edit = "0.25.17"
|
||||
# Downloads that release's zip from its release page (ambrosia.rs), with rustls, as reims-restore
|
||||
# downloads from Apple.
|
||||
ureq = "3.5.1"
|
||||
|
||||
+17
-32
@@ -11,26 +11,32 @@
|
||||
//! here as its Makefile builds `build/ReimsGraphics.elf`: with clang and the Makefile's
|
||||
//! `CFLAGS`, and linked with the `LDFLAGS` by the toolchain's own lld (rust-lld, as GNU's
|
||||
//! `ld.lld`), so the build needs clang and no lld of the host's. Where clang can't build it,
|
||||
//! reims-ctl carries no module, says so as it builds, and refuses to start an arm64 VM;
|
||||
//! - reims-ctl's build stamp, the commit its checkout is at (`src/build_stamp.rs`).
|
||||
//! reims-ctl carries no module, says so as it builds, and refuses to start an arm64 VM.
|
||||
//!
|
||||
//! A reims-ctl for Windows, which runs no arm64 VM (src/host.rs), carries neither the arm64 set
|
||||
//! nor the module.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
#[path = "src/build_stamp.rs"]
|
||||
mod build_stamp;
|
||||
|
||||
fn main() {
|
||||
stamp();
|
||||
let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets it"));
|
||||
let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").expect("cargo sets it"));
|
||||
let out = out_dir.join("set.rs");
|
||||
let set_arm64e = set_code(
|
||||
&crate_dir.join("../../guest/prebuilt-arm64e"),
|
||||
"guest/prebuilt-arm64e",
|
||||
);
|
||||
let module = module_code(&crate_dir.join("../../firmware/ambrosia"), &out_dir);
|
||||
// A reims-ctl for Windows runs no arm64 VM (src/host.rs), and carries no arm64 guest.
|
||||
let windows = std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "windows");
|
||||
let (set_arm64e, module) = if windows {
|
||||
("None".to_string(), "None".to_string())
|
||||
} else {
|
||||
(
|
||||
set_code(
|
||||
&crate_dir.join("../../guest/prebuilt-arm64e"),
|
||||
"guest/prebuilt-arm64e",
|
||||
),
|
||||
module_code(&crate_dir.join("../../firmware/ambrosia"), &out_dir),
|
||||
)
|
||||
};
|
||||
let set = format!(
|
||||
"/// guest/prebuilt/set.toml's set, in its order.\n\
|
||||
pub static SET: Option<&[Kext]> = {};\n\
|
||||
@@ -252,24 +258,3 @@ fn walk(root: &Path, dir: &Path, files: &mut Vec<(String, PathBuf)>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stamps reims-ctl with the commit its checkout is at (`src/build_stamp.rs`), as
|
||||
/// `REIMS_CTL_STAMP`, read again where the checkout's HEAD or index moves or reims-ctl's sources
|
||||
/// change.
|
||||
fn stamp() {
|
||||
let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
|
||||
let root = crate_dir.join("../..");
|
||||
println!(
|
||||
"cargo::rustc-env=REIMS_CTL_STAMP={}",
|
||||
build_stamp::read(&root)
|
||||
);
|
||||
for file in build_stamp::git_files(&root) {
|
||||
println!("cargo::rerun-if-changed={}", file.display());
|
||||
}
|
||||
for source in ["src", "Cargo.toml", "build.rs"] {
|
||||
println!(
|
||||
"cargo::rerun-if-changed={}",
|
||||
crate_dir.join(source).display()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -105,11 +105,19 @@ fn image_from_zip(zip: &[u8]) -> Result<Vec<u8>> {
|
||||
}
|
||||
|
||||
/// Writes `bytes` to `file` through a file beside it renamed into place, so a reader never sees
|
||||
/// it half-written ([`crate::record::replace`]).
|
||||
/// it half-written.
|
||||
fn write(file: &Path, bytes: &[u8]) -> Result<()> {
|
||||
let dir = file.parent().unwrap_or(Path::new("."));
|
||||
std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
|
||||
crate::record::replace(file, bytes).with_context(|| format!("write {}", file.display()))
|
||||
let mut tmp = file.as_os_str().to_os_string();
|
||||
tmp.push(format!(".{}.tmp", std::process::id()));
|
||||
let tmp = PathBuf::from(tmp);
|
||||
let written = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, file));
|
||||
if let Err(e) = written {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e).with_context(|| format!("write {}", file.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `bytes`' SHA-256, in lowercase hex.
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
//! reims-ctl's build stamp, which its build script reads at each build (`build.rs`), and
|
||||
//! `reims-ctl --version` and a report's system.txt show (`REIMS_CTL_STAMP`; the crate compiles
|
||||
//! this module for its tests alone): the commit the checkout is at, `git rev-parse HEAD`, with
|
||||
//! `-dirty` where a tracked file of the tree differed from it or git could not say, and `unknown`
|
||||
//! for a build outside a checkout (no git, or no commit), which never fails the build. Left aside as the tree is compared: submodules, and the workspace's `Cargo.lock`,
|
||||
//! which is committed without metal2vulkan's git `source` lines and which every build of the
|
||||
//! library writes them back into. The build script reads it again where the checkout's HEAD or
|
||||
//! index moves, or reims-ctl's sources change. A diagnostic: nothing decides on it.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// The stamp of a tree whose `git rev-parse HEAD` answered `head` and whose status
|
||||
/// ([`STATUS`]) answered `status`, each `None` where git failed (the module doc).
|
||||
pub fn stamp(head: Option<&str>, status: Option<&str>) -> String {
|
||||
let Some(head) = head.map(str::trim).filter(|h| !h.is_empty()) else {
|
||||
return "unknown".to_owned();
|
||||
};
|
||||
match status {
|
||||
Some(status) if status.trim().is_empty() => head.to_owned(),
|
||||
_ => format!("{head}-dirty"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The status the stamp reads: the tracked files that differ from HEAD, but those the module doc
|
||||
/// leaves aside.
|
||||
pub const STATUS: [&str; 7] = [
|
||||
"status",
|
||||
"--porcelain",
|
||||
"--untracked-files=no",
|
||||
"--ignore-submodules",
|
||||
"--",
|
||||
".",
|
||||
":(exclude)Cargo.lock",
|
||||
];
|
||||
|
||||
/// What `git -C <dir> <args>` writes on its stdout, where it runs and succeeds.
|
||||
pub fn git(dir: &Path, args: &[&str]) -> Option<String> {
|
||||
let out = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(dir)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
out.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// The stamp of the tree at `root`, read from git.
|
||||
pub fn read(root: &Path) -> String {
|
||||
let head = git(root, &["rev-parse", "HEAD"]);
|
||||
let status = head.as_ref().and_then(|_| git(root, &STATUS));
|
||||
stamp(head.as_deref(), status.as_deref())
|
||||
}
|
||||
|
||||
/// The files of the checkout at `root` whose change moves HEAD or the index: its HEAD and index,
|
||||
/// the branch's ref HEAD names, and the packed refs, those that exist (Cargo runs a build script
|
||||
/// again at every build for a path that does not).
|
||||
pub fn git_files(root: &Path) -> Vec<PathBuf> {
|
||||
let dir = |args: &[&str]| git(root, args).map(|d| PathBuf::from(d.trim()));
|
||||
let mut files = Vec::new();
|
||||
if let Some(own) = dir(&["rev-parse", "--absolute-git-dir"]) {
|
||||
files.push(own.join("HEAD"));
|
||||
files.push(own.join("index"));
|
||||
}
|
||||
if let Some(common) = dir(&["rev-parse", "--path-format=absolute", "--git-common-dir"]) {
|
||||
if let Some(branch) = git(root, &["symbolic-ref", "-q", "HEAD"]) {
|
||||
files.push(common.join(branch.trim()));
|
||||
}
|
||||
files.push(common.join("packed-refs"));
|
||||
}
|
||||
files.retain(|f| f.exists());
|
||||
files
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const HEAD: &str = "41f0bba449c1e1f1b2e5d3c4a5b6c7d8e9f00112";
|
||||
|
||||
/// A clean tree's stamp is its commit.
|
||||
#[test]
|
||||
fn a_clean_tree_is_stamped_with_its_commit() {
|
||||
assert_eq!(stamp(Some(&format!("{HEAD}\n")), Some("")), HEAD);
|
||||
}
|
||||
|
||||
/// A tree with a tracked file changed, or whose status git could not give, is marked dirty.
|
||||
#[test]
|
||||
fn a_changed_tree_is_stamped_dirty() {
|
||||
let dirty = format!("{HEAD}-dirty");
|
||||
assert_eq!(
|
||||
stamp(Some(HEAD), Some(" M crates/reims-ctl/src/logs.rs\n")),
|
||||
dirty
|
||||
);
|
||||
assert_eq!(stamp(Some(HEAD), None), dirty);
|
||||
}
|
||||
|
||||
/// A build outside a checkout, where git answers no commit, is stamped unknown.
|
||||
#[test]
|
||||
fn a_build_outside_a_checkout_is_unknown() {
|
||||
assert_eq!(stamp(None, None), "unknown");
|
||||
assert_eq!(stamp(Some("\n"), Some("")), "unknown");
|
||||
let nowhere = std::env::temp_dir().join("reims-ctl-no-checkout-here");
|
||||
assert_eq!(git(&nowhere, &["rev-parse", "HEAD"]), None);
|
||||
assert_eq!(read(&nowhere), "unknown");
|
||||
assert!(git_files(&nowhere).is_empty());
|
||||
}
|
||||
|
||||
/// The build stamped reims-ctl with this checkout's commit, the one the tests run at.
|
||||
#[test]
|
||||
fn reims_ctl_carries_its_build_s_stamp() {
|
||||
let built = env!("REIMS_CTL_STAMP");
|
||||
// Read at run time, so the test names no worktree (docs/development.md).
|
||||
let manifest = std::env::var_os("CARGO_MANIFEST_DIR").unwrap();
|
||||
let root = Path::new(&manifest).join("../..");
|
||||
match git(&root, &["rev-parse", "HEAD"]) {
|
||||
Some(head) => assert!(built.starts_with(head.trim()), "{built} {head}"),
|
||||
None => assert_eq!(built, "unknown"),
|
||||
}
|
||||
}
|
||||
}
|
||||
+132
-555
File diff suppressed because it is too large.
Load diff
+24
-177
@@ -17,7 +17,6 @@ use anyhow::{Context, Result};
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -35,13 +34,6 @@ use windows::{APART, UNSUPPORTED, clone, create, data_ranges, file_system};
|
||||
/// without a word.
|
||||
const LONG: u64 = 1_000_000_000;
|
||||
|
||||
/// The type of the file system the directory `dir` is on, as the host names it: Linux's mount
|
||||
/// table (btrfs, ext4, vfat), macOS's statfs (apfs, exfat, msdos), Windows' volume (NTFS, ReFS,
|
||||
/// FAT32). None where the host gives none, or `dir` does not exist.
|
||||
pub fn file_system_of(dir: &Path) -> Option<String> {
|
||||
file_system(dir)
|
||||
}
|
||||
|
||||
/// Copies `src` to `dst`, a file that does not exist yet, with `src`'s permissions: a reflink or
|
||||
/// clone where the file system makes one, else a full copy, which `progress` hears of first where
|
||||
/// it is long, with its size and why it is no reflink, and then how far it is.
|
||||
@@ -51,18 +43,6 @@ pub fn file(src: &Path, dst: &Path, progress: &mut dyn FnMut(&str)) -> Result<()
|
||||
|
||||
/// [`file()`], where a full copy of more than `long` bytes of data is told.
|
||||
fn copy(src: &Path, dst: &Path, long: u64, progress: &mut dyn FnMut(&str)) -> Result<()> {
|
||||
copy_with(src, dst, long, &clone, progress)
|
||||
}
|
||||
|
||||
/// [`copy`], making the reflink or clone with `clone`. Any refusal of it falls back to the full
|
||||
/// copy, whatever its error: the error only says why in what the copy tells.
|
||||
fn copy_with(
|
||||
src: &Path,
|
||||
dst: &Path,
|
||||
long: u64,
|
||||
clone: &dyn Fn(&Path, &Path) -> io::Result<()>,
|
||||
progress: &mut dyn FnMut(&str),
|
||||
) -> Result<()> {
|
||||
let fail = || format!("could not copy {} to {}", src.display(), dst.display());
|
||||
let refused = match clone(src, dst) {
|
||||
Ok(()) => return Ok(()),
|
||||
@@ -74,136 +54,47 @@ fn copy_with(
|
||||
let ranges = data_ranges(&from, len);
|
||||
let total: u64 = ranges.iter().map(|(a, b)| b - a).sum();
|
||||
if total <= long {
|
||||
return full(&from, &to, &ranges, len, &mut |_| {}, None).with_context(fail);
|
||||
return full(&from, &to, &ranges, len, &mut |_| {}).with_context(fail);
|
||||
}
|
||||
let why = Why::of(&refused, src, dst);
|
||||
let name = src
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
progress(&format!(
|
||||
"copying {} in full, {}, not as a reflink: {}",
|
||||
name_of(src),
|
||||
"copying {name} in full, {}, not as a reflink: {}",
|
||||
size(total),
|
||||
why.note(src, dst)
|
||||
));
|
||||
full_told(&from, &to, &ranges, len, &why.short(), src, progress, None).with_context(fail)
|
||||
}
|
||||
|
||||
/// The file name of `p`, for what a copy says.
|
||||
fn name_of(p: &Path) -> String {
|
||||
p.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`full`], telling `progress` each whole percent of the data copied, at most once a second but
|
||||
/// for the first and the last, with `short`, why it is no reflink.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn full_told(
|
||||
from: &File,
|
||||
to: &File,
|
||||
ranges: &[(u64, u64)],
|
||||
len: u64,
|
||||
short: &str,
|
||||
src: &Path,
|
||||
progress: &mut dyn FnMut(&str),
|
||||
cancel: Option<&AtomicBool>,
|
||||
) -> io::Result<()> {
|
||||
let total: u64 = ranges.iter().map(|(a, b)| b - a).sum();
|
||||
let name = name_of(src);
|
||||
// Each whole percent, at most once a second but for the first and the last.
|
||||
let short = why.short();
|
||||
let mut shown: Option<(u64, Instant)> = None;
|
||||
full(
|
||||
from,
|
||||
to,
|
||||
ranges,
|
||||
len,
|
||||
&mut |done| {
|
||||
let pct = (done.min(total) * 100).checked_div(total).unwrap_or(100);
|
||||
let due = match shown {
|
||||
None => true,
|
||||
Some((p, t)) => p != pct && (pct == 100 || t.elapsed() >= Duration::from_secs(1)),
|
||||
};
|
||||
if due {
|
||||
shown = Some((pct, Instant::now()));
|
||||
progress(&format!(
|
||||
"copying {name} in full ({short}): {pct}% of {}",
|
||||
size(total)
|
||||
));
|
||||
}
|
||||
},
|
||||
cancel,
|
||||
)
|
||||
}
|
||||
|
||||
/// Makes `dst`, a file that does not exist yet, a reflink or clone of `src`; else why not, in a
|
||||
/// few words ("ext4 makes no reflinks"), and no `dst` is left.
|
||||
pub fn reflink(src: &Path, dst: &Path) -> std::result::Result<(), String> {
|
||||
match clone(src, dst) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(dst);
|
||||
Err(Why::of(&e, src, dst).short())
|
||||
full(&from, &to, &ranges, len, &mut |done| {
|
||||
let pct = done.min(total) * 100 / total;
|
||||
let due = match shown {
|
||||
None => true,
|
||||
Some((p, t)) => p != pct && (pct == 100 || t.elapsed() >= Duration::from_secs(1)),
|
||||
};
|
||||
if due {
|
||||
shown = Some((pct, Instant::now()));
|
||||
progress(&format!(
|
||||
"copying {name} in full ({short}): {pct}% of {}",
|
||||
size(total)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a file in the directory `from` can be made a reflink or clone in the directory `to`,
|
||||
/// tried with a file of a few bytes made for it and removed; else why not, as [`reflink`] says.
|
||||
pub fn reflinks_between(from: &Path, to: &Path) -> std::result::Result<(), String> {
|
||||
let tag = format!(".reims-ctl-reflink-{}", std::process::id());
|
||||
let (a, b) = (from.join(&tag), to.join(format!("{tag}.copy")));
|
||||
std::fs::write(&a, b"reflink").map_err(|e| format!("could not write {}: {e}", a.display()))?;
|
||||
let r = reflink(&a, &b);
|
||||
let _ = std::fs::remove_file(&a);
|
||||
let _ = std::fs::remove_file(&b);
|
||||
r
|
||||
}
|
||||
|
||||
/// The bytes of `src` a full copy reads and writes: those of its parts that hold data, its holes
|
||||
/// left out.
|
||||
pub fn data_bytes(src: &Path) -> Result<u64> {
|
||||
let f = File::open(src).with_context(|| format!("open {}", src.display()))?;
|
||||
let len = f.metadata()?.len();
|
||||
Ok(data_ranges(&f, len).iter().map(|(a, b)| b - a).sum())
|
||||
}
|
||||
|
||||
/// A full copy of `src` to `dst`, a file that does not exist yet, where no reflink is made, `why`
|
||||
/// in a few words ([`reflink`]): only the parts of `src` that hold data are read and written, and
|
||||
/// its holes, and blocks of zeros, stay holes in `dst`. `progress` hears how far it is, as
|
||||
/// [`file()`]'s full copy tells it; it stops once `cancel` is set. A copy that fails or stops
|
||||
/// leaves no `dst`.
|
||||
pub fn full_copy(
|
||||
src: &Path,
|
||||
dst: &Path,
|
||||
why: &str,
|
||||
progress: &mut dyn FnMut(&str),
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let fail = || format!("could not copy {} to {}", src.display(), dst.display());
|
||||
let from = File::open(src).with_context(fail)?;
|
||||
let len = from.metadata().with_context(fail)?.len();
|
||||
let to = create(&from, dst).with_context(fail)?;
|
||||
let ranges = data_ranges(&from, len);
|
||||
let r = full_told(&from, &to, &ranges, len, why, src, progress, Some(cancel))
|
||||
.and_then(|()| to.sync_all());
|
||||
drop(to);
|
||||
if let Err(e) = r {
|
||||
let _ = std::fs::remove_file(dst);
|
||||
if e.kind() == io::ErrorKind::Interrupted {
|
||||
anyhow::bail!("the copy of {} was stopped", name_of(src));
|
||||
}
|
||||
return Err(e).with_context(fail);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.with_context(fail)
|
||||
}
|
||||
|
||||
/// Copies `ranges` of `from` to `to`, then makes `to` `len` bytes long; `copied` hears how many
|
||||
/// bytes of the ranges are copied, from 0. Blocks of zeros are left holes, as `cp --sparse=always`
|
||||
/// leaves them. Once `cancel` is set, it stops with an error of kind `Interrupted`.
|
||||
/// leaves them.
|
||||
fn full(
|
||||
from: &File,
|
||||
to: &File,
|
||||
ranges: &[(u64, u64)],
|
||||
len: u64,
|
||||
copied: &mut dyn FnMut(u64),
|
||||
cancel: Option<&AtomicBool>,
|
||||
) -> io::Result<()> {
|
||||
const BLOCK: usize = 4096;
|
||||
let mut buf = vec![0u8; 1 << 20];
|
||||
@@ -212,9 +103,6 @@ fn full(
|
||||
for &(start, end) in ranges {
|
||||
let mut at = start;
|
||||
while at < end {
|
||||
if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, "stopped"));
|
||||
}
|
||||
let n = ((end - at) as usize).min(buf.len());
|
||||
from.read_exact_at(&mut buf[..n], at)?;
|
||||
// Each run of blocks not all zeros, written at once.
|
||||
@@ -405,47 +293,6 @@ mod tests {
|
||||
assert_eq!(refused.short(), "btrfs refused a reflink");
|
||||
}
|
||||
|
||||
/// A refused reflink falls back to a full copy, the source's bytes and holes, whatever the
|
||||
/// refusal's error, on any file system: one that makes none (ext4's `EOPNOTSUPP`, here as
|
||||
/// the host's own code), one whose error names no reason of the list, and one with no OS
|
||||
/// error at all. The refusal leaves its empty file behind, as Linux's does, which the full
|
||||
/// copy writes over.
|
||||
#[test]
|
||||
fn a_refused_reflink_falls_back_to_a_full_copy_whatever_its_error() {
|
||||
let d = dir(&std::env::temp_dir(), "refused");
|
||||
let bytes = sparse_file(&d.join("src"), 4 << 20);
|
||||
#[cfg(unix)]
|
||||
const OTHER: i32 = libc::EINVAL;
|
||||
// ERROR_INVALID_PARAMETER.
|
||||
#[cfg(windows)]
|
||||
const OTHER: i32 = 87;
|
||||
type Refusal = fn() -> io::Error;
|
||||
let unsupported: Refusal = || io::Error::from_raw_os_error(UNSUPPORTED[0]);
|
||||
let refusals: [(Refusal, &str); 3] = [
|
||||
(unsupported, "makes none"),
|
||||
(|| io::Error::from_raw_os_error(OTHER), "refused one"),
|
||||
(|| io::Error::other("no reflink here"), "refused one"),
|
||||
];
|
||||
for (i, (error, says)) in refusals.into_iter().enumerate() {
|
||||
let dst = d.join(format!("copy-{i}"));
|
||||
let refuse = |_: &Path, to: &Path| -> io::Result<()> {
|
||||
std::fs::write(to, b"")?;
|
||||
Err(error())
|
||||
};
|
||||
let mut seen = Vec::new();
|
||||
copy_with(&d.join("src"), &dst, 0, &refuse, &mut |s| {
|
||||
seen.push(s.to_string())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(&dst).unwrap(), bytes, "{i}");
|
||||
let said = seen.first().map(String::as_str).unwrap_or("");
|
||||
assert!(said.starts_with("copying src in full, "), "{i}: {seen:?}");
|
||||
assert!(said.contains(says), "{i}: {said}");
|
||||
assert!(seen.last().unwrap().contains("100% of"), "{i}: {seen:?}");
|
||||
}
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
/// A path's file system is the last mount on the longest mount point above it, whose escapes
|
||||
/// are undone.
|
||||
#[test]
|
||||
@@ -477,7 +324,7 @@ mod tests {
|
||||
let to = create(&from, &d.join("dst")).unwrap();
|
||||
let ranges = data_ranges(&from, len);
|
||||
let mut seen = Vec::new();
|
||||
full(&from, &to, &ranges, len, &mut |n| seen.push(n), None).unwrap();
|
||||
full(&from, &to, &ranges, len, &mut |n| seen.push(n)).unwrap();
|
||||
assert_eq!(std::fs::read(d.join("dst")).unwrap(), bytes);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
|
||||
+107
-1812
File diff suppressed because it is too large.
Load diff
@@ -149,7 +149,7 @@ pub fn host_disks() -> Vec<HostDisk> {
|
||||
/// link in `by_id`, with what `used` says the host uses it for. Left out: optical drives
|
||||
/// (`sr`), floppies, read-only and empty devices, the kernel's own (zram, device-mapper, md,
|
||||
/// RAM disks, which have no `device`), and loop devices without a file.
|
||||
pub(crate) fn read_disks(sys: &Path, by_id: &Path, used: &HostUse) -> Vec<HostDisk> {
|
||||
fn read_disks(sys: &Path, by_id: &Path, used: &HostUse) -> Vec<HostDisk> {
|
||||
let Ok(dir) = std::fs::read_dir(sys.join("block")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
use crate::ipsw;
|
||||
use crate::paths;
|
||||
use crate::vm::{Registry, Vm};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use reims_restore::catalog;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -110,7 +111,7 @@ pub fn delete(name: &str) -> Result<String> {
|
||||
.into_iter()
|
||||
.find(|i| i.name() == name)
|
||||
.with_context(|| format!("no download is named {name}: reims-ctl downloads lists them"))?;
|
||||
if let Some(vm) = used_by(&item.path, name)? {
|
||||
if let Some(vm) = used_by(&item.path) {
|
||||
bail!("{vm} boots from {name}: take it out first (reims-ctl eject {vm}), or delete {vm}");
|
||||
}
|
||||
if being_downloaded(&item.path) {
|
||||
@@ -121,17 +122,17 @@ pub fn delete(name: &str) -> Result<String> {
|
||||
Ok(format!("deleted {name}, freeing {}", size(item.bytes)))
|
||||
}
|
||||
|
||||
/// The VM that boots from `path`, the download named `name`, its installer, if any; an error
|
||||
/// where that can't be told ([`crate::runtime::other_using`]).
|
||||
fn used_by(path: &Path, name: &str) -> Result<Option<String>> {
|
||||
/// The VM that boots from `path`, its installer, if any.
|
||||
fn used_by(path: &Path) -> Option<String> {
|
||||
let same = |p: &Path| match (p.canonicalize(), path.canonicalize()) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => p == path,
|
||||
};
|
||||
let whether = format!("a VM boots from {name}");
|
||||
crate::runtime::other_using(None, &whether, |vm| {
|
||||
let installer = vm.config.q35.as_ref().and_then(|q| q.installer.as_deref());
|
||||
installer.is_some_and(|i| same(&vm.path(i)))
|
||||
let reg = Registry::load().ok()?;
|
||||
reg.vms.iter().find_map(|e| {
|
||||
let vm = Vm::load(&e.dir).ok()?;
|
||||
let installer = vm.config.q35.as_ref()?.installer.as_deref()?;
|
||||
same(&vm.path(installer)).then(|| e.name.clone())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -152,15 +153,14 @@ fn being_downloaded(path: &Path) -> bool {
|
||||
let Ok(f) = std::fs::OpenOptions::new().read(true).open(&lock) else {
|
||||
return false;
|
||||
};
|
||||
// On a file this function holds, which closing lets go of; a download that just ended holds
|
||||
// its lock on for as long as a child its process forked does (try_lock_let_go).
|
||||
!matches!(reims_restore::download::try_lock_let_go(&f), Ok(true))
|
||||
// flock(LOCK_EX | LOCK_NB) on Unix, LockFileEx on Windows, on a file this function holds:
|
||||
// closing it lets go.
|
||||
f.try_lock().is_err()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::vm::{Registry, Vm};
|
||||
|
||||
#[test]
|
||||
fn each_download_says_what_it_is() {
|
||||
@@ -185,27 +185,6 @@ mod tests {
|
||||
assert_eq!(size(950_000_000), "950 MB");
|
||||
}
|
||||
|
||||
/// A download isn't deleted where the list of VMs can't be read, since it may name a VM that
|
||||
/// boots from it: the refusal names the list's error.
|
||||
#[test]
|
||||
fn a_download_is_kept_where_the_list_of_vms_can_t_be_read() {
|
||||
let _env = crate::testenv::Env::new("downloads-unread");
|
||||
let [inst, _] = dirs();
|
||||
std::fs::create_dir_all(&inst).unwrap();
|
||||
let offline = "macOS-Tahoe-26.6.2-25G83-offline-installer.img";
|
||||
std::fs::write(inst.join(offline), b"o").unwrap();
|
||||
let list = paths::registry_file();
|
||||
std::fs::create_dir_all(list.parent().unwrap()).unwrap();
|
||||
std::fs::write(&list, b"[[vm]\n").unwrap();
|
||||
let e = format!("{:#}", delete(offline).unwrap_err());
|
||||
let said = format!(
|
||||
"can't tell whether a VM boots from {offline}: the list of VMs can't be read (parse {}",
|
||||
list.display()
|
||||
);
|
||||
assert!(e.starts_with(&said), "{e}");
|
||||
assert!(inst.join(offline).exists());
|
||||
}
|
||||
|
||||
/// The list holds both directories' files, but no hidden one; delete removes one, but not
|
||||
/// one a VM boots from or one being downloaded.
|
||||
#[test]
|
||||
@@ -261,17 +240,9 @@ mod tests {
|
||||
held.try_lock().unwrap();
|
||||
let e = delete(part).unwrap_err().to_string();
|
||||
assert!(e.contains("is being downloaded now"), "{e}");
|
||||
// The download ends while a child its process forked holds the lock on, until it execs.
|
||||
let child = held.try_clone().unwrap();
|
||||
drop(held);
|
||||
let exec = std::thread::spawn(move || {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
drop(child);
|
||||
});
|
||||
let deleted = delete(part);
|
||||
exec.join().unwrap();
|
||||
assert!(
|
||||
deleted
|
||||
delete(part)
|
||||
.unwrap()
|
||||
.starts_with(&format!("deleted {part}, freeing"))
|
||||
);
|
||||
|
||||
+11
-238
@@ -31,18 +31,6 @@
|
||||
//! - a manifest given by its path (`--gpu FILE.json`), which may be a driver outside the
|
||||
//! loader's search paths, or a second driver for a GPU the loader reaches by its own.
|
||||
//!
|
||||
//! **Two GPUs of the same IDs.** Two cards of one model have the same vendor and device IDs and
|
||||
//! one driver's manifest, so those name neither. The probe reads each GPU's PCI address where its
|
||||
//! driver lists `VK_EXT_pci_bus_info` ([`GpuInfo::pci`]), the list keeps each address apart
|
||||
//! ([`from_probes`]), and such a GPU ([`GpuInfo::twin`]) is picked by its address: `DRI_PRIME=
|
||||
//! pci-0000_02_00_0`, which Mesa's device-select layer reads (Mesa's documentation of
|
||||
//! `DRI_PRIME`), and so does the library itself, on every OS (reims-vgpu-vulkan's
|
||||
//! `device_choice`), with `VK_LOADER_DEVICE_SELECT` for its IDs and no `MESA_VK_DEVICE_SELECT`,
|
||||
//! which the library reads before `DRI_PRIME` and whose IDs name the first of the two in the
|
||||
//! loader's order ([`crate::vm::Gpu::pci`]).
|
||||
//! **Seen** in a user's report: a host with two cards of one model listed one GPU, and its VM
|
||||
//! could be given the second only through a variable of the user's own.
|
||||
//!
|
||||
//! **A probe past its manifest.** A manifest names one driver, so a probe that finds GPUs of
|
||||
//! several drivers (by `VkPhysicalDeviceDriverProperties::driverID`, else by vendor) shows a
|
||||
//! loader that did not keep to it, nor would keep a VM's process to it: its GPUs are named by
|
||||
@@ -54,22 +42,6 @@
|
||||
//! `MESA_VK_DEVICE_SELECT` itself (reims-vgpu-vulkan's `device_choice`), so IDs name the pick
|
||||
//! wherever the loader runs. A VM an older reims-ctl gave a GPU so, under a manifest whose probe
|
||||
//! now goes past it, is named by that GPU's IDs once ([`crate::migrate`], migration 6).
|
||||
//!
|
||||
//! **A VM's driver at its start.** The manifest a VM's settings name is a remembered answer, not
|
||||
//! the host's: a driver update can move it. On Windows a GPU driver's manifest is in the
|
||||
//! DriverStore, in a directory whose name carries a hash, which an update replaces, removing the
|
||||
//! old one: a user's VM named Intel's manifest there by its path, and after an update of the
|
||||
//! GPU's driver every start ended with "vkCreateInstance failed: Unable to find a Vulkan driver".
|
||||
//! A VM's settings get such a path from a reims-ctl before migration 5's, a pick
|
||||
//! by manifest (a CPU implementation, a GPU two drivers reach), `--gpu FILE.json`, or a copy of
|
||||
//! another VM's settings. So each start of a VM whose GPU is named by its manifest alone asks the
|
||||
//! host's manifests again, as the list does, before QEMU runs, and finds the GPU of its name and
|
||||
//! device ID through a manifest of the stored one's file name ([`refind`]): where the stored one
|
||||
//! is gone or offers it no more, the settings name the one that does, saved, and the start says
|
||||
//! so; where none does, the start ends there, naming the GPU and how to pick another
|
||||
//! ([`crate::runtime`], `refind_gpu`). A manifest given by its path and nothing else has nothing
|
||||
//! to find again by: a start ends where the file is gone. Migrations 5 and 6 match a manifest by
|
||||
//! its whole path, once, at an update; they do not see a path that moved.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
@@ -105,14 +77,6 @@ pub struct GpuInfo {
|
||||
pub driver_name: String,
|
||||
#[serde(default)]
|
||||
pub driver_info: String,
|
||||
/// Its PCI address, `0000:02:00.0`, where the driver lists `VK_EXT_pci_bus_info`: none where
|
||||
/// it does not.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pci: Option<String>,
|
||||
/// Whether another GPU of the list has its vendor and device IDs at another PCI address, so
|
||||
/// that only its address names it (the module doc, "Two GPUs of the same IDs").
|
||||
#[serde(default)]
|
||||
pub twin: bool,
|
||||
}
|
||||
|
||||
impl GpuInfo {
|
||||
@@ -125,23 +89,18 @@ impl GpuInfo {
|
||||
.file_name()
|
||||
.map(|f| f.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
match (self.twin, &self.pci) {
|
||||
(true, Some(pci)) => format!("{} ({}, {file}, at {pci})", self.name, self.kind),
|
||||
_ => format!("{} ({}, {file})", self.name, self.kind),
|
||||
}
|
||||
format!("{} ({}, {file})", self.name, self.kind)
|
||||
}
|
||||
|
||||
/// The VM's settings for this GPU: named by its IDs, unless it is a CPU implementation or
|
||||
/// another manifest reaches a GPU of the same IDs, which its driver's manifest names alone;
|
||||
/// by its IDs wherever its probe went past its manifest (the module doc); and by its PCI
|
||||
/// address too where another GPU of the list has its IDs.
|
||||
/// by its IDs wherever its probe went past its manifest (the module doc).
|
||||
pub fn to_config(&self) -> crate::vm::Gpu {
|
||||
let by_ids = self.past_manifest || (self.kind != "cpu" && !self.shares_ids);
|
||||
crate::vm::Gpu {
|
||||
driver_file: Some(self.driver_file.clone()),
|
||||
device_id: self.shares_driver.then_some(self.device_id),
|
||||
select: by_ids.then(|| format!("{:04x}:{:04x}", self.vendor_id, self.device_id)),
|
||||
pci: self.pci.clone().filter(|_| self.twin),
|
||||
name: Some(self.name.clone()),
|
||||
}
|
||||
}
|
||||
@@ -251,15 +210,13 @@ pub fn from_probes(probes: Vec<Vec<GpuInfo>>) -> Vec<GpuInfo> {
|
||||
}
|
||||
// Those found through their own manifest first. One GPU can be reached through two manifests
|
||||
// (a 32-bit and a 64-bit one, say): keep the first. One found past its manifest is kept only
|
||||
// where none kept has its IDs, which alone name it. A GPU at another PCI address than one
|
||||
// kept is another GPU, whatever its IDs, name and manifest: two cards of one model.
|
||||
// where none kept has its IDs, which alone name it.
|
||||
found.sort_by_key(|g| g.past_manifest);
|
||||
let mut gpus: Vec<GpuInfo> = Vec::new();
|
||||
for g in found {
|
||||
let ids = (g.vendor_id, g.device_id);
|
||||
let seen = gpus.iter().any(|k| {
|
||||
(k.vendor_id, k.device_id) == ids
|
||||
&& !apart(k, &g)
|
||||
&& (g.past_manifest
|
||||
|| (k.name == g.name && k.driver_file.file_name() == g.driver_file.file_name()))
|
||||
});
|
||||
@@ -279,32 +236,25 @@ pub fn from_probes(probes: Vec<Vec<GpuInfo>>) -> Vec<GpuInfo> {
|
||||
gpus
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are at two PCI addresses, so two GPUs, where both drivers give one.
|
||||
fn apart(a: &GpuInfo, b: &GpuInfo) -> bool {
|
||||
matches!((&a.pci, &b.pci), (Some(x), Some(y)) if x != y)
|
||||
}
|
||||
|
||||
/// Marks each of `gpus` that shares its driver with another ([`GpuInfo::shares_driver`]), each
|
||||
/// whose IDs another manifest reaches too ([`GpuInfo::shares_ids`]), and each whose IDs another
|
||||
/// GPU at another PCI address has ([`GpuInfo::twin`]).
|
||||
/// Marks each of `gpus` that shares its driver with another ([`GpuInfo::shares_driver`]), and each
|
||||
/// whose IDs another manifest reaches too ([`GpuInfo::shares_ids`]).
|
||||
fn mark_shared(gpus: &mut [GpuInfo]) {
|
||||
let shared: Vec<(bool, bool, bool)> = gpus
|
||||
let shared: Vec<(bool, bool)> = gpus
|
||||
.iter()
|
||||
.map(|g| {
|
||||
let others = || gpus.iter().filter(|o| !std::ptr::eq(*o, g));
|
||||
let ids = (g.vendor_id, g.device_id);
|
||||
let same_ids = |o: &GpuInfo| (o.vendor_id, o.device_id) == ids;
|
||||
(
|
||||
others().any(|o| o.driver_file == g.driver_file),
|
||||
others().any(|o| o.driver_file != g.driver_file && same_ids(o) && !apart(o, g)),
|
||||
others().any(|o| same_ids(o) && apart(o, g)),
|
||||
others().any(|o| {
|
||||
o.driver_file != g.driver_file
|
||||
&& (o.vendor_id, o.device_id) == (g.vendor_id, g.device_id)
|
||||
}),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
for (g, (driver, ids, twin)) in gpus.iter_mut().zip(shared) {
|
||||
for (g, (driver, ids)) in gpus.iter_mut().zip(shared) {
|
||||
g.shares_driver = driver;
|
||||
g.shares_ids = ids;
|
||||
g.twin = twin;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,55 +299,6 @@ fn probe(exe: &std::path::Path, file: &std::path::Path) -> Vec<GpuInfo> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the driver of a VM's GPU named by its manifest alone ([`crate::vm::Gpu::select`] none)
|
||||
/// is now, by [`refind`].
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Driver {
|
||||
/// The stored manifest still offers the GPU.
|
||||
Kept,
|
||||
/// The stored manifest is gone or offers the GPU no more, and another of the same file name
|
||||
/// offers it: as after a driver update on Windows, which puts the driver in a new directory
|
||||
/// of the DriverStore, whose name carries a hash, and removes the old one.
|
||||
Moved(PathBuf),
|
||||
/// No manifest offers it.
|
||||
Gone,
|
||||
}
|
||||
|
||||
/// Where the driver of `g`, a VM's GPU named by its manifest ([`crate::vm::Gpu::driver_file`])
|
||||
/// and name with no IDs, is in what the host's manifests' `probes` found now (in the loader's
|
||||
/// order, [`probes`]): a GPU of `g`'s name and device ID (where it keeps one), through a manifest
|
||||
/// of the stored one's file name, the stored one first. The stored path is a remembered answer:
|
||||
/// the host's list says where the driver is (the module doc, "A VM's driver at its start").
|
||||
pub fn refind(g: &crate::vm::Gpu, probes: &[Vec<GpuInfo>]) -> Driver {
|
||||
let (Some(file), Some(name)) = (&g.driver_file, &g.name) else {
|
||||
return Driver::Kept;
|
||||
};
|
||||
// Windows' paths are the same file whatever their case and separators.
|
||||
let fold = |p: &std::path::Path| {
|
||||
let s = p.to_string_lossy();
|
||||
if cfg!(windows) {
|
||||
s.replace('/', "\\").to_lowercase()
|
||||
} else {
|
||||
s.into_owned()
|
||||
}
|
||||
};
|
||||
let file_name = |p: &std::path::Path| p.file_name().map(|n| fold(std::path::Path::new(n)));
|
||||
let offering: Vec<&GpuInfo> = (probes.iter().flatten())
|
||||
.filter(|f| {
|
||||
&f.name == name
|
||||
&& g.device_id.is_none_or(|id| id == f.device_id)
|
||||
&& file_name(&f.driver_file) == file_name(file)
|
||||
})
|
||||
.collect();
|
||||
if offering.iter().any(|f| fold(&f.driver_file) == fold(file)) {
|
||||
return Driver::Kept;
|
||||
}
|
||||
match offering.first() {
|
||||
Some(f) => Driver::Moved(f.driver_file.clone()),
|
||||
None => Driver::Gone,
|
||||
}
|
||||
}
|
||||
|
||||
/// `reims-ctl __vulkan-probe`: one JSON line per physical device the loader finds.
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
pub fn probe_main() -> i32 {
|
||||
@@ -455,8 +356,6 @@ pub fn probe_main() -> i32 {
|
||||
driver_version: p.driver_version,
|
||||
driver_name,
|
||||
driver_info,
|
||||
pci: pci_address(&instance, pd),
|
||||
twin: false,
|
||||
};
|
||||
println!("{}", serde_json::to_string(&info).unwrap());
|
||||
}
|
||||
@@ -466,31 +365,6 @@ pub fn probe_main() -> i32 {
|
||||
0
|
||||
}
|
||||
|
||||
/// `pd`'s PCI address, `0000:02:00.0`, where its driver lists `VK_EXT_pci_bus_info`.
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
fn pci_address(instance: &ash::Instance, pd: ash::vk::PhysicalDevice) -> Option<String> {
|
||||
use ash::vk;
|
||||
// SAFETY: `pd` is the instance's; the structures live across each call.
|
||||
unsafe {
|
||||
let name = ash::ext::pci_bus_info::NAME;
|
||||
let lists = instance
|
||||
.enumerate_device_extension_properties(pd)
|
||||
.ok()?
|
||||
.iter()
|
||||
.any(|e| e.extension_name_as_c_str() == Ok(name));
|
||||
if !lists {
|
||||
return None;
|
||||
}
|
||||
let mut bus = vk::PhysicalDevicePCIBusInfoPropertiesEXT::default();
|
||||
let mut p2 = vk::PhysicalDeviceProperties2::default().push_next(&mut bus);
|
||||
instance.get_physical_device_properties2(pd, &mut p2);
|
||||
Some(format!(
|
||||
"{:04x}:{:02x}:{:02x}.{:x}",
|
||||
bus.pci_domain, bus.pci_bus, bus.pci_device, bus.pci_function
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", windows)))]
|
||||
pub fn probe_main() -> i32 {
|
||||
1
|
||||
@@ -514,59 +388,9 @@ mod tests {
|
||||
driver_version: 0,
|
||||
driver_name: String::new(),
|
||||
driver_info: String::new(),
|
||||
pci: None,
|
||||
twin: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A VM's GPU named by its manifest alone finds its driver again by its name, device ID and
|
||||
/// manifest's file name: where it is, kept; in another directory, as a driver update on
|
||||
/// Windows moves it, moved; nowhere, gone. Another GPU of the manifest, or another manifest
|
||||
/// for the same GPU, is not it.
|
||||
#[test]
|
||||
fn a_vm_finds_its_gpus_driver_again() {
|
||||
let (old, new) = (
|
||||
"/ds/iigd_dch.inf_amd64_0a1b/igvk64.json",
|
||||
"/ds/iigd_dch.inf_amd64_9f8e/igvk64.json",
|
||||
);
|
||||
let uhd = "Intel(R) UHD Graphics 630";
|
||||
let vm = crate::vm::Gpu {
|
||||
driver_file: Some(old.into()),
|
||||
device_id: None,
|
||||
select: None,
|
||||
pci: None,
|
||||
name: Some(uhd.into()),
|
||||
};
|
||||
let nv = gpu(
|
||||
"GTX 1650 Ti",
|
||||
(0x10de, 0x1f95),
|
||||
"discrete",
|
||||
"/nv/nv-vk64.json",
|
||||
);
|
||||
let at = |file: &str| vec![gpu(uhd, (0x8086, 0x3e9b), "integrated", file)];
|
||||
assert_eq!(refind(&vm, &[vec![nv.clone()], at(old)]), Driver::Kept);
|
||||
assert_eq!(
|
||||
refind(&vm, &[vec![nv.clone()], at(new)]),
|
||||
Driver::Moved(new.into())
|
||||
);
|
||||
assert_eq!(refind(&vm, &[at(new), at(old)]), Driver::Kept);
|
||||
assert_eq!(refind(&vm, &[vec![nv.clone()]]), Driver::Gone);
|
||||
assert_eq!(refind(&vm, &[]), Driver::Gone);
|
||||
// Another manifest's file name, or another device ID, is another driver or GPU.
|
||||
assert_eq!(refind(&vm, &[at("/ds/x/igvk32.json")]), Driver::Gone);
|
||||
let with_id = crate::vm::Gpu {
|
||||
device_id: Some(0x3e92),
|
||||
..vm.clone()
|
||||
};
|
||||
assert_eq!(refind(&with_id, &[at(new)]), Driver::Gone);
|
||||
// Nothing to find it by: as it is.
|
||||
let typed = crate::vm::Gpu {
|
||||
name: None,
|
||||
..vm.clone()
|
||||
};
|
||||
assert_eq!(refind(&typed, &[]), Driver::Kept);
|
||||
}
|
||||
|
||||
/// RADV drives two GPUs, and AMDVLK reaches one of them too; NVIDIA's driver and lavapipe
|
||||
/// one each.
|
||||
#[test]
|
||||
@@ -627,7 +451,6 @@ mod tests {
|
||||
driver_file: Some("/icd/nvidia.json".into()),
|
||||
device_id: None,
|
||||
select: Some("10de:2204".into()),
|
||||
pci: None,
|
||||
name: Some("NVIDIA GeForce RTX 3090".into()),
|
||||
}
|
||||
);
|
||||
@@ -647,56 +470,6 @@ mod tests {
|
||||
assert_eq!(small.to_config().selected().unwrap(), Some((0x1af4, 0x50)));
|
||||
}
|
||||
|
||||
/// Two cards of one model, the same IDs, name and manifest at two PCI addresses, are two
|
||||
/// GPUs of the list, each picked by its address and labelled with it; a probe that found
|
||||
/// them again past its manifest, at their addresses, adds neither again; and where the
|
||||
/// driver gives no address, the two are one entry, as before addresses were read. Seen on a
|
||||
/// host with two FirePro D700s (1002:6798), which the list gave as one.
|
||||
#[test]
|
||||
fn two_cards_of_one_model_are_listed_and_picked_by_their_addresses() {
|
||||
let d700 = |file: &str, pci: Option<&str>| GpuInfo {
|
||||
pci: pci.map(String::from),
|
||||
..gpu(
|
||||
"AMD Radeon R9 200 / HD 7900 Series (RADV TAHITI)",
|
||||
(0x1002, 0x6798),
|
||||
"discrete",
|
||||
file,
|
||||
)
|
||||
};
|
||||
let (radv, lvp) = ("/icd/radeon_icd.x86_64.json", "/icd/lvp_icd.x86_64.json");
|
||||
let (a, b) = ("0000:02:00.0", "0000:06:00.0");
|
||||
let list = from_probes(vec![
|
||||
vec![d700(radv, Some(a)), d700(radv, Some(b))],
|
||||
vec![
|
||||
gpu("llvmpipe", (0x10005, 0), "cpu", lvp),
|
||||
d700(lvp, Some(a)),
|
||||
d700(lvp, Some(b)),
|
||||
],
|
||||
]);
|
||||
assert_eq!(list.len(), 3, "{list:?}");
|
||||
assert_eq!(list[2].name, "llvmpipe");
|
||||
for g in &list[..2] {
|
||||
assert!(g.twin, "{g:?}");
|
||||
assert_eq!(g.driver_file.to_str(), Some(radv));
|
||||
}
|
||||
let (label, want) = (list[1].label(), format!("x86_64.json, at {b})"));
|
||||
assert!(label.ends_with(&want), "{label}");
|
||||
let pick = list[1].to_config();
|
||||
assert_eq!(pick.pci.as_deref(), Some(b));
|
||||
assert_eq!(pick.select.as_deref(), Some("1002:6798"));
|
||||
let prime = pick.dri_prime().unwrap();
|
||||
assert_eq!(prime.as_deref(), Some("pci-0000_06_00_0"));
|
||||
assert_eq!(list[0].to_config().pci.as_deref(), Some(a));
|
||||
// One card alone keeps no address in its settings: its IDs name it.
|
||||
let one = from_probes(vec![vec![d700(radv, Some(a))]]);
|
||||
assert!(!one[0].twin);
|
||||
assert_eq!(one[0].to_config().pci, None);
|
||||
// No address from the driver: the two are one entry, named by their IDs.
|
||||
let blind = from_probes(vec![vec![d700(radv, None), d700(radv, None)]]);
|
||||
assert_eq!(blind.len(), 1);
|
||||
assert_eq!(blind[0].to_config().pci, None);
|
||||
}
|
||||
|
||||
/// A probe that found several drivers' GPUs went past its manifest: its GPUs are named by
|
||||
/// their IDs, and one a probe of its own manifest found is listed from that probe. Seen on a
|
||||
/// Windows host, where the probe of Intel's manifest found the GTX too and saved it under
|
||||
|
||||
+21
-484
@@ -5,16 +5,15 @@
|
||||
//! - Linux and Windows on x86-64: [`Profile::Q35X86_64`], `q35` booted through OpenCore, with
|
||||
//! reims-vgpu's own GPU device, on KVM on Linux and on the Windows Hypervisor Platform (WHPX)
|
||||
//! on Windows;
|
||||
//! - an arm64 Mac, arm64 Linux, and Linux and Windows on x86-64: [`Profile::VmappleArm64`],
|
||||
//! QEMU's `vmapple` booted by Ambrosia (ambrosia.rs), with reims-vgpu's own GPU device, whose
|
||||
//! VMs reims-ctl makes by restoring macOS from an IPSW (restore.rs): on Hypervisor.framework
|
||||
//! (HVF) on a Mac, on KVM on arm64 Linux, and emulated by QEMU's TCG on x86-64, where an arm64
|
||||
//! guest runs several times slower than on an arm64 host. On x86-64 it is the second profile,
|
||||
//! an IPSW's, and q35 the default. Of Windows we have only a contributor's report (PR 203):
|
||||
//! macOS 27.2.1 booted to its desktop on Windows 11, on an Intel Core i7-12700H with an RTX
|
||||
//! 3060 Laptop GPU; the lab has run none there (docs/qemu.md, "arm64 guests").
|
||||
//! - an arm64 Mac, arm64 Linux and Linux on x86-64: [`Profile::VmappleArm64`], QEMU's `vmapple`
|
||||
//! booted by Ambrosia (ambrosia.rs), with reims-vgpu's own GPU device, whose VMs reims-ctl
|
||||
//! makes by restoring macOS from an IPSW (restore.rs): on Hypervisor.framework (HVF) on a Mac,
|
||||
//! on KVM on arm64 Linux, and emulated by QEMU's TCG on x86-64, where an arm64 guest runs
|
||||
//! several times slower than on an arm64 host. On Linux on x86-64 it is the second profile, an
|
||||
//! IPSW's, and q35 the default.
|
||||
//!
|
||||
//! Any other host runs none ([`UNSUPPORTED`]).
|
||||
//! Any other host runs none ([`UNSUPPORTED`]). Windows on x86-64 runs no arm64 VM: its QEMU is
|
||||
//! built for x86-64 guests alone (scripts/install-ctl.sh).
|
||||
//!
|
||||
//! Another host or guest architecture is another profile (x86-64 guests on an Intel Mac would be
|
||||
//! `q35` on HVF, without the memfd RAM only Linux has): add it here and in `qemu.rs`.
|
||||
@@ -25,7 +24,7 @@ use std::fmt;
|
||||
|
||||
/// What reims-ctl tells a host it runs no VMs on, for a create or a start there.
|
||||
pub const UNSUPPORTED: &str = "reims-ctl runs x86-64 VMs on Linux and Windows x86-64 hosts, \
|
||||
and arm64 VMs on arm64 Macs, arm64 Linux, and x86-64 Linux and Windows";
|
||||
and arm64 VMs on arm64 Macs, arm64 Linux and Linux on x86-64";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Os {
|
||||
@@ -106,268 +105,10 @@ pub fn avx512_xstate_offsets() -> Option<[u32; 3]> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The first macOS whose x86-64 guests need AVX2 of the host's CPU, which a KVM or WHPX guest's
|
||||
/// CPU has only where the host's has: QEMU drops a feature the host lacks from any CPU model.
|
||||
/// **Measured** 2026-12-03 under KVM on a Core i9-13900H, with AVX2 hidden from the guest
|
||||
/// (potluck jobs m3-max-86342 and m3-max-86386): macOS 13.7.8, 14.8.9, 15.8.2 and 26.7.2 on
|
||||
/// reims-ctl's Skylake-Client-noTSX-IBRS line with `-avx2`, and 26.7.2 also on that line with
|
||||
/// what an Ivy Bridge lacks hidden too (FMA, BMI1, BMI2, MOVBE, LZCNT, RDSEED, ADX, SMAP,
|
||||
/// INVPCID, XSAVEC and PCID) and on IvyBridge-IBRS. In every boot the kernel starts and mounts
|
||||
/// the system, then launchd cannot load `/usr/lib/libSystem.B.dylib` ("no dyld cache": the
|
||||
/// system's shared cache is built for CPUs with AVX2 alone), the kernel panics ("initproc failed
|
||||
/// to start") and the VM restarts, over and over. A user's report of macOS 26.7.3 on a Xeon E5
|
||||
/// v2 (Ivy Bridge-EP, no AVX2) stopping at OpenCore's handoff did not reproduce. No macOS before
|
||||
/// 13 was booted without AVX2 here, so none is refused: the bound moves only on evidence. A
|
||||
/// create refuses such a VM, and doctor names the CPU; a start refuses nothing, since a user's
|
||||
/// own CPU arguments and kexts run such a macOS on such a CPU, so a VM of it made elsewhere
|
||||
/// still restarts at its first process with no word of ours.
|
||||
pub const AVX2_FROM_MACOS: u32 = 13;
|
||||
|
||||
/// Whether the host's CPU runs AVX2 code, as CPUID and the OS's saved state say
|
||||
/// (`is_x86_feature_detected!`); None on a host other than x86-64, whose x86-64 VMs reims-ctl
|
||||
/// does not make.
|
||||
pub fn has_avx2() -> Option<bool> {
|
||||
#[cfg(test)]
|
||||
if let Some(avx2) = tests::AVX2.with(|a| *a.borrow()) {
|
||||
return avx2;
|
||||
}
|
||||
cpu_has_avx2()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
fn cpu_has_avx2() -> Option<bool> {
|
||||
Some(std::arch::is_x86_feature_detected!("avx2"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
fn cpu_has_avx2() -> Option<bool> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The CPU model an x86-64 guest's `-cpu` names in place of reims-ctl's own
|
||||
/// (`vm::default_cpu_model`, Skylake-Client-noTSX-IBRS) on a host whose CPU lacks AVX2
|
||||
/// ([`model_without_avx2`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HostModel {
|
||||
/// QEMU's model: the newest of [`model_without_avx2`]'s whose features the host's CPU has.
|
||||
pub name: &'static str,
|
||||
/// `+feature`, by QEMU's name, for each feature of reims-ctl's own model that `name` lacks
|
||||
/// and the host's CPU has, in [`model_without_avx2`]'s order.
|
||||
pub flags: Vec<String>,
|
||||
/// The `+feature`s of reims-ctl's own flags (`vm::default_cpu_flags`) whose feature the
|
||||
/// host's CPU lacks: the line leaves them out of the VM's flags.
|
||||
pub drop: Vec<String>,
|
||||
}
|
||||
|
||||
/// What an x86-64 guest's CPU line names on a host whose CPU has the features `has` answers yes for
|
||||
/// (QEMU's names), where reims-ctl's own model, Skylake-Client-noTSX-IBRS, would name a CPU the
|
||||
/// host is not: None where the host has AVX2, and the VM's model stays. Otherwise a line that names
|
||||
/// no model the host's CPU is not and no feature it lacks: the newest of IvyBridge, SandyBridge,
|
||||
/// Westmere and Nehalem whose features the host has (`-IBRS`, its IBRS variant, where the host has
|
||||
/// IBRS), then `+` each feature of Skylake-Client-noTSX-IBRS that the model lacks and the host has,
|
||||
/// and reims-ctl's own flags without those whose feature the host lacks ([`HostModel::drop`]). The
|
||||
/// guest's feature bits are then what Skylake-Client-noTSX-IBRS gave it on that host, where QEMU
|
||||
/// dropped what the host lacks with `check`'s warning, but for KVM's own x2APIC, TSC deadline timer
|
||||
/// and ARAT on a CPU whose CPUID lacks them. Nehalem is the floor: an older CPU gets its name. An
|
||||
/// AMD CPU gets the Intel model whose features it has, since no Mac has an AMD CPU. The guest's
|
||||
/// family and model are OpenCore's leaf 1 spoof in an image reims-util makes (docs/qemu.md, "x86-64
|
||||
/// macOS guests: the CPU model"); macOS 13 and later on such a host still stop at their first
|
||||
/// process ([`AVX2_FROM_MACOS`]).
|
||||
pub fn model_without_avx2(has: &dyn Fn(&str) -> bool) -> Option<HostModel> {
|
||||
if has("avx2") {
|
||||
return None;
|
||||
}
|
||||
// Newest first: each model, its IBRS variant, and the features it has beyond the next; a
|
||||
// host has a model where it has those of the model and of every one after it.
|
||||
const MODELS: [(&str, &str, &[&str]); 4] = [
|
||||
(
|
||||
"IvyBridge",
|
||||
"IvyBridge-IBRS",
|
||||
&["f16c", "rdrand", "fsgsbase", "smep", "erms"],
|
||||
),
|
||||
(
|
||||
"SandyBridge",
|
||||
"SandyBridge-IBRS",
|
||||
&[
|
||||
"avx",
|
||||
"xsave",
|
||||
"xsaveopt",
|
||||
"rdtscp",
|
||||
"x2apic",
|
||||
"tsc-deadline",
|
||||
],
|
||||
),
|
||||
("Westmere", "Westmere-IBRS", &["aes", "pclmulqdq", "arat"]),
|
||||
("Nehalem", "Nehalem-IBRS", &[]),
|
||||
];
|
||||
// Skylake-Client-noTSX-IBRS's features beyond IvyBridge's, but for AVX2, which the host
|
||||
// lacks, and TSX, which the model leaves out.
|
||||
const SKYLAKES: [&str; 13] = [
|
||||
"pcid",
|
||||
"fma",
|
||||
"movbe",
|
||||
"bmi1",
|
||||
"bmi2",
|
||||
"abm",
|
||||
"3dnowprefetch",
|
||||
"invpcid",
|
||||
"rdseed",
|
||||
"adx",
|
||||
"smap",
|
||||
"xsavec",
|
||||
"xgetbv1",
|
||||
];
|
||||
let i = (0..MODELS.len()).find(|&i| {
|
||||
MODELS[i..]
|
||||
.iter()
|
||||
.all(|(_, _, needs)| needs.iter().all(|f| has(f)))
|
||||
})?;
|
||||
let (plain, ibrs, _) = MODELS[i];
|
||||
let lacks = SKYLAKES
|
||||
.iter()
|
||||
.chain(MODELS[..i].iter().flat_map(|(_, _, needs)| needs.iter()));
|
||||
let flags = lacks.filter(|f| has(f)).map(|f| format!("+{f}")).collect();
|
||||
let drop = crate::vm::default_cpu_flags()
|
||||
.split(',')
|
||||
.filter(|f| f.strip_prefix('+').is_some_and(|f| !has(f)))
|
||||
.map(String::from)
|
||||
.collect();
|
||||
Some(HostModel {
|
||||
name: if has("spec-ctrl") { ibrs } else { plain },
|
||||
flags,
|
||||
drop,
|
||||
})
|
||||
}
|
||||
|
||||
/// [`model_without_avx2`] of this host's CPU, by [`has_avx2`] and CPUID: None on a CPU with
|
||||
/// AVX2, and on a host other than x86-64.
|
||||
pub fn host_model_without_avx2() -> Option<HostModel> {
|
||||
if has_avx2() != Some(false) {
|
||||
return None;
|
||||
}
|
||||
model_without_avx2(&|f| f != "avx2" && cpuid_has(f))
|
||||
}
|
||||
|
||||
/// Whether CPUID gives this host's CPU `feature`, by QEMU's name: one of those
|
||||
/// [`model_without_avx2`] asks of a host; false for another.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
fn cpuid_has(feature: &str) -> bool {
|
||||
use std::arch::x86_64::{__cpuid, __cpuid_count};
|
||||
// The leaf, its subleaf, the register (EAX 0, EBX 1, ECX 2, EDX 3) and the bit.
|
||||
let (leaf, sub, reg, bit): (u32, u32, usize, u32) = match feature {
|
||||
"pclmulqdq" => (1, 0, 2, 1),
|
||||
"ssse3" => (1, 0, 2, 9),
|
||||
"fma" => (1, 0, 2, 12),
|
||||
"pcid" => (1, 0, 2, 17),
|
||||
"sse4.2" => (1, 0, 2, 20),
|
||||
"x2apic" => (1, 0, 2, 21),
|
||||
"movbe" => (1, 0, 2, 22),
|
||||
"popcnt" => (1, 0, 2, 23),
|
||||
"tsc-deadline" => (1, 0, 2, 24),
|
||||
"aes" => (1, 0, 2, 25),
|
||||
"xsave" => (1, 0, 2, 26),
|
||||
"avx" => (1, 0, 2, 28),
|
||||
"f16c" => (1, 0, 2, 29),
|
||||
"rdrand" => (1, 0, 2, 30),
|
||||
"fsgsbase" => (7, 0, 1, 0),
|
||||
"bmi1" => (7, 0, 1, 3),
|
||||
"smep" => (7, 0, 1, 7),
|
||||
"bmi2" => (7, 0, 1, 8),
|
||||
"erms" => (7, 0, 1, 9),
|
||||
"invpcid" => (7, 0, 1, 10),
|
||||
"rdseed" => (7, 0, 1, 18),
|
||||
"adx" => (7, 0, 1, 19),
|
||||
"smap" => (7, 0, 1, 20),
|
||||
"spec-ctrl" => (7, 0, 3, 26),
|
||||
"arat" => (6, 0, 0, 2),
|
||||
"xsaveopt" => (0xd, 1, 0, 0),
|
||||
"xsavec" => (0xd, 1, 0, 1),
|
||||
"xgetbv1" => (0xd, 1, 0, 2),
|
||||
"abm" => (0x8000_0001, 0, 2, 5),
|
||||
"3dnowprefetch" => (0x8000_0001, 0, 2, 8),
|
||||
"rdtscp" => (0x8000_0001, 0, 3, 27),
|
||||
_ => return false,
|
||||
};
|
||||
if __cpuid(leaf & 0x8000_0000).eax < leaf {
|
||||
return false;
|
||||
}
|
||||
let r = __cpuid_count(leaf, sub);
|
||||
([r.eax, r.ebx, r.ecx, r.edx][reg] >> bit) & 1 == 1
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
fn cpuid_has(_feature: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Why an x86-64 VM of macOS `major` does not run on this host, where that macOS needs AVX2
|
||||
/// ([`AVX2_FROM_MACOS`]) and the host's CPU has none; None where it runs.
|
||||
pub fn without_avx2(major: u32) -> Option<String> {
|
||||
if major < AVX2_FROM_MACOS {
|
||||
return None;
|
||||
}
|
||||
no_avx2(&format!("x86-64 macOS {major} needs"))
|
||||
}
|
||||
|
||||
/// Why no x86-64 macOS from [`AVX2_FROM_MACOS`] on runs on this host, whose CPU has no AVX2:
|
||||
/// doctor's cpu line. None where they run.
|
||||
pub fn without_avx2_from() -> Option<String> {
|
||||
no_avx2(&format!("x86-64 macOS {AVX2_FROM_MACOS} and later need"))
|
||||
}
|
||||
|
||||
/// The reason [`without_avx2`] and [`without_avx2_from`] give, after `needs` ("x86-64 macOS 13
|
||||
/// needs"), where the host's CPU has no AVX2.
|
||||
fn no_avx2(needs: &str) -> Option<String> {
|
||||
if has_avx2() != Some(false) {
|
||||
return None;
|
||||
}
|
||||
let cpu = cpu_brand().map(|b| format!(", {b},")).unwrap_or_default();
|
||||
Some(format!(
|
||||
"{needs} a CPU with AVX2, and this host's CPU{cpu} has none: the system libraries are \
|
||||
built for CPUs with AVX2 alone, so the first process cannot start, and the VM restarts \
|
||||
over and over"
|
||||
))
|
||||
}
|
||||
|
||||
/// The host CPU's brand string, as CPUID's leaves 0x80000002 to 0x80000004 give it, without the
|
||||
/// spaces and NULs around it: "13th Gen Intel(R) Core(TM) i9-13900H", "AMD Ryzen 7 7840HS w/
|
||||
/// Radeon 780M Graphics". None on a host other than x86-64, or a CPU without the leaves.
|
||||
pub fn cpu_brand() -> Option<String> {
|
||||
#[cfg(test)]
|
||||
if let Some(brand) = tests::BRAND.with(|b| b.borrow().clone()) {
|
||||
return brand;
|
||||
}
|
||||
cpuid_brand()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
fn cpuid_brand() -> Option<String> {
|
||||
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 r = __cpuid(leaf);
|
||||
[r.eax, r.ebx, r.ecx, r.edx]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
})
|
||||
.collect();
|
||||
let brand = String::from_utf8_lossy(&bytes);
|
||||
let brand = brand.trim_matches(|c: char| c == '\0' || c.is_whitespace());
|
||||
(!brand.is_empty()).then(|| brand.to_string())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
fn cpuid_brand() -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether a window can open for a QEMU run with `env` over this process's environment: it names
|
||||
/// a Wayland compositor or an X server. Without one, QEMU's GTK window ends QEMU as it starts,
|
||||
/// where the library's runs headless.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[cfg(unix)]
|
||||
pub fn has_screen(env: &BTreeMap<String, String>) -> bool {
|
||||
["WAYLAND_DISPLAY", "DISPLAY"]
|
||||
.iter()
|
||||
@@ -377,15 +118,6 @@ pub fn has_screen(env: &BTreeMap<String, String>) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a window can open for a QEMU run: on a Mac, this process's security session reaches
|
||||
/// the window server, as a signed-in user's does and an SSH login's does not
|
||||
/// ([`crate::os::session_has_graphics`]). A VM's variables name no screen there: AppKit reads
|
||||
/// neither X's nor Wayland's.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn has_screen(_env: &BTreeMap<String, String>) -> bool {
|
||||
crate::os::session_has_graphics()
|
||||
}
|
||||
|
||||
/// Whether a window can open for a QEMU run: on Windows, this process's window station is the
|
||||
/// one a signed-in user's desktop shows, as it is not for a service's or an SSH login's.
|
||||
#[cfg(windows)]
|
||||
@@ -423,7 +155,8 @@ pub enum Profile {
|
||||
impl Profile {
|
||||
pub fn supported_on(host: Host) -> &'static [Profile] {
|
||||
match (host.os, host.arch) {
|
||||
(Os::Linux | Os::Windows, Arch::X86_64) => &[Profile::Q35X86_64, Profile::VmappleArm64],
|
||||
(Os::Linux, Arch::X86_64) => &[Profile::Q35X86_64, Profile::VmappleArm64],
|
||||
(Os::Windows, Arch::X86_64) => &[Profile::Q35X86_64],
|
||||
(Os::Mac | Os::Linux, Arch::Aarch64) => &[Profile::VmappleArm64],
|
||||
_ => &[],
|
||||
}
|
||||
@@ -454,7 +187,6 @@ impl Profile {
|
||||
match self {
|
||||
Profile::Q35X86_64 if cfg!(windows) => "qemu-system-x86_64.exe",
|
||||
Profile::Q35X86_64 => "qemu-system-x86_64",
|
||||
Profile::VmappleArm64 if cfg!(windows) => "qemu-system-aarch64.exe",
|
||||
Profile::VmappleArm64 => "qemu-system-aarch64",
|
||||
}
|
||||
}
|
||||
@@ -498,10 +230,10 @@ impl Profile {
|
||||
|
||||
/// Whether QEMU takes all of the guest's RAM from the host as it starts, so a host short of
|
||||
/// memory ends a start: the x86-64 machine's memfd is allocated whole on Linux (`prealloc`,
|
||||
/// [`crate::qemu`]'s module doc), and either machine's section committed whole on Windows.
|
||||
/// The arm64 machine's memfd is allocated as the guest touches it.
|
||||
/// [`crate::qemu`]'s module doc), and its section committed whole on Windows. The arm64
|
||||
/// machine's memfd is allocated as the guest touches it.
|
||||
pub fn ram_whole_at_start(self, host: Host) -> bool {
|
||||
self.section_ram(host) || (self == Profile::Q35X86_64 && self.memfd_ram(host))
|
||||
self == Profile::Q35X86_64 && (self.memfd_ram(host) || self.section_ram(host))
|
||||
}
|
||||
|
||||
/// Whether a Vulkan GPU can be chosen: the library runs on the host's Vulkan GPUs on Linux
|
||||
@@ -518,172 +250,9 @@ impl fmt::Display for Profile {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
thread_local! {
|
||||
/// What [`cpu_brand`] answers on this test's thread, where set: [`with_cpu_brand`].
|
||||
pub(crate) static BRAND: std::cell::RefCell<Option<Option<String>>> =
|
||||
const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// What [`has_avx2`] answers on this test's thread, where set: [`with_avx2`].
|
||||
pub(crate) static AVX2: std::cell::RefCell<Option<Option<bool>>> =
|
||||
const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` with [`has_avx2`] answering `avx2` on this thread: a fake of the CPU's features.
|
||||
pub(crate) fn with_avx2<T>(avx2: Option<bool>, f: impl FnOnce() -> T) -> T {
|
||||
let old = AVX2.with(|a| a.replace(Some(avx2)));
|
||||
let out = f();
|
||||
AVX2.with(|a| *a.borrow_mut() = old);
|
||||
out
|
||||
}
|
||||
|
||||
/// An x86-64 VM of macOS 13 or later is refused on a CPU without AVX2, naming AVX2, the CPU
|
||||
/// and what needs it, the system libraries; macOS 12, a CPU with AVX2 and a host other than
|
||||
/// x86-64 are not. Doctor's reason names every macOS from 13.
|
||||
#[test]
|
||||
fn macos_13_and_later_is_refused_on_a_cpu_without_avx2() {
|
||||
let ivy = "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz";
|
||||
for major in [13, 14, 15, 26] {
|
||||
let why = with_cpu_brand(Some(ivy), || with_avx2(Some(false), || without_avx2(major)));
|
||||
let why = why.expect("refused");
|
||||
assert!(
|
||||
why.starts_with(&format!("x86-64 macOS {major} needs a CPU with AVX2")),
|
||||
"{why}"
|
||||
);
|
||||
assert!(
|
||||
why.contains("system libraries are built for CPUs with AVX2 alone"),
|
||||
"{why}"
|
||||
);
|
||||
let cpu = format!("this host's CPU, {ivy}, has none");
|
||||
assert!(why.contains(&cpu), "{why}");
|
||||
}
|
||||
assert_eq!(with_avx2(Some(false), || without_avx2(12)), None);
|
||||
assert_eq!(with_avx2(Some(true), || without_avx2(13)), None);
|
||||
assert_eq!(with_avx2(None, || without_avx2(26)), None);
|
||||
let unnamed = with_cpu_brand(None, || with_avx2(Some(false), || without_avx2(26)));
|
||||
assert!(unnamed.unwrap().contains("this host's CPU has none"));
|
||||
let from = with_avx2(Some(false), without_avx2_from).expect("refused");
|
||||
assert!(
|
||||
from.starts_with("x86-64 macOS 13 and later need a CPU with AVX2"),
|
||||
"{from}"
|
||||
);
|
||||
assert_eq!(with_avx2(Some(true), without_avx2_from), None);
|
||||
}
|
||||
|
||||
/// On a host whose CPU lacks AVX2 the guest's CPU names the newest model the host's CPU has
|
||||
/// every feature of, its IBRS variant where the host has IBRS, adds each feature of
|
||||
/// reims-ctl's own model that the host has and that model lacks, and leaves out reims-ctl's
|
||||
/// own flags whose feature the host lacks: nothing on the line is a feature the host lacks.
|
||||
/// A host with AVX2 keeps reims-ctl's model. The hosts are CPUs without AVX2, their features
|
||||
/// from Intel's and AMD's lists: an Ivy Bridge-EP Xeon, a Sandy Bridge-EP Xeon, an AMD FX
|
||||
/// (Piledriver, with no x2APIC, TSC deadline timer or IBRS), a Pentium Gold of the Coffee
|
||||
/// Lake generation, which has no AVX, and a Core i7 of the Nehalem generation.
|
||||
#[test]
|
||||
fn a_host_without_avx2_gets_the_newest_model_it_is() {
|
||||
let model = |has: &[&str]| model_without_avx2(&|f| has.contains(&f)).unwrap();
|
||||
let flags = |m: &HostModel| m.flags.join(",");
|
||||
let drop = |m: &HostModel| m.drop.join(",");
|
||||
let nehalem = ["ssse3", "sse4.2", "popcnt", "rdtscp"];
|
||||
let westmere = [&nehalem[..], &["aes", "pclmulqdq", "arat", "spec-ctrl"]].concat();
|
||||
let sandy = [
|
||||
&westmere[..],
|
||||
&["avx", "xsave", "xsaveopt", "x2apic", "tsc-deadline", "pcid"],
|
||||
]
|
||||
.concat();
|
||||
let ivy_ep = [&sandy[..], &["f16c", "rdrand", "fsgsbase", "smep", "erms"]].concat();
|
||||
let ivy = model(&ivy_ep);
|
||||
assert_eq!(ivy.name, "IvyBridge-IBRS");
|
||||
assert_eq!(flags(&ivy), "+pcid");
|
||||
assert_eq!(drop(&ivy), "");
|
||||
let sandy = model(&sandy);
|
||||
assert_eq!(sandy.name, "SandyBridge-IBRS");
|
||||
assert_eq!(flags(&sandy), "+pcid");
|
||||
assert_eq!(drop(&sandy), "");
|
||||
let fx = [
|
||||
&nehalem[..],
|
||||
&[
|
||||
"aes",
|
||||
"pclmulqdq",
|
||||
"arat",
|
||||
"avx",
|
||||
"xsave",
|
||||
"xsaveopt",
|
||||
"f16c",
|
||||
],
|
||||
&["fma", "bmi1", "abm", "3dnowprefetch"],
|
||||
]
|
||||
.concat();
|
||||
let fx = model(&fx);
|
||||
assert_eq!(fx.name, "Westmere");
|
||||
assert_eq!(
|
||||
flags(&fx),
|
||||
"+fma,+bmi1,+abm,+3dnowprefetch,+f16c,+avx,+xsave,+xsaveopt,+rdtscp"
|
||||
);
|
||||
assert_eq!(drop(&fx), "");
|
||||
let pentium = [
|
||||
&westmere[..],
|
||||
&[
|
||||
"x2apic",
|
||||
"tsc-deadline",
|
||||
"pcid",
|
||||
"movbe",
|
||||
"rdrand",
|
||||
"rdseed",
|
||||
],
|
||||
&[
|
||||
"fsgsbase",
|
||||
"smep",
|
||||
"smap",
|
||||
"erms",
|
||||
"invpcid",
|
||||
"adx",
|
||||
"3dnowprefetch",
|
||||
],
|
||||
&["xsave", "xsaveopt", "xsavec", "xgetbv1"],
|
||||
]
|
||||
.concat();
|
||||
let pentium = model(&pentium);
|
||||
assert_eq!(pentium.name, "Westmere-IBRS");
|
||||
assert_eq!(
|
||||
flags(&pentium),
|
||||
"+pcid,+movbe,+3dnowprefetch,+invpcid,+rdseed,+adx,+smap,+xsavec,+xgetbv1,\
|
||||
+rdrand,+fsgsbase,+smep,+erms,+xsave,+xsaveopt,+rdtscp,+x2apic,+tsc-deadline"
|
||||
);
|
||||
assert_eq!(drop(&pentium), "+avx");
|
||||
let nehalem = model(&nehalem);
|
||||
assert_eq!(nehalem.name, "Nehalem");
|
||||
assert_eq!(flags(&nehalem), "+rdtscp");
|
||||
assert_eq!(drop(&nehalem), "+avx,+aes,+xsave,+xsaveopt");
|
||||
let haswell = [&ivy_ep[..], &["avx2", "fma", "bmi1", "bmi2", "movbe"]].concat();
|
||||
assert_eq!(model_without_avx2(&|f| haswell.contains(&f)), None);
|
||||
}
|
||||
|
||||
/// Runs `f` with [`cpu_brand`] answering `brand` on this thread.
|
||||
pub(crate) fn with_cpu_brand<T>(brand: Option<&str>, f: impl FnOnce() -> T) -> T {
|
||||
let old = BRAND.with(|b| b.replace(Some(brand.map(String::from))));
|
||||
let out = f();
|
||||
BRAND.with(|b| *b.borrow_mut() = old);
|
||||
out
|
||||
}
|
||||
|
||||
/// The brand string is CPUID's, with the padding Intel's older CPUs put before it gone; a
|
||||
/// host other than x86-64 has none.
|
||||
#[test]
|
||||
fn the_cpu_brand_is_cpuids_trimmed() {
|
||||
let brand = cpuid_brand();
|
||||
if cfg!(target_arch = "x86_64") {
|
||||
let b = brand.expect("an x86-64 CPU names itself");
|
||||
assert_eq!(b, b.trim(), "{b:?}");
|
||||
assert!(!b.contains('\0'), "{b:?}");
|
||||
} else {
|
||||
assert_eq!(brand, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux on x86-64 runs x86-64 guests on KVM in memfd RAM, and arm64 guests on vmapple under
|
||||
/// TCG; an arm64 Mac and arm64 Linux run arm64 guests on vmapple, under HVF and KVM; an Intel
|
||||
/// Mac, Windows on arm64 and any other host run none.
|
||||
@@ -738,14 +307,7 @@ pub(crate) mod tests {
|
||||
assert_eq!(arm.accel_arg(arm_linux), "kvm");
|
||||
assert!(arm.memfd_ram(arm_linux) && arm.gpu_choice(arm_linux));
|
||||
assert!(arm.describe(arm_linux).ends_with("KVM)"));
|
||||
assert_eq!(
|
||||
arm.qemu_binary(),
|
||||
if cfg!(windows) {
|
||||
"qemu-system-aarch64.exe"
|
||||
} else {
|
||||
"qemu-system-aarch64"
|
||||
}
|
||||
);
|
||||
assert_eq!(arm.qemu_binary(), "qemu-system-aarch64");
|
||||
for (os, arch) in [
|
||||
(Os::Mac, Arch::X86_64),
|
||||
(Os::Windows, Arch::Aarch64),
|
||||
@@ -755,8 +317,8 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows on x86-64 runs x86-64 guests on WHPX and arm64 guests under TCG, each in RAM of a
|
||||
/// shared section rather than a memfd, with a Vulkan GPU to choose.
|
||||
/// Windows on x86-64 runs x86-64 guests on WHPX, in RAM of a shared section rather than a
|
||||
/// memfd, with a Vulkan GPU to choose.
|
||||
#[test]
|
||||
fn windows_on_x86_64_runs_vms_on_whpx() {
|
||||
let windows = Host {
|
||||
@@ -764,24 +326,16 @@ pub(crate) mod tests {
|
||||
arch: Arch::X86_64,
|
||||
};
|
||||
let q35 = Profile::Q35X86_64;
|
||||
let arm = Profile::VmappleArm64;
|
||||
assert_eq!(Profile::supported_on(windows), [q35, arm]);
|
||||
assert_eq!(windows.default_profile(), Some(q35));
|
||||
assert_eq!(Profile::supported_on(windows), [q35]);
|
||||
assert_eq!(q35.accel(windows), "whpx");
|
||||
assert!(q35.section_ram(windows) && !q35.memfd_ram(windows));
|
||||
assert!(q35.ram_whole_at_start(windows));
|
||||
assert!(q35.gpu_choice(windows));
|
||||
assert!(q35.describe(windows).ends_with("WHPX)"));
|
||||
assert_eq!(arm.accel(windows), "tcg");
|
||||
assert_eq!(arm.accel_arg(windows), "tcg,thread=multi");
|
||||
assert!(arm.section_ram(windows) && !arm.memfd_ram(windows));
|
||||
assert!(arm.ram_whole_at_start(windows));
|
||||
assert!(arm.gpu_choice(windows));
|
||||
assert!(arm.describe(windows).ends_with("emulated by TCG)"));
|
||||
assert_eq!(windows.to_string(), "Windows on x86-64");
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_vms_environment_decides_its_screen_over_this_process() {
|
||||
let env = |v: &str| {
|
||||
@@ -790,21 +344,4 @@ pub(crate) mod tests {
|
||||
assert!(has_screen(&env(":0")));
|
||||
assert!(!has_screen(&env("")));
|
||||
}
|
||||
|
||||
/// On a Mac a window opens on the window server of this process's security session, which a
|
||||
/// signed-in user's session reaches and an SSH login's does not: X's and Wayland's variables,
|
||||
/// which AppKit reads none of, decide nothing there.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn a_mac_has_a_screen_by_its_session_not_by_x_or_wayland() {
|
||||
let env = |v: &str| {
|
||||
BTreeMap::from(["WAYLAND_DISPLAY", "DISPLAY"].map(|k| (k.to_string(), v.to_string())))
|
||||
};
|
||||
assert_eq!(has_screen(&env(":0")), has_screen(&env("")));
|
||||
assert_eq!(has_screen(&env("")), has_screen(&BTreeMap::new()));
|
||||
assert_eq!(
|
||||
has_screen(&BTreeMap::new()),
|
||||
crate::os::session_has_graphics()
|
||||
);
|
||||
}
|
||||
}
|
||||
+37
-327
@@ -31,7 +31,7 @@ pub const INSTALL_SCRIPT: &str = if cfg!(windows) {
|
||||
"scripts/install-ctl.sh"
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Install {
|
||||
/// The reims-vgpu checkout the install built from, which `update` pulls.
|
||||
pub repo: PathBuf,
|
||||
@@ -54,37 +54,21 @@ fn is_empty(p: &Path) -> bool {
|
||||
}
|
||||
|
||||
impl Install {
|
||||
/// The data directory's record, else, where it has none, an earlier reims-ctl's in the config
|
||||
/// directory; `None` where neither is there. An error where one is there that this build
|
||||
/// can't read, or can't read as the record: taken for none, the data directory's would give
|
||||
/// the config directory's, an earlier install's, in its place, or no install at all.
|
||||
pub fn load() -> Result<Option<Install>> {
|
||||
for file in [paths::install_file(), paths::config_install_file()] {
|
||||
match std::fs::read_to_string(&file) {
|
||||
Ok(text) => {
|
||||
let read = toml::from_str(&text).map(Some);
|
||||
return read.with_context(|| format!("parse {}", file.display()));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e).with_context(|| format!("read {}", file.display())),
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
/// The data directory's record, else an earlier reims-ctl's in the config directory.
|
||||
pub fn load() -> Option<Install> {
|
||||
let text = std::fs::read_to_string(paths::install_file())
|
||||
.or_else(|_| std::fs::read_to_string(paths::config_install_file()))
|
||||
.ok()?;
|
||||
toml::from_str(&text).ok()
|
||||
}
|
||||
|
||||
/// Writes the record into the data directory, over its file as it is, keeping what another
|
||||
/// build of reims-ctl wrote there in its place and form ([`crate::record::text_over`]), and
|
||||
/// refused, with the file left as it is, where this build can't read it or keep what it holds
|
||||
/// ([`crate::record::Refused`]). The text goes into a file beside it, renamed over it, so a
|
||||
/// write cut short leaves the record whole. Then it removes an earlier reims-ctl's record in
|
||||
/// Writes the record into the data directory, and removes an earlier reims-ctl's record in
|
||||
/// the config directory where that one named a QEMU build of this data directory: the same
|
||||
/// install's, which this replaces. One of another data directory's install stays.
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let file = paths::install_file();
|
||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
||||
let old = crate::record::old_text(&file)?;
|
||||
let text = crate::record::text_over(self, &file, old.as_deref(), &[])?;
|
||||
crate::record::replace(&file, text.as_bytes())
|
||||
std::fs::write(&file, toml::to_string_pretty(self)?)
|
||||
.with_context(|| format!("write {}", file.display()))?;
|
||||
let old = paths::config_install_file();
|
||||
if let Ok(text) = std::fs::read_to_string(&old)
|
||||
@@ -238,44 +222,26 @@ fn lists_property(out: &str, name: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// What `qemu -smbios OPTION -version` answered, by binary, its modification time and the option.
|
||||
type SmbiosProbes = HashMap<(PathBuf, Option<std::time::SystemTime>, &'static str), bool>;
|
||||
/// What `qemu -smbios type=17,memory_type=26 -version` answered, by binary and its modification
|
||||
/// time.
|
||||
type SmbiosProbes = HashMap<(PathBuf, Option<std::time::SystemTime>), bool>;
|
||||
|
||||
/// Whether `qemu` takes `-smbios type=17`'s `memory_type`, the memory devices' SMBIOS Memory
|
||||
/// Type, which reims-vgpu's QEMU has since vendor/qemu's `0c91b471` ([`smbios_takes`]).
|
||||
pub fn smbios_takes_memory_type(qemu: &Path) -> bool {
|
||||
smbios_takes(qemu, "type=17,memory_type=26")
|
||||
}
|
||||
|
||||
/// Whether `qemu` takes `-smbios type=16`'s `error_correction`, the memory array's SMBIOS Memory
|
||||
/// Error Correction, which reims-vgpu's QEMU has since vendor/qemu's `d72b4ac3`
|
||||
/// ([`smbios_takes`]).
|
||||
pub fn smbios_takes_error_correction(qemu: &Path) -> bool {
|
||||
smbios_takes(qemu, "type=16,error_correction=3")
|
||||
}
|
||||
|
||||
/// Whether `qemu` takes `-smbios type=17`'s `slots` and `form_factor`, the memory array's empty
|
||||
/// slots and its devices' SMBIOS Form Factor, which reims-vgpu's QEMU has since vendor/qemu's
|
||||
/// `445170b5` ([`smbios_takes`]).
|
||||
pub fn smbios_takes_memory_slots(qemu: &Path) -> bool {
|
||||
smbios_takes(qemu, "type=17,slots=4,form_factor=13")
|
||||
}
|
||||
|
||||
/// Whether `qemu` takes `-smbios option`. A QEMU without it, upstream's or one built from an
|
||||
/// older tree (`REIMS_CTL_QEMU` names any), ends at its start on the option. QEMU takes its
|
||||
/// options in order, so it checks `-smbios` and exits with an error before `-version` prints and
|
||||
/// exits with 0. Cached per binary and option, by the binary's path and modification time; false
|
||||
/// Type, which reims-vgpu's QEMU has since vendor/qemu's `0c91b471`. A QEMU without it, upstream's
|
||||
/// or one built from an older tree (`REIMS_CTL_QEMU` names any), ends at its start on the option.
|
||||
/// QEMU takes its options in order, so it checks `-smbios` and exits with an error before
|
||||
/// `-version` prints and exits with 0. Cached per binary, by its path and modification time; false
|
||||
/// where QEMU does not run.
|
||||
fn smbios_takes(qemu: &Path, option: &'static str) -> bool {
|
||||
pub fn smbios_takes_memory_type(qemu: &Path) -> bool {
|
||||
static CACHE: OnceLock<Mutex<SmbiosProbes>> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(Default::default);
|
||||
let mtime = std::fs::metadata(qemu).and_then(|m| m.modified()).ok();
|
||||
let key = (qemu.to_path_buf(), mtime, option);
|
||||
let key = (qemu.to_path_buf(), mtime);
|
||||
if let Some(v) = cache.lock().unwrap().get(&key) {
|
||||
return *v;
|
||||
}
|
||||
let takes = std::process::Command::new(qemu)
|
||||
.args(["-smbios", option, "-version"])
|
||||
.args(["-smbios", "type=17,memory_type=26", "-version"])
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
@@ -323,22 +289,6 @@ mod tests {
|
||||
script[start..start + len].to_string()
|
||||
}
|
||||
|
||||
/// bash, as a shell finds it on PATH: on Windows MSYS2's, which the installer runs in. A
|
||||
/// `Command::new("bash")` there looks in System32 before PATH, and takes WSL's launcher where
|
||||
/// WSL is installed: it ran none of these tests on GitHub's Windows runners, which have WSL
|
||||
/// and no distribution for it (2026-12-03).
|
||||
fn bash() -> std::process::Command {
|
||||
#[cfg(windows)]
|
||||
let program = (std::env::var_os("PATH").iter())
|
||||
.flat_map(std::env::split_paths)
|
||||
.map(|dir| dir.join("bash.exe"))
|
||||
.find(|exe| exe.is_file())
|
||||
.unwrap_or_else(|| "bash".into());
|
||||
#[cfg(not(windows))]
|
||||
let program = "bash";
|
||||
std::process::Command::new(program)
|
||||
}
|
||||
|
||||
/// What the prune test runs as a QEMU: this test binary, copied into a build, idling here.
|
||||
#[test]
|
||||
fn idle_as_a_qemu() {
|
||||
@@ -364,25 +314,19 @@ mod tests {
|
||||
assert!(!lists_property(none, "x-avx512-xstate"));
|
||||
}
|
||||
|
||||
/// A QEMU that does not run, or that refuses the probe's options, takes neither `memory_type`
|
||||
/// nor `error_correction`: this test binary stands for one that refuses them, as libtest ends
|
||||
/// on an option it does not know.
|
||||
/// A QEMU that does not run, or that refuses the probe's options, takes no `memory_type`:
|
||||
/// this test binary stands for one that refuses them, as libtest ends on an option it does
|
||||
/// not know.
|
||||
#[test]
|
||||
fn a_qemu_that_refuses_the_probe_takes_no_memory_type() {
|
||||
let missing = std::env::temp_dir().join("reims-ctl-no-such-qemu");
|
||||
assert!(!smbios_takes_memory_type(&missing));
|
||||
assert!(!smbios_takes_error_correction(&missing));
|
||||
let refuses = std::env::current_exe().unwrap();
|
||||
assert!(!smbios_takes_memory_type(&refuses));
|
||||
assert!(!smbios_takes_error_correction(&refuses));
|
||||
assert!(!smbios_takes_memory_slots(&missing));
|
||||
assert!(!smbios_takes_memory_slots(&refuses));
|
||||
}
|
||||
|
||||
/// A QEMU that takes the probe's options takes `memory_type`: a stand-in that ends with 0
|
||||
/// only when it is asked for `type=17,memory_type=26`, as reims-vgpu's QEMU does. It refuses
|
||||
/// `type=16,error_correction=3`, as a QEMU built between the two options does, and is said
|
||||
/// not to take that one.
|
||||
/// only when it is asked for `type=17,memory_type=26`, as reims-vgpu's QEMU does.
|
||||
#[test]
|
||||
fn a_qemu_that_takes_the_probe_takes_the_memory_type() {
|
||||
let d = std::env::temp_dir().join(format!("reims-ctl-smbios-{}", std::process::id()));
|
||||
@@ -391,46 +335,9 @@ mod tests {
|
||||
&d.join("qemu"),
|
||||
"#!/bin/sh\ncase \" $* \" in *\" -smbios type=17,memory_type=26 \"*) exit 0 ;; esac\nexit 1\n",
|
||||
);
|
||||
let answers = (
|
||||
smbios_takes_memory_type(&takes),
|
||||
smbios_takes_error_correction(&takes),
|
||||
);
|
||||
let answer = smbios_takes_memory_type(&takes);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
assert_eq!(answers, (true, false), "(memory_type, error_correction)");
|
||||
}
|
||||
|
||||
/// A QEMU that takes `type=16,error_correction=3` takes the memory array's error correction:
|
||||
/// a stand-in that ends with 0 only when asked for it.
|
||||
#[test]
|
||||
fn a_qemu_that_takes_the_probe_takes_the_error_correction() {
|
||||
let d = std::env::temp_dir().join(format!("reims-ctl-smbios16-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let takes = crate::testenv::program(
|
||||
&d.join("qemu"),
|
||||
"#!/bin/sh\ncase \" $* \" in *\" -smbios type=16,error_correction=3 \"*) exit 0 ;; esac\nexit 1\n",
|
||||
);
|
||||
let answer = smbios_takes_error_correction(&takes);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
assert!(answer, "a QEMU that takes error_correction is said not to");
|
||||
}
|
||||
|
||||
/// A QEMU that takes `type=17,slots=4,form_factor=13` takes the memory array's slots: a
|
||||
/// stand-in that ends with 0 only when asked for them. It refuses `memory_type`, as no QEMU
|
||||
/// does, and is said not to take that one: each option is asked of QEMU on its own.
|
||||
#[test]
|
||||
fn a_qemu_that_takes_the_probe_takes_the_memory_slots() {
|
||||
let d = std::env::temp_dir().join(format!("reims-ctl-smbios17-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let takes = crate::testenv::program(
|
||||
&d.join("qemu"),
|
||||
"#!/bin/sh\ncase \" $* \" in *\" -smbios type=17,slots=4,form_factor=13 \"*) exit 0 ;; esac\nexit 1\n",
|
||||
);
|
||||
let answers = (
|
||||
smbios_takes_memory_slots(&takes),
|
||||
smbios_takes_memory_type(&takes),
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
assert_eq!(answers, (true, false), "(slots, memory_type)");
|
||||
assert!(answer, "a QEMU that takes memory_type is said not to");
|
||||
}
|
||||
|
||||
/// The installer's prune keeps a build older than the newest three while a QEMU runs from
|
||||
@@ -496,7 +403,7 @@ mod tests {
|
||||
}
|
||||
};
|
||||
link(builds[4]);
|
||||
let pruned = bash()
|
||||
let pruned = std::process::Command::new("bash")
|
||||
.arg("-c")
|
||||
.arg(format!("set -euo pipefail\n{functions}prune_qemu \"$1\""))
|
||||
.arg("prune")
|
||||
@@ -567,7 +474,7 @@ mod tests {
|
||||
.unwrap();
|
||||
link(builds[4]);
|
||||
let prune = || {
|
||||
bash()
|
||||
std::process::Command::new("bash")
|
||||
.arg("-c")
|
||||
.arg(format!(
|
||||
"set -euo pipefail\nWINDOWS=1\n{functions}prune_qemu \"$(cygpath -u \"$1\")\""
|
||||
@@ -613,7 +520,7 @@ mod tests {
|
||||
let line = text[at..].lines().nth(1).expect("the configure line");
|
||||
assert!(line.contains("\"${CONFIGURE[@]}\""), "{line}");
|
||||
let configure = |shell: Option<&str>| {
|
||||
let mut bash = bash();
|
||||
let mut bash = std::process::Command::new("bash");
|
||||
bash.arg("-c")
|
||||
.arg(format!(
|
||||
"set -euo pipefail\nBUILD=.\nPC=/dist/lib/pkgconfig\n\
|
||||
@@ -688,7 +595,7 @@ mod tests {
|
||||
"for n in {}; do printf '%s=%s\\n' \"$n\" \"${{!n-}}\"; done\n",
|
||||
names.join(" ")
|
||||
);
|
||||
let mut bash = bash();
|
||||
let mut bash = std::process::Command::new("bash");
|
||||
bash.arg("-c")
|
||||
.arg(format!("set -euo pipefail\n{exports}{print}"))
|
||||
.env("MSYSTEM", "CLANG64")
|
||||
@@ -725,7 +632,7 @@ mod tests {
|
||||
.iter()
|
||||
.map(|f| script_function(&text, f))
|
||||
.collect();
|
||||
let out = bash()
|
||||
let out = std::process::Command::new("bash")
|
||||
.arg("-c")
|
||||
.arg(format!("set -euo pipefail\n{functions}{body}"))
|
||||
.current_dir(dir)
|
||||
@@ -854,7 +761,7 @@ mod tests {
|
||||
let root = std::env::temp_dir().join(format!("reims-ctl-skip-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let out = bash()
|
||||
let out = std::process::Command::new("bash")
|
||||
.arg(&script)
|
||||
.arg("--skip-qemu")
|
||||
.env("XDG_DATA_HOME", root.join("data"))
|
||||
@@ -929,7 +836,7 @@ mod tests {
|
||||
commit("crates/reims-ctl/src/main.rs");
|
||||
commit("docs/qemu.md");
|
||||
let kept = |build: &str| {
|
||||
let mut bash = bash();
|
||||
let mut bash = std::process::Command::new("bash");
|
||||
for v in crate::update::GIT_REPOSITORY_ENV {
|
||||
bash.env_remove(v);
|
||||
}
|
||||
@@ -964,128 +871,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// What the installer says last (its `check_note`): how to check the host with the
|
||||
/// reims-ctl it installed and, where the user's shell won't run that one as reims-ctl, what
|
||||
/// puts the directory it installed into first on PATH, naming that directory. Cargo's home's
|
||||
/// bin is put first by rustup's env file there (`$HOME/.cargo/env`, or CARGO_HOME's);
|
||||
/// CARGO_INSTALL_ROOT's bin by nothing of rustup's, where the installer named the default
|
||||
/// env file all the same. Where the shell runs it first, nothing. On Windows, a new window
|
||||
/// has no CARGO_INSTALL_ROOT's bin on its PATH, so the check runs reims-ctl by its full path.
|
||||
#[test]
|
||||
fn the_installers_path_advice_names_the_directory_it_installed_into() {
|
||||
let dir = std::env::var_os("CARGO_MANIFEST_DIR")
|
||||
.expect("CARGO_MANIFEST_DIR: run the tests with cargo");
|
||||
let text =
|
||||
std::fs::read_to_string(Path::new(&dir).join("../../scripts/install-ctl.sh")).unwrap();
|
||||
let functions: String = ["shown", "check_note"]
|
||||
.iter()
|
||||
.map(|f| script_function(&text, f))
|
||||
.collect();
|
||||
// check_note for `bin` in a shell whose PATH was `start`, with `env` and the script's
|
||||
// WINDOWS; what it writes to its standard output and error. Its cygpath writes /c/x/y as
|
||||
// Windows writes it, C:\x\y.
|
||||
let note = |windows: bool, env: &[(&str, &str)], bin: &str, start: &str| {
|
||||
// The script goes to bash on its standard input, not as a `-c` argument: on Windows
|
||||
// an argument passes through the command line's quoting, which MSYS2's bash reads
|
||||
// back otherwise for the quotes in the installer's text.
|
||||
let script = format!(
|
||||
"set -euo pipefail\nwarn() {{ printf 'warning: %s\\n' \"$*\" >&2; }}\n\
|
||||
cygpath() {{ local p=\"${{2#/c}}\"; printf 'C:%s' \"${{p//\\//\\\\}}\"; }}\n\
|
||||
{functions}WINDOWS={} START_PATH=\"$1\"\ncheck_note \"$2\"\n",
|
||||
u8::from(windows)
|
||||
);
|
||||
let mut bash = bash();
|
||||
bash.arg("-s")
|
||||
.arg(start)
|
||||
.arg(bin)
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.env("HOME", "/home/u")
|
||||
.env_remove("CARGO_HOME")
|
||||
.env_remove("CARGO_INSTALL_ROOT")
|
||||
// On Windows, MSYS2's bash, as the installer runs in.
|
||||
.env("MSYSTEM", "CLANG64")
|
||||
.env("CHERE_INVOKING", "1");
|
||||
for (k, v) in env {
|
||||
bash.env(k, v);
|
||||
}
|
||||
let mut child = bash.spawn().unwrap();
|
||||
std::io::Write::write_all(&mut child.stdin.take().unwrap(), script.as_bytes()).unwrap();
|
||||
let out = child.wait_with_output().unwrap();
|
||||
let err = String::from_utf8(out.stderr).unwrap();
|
||||
assert!(out.status.success(), "{err}");
|
||||
(String::from_utf8(out.stdout).unwrap(), err)
|
||||
};
|
||||
let checked = |bin: &str| format!("Check this host:\n {bin} doctor\n");
|
||||
let start = "/usr/bin:/bin";
|
||||
|
||||
let bin = "/opt/ctl/bin/reims-ctl";
|
||||
assert_eq!(
|
||||
note(false, &[("CARGO_INSTALL_ROOT", "/opt/ctl")], bin, start),
|
||||
(
|
||||
checked(bin) + "\n",
|
||||
"warning: /opt/ctl/bin, CARGO_INSTALL_ROOT's bin, is not first on your PATH, and \
|
||||
a new terminal won't put it there: add it in your shell's profile, as with: \
|
||||
export PATH=\"/opt/ctl/bin:$PATH\"\n"
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
let bin = "/home/u/.cargo/bin/reims-ctl";
|
||||
assert_eq!(
|
||||
note(false, &[], bin, start),
|
||||
(
|
||||
checked(bin) + "\n",
|
||||
"warning: /home/u/.cargo/bin is not first on your PATH: open a new terminal, or \
|
||||
run: . \"$HOME/.cargo/env\"\n"
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
let bin = "/opt/cargo/bin/reims-ctl";
|
||||
assert_eq!(
|
||||
note(false, &[("CARGO_HOME", "/opt/cargo")], bin, start),
|
||||
(
|
||||
checked(bin) + "\n",
|
||||
"warning: /opt/cargo/bin is not first on your PATH: open a new terminal, or run: \
|
||||
. \"/opt/cargo/env\"\n"
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let root = std::env::temp_dir().join(format!("reims-ctl-path-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("bin")).unwrap();
|
||||
let ctl = crate::testenv::program(&root.join("bin/reims-ctl"), "#!/bin/sh\n");
|
||||
let (root_s, ctl_s) = (root.to_str().unwrap(), ctl.to_str().unwrap());
|
||||
let first = format!("{root_s}/bin:{start}");
|
||||
let said = note(false, &[("CARGO_INSTALL_ROOT", root_s)], ctl_s, &first);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
assert_eq!(said, (checked(ctl_s), String::new()));
|
||||
}
|
||||
|
||||
let window = "Check this host, in a new PowerShell or Windows Terminal window:\n";
|
||||
assert_eq!(
|
||||
note(
|
||||
true,
|
||||
&[("CARGO_INSTALL_ROOT", "C:\\ctl")],
|
||||
"/c/ctl/bin/reims-ctl.exe",
|
||||
start
|
||||
),
|
||||
(
|
||||
format!("{window} & 'C:\\ctl\\bin\\reims-ctl.exe' doctor\n\n"),
|
||||
"warning: C:\\ctl\\bin, CARGO_INSTALL_ROOT's bin, is on no PATH rustup set: add \
|
||||
it to your PATH (Windows' \"Edit environment variables for your account\") to \
|
||||
run reims-ctl by its name\n"
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
note(true, &[], "/c/Users/u/.cargo/bin/reims-ctl.exe", start),
|
||||
(format!("{window} reims-ctl doctor\n"), String::new())
|
||||
);
|
||||
}
|
||||
|
||||
/// The install's record is in the data directory, beside the QEMU builds it names: an
|
||||
/// install into a scratch data directory records itself there, and the user's record stays
|
||||
/// as it was, an earlier reims-ctl's in the config directory too, which the user's own
|
||||
@@ -1105,98 +890,23 @@ mod tests {
|
||||
std::fs::create_dir_all(old.parent().unwrap()).unwrap();
|
||||
std::fs::write(&old, toml::to_string_pretty(&record("aaaaaaa")).unwrap()).unwrap();
|
||||
let old_text = std::fs::read(&old).unwrap();
|
||||
assert_eq!(Install::load().unwrap().unwrap().commit, "aaaaaaa");
|
||||
assert_eq!(Install::load().unwrap().commit, "aaaaaaa");
|
||||
|
||||
let scratch = env.root.join("scratch");
|
||||
env.set("REIMS_CTL_DATA_DIR", &scratch);
|
||||
record("bbbbbbb").save().unwrap();
|
||||
assert!(scratch.join("install.toml").is_file());
|
||||
assert_eq!(Install::load().unwrap().unwrap().commit, "bbbbbbb");
|
||||
assert_eq!(Install::load().unwrap().commit, "bbbbbbb");
|
||||
assert_eq!(std::fs::read(&old).unwrap(), old_text);
|
||||
|
||||
env.set("REIMS_CTL_DATA_DIR", &own);
|
||||
assert_eq!(Install::load().unwrap().unwrap().commit, "aaaaaaa");
|
||||
assert_eq!(Install::load().unwrap().commit, "aaaaaaa");
|
||||
record("ccccccc").save().unwrap();
|
||||
assert!(!old.exists());
|
||||
assert!(own.join("install.toml").is_file());
|
||||
assert_eq!(Install::load().unwrap().unwrap().commit, "ccccccc");
|
||||
assert_eq!(Install::load().unwrap().commit, "ccccccc");
|
||||
env.set("REIMS_CTL_DATA_DIR", &scratch);
|
||||
assert_eq!(Install::load().unwrap().unwrap().commit, "bbbbbbb");
|
||||
}
|
||||
|
||||
/// The install's save over a record this build can't read, as one that isn't UTF-8 or that its
|
||||
/// mode keeps from the user, is refused, naming the file, and leaves the file byte for byte.
|
||||
#[test]
|
||||
fn the_install_s_save_over_a_record_this_build_cannot_read_leaves_it() {
|
||||
let env = crate::testenv::Env::new("unreadable-install-record");
|
||||
let record = Install {
|
||||
repo: env.root.join("repo"),
|
||||
commit: "aaaaaaa".into(),
|
||||
qemu: paths::qemu_root().join("20261118-000000-aaaaaaa"),
|
||||
installed_at: String::new(),
|
||||
shell: PathBuf::new(),
|
||||
};
|
||||
crate::record::assert_unreadable_refused(&paths::install_file(), &|| record.save());
|
||||
}
|
||||
|
||||
/// An install's record this build can't read, one that isn't UTF-8 or that isn't the record,
|
||||
/// is not taken for none: its load is an error naming the file, not an earlier reims-ctl's
|
||||
/// record in the config directory nor no install, and the file is left byte for byte.
|
||||
#[test]
|
||||
fn an_install_record_this_build_cannot_read_is_not_taken_for_none() {
|
||||
let env = crate::testenv::Env::new("unreadable-install-load");
|
||||
let record = Install {
|
||||
repo: env.root.join("repo"),
|
||||
commit: "aaaaaaa".into(),
|
||||
qemu: paths::qemu_root().join("20261118-000000-aaaaaaa"),
|
||||
installed_at: String::new(),
|
||||
shell: PathBuf::new(),
|
||||
};
|
||||
let old = paths::config_install_file();
|
||||
std::fs::create_dir_all(old.parent().unwrap()).unwrap();
|
||||
std::fs::write(&old, toml::to_string_pretty(&record).unwrap()).unwrap();
|
||||
let file = paths::install_file();
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let held: [&[u8]; 2] = [b"commit = \"\xff\"\n", b"commit = 7\n"];
|
||||
for held in held {
|
||||
std::fs::write(&file, held).unwrap();
|
||||
let e = format!("{:#}", Install::load().unwrap_err());
|
||||
assert!(e.contains(&file.display().to_string()), "{e}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), held);
|
||||
}
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
assert_eq!(Install::load().unwrap(), Some(record));
|
||||
}
|
||||
|
||||
/// The install's record keeps what a newer reims-ctl wrote into it: a key of its own and a
|
||||
/// table of its own stay as written, byte for byte, as an install records another commit,
|
||||
/// whose line is all that changes.
|
||||
#[test]
|
||||
fn the_install_record_keeps_what_a_newer_build_wrote() {
|
||||
let env = crate::testenv::Env::new("newer-install-record");
|
||||
let record = Install {
|
||||
repo: env.root.join("repo"),
|
||||
commit: "aaaaaaa".into(),
|
||||
qemu: paths::qemu_root().join("20261118-000000-aaaaaaa"),
|
||||
installed_at: "2026-12-03 10:00:00 -0800".into(),
|
||||
shell: PathBuf::new(),
|
||||
};
|
||||
record.save().unwrap();
|
||||
let file = paths::install_file();
|
||||
let ours = std::fs::read_to_string(&file).unwrap();
|
||||
let line = "commit = \"aaaaaaa\"\n";
|
||||
let newer = ours.replacen(line, &format!("{line}channel = \"development\"\n"), 1)
|
||||
+ "\n[library]\nmetal2vulkan = \"0123abc\"\n";
|
||||
assert!(newer.contains("channel = "), "{newer}");
|
||||
std::fs::write(&file, &newer).unwrap();
|
||||
let mut i = Install::load().unwrap().unwrap();
|
||||
assert_eq!(i, record);
|
||||
i.commit = "bbbbbbb".into();
|
||||
i.save().unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&file).unwrap(),
|
||||
newer.replacen(line, "commit = \"bbbbbbb\"\n", 1)
|
||||
);
|
||||
assert_eq!(Install::load().unwrap().commit, "bbbbbbb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -32,10 +32,7 @@ pub fn on_disk() -> Vec<OnDisk> {
|
||||
/// Whether a create's `--ipsw` names a file rather than a release: a path, or a name that is
|
||||
/// there.
|
||||
pub fn is_path(s: &str) -> bool {
|
||||
s.contains('/')
|
||||
|| (cfg!(windows) && s.contains('\\'))
|
||||
|| s.ends_with(".ipsw")
|
||||
|| Path::new(s).exists()
|
||||
s.contains('/') || s.ends_with(".ipsw") || Path::new(s).exists()
|
||||
}
|
||||
|
||||
/// The IPSW a create named.
|
||||
|
||||
+22
-360
@@ -1,13 +1,7 @@
|
||||
//! Bug reports: a zip of a VM's logs, its settings, the exact QEMU command, what the host is
|
||||
//! and vulkaninfo's whole report of it, in the downloads folder, for someone to attach to a
|
||||
//! report. A running VM's library is asked first for its degradation counts as they are then,
|
||||
//! twice, [`PACING_SPAN`] apart, before anything else of the report runs on the host
|
||||
//! ([`ask_pacing`]), so its QEMU log in the zip ends with them, its build, and its pacing line over
|
||||
//! those 10 s: what limits a slow app (docs/conventions.md, "The pacing line"). A stopped VM's
|
||||
//! state.txt says why it stopped, and whether the counts its log holds are as of the run's end
|
||||
//! ([`stopped_state`]): a QEMU killed or crashed wrote none at its end. system.txt's head
|
||||
//! names reims-ctl's build, the library's as the VM's QEMU log names it, and the install's, and
|
||||
//! says so where they differ ([`builds`]).
|
||||
//! report. A running VM's library is asked first for its degradation counts as they are then
|
||||
//! ([`ask_counts`]), so its QEMU log in the zip ends with them.
|
||||
|
||||
use crate::gpu::GpuInfo;
|
||||
use crate::host::{Host, Os};
|
||||
@@ -41,8 +35,7 @@ const ADAPTERS_QUERY: &str = "$ProgressPreference = 'SilentlyContinue'; \
|
||||
'{0} [{1}] driver {2}' -f $_.Name, $_.PNPDeviceID, $_.DriverVersion }";
|
||||
|
||||
/// How long the ask for a running VM's counts waits for QMP's greeting and its answer: QMP takes
|
||||
/// one client at a time, so the ask waits while another holds it (reims-ctl's viewer holds it
|
||||
/// for one exchange at a time, a frame or a batch of input).
|
||||
/// one client at a time, so the ask waits while another holds it (reims-ctl's viewer).
|
||||
const COUNTS_WAIT: Duration = Duration::from_secs(3);
|
||||
|
||||
/// The QOM path of a VM's display device, which qemu.rs names `gfx`.
|
||||
@@ -52,34 +45,13 @@ const DISPLAY_PATH: &str = "/machine/peripheral/gfx";
|
||||
/// counts into QEMU's log before QMP answers (vendor/qemu hw/display/reims-graphics-pci.c).
|
||||
const COUNTS_PROPERTY: &str = "x-write-counts";
|
||||
|
||||
/// How far apart the report's two asks for the counts are: the span the library's pacing line
|
||||
/// covers, which it writes at the second.
|
||||
pub const PACING_SPAN: Duration = Duration::from_secs(10);
|
||||
|
||||
pub fn bundle(vm: &Vm, host: Host) -> Result<PathBuf> {
|
||||
let stamp = runtime::now_stamp("%Y%m%d-%H%M%S");
|
||||
let out = crate::paths::downloads_dir().join(format!("reims-ctl-{}-{stamp}.zip", vm.name()));
|
||||
let mut zip = Zip::create(&out)?;
|
||||
let prefix = format!("reims-ctl-{}-{stamp}", vm.name());
|
||||
// First, before vulkaninfo loads the host's GPU, and so before the logs are read: the
|
||||
// counts, the build and the pacing line of the 10 s between the two asks.
|
||||
let state = match runtime::pid(vm) {
|
||||
Some(p) => format!(
|
||||
"running, pid {p}\n{}\n",
|
||||
ask_pacing(&vm.qmp_socket(), PACING_SPAN)
|
||||
),
|
||||
None => stopped_state(&runtime::tail(&vm.qemu_log(), usize::MAX)),
|
||||
};
|
||||
let vulkaninfo = run_limited(Command::new("vulkaninfo"), VULKANINFO_LIMIT);
|
||||
let library = read_tail(&vm.qemu_log(), LOG_CAP)
|
||||
.ok()
|
||||
.and_then(|log| library_build(&String::from_utf8_lossy(&log)));
|
||||
let system = system_info(
|
||||
host,
|
||||
&runtime::warnings(vm, host),
|
||||
&vulkaninfo.end,
|
||||
library.as_ref(),
|
||||
);
|
||||
let system = system_info(host, &runtime::warnings(vm, host), &vulkaninfo.end);
|
||||
zip.add(&format!("{prefix}/system.txt"), system.as_bytes())?;
|
||||
zip.add(
|
||||
&format!("{prefix}/vulkaninfo.txt"),
|
||||
@@ -95,6 +67,11 @@ pub fn bundle(vm: &Vm, host: Host) -> Result<PathBuf> {
|
||||
.as_bytes(),
|
||||
)?;
|
||||
}
|
||||
// Before the logs are read, so that QEMU's ends with the counts as of the report.
|
||||
let state = match runtime::pid(vm) {
|
||||
Some(p) => format!("running, pid {p}\n{}\n", ask_counts(&vm.qmp_socket())),
|
||||
None => "stopped\n".to_string(),
|
||||
};
|
||||
zip.add(&format!("{prefix}/state.txt"), state.as_bytes())?;
|
||||
if let Ok(rd) = std::fs::read_dir(vm.logs_dir()) {
|
||||
let mut files: Vec<PathBuf> = rd
|
||||
@@ -116,157 +93,21 @@ pub fn bundle(vm: &Vm, host: Host) -> Result<PathBuf> {
|
||||
}
|
||||
|
||||
/// Asks the VM on QMP's `socket` to write its library's degradation counts into its QEMU log now
|
||||
/// (reims-graphics-pci's [`COUNTS_PROPERTY`]), with its build and, at an ask 2 to 60 s after
|
||||
/// another, its pacing line. A VM on VMware SVGA has no such property, and QMP says so.
|
||||
fn ask(socket: &Path) -> Result<()> {
|
||||
let mut qmp = crate::qmp::Qmp::connect(socket, COUNTS_WAIT)?;
|
||||
let set = json!({ "path": DISPLAY_PATH, "property": COUNTS_PROPERTY, "value": true });
|
||||
qmp.execute("qom-set", Some(set)).map(drop)
|
||||
}
|
||||
|
||||
/// [`ask`]s once: state.txt's line that says whether the library wrote its counts.
|
||||
/// (reims-graphics-pci's [`COUNTS_PROPERTY`]): state.txt's line that says whether it did. A VM
|
||||
/// on VMware SVGA has no such property, and QMP says so.
|
||||
fn ask_counts(socket: &Path) -> String {
|
||||
match ask(socket) {
|
||||
Ok(()) => "degradation counts: the library wrote them into logs/qemu.log for this report, \
|
||||
where it had counted any"
|
||||
let asked = crate::qmp::Qmp::connect(socket, COUNTS_WAIT).and_then(|mut qmp| {
|
||||
let set = json!({ "path": DISPLAY_PATH, "property": COUNTS_PROPERTY, "value": true });
|
||||
qmp.execute("qom-set", Some(set))
|
||||
});
|
||||
match asked {
|
||||
Ok(_) => "degradation counts: the library wrote them into logs/qemu.log for this report, \
|
||||
where it had counted any"
|
||||
.to_string(),
|
||||
Err(e) => format!("degradation counts: not written for this report: {e:#}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ask`]s twice, `apart` apart, so the library writes its pacing line over the span between
|
||||
/// the two at the second: state.txt's lines that say whether it did. Where the first ask fails,
|
||||
/// the second is not made.
|
||||
fn ask_pacing(socket: &Path, apart: Duration) -> String {
|
||||
let first = Instant::now();
|
||||
if let Err(e) = ask(socket) {
|
||||
return format!("degradation counts: not written for this report: {e:#}");
|
||||
}
|
||||
std::thread::sleep(apart.saturating_sub(first.elapsed()));
|
||||
let counts = ask_counts(socket);
|
||||
let pacing = if counts.contains("not written") {
|
||||
"pacing: not written for this report".to_string()
|
||||
} else {
|
||||
format!(
|
||||
"pacing: the library wrote its line over the {} s between two asks into \
|
||||
logs/qemu.log, where its build writes one",
|
||||
apart.as_secs()
|
||||
)
|
||||
};
|
||||
format!("{counts}\n{pacing}")
|
||||
}
|
||||
|
||||
/// state.txt's lines for a VM that is not running, whose QEMU log ends with `log`: why it
|
||||
/// stopped ([`runtime::stopped`]), and whether the library's degradation counts in the log are as
|
||||
/// of the run's end, which they are where QEMU exited, as the library writes them at the
|
||||
/// process's exit; where it was killed, crashed or a fatal error ended it, the log's last are
|
||||
/// from earlier in the run, or there are none. Only "stopped" for a run whose end its log does
|
||||
/// not tell (an earlier reims-ctl's start).
|
||||
fn stopped_state(log: &str) -> String {
|
||||
let Some(s) = runtime::stopped(log) else {
|
||||
return "stopped\n".to_string();
|
||||
};
|
||||
let counted = runtime::last_run_has(log, COUNTS_LINE);
|
||||
let counts = match (s.exited, counted) {
|
||||
(true, _) => {
|
||||
"degradation counts: as of the run's end: the library writes them into logs/qemu.log \
|
||||
as QEMU exits, where it had counted any"
|
||||
}
|
||||
(false, true) => {
|
||||
"degradation counts: not as of the run's end, which wrote none: logs/qemu.log's last \
|
||||
are from earlier in the run"
|
||||
}
|
||||
(false, false) => {
|
||||
"degradation counts: none in logs/qemu.log from this run, whose end wrote none"
|
||||
}
|
||||
};
|
||||
format!("stopped: {}\n{counts}\n", s.why)
|
||||
}
|
||||
|
||||
/// How the library's line of its degradation counts starts (docs/conventions.md).
|
||||
const COUNTS_LINE: &str = "reims-vgpu: degradation counts: ";
|
||||
|
||||
/// The library's build as a VM's QEMU log names it ([`library_build`]): the commit it was built
|
||||
/// from and the metal2vulkan commit it was built on.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct LibraryBuild {
|
||||
commit: String,
|
||||
pin: String,
|
||||
/// Whether a report's ask wrote it, rather than the device's start.
|
||||
asked: bool,
|
||||
}
|
||||
|
||||
/// The library's build as a VM's QEMU log `log` names it last: from the line a report's ask writes
|
||||
/// (`reims-vgpu: build <commit> on metal2vulkan <pin>`) or the one its device writes as it starts
|
||||
/// (`reims-vgpu <commit> on metal2vulkan <pin>; …`), whichever is later.
|
||||
fn library_build(log: &str) -> Option<LibraryBuild> {
|
||||
log.lines().rev().find_map(|line| {
|
||||
let (before, after) = line.split_once(" on metal2vulkan ")?;
|
||||
let (lead, commit) = before.rsplit_once(' ')?;
|
||||
let asked = lead.ends_with("reims-vgpu: build");
|
||||
if !asked && !lead.ends_with("reims-vgpu") {
|
||||
return None;
|
||||
}
|
||||
let pin = after.split([';', ' ']).next()?.trim();
|
||||
(!commit.is_empty() && !pin.is_empty()).then(|| LibraryBuild {
|
||||
commit: commit.to_string(),
|
||||
pin: pin.to_string(),
|
||||
asked,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The commit a build stamp names (`build_stamp.rs`), without its dirty mark; `None` for
|
||||
/// `unknown`.
|
||||
fn commit_of(stamp: &str) -> Option<&str> {
|
||||
let commit = stamp.trim();
|
||||
let commit = commit.strip_suffix("-dirty").unwrap_or(commit);
|
||||
(!commit.is_empty() && commit != "unknown").then_some(commit)
|
||||
}
|
||||
|
||||
/// The head of system.txt's reims-ctl section: reims-ctl's build `ctl` (its stamp, `-dirty`
|
||||
/// where its checkout had local changes, `unknown` outside one), the VM's library's `library` as
|
||||
/// its QEMU log names it, with the metal2vulkan commit it was built on, and the commit of the
|
||||
/// install record, `install`, where there is one. Where the commits of those known differ (a
|
||||
/// short commit matching a long one it begins), a first line says so: a reims-ctl or a QEMU from
|
||||
/// another build than the install's is itself the answer to many reports.
|
||||
fn builds(ctl: &str, library: Option<&LibraryBuild>, install: Option<&str>) -> String {
|
||||
let mut known: Vec<(&str, &str)> = Vec::new();
|
||||
if let Some(c) = commit_of(ctl) {
|
||||
known.push(("reims-ctl", c));
|
||||
}
|
||||
if let Some(c) = library.and_then(|l| commit_of(&l.commit)) {
|
||||
known.push(("the VM's library", c));
|
||||
}
|
||||
if let Some(c) = install.and_then(commit_of) {
|
||||
known.push(("the install record", c));
|
||||
}
|
||||
let same = |a: &str, b: &str| a.starts_with(b) || b.starts_with(a);
|
||||
let differ = known
|
||||
.iter()
|
||||
.any(|(_, a)| known.iter().any(|(_, b)| !same(a, b)));
|
||||
let mut s = String::new();
|
||||
if differ {
|
||||
let names: Vec<String> = known.iter().map(|(n, c)| format!("{n} {c}")).collect();
|
||||
s.push_str(&format!("builds differ: {}\n", names.join(", ")));
|
||||
}
|
||||
s.push_str(&format!("build {ctl}\n"));
|
||||
match library {
|
||||
Some(l) => s.push_str(&format!(
|
||||
"library build {} on metal2vulkan {} ({})\n",
|
||||
l.commit,
|
||||
l.pin,
|
||||
if l.asked {
|
||||
"the running VM's, at this report's ask"
|
||||
} else {
|
||||
"the VM's last start, in logs/qemu.log"
|
||||
}
|
||||
)),
|
||||
None => s.push_str("library build: not in logs/qemu.log\n"),
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn read_tail(p: &Path, cap: u64) -> Result<Vec<u8>> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut f = std::fs::File::open(p)?;
|
||||
@@ -522,39 +363,18 @@ fn vulkan_gpus(gpus: &[GpuInfo]) -> String {
|
||||
/// What the host is: the parts a report about a guest's graphics needs.
|
||||
/// What the host is, and `warnings`, the ones reims-ctl gives the VM as the report is made: what
|
||||
/// its user was shown. `vulkaninfo` is how the run of vulkaninfo's whole report ended
|
||||
/// ([`vulkan_summary`]); `library` the VM's library's build as its QEMU log names it. The head
|
||||
/// names the builds and says where they differ ([`builds`]).
|
||||
fn system_info(
|
||||
host: Host,
|
||||
warnings: &[String],
|
||||
vulkaninfo: &End,
|
||||
library: Option<&LibraryBuild>,
|
||||
) -> String {
|
||||
let (install, unread) = match crate::install::Install::load() {
|
||||
Ok(install) => (install, None),
|
||||
Err(e) => (None, Some(format!("{e:#}"))),
|
||||
};
|
||||
/// ([`vulkan_summary`]).
|
||||
fn system_info(host: Host, warnings: &[String], vulkaninfo: &End) -> String {
|
||||
let mut s = String::new();
|
||||
let mut section = |title: &str, body: String| {
|
||||
s.push_str(&format!("== {title}\n{body}\n\n"));
|
||||
};
|
||||
section(
|
||||
"reims-ctl",
|
||||
format!(
|
||||
"version {}\n{}host {host}",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
builds(
|
||||
env!("REIMS_CTL_STAMP"),
|
||||
library,
|
||||
install.as_ref().map(|i| i.commit.as_str())
|
||||
)
|
||||
),
|
||||
format!("version {}\nhost {host}", env!("CARGO_PKG_VERSION")),
|
||||
);
|
||||
section("warnings", warnings_list(warnings));
|
||||
if let Some(why) = unread {
|
||||
section("install", why);
|
||||
}
|
||||
if let Some(i) = install {
|
||||
if let Some(i) = crate::install::Install::load() {
|
||||
section(
|
||||
"install",
|
||||
format!(
|
||||
@@ -800,47 +620,6 @@ mod tests {
|
||||
seen
|
||||
}
|
||||
|
||||
/// A stopped VM's state.txt says why it stopped, and whether the degradation counts in its
|
||||
/// QEMU log are as of the run's end: they are where QEMU exited, as the library writes them
|
||||
/// at its exit; where QEMU was killed or crashed, the log's last are from earlier in the run,
|
||||
/// or there are none. A run whose end its log does not tell says "stopped" alone.
|
||||
#[test]
|
||||
fn a_stopped_vms_state_says_whether_its_counts_are_as_of_its_end() {
|
||||
let run = |trace: &str, lines: &str| {
|
||||
format!(
|
||||
"reims-ctl 0.1.0 started t at 2026-12-02 11:00:00 -0800\n#!/bin/sh\n\
|
||||
exec qemu-system-x86_64 \\\n -name t{trace}\n----\n{lines}"
|
||||
)
|
||||
};
|
||||
let traced = " \\\n -trace qemu_system_shutdown_request";
|
||||
let counts = "reims-vgpu: degradation counts: rt-refused-x 2\n";
|
||||
let shut = format!("{counts}qemu_system_shutdown_request reason=6\n{counts}");
|
||||
assert_eq!(
|
||||
stopped_state(&run(traced, &shut)),
|
||||
"stopped: its guest shut down\n\
|
||||
degradation counts: as of the run's end: the library writes them into \
|
||||
logs/qemu.log as QEMU exits, where it had counted any\n"
|
||||
);
|
||||
let killed = "stopped: QEMU ended without shutting it down, as it does when killed or when it \
|
||||
crashes\n";
|
||||
assert_eq!(
|
||||
stopped_state(&run(traced, counts)),
|
||||
format!(
|
||||
"{killed}degradation counts: not as of the run's end, which wrote none: \
|
||||
logs/qemu.log's last are from earlier in the run\n"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
stopped_state(&run(traced, "")),
|
||||
format!(
|
||||
"{killed}degradation counts: none in logs/qemu.log from this run, whose end \
|
||||
wrote none\n"
|
||||
)
|
||||
);
|
||||
assert_eq!(stopped_state(&run("", counts)), "stopped\n");
|
||||
assert_eq!(stopped_state(""), "stopped\n");
|
||||
}
|
||||
|
||||
/// A running VM is asked to write its library's degradation counts with a qom-set of its
|
||||
/// display device's x-write-counts property, and state.txt's line says whether it did: a
|
||||
/// refusal, as a VM on VMware SVGA answers, and a socket nothing listens on say why not
|
||||
@@ -894,121 +673,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A running VM is asked twice, the span apart, so its library writes its pacing line over
|
||||
/// the span at the second ask; a VM whose first ask fails is asked no more.
|
||||
#[test]
|
||||
fn a_running_vm_is_asked_twice_for_its_pacing() {
|
||||
let env = crate::testenv::Env::new("report-pacing");
|
||||
let socket = |name: &str| {
|
||||
let runtime = crate::paths::runtime_dir();
|
||||
let short = crate::paths::short_runtime_dir();
|
||||
let name = format!("report-pacing-{name}-{}", std::process::id());
|
||||
let s = crate::vm::qmp_socket_in(&env.root.join(&name), &name, &runtime, &short);
|
||||
std::fs::create_dir_all(s.parent().unwrap()).unwrap();
|
||||
let _ = std::fs::remove_file(&s);
|
||||
s
|
||||
};
|
||||
let (written, refused) = (socket("written"), socket("refused"));
|
||||
let asked = fake_qmp(&written, "{\"return\": {}}");
|
||||
let no = "{\"error\": {\"class\": \"GenericError\", \
|
||||
\"desc\": \"Property 'vmware-svga.x-write-counts' not found\"}}";
|
||||
let refusals = fake_qmp(&refused, no);
|
||||
let apart = Duration::from_millis(300);
|
||||
let started = Instant::now();
|
||||
let wrote = ask_pacing(&written, apart);
|
||||
assert!(started.elapsed() >= apart);
|
||||
let not = ask_pacing(&refused, apart);
|
||||
for s in [&written, &refused] {
|
||||
let _ = std::fs::remove_file(s);
|
||||
}
|
||||
assert_eq!(asked.lock().unwrap().len(), 2);
|
||||
assert_eq!(refusals.lock().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
wrote,
|
||||
"degradation counts: the library wrote them into logs/qemu.log for this report, where \
|
||||
it had counted any\npacing: the library wrote its line over the 0 s between two asks \
|
||||
into logs/qemu.log, where its build writes one"
|
||||
);
|
||||
assert_eq!(
|
||||
not,
|
||||
"degradation counts: not written for this report: QMP qom-set: Property \
|
||||
'vmware-svga.x-write-counts' not found"
|
||||
);
|
||||
}
|
||||
|
||||
/// The library's build is the last a QEMU log names: a report's ask's line, or the line its
|
||||
/// device writes as it starts, in the library's log format; none where the log names none.
|
||||
#[test]
|
||||
fn the_library_s_build_is_the_last_the_log_names() {
|
||||
let start = "reims-vgpu WARN reims_vgpu_vulkan::rt_platform::device: reims-vgpu \
|
||||
3731afd9b1aa-dirty on metal2vulkan 0b0ac58eb0f6; rt's Shared memory: type 2, \
|
||||
HOST_VISIBLE";
|
||||
let ask = "reims-vgpu: build 41f0bba449cc on metal2vulkan 0b0ac58eb0f6";
|
||||
let started = LibraryBuild {
|
||||
commit: "3731afd9b1aa-dirty".into(),
|
||||
pin: "0b0ac58eb0f6".into(),
|
||||
asked: false,
|
||||
};
|
||||
let at_ask = LibraryBuild {
|
||||
commit: "41f0bba449cc".into(),
|
||||
pin: "0b0ac58eb0f6".into(),
|
||||
asked: true,
|
||||
};
|
||||
assert_eq!(
|
||||
library_build(&format!("qemu\n{start}\nmore\n")),
|
||||
Some(started.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
library_build(&format!("{start}\n{ask}\n")),
|
||||
Some(at_ask.clone())
|
||||
);
|
||||
assert_eq!(library_build(&format!("{ask}\n{start}\n")), Some(started));
|
||||
assert_eq!(
|
||||
library_build("qemu-system-x86_64: on metal2vulkan nothing\n"),
|
||||
None
|
||||
);
|
||||
assert_eq!(library_build(""), None);
|
||||
}
|
||||
|
||||
/// system.txt's head: reims-ctl's stamp, dirty or unknown as built, the library's build, and
|
||||
/// a first line where the commits known differ, a short commit matching a long one it begins.
|
||||
#[test]
|
||||
fn the_head_names_the_builds_and_says_where_they_differ() {
|
||||
let library = |commit: &str| LibraryBuild {
|
||||
commit: commit.into(),
|
||||
pin: "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699".into(),
|
||||
asked: true,
|
||||
};
|
||||
let long = "41f0bba449c1e1f1b2e5d3c4a5b6c7d8e9f00112";
|
||||
// Stamped: one commit, long and short.
|
||||
assert_eq!(
|
||||
builds(long, Some(&library(long)), Some("41f0bba449")),
|
||||
format!(
|
||||
"build {long}\nlibrary build {long} on metal2vulkan \
|
||||
0b0ac58eb0f69ed3b37007fbdf3b135a46f90699 (the running VM's, at this report's \
|
||||
ask)\n"
|
||||
)
|
||||
);
|
||||
// Dirty: the same commit, so no line says they differ.
|
||||
let dirty = format!("{long}-dirty");
|
||||
let head = builds(&dirty, Some(&library(&dirty)), Some("41f0bba449"));
|
||||
assert!(head.starts_with(&format!("build {dirty}\n")), "{head}");
|
||||
// Unknown: a build outside a checkout is compared with nothing.
|
||||
let head = builds("unknown", None, Some("3731afd9b1"));
|
||||
assert_eq!(head, "build unknown\nlibrary build: not in logs/qemu.log\n");
|
||||
// Mismatch: the VM's library is another commit's.
|
||||
let head = builds(long, Some(&library("3731afd9b1aa")), Some("41f0bba449"));
|
||||
assert!(
|
||||
head.starts_with(&format!(
|
||||
"builds differ: reims-ctl {long}, the VM's library 3731afd9b1aa, the install \
|
||||
record 41f0bba449\nbuild {long}\n"
|
||||
)),
|
||||
"{head}"
|
||||
);
|
||||
let head = builds(long, None, Some("3731afd9b1"));
|
||||
assert!(head.starts_with("builds differ: reims-ctl"), "{head}");
|
||||
}
|
||||
|
||||
/// system.txt's Vulkan GPUs: each GPU's label, IDs and manifest on a line, and below it its
|
||||
/// driver's version raw, with the driver's own name and text where it says them, as a
|
||||
/// Vulkan 1.2 driver does; `none` where no probe found a GPU.
|
||||
@@ -1027,8 +691,6 @@ mod tests {
|
||||
driver_version: version,
|
||||
driver_name: String::new(),
|
||||
driver_info: String::new(),
|
||||
pci: None,
|
||||
twin: false,
|
||||
};
|
||||
let uhd = GpuInfo {
|
||||
driver_id: 5,
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
//! command it opens its interactive interface.
|
||||
|
||||
mod ambrosia;
|
||||
#[cfg(test)]
|
||||
mod build_stamp;
|
||||
mod cli;
|
||||
mod copy;
|
||||
mod create;
|
||||
@@ -23,14 +21,11 @@ mod opencore;
|
||||
mod os;
|
||||
mod paths;
|
||||
mod prebuilt;
|
||||
mod processor;
|
||||
mod qemu;
|
||||
mod qmp;
|
||||
mod record;
|
||||
mod reims_util;
|
||||
mod restore;
|
||||
mod runtime;
|
||||
mod snapshot;
|
||||
#[cfg(test)]
|
||||
mod testenv;
|
||||
mod tui;
|
||||
@@ -43,7 +38,6 @@ use clap::Parser;
|
||||
|
||||
fn main() {
|
||||
quiet_on_closed_stdout();
|
||||
update::note_binary();
|
||||
let cli = cli::Cli::parse();
|
||||
match cli::main(cli) {
|
||||
Ok(code) => std::process::exit(code),
|
||||
|
||||
+18
-128
@@ -79,31 +79,18 @@ fn state_file() -> PathBuf {
|
||||
paths::config_dir().join("migrations.toml")
|
||||
}
|
||||
|
||||
/// The migrations' record: none run where there is no file. An error where there is one this
|
||||
/// build can't read, or can't read as the record: taken for none run, every migration would run
|
||||
/// again on each VM, at every run, since its save is refused over the file
|
||||
/// ([`crate::record::old_text`]).
|
||||
fn load() -> Result<State> {
|
||||
let file = state_file();
|
||||
match std::fs::read_to_string(&file) {
|
||||
Ok(text) => toml::from_str(&text).with_context(|| format!("parse {}", file.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(State::default()),
|
||||
Err(e) => Err(e).with_context(|| format!("read {}", file.display())),
|
||||
}
|
||||
fn load() -> State {
|
||||
std::fs::read_to_string(state_file())
|
||||
.ok()
|
||||
.and_then(|t| toml::from_str(&t).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Writes `state` over its file as it is, keeping what another build of reims-ctl wrote there in
|
||||
/// its place and form ([`crate::record::text_over`]); refused, with the file left as it is, where
|
||||
/// this build can't read it or keep what it holds ([`crate::record::Refused`]).
|
||||
fn save(state: &State) -> Result<()> {
|
||||
let file = state_file();
|
||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
||||
let tmp = file.with_extension("toml.tmp");
|
||||
let old = crate::record::old_text(&file)?;
|
||||
std::fs::write(
|
||||
&tmp,
|
||||
crate::record::text_over(state, &file, old.as_deref(), &[])?,
|
||||
)?;
|
||||
std::fs::write(&tmp, toml::to_string_pretty(state)?)?;
|
||||
std::fs::rename(&tmp, &file).with_context(|| format!("write {}", file.display()))
|
||||
}
|
||||
|
||||
@@ -310,16 +297,12 @@ fn plan_of(n: u32, vm: &Vm, running: bool) -> Plan {
|
||||
/// Runs the migrations this reims-ctl carries that have not run, on every VM in the registry,
|
||||
/// telling `say` what each did. Where none has run yet and there are VMs, the first line says the
|
||||
/// update worked. A record that can't be written is told, and the migrations run again next time.
|
||||
/// One that can't be read is told, and none runs until it can be.
|
||||
pub fn run(say: &mut dyn FnMut(&str)) {
|
||||
if load().is_ok_and(|state| state.done >= CURRENT) {
|
||||
if load().done >= CURRENT {
|
||||
return;
|
||||
}
|
||||
let Some(_lock) = lock() else { return };
|
||||
let mut state = match load() {
|
||||
Ok(state) => state,
|
||||
Err(e) => return say(&format!("reims-ctl's update of its VMs waits: {e:#}")),
|
||||
};
|
||||
let mut state = load();
|
||||
if state.done >= CURRENT {
|
||||
return;
|
||||
}
|
||||
@@ -343,9 +326,7 @@ pub fn run(say: &mut dyn FnMut(&str)) {
|
||||
// A VM that waited for its start since an earlier update still has every migration to run.
|
||||
let waited = state.deferred.iter().any(|d| same_dir(d, &vm.dir));
|
||||
let first = if waited { 1 } else { state.done + 1 };
|
||||
// A VM whose restore was cut off part way waits too, as one that runs: its files change
|
||||
// only as that restore, run again, finishes.
|
||||
let running = runtime::running(&vm) || crate::snapshot::cut_off(&vm).is_some();
|
||||
let running = runtime::running(&vm);
|
||||
let mut defer = false;
|
||||
for n in first..=CURRENT {
|
||||
let p = plan_of(n, &vm, running);
|
||||
@@ -375,35 +356,13 @@ pub fn run(say: &mut dyn FnMut(&str)) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The last migration run: the level a VM's snapshot records ([`crate::snapshot`]). An error,
|
||||
/// naming the record, where it can't be read ([`load`]): a snapshot taken then would record a
|
||||
/// level that isn't known, so a snapshot waits until it can be read.
|
||||
pub fn level() -> Result<u32> {
|
||||
load().map(|state| state.done)
|
||||
}
|
||||
|
||||
/// Has the migrations run again on the VM in `dir` at its next start ([`at_start`]): its
|
||||
/// snapshot, restored, is of an older level, from before some of them ran. An error where that
|
||||
/// can't be recorded: the migrations' lock can't be taken, or their record read or written.
|
||||
pub fn defer(dir: &Path) -> Result<()> {
|
||||
let _lock = lock().context("reims-ctl's migrations lock can't be taken")?;
|
||||
let mut state = load()?;
|
||||
if !state.deferred.iter().any(|d| same_dir(d, dir)) {
|
||||
state.deferred.push(dir.to_path_buf());
|
||||
save(&state)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// At a start of a stopped VM, a migration that waited while it ran, now, telling `progress`.
|
||||
/// None where the migrations' record can't be read, which [`run`] tells.
|
||||
pub fn at_start(vm: &mut Vm, progress: &mut dyn FnMut(&str)) {
|
||||
let deferred = |state: State| state.deferred.iter().any(|d| same_dir(d, &vm.dir));
|
||||
if !load().is_ok_and(deferred) {
|
||||
if !load().deferred.iter().any(|d| same_dir(d, &vm.dir)) {
|
||||
return;
|
||||
}
|
||||
let Some(_lock) = lock() else { return };
|
||||
let Ok(mut state) = load() else { return };
|
||||
let mut state = load();
|
||||
let before = state.deferred.len();
|
||||
state.deferred.retain(|d| !same_dir(d, &vm.dir));
|
||||
if state.deferred.len() == before || save(&state).is_err() {
|
||||
@@ -668,42 +627,6 @@ mod tests {
|
||||
env.set("REIMS_CTL_UTIL", &util);
|
||||
}
|
||||
|
||||
/// The migrations' save over a record this build can't read, as one that isn't UTF-8 or that
|
||||
/// its mode keeps from the user, is refused, naming the file, and leaves the file byte for
|
||||
/// byte.
|
||||
#[test]
|
||||
fn the_migrations_save_over_a_record_this_build_cannot_read_leaves_it() {
|
||||
let _env = crate::testenv::Env::new("unreadable-migrations");
|
||||
let state = State {
|
||||
done: CURRENT,
|
||||
deferred: vec![],
|
||||
};
|
||||
crate::record::assert_unreadable_refused(&state_file(), &|| save(&state));
|
||||
}
|
||||
|
||||
/// A migrations' record this build can't read, one that isn't UTF-8 or that isn't the record
|
||||
/// (a `done` that isn't a number), is not taken for none run: no migration runs, the run says
|
||||
/// why, naming the file, and the record is left byte for byte.
|
||||
#[test]
|
||||
fn a_migrations_record_this_build_cannot_read_runs_none() {
|
||||
let _env = crate::testenv::Env::new("unreadable-migrations-run");
|
||||
let file = state_file();
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let held: [&[u8]; 2] = [b"done = \"\xff\"\n", b"done = \"six\"\n"];
|
||||
for held in held {
|
||||
std::fs::write(&file, held).unwrap();
|
||||
let mut said = Vec::new();
|
||||
run(&mut |s| said.push(s.to_string()));
|
||||
assert_eq!(said.len(), 1, "{said:?}");
|
||||
assert!(
|
||||
said[0].starts_with("reims-ctl's update of its VMs waits: "),
|
||||
"{said:?}"
|
||||
);
|
||||
assert!(said[0].contains("migrations.toml"), "{said:?}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), held);
|
||||
}
|
||||
}
|
||||
|
||||
/// Migration 1 is for an x86-64 VM whose settings name no graphics, stopped; one whose
|
||||
/// settings name graphics, as its user chose (apple-gfx among them, migration 3's), is left
|
||||
/// be.
|
||||
@@ -946,7 +869,7 @@ mod tests {
|
||||
.exists()
|
||||
);
|
||||
assert!(!env.root.join("fresh/opencore.img.pre-migration-2").exists());
|
||||
assert_eq!(load().unwrap().done, CURRENT);
|
||||
assert_eq!(load().done, CURRENT);
|
||||
let mut said = Vec::new();
|
||||
run(&mut |s| said.push(s.to_string()));
|
||||
assert!(said.is_empty(), "{said:?}");
|
||||
@@ -999,33 +922,6 @@ mod tests {
|
||||
assert_eq!(plan_of(3, &Vm::load(&dir).unwrap(), false), Plan::Skip);
|
||||
}
|
||||
|
||||
/// The migrations' record keeps what a newer reims-ctl wrote into it: a key of its own and a
|
||||
/// table of its own stay as written, byte for byte, as the last migration run changes, whose
|
||||
/// line is all that changes.
|
||||
#[test]
|
||||
fn the_migrations_record_keeps_what_a_newer_build_wrote() {
|
||||
let env = crate::testenv::Env::new("newer-migrations");
|
||||
save(&State {
|
||||
done: 3,
|
||||
deferred: vec![env.root.join("vms/a")],
|
||||
})
|
||||
.unwrap();
|
||||
let file = state_file();
|
||||
let ours = std::fs::read_to_string(&file).unwrap();
|
||||
let newer = ours.replacen("done = 3\n", "done = 3\nstarted = \"2026-12-03\"\n", 1)
|
||||
+ "\n[notes]\nskipped = [\"b\"]\n";
|
||||
assert!(newer.contains("started = "), "{newer}");
|
||||
std::fs::write(&file, &newer).unwrap();
|
||||
let mut state = load().unwrap();
|
||||
assert_eq!(state.done, 3);
|
||||
state.done = 4;
|
||||
save(&state).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&file).unwrap(),
|
||||
newer.replacen("done = 3\n", "done = 4\n", 1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_4_finds_each_legacy_component_for_every_graphics_choice() {
|
||||
let env = crate::testenv::Env::new("migrate-graft-plan");
|
||||
@@ -1177,15 +1073,15 @@ mod tests {
|
||||
said.iter().any(|line| line.starts_with("busy is running")),
|
||||
"{said:?}"
|
||||
);
|
||||
assert_eq!(load().unwrap().deferred, vec![dir.clone()]);
|
||||
assert_eq!(load().unwrap().done, CURRENT);
|
||||
assert_eq!(load().deferred, vec![dir.clone()]);
|
||||
assert_eq!(load().done, CURRENT);
|
||||
assert_eq!(std::fs::read(dir.join("opencore.img")).unwrap(), before);
|
||||
assert!(!args.exists());
|
||||
process.kill().unwrap();
|
||||
process.wait().unwrap();
|
||||
std::fs::remove_file(pidfile).unwrap();
|
||||
at_start(&mut v, &mut |_| {});
|
||||
assert!(load().unwrap().deferred.is_empty());
|
||||
assert!(load().deferred.is_empty());
|
||||
assert_eq!(plan_of(4, &v, false), Plan::Skip);
|
||||
assert!(dir.join("opencore.img.pre-migration-4").exists());
|
||||
assert!(
|
||||
@@ -1220,8 +1116,6 @@ mod tests {
|
||||
driver_version: 0,
|
||||
driver_name: String::new(),
|
||||
driver_info: String::new(),
|
||||
pci: None,
|
||||
twin: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1278,7 +1172,6 @@ mod tests {
|
||||
driver_file: Some(NVIDIA.into()),
|
||||
device_id: None,
|
||||
select: Some("10de:2204".into()),
|
||||
pci: None,
|
||||
name: Some("NVIDIA GeForce RTX 3090".into()),
|
||||
};
|
||||
assert_eq!(plan, Plan::Gpu(want.clone()));
|
||||
@@ -1306,7 +1199,6 @@ mod tests {
|
||||
driver_file: Some(RADEON.into()),
|
||||
device_id: Some(0x744c),
|
||||
select: Some("1002:744c".into()),
|
||||
pci: None,
|
||||
name: Some("AMD Radeon RX 7900 XTX (RADV NAVI31)".into()),
|
||||
})
|
||||
);
|
||||
@@ -1421,7 +1313,6 @@ mod tests {
|
||||
driver_file: Some(NV.into()),
|
||||
device_id: None,
|
||||
select: Some("10de:1f95".into()),
|
||||
pci: None,
|
||||
name: Some(GTX.into()),
|
||||
};
|
||||
assert_eq!(plan, Plan::Gpu(want.clone()));
|
||||
@@ -1458,7 +1349,6 @@ mod tests {
|
||||
driver_file: Some(INTEL.into()),
|
||||
device_id: Some(0x1f95),
|
||||
select: Some("10de:1f95".into()),
|
||||
pci: None,
|
||||
name: Some(GTX.into()),
|
||||
})
|
||||
);
|
||||
@@ -1509,7 +1399,7 @@ mod tests {
|
||||
let mut said = Vec::new();
|
||||
run(&mut |s| said.push(s.to_string()));
|
||||
assert!(said.is_empty(), "{said:?}");
|
||||
assert_eq!(load().unwrap().done, CURRENT);
|
||||
assert_eq!(load().done, CURRENT);
|
||||
let _ = std::fs::remove_file(state_file());
|
||||
|
||||
// Three VMs: two whose settings name no graphics, one of them running, and one its user
|
||||
@@ -1545,7 +1435,7 @@ mod tests {
|
||||
"{said:?}"
|
||||
);
|
||||
assert!(!said.iter().any(|s| s.starts_with("chosen")), "{said:?}");
|
||||
let state = load().unwrap();
|
||||
let state = load();
|
||||
assert_eq!(state.done, CURRENT);
|
||||
assert_eq!(state.deferred, vec![env.root.join("busy")]);
|
||||
let mut said = Vec::new();
|
||||
@@ -1564,7 +1454,7 @@ mod tests {
|
||||
said[0].starts_with("on reims-vgpu's own GPU device"),
|
||||
"{said:?}"
|
||||
);
|
||||
assert!(load().unwrap().deferred.is_empty());
|
||||
assert!(load().deferred.is_empty());
|
||||
let mut said = Vec::new();
|
||||
at_start(&mut v, &mut |s| said.push(s.to_string()));
|
||||
assert!(said.is_empty(), "{said:?}");
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -60,25 +60,6 @@ pub fn local_now() -> super::LocalTime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this process's security session reaches the window server, where a window can open:
|
||||
/// a signed-in user's session does, and an SSH login's does not. Security's `SessionGetInfo` for
|
||||
/// the caller's session, its `sessionHasGraphicAccess` bit (the SDK's AuthSession.h).
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn session_has_graphics() -> bool {
|
||||
#[link(name = "Security", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn SessionGetInfo(session: u32, session_id: *mut u32, attributes: *mut u32) -> i32;
|
||||
}
|
||||
/// `callerSecuritySession`: the session of the process that asks.
|
||||
const CALLER_SESSION: u32 = u32::MAX;
|
||||
/// `sessionHasGraphicAccess`.
|
||||
const GRAPHIC_ACCESS: u32 = 0x0010;
|
||||
let (mut id, mut attributes) = (0u32, 0u32);
|
||||
// SAFETY: both pointers are to locals, which the call writes.
|
||||
let status = unsafe { SessionGetInfo(CALLER_SESSION, &mut id, &mut attributes) };
|
||||
status == 0 && attributes & GRAPHIC_ACCESS != 0
|
||||
}
|
||||
|
||||
/// The host's RAM in MiB, where the host says.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn memory_mib() -> Option<u64> {
|
||||
@@ -136,22 +117,15 @@ pub fn uid() -> u32 {
|
||||
unsafe { libc::getuid() }
|
||||
}
|
||||
|
||||
/// What tells the file `m` describes, at `_path`, from another put there since: its device and
|
||||
/// inode, which a new file has its own of.
|
||||
pub fn file_id(_path: &Path, m: &std::fs::Metadata) -> Option<(u64, u64)> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
Some((m.dev(), m.ino()))
|
||||
}
|
||||
|
||||
/// The group that owns the file `m` describes.
|
||||
pub fn gid(m: &std::fs::Metadata) -> Option<u32> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
Some(m.gid())
|
||||
}
|
||||
|
||||
/// When the inode of the file `m` describes, at `_path`, last changed (its ctime): any write to
|
||||
/// the file, or change of its times, sets it to the present, and no program can set it otherwise.
|
||||
pub fn changed(_path: &Path, m: &std::fs::Metadata) -> Option<std::time::SystemTime> {
|
||||
/// When the inode of the file `m` describes last changed (its ctime): any write to the file, or
|
||||
/// change of its times, sets it to the present, and no program can set it otherwise.
|
||||
pub fn changed(m: &std::fs::Metadata) -> Option<std::time::SystemTime> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let secs = u64::try_from(m.ctime()).ok()?;
|
||||
let nanos = u32::try_from(m.ctime_nsec()).ok()?;
|
||||
@@ -449,105 +423,6 @@ pub fn allocated(m: &std::fs::Metadata) -> u64 {
|
||||
m.blocks() * 512
|
||||
}
|
||||
|
||||
/// The bytes of the file at `p` that no other file shares, as the file system counts its
|
||||
/// reflinks: the extents FIEMAP does not mark shared, as btrfs and XFS mark them (on a file
|
||||
/// system that makes no reflinks, all of them); None where it answers no FIEMAP (tmpfs).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn private_bytes(p: &Path) -> Option<u64> {
|
||||
use std::os::fd::AsRawFd;
|
||||
/// struct fiemap and struct fiemap_extent (linux/fiemap.h).
|
||||
#[repr(C)]
|
||||
struct Fiemap {
|
||||
start: u64,
|
||||
length: u64,
|
||||
flags: u32,
|
||||
mapped: u32,
|
||||
count: u32,
|
||||
reserved: u32,
|
||||
extents: [Extent; 256],
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Extent {
|
||||
logical: u64,
|
||||
physical: u64,
|
||||
length: u64,
|
||||
reserved64: [u64; 2],
|
||||
flags: u32,
|
||||
reserved: [u32; 3],
|
||||
}
|
||||
/// _IOWR('f', 11, struct fiemap), the header of 32 bytes.
|
||||
const FS_IOC_FIEMAP: u64 = 0xc020_660b;
|
||||
const FIEMAP_FLAG_SYNC: u32 = 1;
|
||||
const FIEMAP_EXTENT_LAST: u32 = 1;
|
||||
const FIEMAP_EXTENT_SHARED: u32 = 0x2000;
|
||||
let f = std::fs::File::open(p).ok()?;
|
||||
let mut private = 0;
|
||||
let mut at = 0u64;
|
||||
loop {
|
||||
// SAFETY: all zeros is a valid Fiemap.
|
||||
let mut m: Box<Fiemap> = Box::new(unsafe { std::mem::zeroed() });
|
||||
m.start = at;
|
||||
m.length = u64::MAX - at;
|
||||
m.flags = FIEMAP_FLAG_SYNC;
|
||||
m.count = m.extents.len() as u32;
|
||||
// SAFETY: m is a struct fiemap with room for `count` extents, alive for the call.
|
||||
if unsafe { libc::ioctl(f.as_raw_fd(), FS_IOC_FIEMAP as _, &mut *m as *mut Fiemap) } != 0 {
|
||||
return None;
|
||||
}
|
||||
let got = &m.extents[..(m.mapped as usize).min(m.extents.len())];
|
||||
for e in got {
|
||||
if e.flags & FIEMAP_EXTENT_SHARED == 0 {
|
||||
private += e.length;
|
||||
}
|
||||
}
|
||||
match got.last() {
|
||||
Some(e) if e.flags & FIEMAP_EXTENT_LAST == 0 => at = e.logical + e.length,
|
||||
_ => return Some(private),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of the file at `p` that no other file shares, as APFS counts its clones: its private
|
||||
/// size (getattrlist's ATTR_CMNEXT_PRIVATESIZE); None where the file system answers none.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn private_bytes(p: &Path) -> Option<u64> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
#[repr(C, packed(4))]
|
||||
struct Answer {
|
||||
length: u32,
|
||||
returned: libc::attribute_set_t,
|
||||
private: libc::off_t,
|
||||
}
|
||||
let path = std::ffi::CString::new(p.as_os_str().as_bytes()).ok()?;
|
||||
let mut list = libc::attrlist {
|
||||
bitmapcount: libc::ATTR_BIT_MAP_COUNT,
|
||||
reserved: 0,
|
||||
commonattr: libc::ATTR_CMN_RETURNED_ATTRS,
|
||||
volattr: 0,
|
||||
dirattr: 0,
|
||||
fileattr: 0,
|
||||
forkattr: libc::ATTR_CMNEXT_PRIVATESIZE,
|
||||
};
|
||||
// SAFETY: all zeros is a valid Answer.
|
||||
let mut a: Answer = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: path is NUL-terminated, and list and a are alive for the call, a of its size.
|
||||
let r = unsafe {
|
||||
libc::getattrlist(
|
||||
path.as_ptr(),
|
||||
(&mut list as *mut libc::attrlist).cast(),
|
||||
(&mut a as *mut Answer).cast(),
|
||||
std::mem::size_of::<Answer>(),
|
||||
libc::FSOPT_ATTR_CMN_EXTENDED,
|
||||
)
|
||||
};
|
||||
let returned = { a.returned };
|
||||
let private = { a.private };
|
||||
(r == 0 && returned.forkattr & libc::ATTR_CMNEXT_PRIVATESIZE != 0)
|
||||
.then(|| u64::try_from(private).ok())
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Whether `a` and `b`, which exist, are on one file system: the same device.
|
||||
pub fn same_file_system(a: &Path, b: &Path) -> bool {
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
|
||||
@@ -197,70 +197,15 @@ pub fn owned_by_me(_m: &std::fs::Metadata) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// What tells the file at `path` from another put there since: its volume's serial number and
|
||||
/// its file index, which a new file has its own of, as std's metadata does not give. Not its
|
||||
/// creation time: NTFS gives a file made at a name moments after another left it that file's
|
||||
/// creation time (its "tunneling"), as an update's set-aside copy is made. None where the file
|
||||
/// cannot be opened to read its attributes.
|
||||
pub fn file_id(path: &Path, _m: &std::fs::Metadata) -> Option<(u64, u64)> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
BY_HANDLE_FILE_INFORMATION, FILE_READ_ATTRIBUTES, GetFileInformationByHandle,
|
||||
};
|
||||
let f = std::fs::OpenOptions::new()
|
||||
.access_mode(FILE_READ_ATTRIBUTES)
|
||||
.open(path)
|
||||
.ok()?;
|
||||
let mut info = BY_HANDLE_FILE_INFORMATION::default();
|
||||
// SAFETY: the handle is the open file's, and the call writes the structure given.
|
||||
if unsafe { GetFileInformationByHandle(f.as_raw_handle(), &mut info) } == 0 {
|
||||
return None;
|
||||
}
|
||||
let index = (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow);
|
||||
Some((u64::from(info.dwVolumeSerialNumber), index))
|
||||
}
|
||||
|
||||
/// The group that owns the file `m` describes: none on Windows.
|
||||
pub fn gid(_m: &std::fs::Metadata) -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
/// When the file at `path` last changed, as Unix's ctime tells: its change time, which NTFS sets
|
||||
/// to the present at any write to the file and any change of its times or attributes, and which
|
||||
/// std's metadata does not give (`FILE_BASIC_INFO`'s `ChangeTime`). None where the file system
|
||||
/// keeps none, which it answers as 0, or the file's attributes cannot be read. Opened to read its
|
||||
/// attributes alone, the file is read while another program, a running QEMU among them, has it
|
||||
/// open however it shares it.
|
||||
pub fn changed(path: &Path, _m: &std::fs::Metadata) -> Option<std::time::SystemTime> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FILE_BASIC_INFO, FILE_READ_ATTRIBUTES, FileBasicInfo, GetFileInformationByHandleEx,
|
||||
};
|
||||
/// The Unix epoch, 1970-01-01, in a FILETIME's 100 ns units since 1601-01-01.
|
||||
const UNIX_EPOCH_TICKS: i64 = 116_444_736_000_000_000;
|
||||
let f = std::fs::OpenOptions::new()
|
||||
.access_mode(FILE_READ_ATTRIBUTES)
|
||||
.open(path)
|
||||
.ok()?;
|
||||
let mut info = FILE_BASIC_INFO::default();
|
||||
// SAFETY: the handle is the open file's, and the buffer is a FILE_BASIC_INFO of the size
|
||||
// given, which FileBasicInfo asks for.
|
||||
let ok = unsafe {
|
||||
GetFileInformationByHandleEx(
|
||||
f.as_raw_handle(),
|
||||
FileBasicInfo,
|
||||
(&mut info as *mut FILE_BASIC_INFO).cast(),
|
||||
std::mem::size_of::<FILE_BASIC_INFO>() as u32,
|
||||
)
|
||||
};
|
||||
if ok == 0 || info.ChangeTime <= 0 {
|
||||
return None;
|
||||
}
|
||||
let ticks = u64::try_from(info.ChangeTime - UNIX_EPOCH_TICKS).ok()?;
|
||||
let since = std::time::Duration::new(ticks / 10_000_000, (ticks % 10_000_000) as u32 * 100);
|
||||
Some(std::time::UNIX_EPOCH + since)
|
||||
/// When the file `m` describes last changed, as Unix's ctime tells: none, as std's metadata on
|
||||
/// Windows gives no such time.
|
||||
pub fn changed(_m: &std::fs::Metadata) -> Option<std::time::SystemTime> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether this process may open the file `p` to read and write it.
|
||||
@@ -1192,12 +1137,6 @@ pub fn allocated(m: &std::fs::Metadata) -> u64 {
|
||||
m.len()
|
||||
}
|
||||
|
||||
/// The bytes of the file at `p` that no other file shares: None, as Windows tells no file's
|
||||
/// share of the clusters a block clone shares.
|
||||
pub fn private_bytes(_p: &Path) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `a` and `b`, which exist, are on one volume: the same volume path
|
||||
/// (`GetVolumePathNameW`, which a folder a volume is mounted on answers too).
|
||||
pub fn same_file_system(a: &Path, b: &Path) -> bool {
|
||||
|
||||
@@ -53,7 +53,8 @@ impl Kext {
|
||||
}
|
||||
|
||||
// What build.rs embeds: the sets, `SET` and `SET_ARM64E`, each None where the checkout it was
|
||||
// built from had none, and `AMBROSIA_MODULE`, None where clang could not build it.
|
||||
// built from had none, and `AMBROSIA_MODULE`, None where clang could not build it; for Windows,
|
||||
// neither `SET_ARM64E` nor `AMBROSIA_MODULE`.
|
||||
include!(concat!(env!("OUT_DIR"), "/set.rs"));
|
||||
|
||||
/// The config.plist of the device's bundle for Ambrosia, `firmware/ambrosia/config.plist`: it
|
||||
@@ -380,12 +381,8 @@ fn newc_member(out: &mut Vec<u8>, ino: u32, mode: u32, path: &str, data: &[u8])
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The bundles of the guest's kexts, written there if they are not, in the set's order; for
|
||||
/// every OpenCore image reims-util makes with them. Refused where this reims-ctl was updated
|
||||
/// since it started: the image would hold this build's kexts, which don't match the installed
|
||||
/// QEMU ([`crate::update::refuse_replaced`]).
|
||||
/// The bundles of the guest's kexts, written there if they are not, in the set's order.
|
||||
pub fn guest_kexts() -> Result<Vec<PathBuf>> {
|
||||
crate::update::refuse_replaced()?;
|
||||
kexts_in(&dir(), set()?)
|
||||
}
|
||||
|
||||
@@ -405,6 +402,17 @@ fn hash<'a>(parts: impl IntoIterator<Item = &'a [u8]>) -> String {
|
||||
format!("{h:016x}")
|
||||
}
|
||||
|
||||
/// A name for a file or directory written beside its place, apart from every other writer's.
|
||||
fn beside(place: &Path) -> PathBuf {
|
||||
let t = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos();
|
||||
let mut name = place.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(format!(".{}-{t}.tmp", std::process::id()));
|
||||
place.with_file_name(name)
|
||||
}
|
||||
|
||||
/// `rom` in `dir`, as [`rom_file`] names it.
|
||||
fn rom_in(dir: &Path, rom: &[u8]) -> Result<PathBuf> {
|
||||
file_in(dir, "ReimsGraphics", "rom", rom)
|
||||
@@ -417,7 +425,12 @@ fn file_in(dir: &Path, stem: &str, ext: &str, bytes: &[u8]) -> Result<PathBuf> {
|
||||
return Ok(file);
|
||||
}
|
||||
std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
|
||||
crate::record::replace(&file, bytes).with_context(|| format!("write {}", file.display()))?;
|
||||
let tmp = beside(&file);
|
||||
let written = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, &file));
|
||||
if let Err(e) = written {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e).with_context(|| format!("write {}", file.display()));
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
@@ -444,7 +457,7 @@ fn kexts_in(dir: &Path, set: &[Kext]) -> Result<Vec<PathBuf>> {
|
||||
if whole(&place) {
|
||||
return Ok(bundles(&place));
|
||||
}
|
||||
let tmp = crate::record::beside(&place);
|
||||
let tmp = beside(&place);
|
||||
let write = || -> std::io::Result<()> {
|
||||
for k in set {
|
||||
for (p, b) in k.files {
|
||||
@@ -462,7 +475,7 @@ fn kexts_in(dir: &Path, set: &[Kext]) -> Result<Vec<PathBuf>> {
|
||||
// One that is not whole, left by an earlier write that stopped, goes aside first; one a writer
|
||||
// at once with this one renamed into place first is whole, and stays.
|
||||
if place.exists() && !whole(&place) {
|
||||
let old = crate::record::beside(&place);
|
||||
let old = beside(&place);
|
||||
if std::fs::rename(&place, &old).is_ok() {
|
||||
let _ = std::fs::remove_dir_all(&old);
|
||||
}
|
||||
@@ -821,17 +834,18 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Every reims-ctl carries the arm64 guest's set, Windows' among them (build.rs): a checkout
|
||||
/// without guest/prebuilt-arm64e fails here.
|
||||
/// A reims-ctl for Windows, which runs no arm64 VM, carries neither the arm64 set nor the
|
||||
/// module (build.rs).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_arm64_set_is_carried() {
|
||||
let set = super::SET_ARM64E.expect("guest/prebuilt-arm64e/set.toml");
|
||||
assert!(!set.is_empty());
|
||||
fn a_reims_ctl_for_windows_carries_no_arm64_guest() {
|
||||
assert!(super::SET_ARM64E.is_none());
|
||||
assert!(AMBROSIA_MODULE.is_none());
|
||||
}
|
||||
|
||||
/// The module build.rs built is an aarch64 ELF static PIE, the module format Ambrosia loads:
|
||||
/// a checkout whose clang can't build it fails here, not at an arm64 VM's start, on every host
|
||||
/// reims-ctl builds on, Windows among them.
|
||||
/// a checkout whose clang can't build it fails here, not at an arm64 VM's start.
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn the_module_is_built() {
|
||||
let elf = AMBROSIA_MODULE.expect(
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
//! The processor an x86-64 guest's About This Mac names, from the host's CPU.
|
||||
//!
|
||||
//! macOS names the processor from two values of the guest's, never from CPUID's brand string:
|
||||
//! Apple's processor type, SMBIOS type 131, whose high byte is the family ("Intel Core i7"), and
|
||||
//! the core count `machdep.cpu.core_count` reads, which with QEMU's CPU is the VM's vCPUs rounded
|
||||
//! up to a power of two: 4 for 3 vCPUs, 8 for 5 to 8, 16 for 9 to 16 (measured at 3 to 9 vCPUs on
|
||||
//! macOS 26.7.2; System Information's "Total Number of Cores" is the vCPUs themselves, SMBIOS type
|
||||
//! 4's). The name is the family with that count before it, "Quad-Core Intel Core i7", where Apple's
|
||||
//! table of names has that pair, and "Unknown" where it has not: the table is Intel's Macs'
|
||||
//! (AppleSystemInfo's Processors.loctable), which has, among others, "Dual-Core" and "Quad-Core
|
||||
//! Intel Core i3", "Dual-Core", "Quad-Core", "6-Core" and "8-Core Intel Core i5" and "Intel Core
|
||||
//! i7", "6-Core", "8-Core" and "10-Core Intel Core i9", "Single-Core", "Dual-Core", "Quad-Core" and
|
||||
//! "6-Core Intel Xeon", and "8-Core" to "28-Core Intel Xeon W". Only the powers of two are reached,
|
||||
//! so a VM of 9 vCPUs or more on a Core i9 host is "Unknown" (16 cores), as is one of 5 to 8 on a
|
||||
//! Core i3 host. About This Mac, Settings' About and System Information show the same name ("x86-64
|
||||
//! macOS guests: About This Mac", docs/qemu.md).
|
||||
//!
|
||||
//! OpenCore writes type 131 from its config.plist's PlatformInfo > Generic > ProcessorType, and
|
||||
//! picks one itself where that is 0, as reims-util's images have it: from QEMU's CPU, model 0x5E,
|
||||
//! with no family in its brand string, it picks 0x0905, Core i3, which shows as "Quad-Core Intel
|
||||
//! Core i3" with 4 vCPUs and "Unknown" with 8 (measured on macOS 26.7.2). reims-ctl writes the
|
||||
//! value for the host's CPU instead, at each start ([`crate::opencore::match_processor_type`]):
|
||||
//! the family its brand string states ([`Family::of`]), Intel's own words or AMD's rank of the
|
||||
//! same steps, and 0, OpenCore's own pick, for a CPU that states none. The CPU the guest runs
|
||||
//! on, its model and its features, is the same whatever the value: only the name changes.
|
||||
|
||||
/// A family of the host's CPU that Apple has names for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Family {
|
||||
CoreI3,
|
||||
CoreI5,
|
||||
CoreI7,
|
||||
CoreI9,
|
||||
Xeon,
|
||||
}
|
||||
|
||||
impl Family {
|
||||
/// The family a CPU's brand string states, by its words, whatever their case, "(R)" and
|
||||
/// "(TM)" aside:
|
||||
/// - Intel's "i3", "i5", "i7" and "i9", alone or before a model number ("Core(TM) i7-8700B");
|
||||
/// - Intel's newer "Core Ultra 5", "Core Ultra 7" and "Core Ultra 9", and "Core 3" to "Core 7",
|
||||
/// as the same steps;
|
||||
/// - "Xeon", and AMD's "Threadripper" and "EPYC", as Xeon;
|
||||
/// - AMD's "Ryzen 3", "Ryzen 5", "Ryzen 7" and "Ryzen 9", "AI" and "PRO" between the two
|
||||
/// words read past ("Ryzen AI 9 HX 370"), as i3 to i9, the same rank.
|
||||
///
|
||||
/// None for any other: a Pentium, a Celeron, a Core 2, an Athlon, an "AI Max+".
|
||||
pub fn of(brand: &str) -> Option<Family> {
|
||||
let words: Vec<String> = brand
|
||||
.to_ascii_lowercase()
|
||||
.replace("(r)", " ")
|
||||
.replace("(tm)", " ")
|
||||
.split(|c: char| c.is_whitespace() || c == '-')
|
||||
.filter(|w| !w.is_empty())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
let has = |w: &str| words.iter().any(|x| x == w);
|
||||
if has("xeon") || has("threadripper") || has("epyc") {
|
||||
return Some(Family::Xeon);
|
||||
}
|
||||
let rank = |w: &str| match w {
|
||||
"3" | "i3" => Some(Family::CoreI3),
|
||||
"5" | "i5" => Some(Family::CoreI5),
|
||||
"7" | "i7" => Some(Family::CoreI7),
|
||||
"9" | "i9" => Some(Family::CoreI9),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(f) = words
|
||||
.iter()
|
||||
.find_map(|w| w.starts_with('i').then(|| rank(w)).flatten())
|
||||
{
|
||||
return Some(f);
|
||||
}
|
||||
// The rank after "Core" ("Ultra" read past) or "Ryzen" ("AI" and "PRO" read past).
|
||||
words.iter().enumerate().find_map(|(i, w)| {
|
||||
let skip: &[&str] = match w.as_str() {
|
||||
"core" => &["ultra"],
|
||||
"ryzen" => &["ai", "pro"],
|
||||
_ => return None,
|
||||
};
|
||||
let next = words[i + 1..]
|
||||
.iter()
|
||||
.find(|x| !skip.contains(&x.as_str()))?;
|
||||
next.parse::<u8>().ok().and_then(|_| rank(next))
|
||||
})
|
||||
}
|
||||
|
||||
/// Apple's processor type for the family, in a guest of `cpus` vCPUs: a value Intel's Macs
|
||||
/// had, whose family Apple's table names at the core count macOS reads, `cpus` rounded up to
|
||||
/// a power of two, where any of the family's types is named there. A Xeon is "Intel Xeon",
|
||||
/// 0x0501, up to 4 vCPUs, and "Intel Xeon W", 0x0F01, from 5: macOS counts 5 to 8 vCPUs as 8
|
||||
/// cores, which "Intel Xeon" has no name for and "Intel Xeon W" has.
|
||||
pub fn processor_type(self, cpus: u32) -> u16 {
|
||||
match self {
|
||||
Family::CoreI3 => 0x0909,
|
||||
Family::CoreI5 => 0x0609,
|
||||
Family::CoreI7 => 0x0709,
|
||||
Family::CoreI9 => 0x1009,
|
||||
Family::Xeon if cpus <= 4 => 0x0501,
|
||||
Family::Xeon => 0x0F01,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ProcessorType an x86-64 VM of `cpus` vCPUs gets on a host whose CPU's brand string is
|
||||
/// `brand`: its family's ([`Family::processor_type`]), or 0, OpenCore's own pick, where it states
|
||||
/// none or the host gives none.
|
||||
pub fn processor_type(brand: Option<&str>, cpus: u32) -> u16 {
|
||||
brand
|
||||
.and_then(Family::of)
|
||||
.map_or(0, |f| f.processor_type(cpus))
|
||||
}
|
||||
|
||||
/// Apple's name for the family of a processor type, as About This Mac shows it after the core
|
||||
/// count: "Intel Core i7"; None for 0 and any type reims-ctl does not write.
|
||||
pub fn family_name(processor_type: u16) -> Option<&'static str> {
|
||||
Some(match processor_type >> 8 {
|
||||
0x09 => "Intel Core i3",
|
||||
0x06 => "Intel Core i5",
|
||||
0x07 => "Intel Core i7",
|
||||
0x10 => "Intel Core i9",
|
||||
0x05 => "Intel Xeon",
|
||||
0x0F => "Intel Xeon W",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Each brand string to the family it states: Intel's words from the first Core i7 to Core
|
||||
/// Ultra, Xeon's, and AMD's Ryzen ranks, Threadripper and EPYC; None where it states none.
|
||||
#[test]
|
||||
fn a_brand_string_states_its_family() {
|
||||
use Family::*;
|
||||
let cases: &[(&str, Option<Family>)] = &[
|
||||
(
|
||||
"Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz",
|
||||
Some(CoreI7),
|
||||
),
|
||||
("Intel(R) Core(TM) i3-8100B CPU @ 3.60GHz", Some(CoreI3)),
|
||||
("Intel(R) Core(TM) i5-1035G1 CPU @ 1.00GHz", Some(CoreI5)),
|
||||
("Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz", Some(CoreI7)),
|
||||
("12th Gen Intel(R) Core(TM) i7-12700H", Some(CoreI7)),
|
||||
("13th Gen Intel(R) Core(TM) i9-13900H", Some(CoreI9)),
|
||||
("Intel(R) Core(TM) Ultra 5 125H", Some(CoreI5)),
|
||||
("Intel(R) Core(TM) Ultra 7 155H", Some(CoreI7)),
|
||||
("Intel(R) Core(TM) Ultra 9 275HX", Some(CoreI9)),
|
||||
("Intel(R) Core(TM) 3 100U", Some(CoreI3)),
|
||||
("Intel(R) Core(TM) 7 150U", Some(CoreI7)),
|
||||
("Intel(R) Xeon(R) W-2145 CPU @ 3.70GHz", Some(Xeon)),
|
||||
("Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz", Some(Xeon)),
|
||||
("Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz", Some(Xeon)),
|
||||
("AMD Ryzen 3 3200G with Radeon Vega Graphics", Some(CoreI3)),
|
||||
("AMD Ryzen 5 5600X 6-Core Processor", Some(CoreI5)),
|
||||
("AMD Ryzen 5 PRO 4650G with Radeon Graphics", Some(CoreI5)),
|
||||
("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics", Some(CoreI7)),
|
||||
("AMD Ryzen 7 8745H w/ Radeon 780M Graphics", Some(CoreI7)),
|
||||
("AMD Ryzen 9 7950X 16-Core Processor", Some(CoreI9)),
|
||||
("AMD Ryzen AI 9 HX 370 w/ Radeon 890M", Some(CoreI9)),
|
||||
("AMD Ryzen AI 7 PRO 360 w/ Radeon 880M", Some(CoreI7)),
|
||||
("AMD Ryzen Threadripper PRO 5995WX 64-Cores", Some(Xeon)),
|
||||
("AMD EPYC 7763 64-Core Processor", Some(Xeon)),
|
||||
("Intel(R) Core(TM)2 Duo CPU E8400 @ 3.00GHz", None),
|
||||
("Intel(R) Core(TM) m3-7Y30 CPU @ 1.00GHz", None),
|
||||
("Intel(R) Pentium(R) Gold 7505 @ 2.00GHz", None),
|
||||
("Intel(R) Celeron(R) N4020 CPU @ 1.10GHz", None),
|
||||
("Intel(R) N100", None),
|
||||
("AMD Athlon Silver 3050U with Radeon Graphics", None),
|
||||
("AMD Ryzen AI Max+ 395 w/ Radeon 8060S", None),
|
||||
("AMD Ryzen Z1 Extreme", None),
|
||||
("Intel Core Processor (Skylake, IBRS, no TSX)", None),
|
||||
("", None),
|
||||
];
|
||||
for (brand, family) in cases {
|
||||
assert_eq!(Family::of(brand), *family, "{brand:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The value for each family, which Apple's table names: Core i3 to i9 by their family's
|
||||
/// type whatever the count, a Xeon as "Intel Xeon" up to 4 vCPUs and "Intel Xeon W" from 5;
|
||||
/// 0 where the host states no family, or gives no brand string.
|
||||
#[test]
|
||||
fn each_family_has_its_processor_type() {
|
||||
let i7 = Some("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics");
|
||||
assert_eq!(processor_type(i7, 8), 0x0709);
|
||||
assert_eq!(processor_type(i7, 4), 0x0709);
|
||||
assert_eq!(
|
||||
processor_type(Some("13th Gen Intel(R) Core(TM) i9-13900H"), 8),
|
||||
0x1009
|
||||
);
|
||||
assert_eq!(
|
||||
processor_type(Some("Intel(R) Core(TM) i3-8100B"), 4),
|
||||
0x0909
|
||||
);
|
||||
assert_eq!(
|
||||
processor_type(Some("Intel(R) Core(TM) Ultra 5 125H"), 6),
|
||||
0x0609
|
||||
);
|
||||
let xeon = Some("Intel(R) Xeon(R) W-2145 CPU @ 3.70GHz");
|
||||
assert_eq!(processor_type(xeon, 1), 0x0501);
|
||||
assert_eq!(processor_type(xeon, 4), 0x0501);
|
||||
assert_eq!(processor_type(xeon, 5), 0x0F01);
|
||||
assert_eq!(processor_type(xeon, 6), 0x0F01);
|
||||
assert_eq!(processor_type(xeon, 8), 0x0F01);
|
||||
assert_eq!(processor_type(Some("Intel(R) Pentium(R) Gold 7505"), 4), 0);
|
||||
assert_eq!(processor_type(None, 8), 0);
|
||||
for t in [0x0909, 0x0609, 0x0709, 0x1009, 0x0501, 0x0F01] {
|
||||
assert!(family_name(t).is_some(), "{t:#06x}");
|
||||
}
|
||||
assert_eq!(family_name(0), None);
|
||||
}
|
||||
}
|
||||
+95
-538
@@ -4,13 +4,9 @@
|
||||
//!
|
||||
//! Every VM gets:
|
||||
//! - on reims-vgpu's own device, the library's window for each of its displays: `-display none`
|
||||
//! with `REIMS_VGPU_WINDOW` unset, never a window of QEMU's own; a headless start
|
||||
//! (`reims-ctl start --headless`, [`Ctx::headless`]) gives it `0`, which keeps the device
|
||||
//! headless, each display offering the guest the resolution as its mode;
|
||||
//! with `REIMS_VGPU_WINDOW` unset (`0` would keep the device headless), never a window of
|
||||
//! QEMU's own;
|
||||
//! - a QMP socket (`-qmp`), through which reims-ctl stops the VM;
|
||||
//! - QEMU's trace of each ask to shut the VM down, with its cause, in QEMU's log
|
||||
//! ([`SHUTDOWN_TRACE`]), which tells why a stopped VM stopped
|
||||
//! ([`crate::runtime::stop_reason`]);
|
||||
//! - QEMU's pid file;
|
||||
//! - user networking with virtio-net, and an optional SSH port forward; with networking off,
|
||||
//! `-nic none`, without which QEMU gives the machine its default NIC on user networking (on
|
||||
@@ -77,16 +73,15 @@
|
||||
//! (`max-ram-below-4g=1G`): with more, the guest's kext finds no region. It has as many
|
||||
//! displays as the VM's settings give, its `displays`, named only above one, the device's own
|
||||
//! count, since a QEMU built before the property refuses it. Each display opens in a window of
|
||||
//! the library's at its size of the resolution ([`crate::vm::Display::qemu_resolution`], the
|
||||
//! device's `resolution`: one size for every window, or one for each, comma-separated, each
|
||||
//! comma doubled on QEMU's line; 1920x1080 by default) and follows its window's size at the
|
||||
//! the library's at the resolution's size ([`crate::vm::Display::window_size`], the device's
|
||||
//! `resolution`, every window's; 1920x1080 by default) and follows its window's size at the
|
||||
//! rate of the host screen the window is on; borderless reaches every window as
|
||||
//! `REIMS_VGPU_WINDOW_BORDERLESS`.
|
||||
//! `REIMS_VGPU_WINDOW_BORDERLESS`, and capture turned off as `REIMS_VGPU_WINDOW_CAPTURE=0`.
|
||||
//! - QEMU's `vmware-svga` (`graphics = "vmware-svga"`). The library then draws nothing, so the
|
||||
//! window's and the GPU's variables are left out, and QEMU's own window, GTK's (`-display
|
||||
//! gtk`), shows the display. Where QEMU's environment names no Wayland compositor or X server,
|
||||
//! GTK's window would end QEMU as it starts, so it is `-display none` there, and the guest runs
|
||||
//! headless, as on the library's window; a headless start is `-display none` too.
|
||||
//! headless, as on the library's window.
|
||||
//!
|
||||
//! The arm64 machine, `vmapple-arm64` ([`vmapple`]), is QEMU's `vmapple`, with the command line
|
||||
//! Ambrosia's boot check boots arm64 guests on (firmware/ambrosia/check-boot.sh, docs/qemu.md
|
||||
@@ -100,9 +95,7 @@
|
||||
//! x86-64 VM's below by `-global` (the machine makes the controller itself), and its `uuid` is the
|
||||
//! VM's ECID, which the tickets of its macOS are bound to. It runs on HVF on a Mac, with the GIC in the kernel, on
|
||||
//! KVM on arm64 Linux, and on TCG, a thread for each vCPU, on x86-64 ([`Profile::accel_arg`]). On
|
||||
//! Linux its RAM is a shared memfd, as the library there needs, not allocated as QEMU starts,
|
||||
//! and on Windows a pagefile-backed section, as the x86-64 machine's, committed whole as QEMU
|
||||
//! starts.
|
||||
//! Linux its RAM is a shared memfd, as the library there needs, not allocated as QEMU starts.
|
||||
//! On a Linux host it takes the host's USB devices as an x86-64 VM does, on that controller's
|
||||
//! bus ([`crate::usb::bus`]); it takes no host disk and no VMware SVGA. With audio on, under KVM,
|
||||
//! it has the same two virtio sound devices as an x86-64 VM, after the GPU, where QEMU puts them,
|
||||
@@ -147,33 +140,14 @@ pub struct Ctx {
|
||||
pub sound: crate::os::SoundDevices,
|
||||
/// Whether the host's KVM offers VMX to guests ([`crate::host::kvm_nested_vmx`]).
|
||||
pub nested_vmx: bool,
|
||||
/// What an x86-64 guest's CPU line names in place of reims-ctl's own model on a host whose
|
||||
/// CPU lacks AVX2 ([`crate::host::host_model_without_avx2`]); None on any other host.
|
||||
pub model_without_avx2: Option<crate::host::HostModel>,
|
||||
/// Whether the guest's CPU lists the AVX-512 state components in CPUID leaf 0xD, QEMU's
|
||||
/// `x-avx512-xstate` ([`avx512_xstate`]).
|
||||
pub avx512_xstate: bool,
|
||||
/// Whether QEMU takes `-smbios type=17`'s `memory_type`
|
||||
/// ([`crate::install::smbios_takes_memory_type`]).
|
||||
pub smbios_memory_type: bool,
|
||||
/// The memory's SMBIOS Memory Error Correction, `-smbios type=16`'s `error_correction`, as the
|
||||
/// presented Mac's RAM has it ([`crate::reims_util::model_memory_error_correction`]); None
|
||||
/// where QEMU does not take the option ([`crate::install::smbios_takes_error_correction`]),
|
||||
/// or the VM's image presents a Mac whose RAM reims-ctl does not know.
|
||||
pub smbios_error_correction: Option<u8>,
|
||||
/// The memory array's slots, `-smbios type=17`'s `slots` and `form_factor`, as the presented
|
||||
/// Mac has them ([`crate::reims_util::model_memory_slots`]); None where QEMU does not take the
|
||||
/// options ([`crate::install::smbios_takes_memory_slots`]), or the VM's image presents a Mac
|
||||
/// whose slots reims-ctl does not know.
|
||||
pub smbios_memory_slots: Option<crate::reims_util::MemorySlots>,
|
||||
/// The host CPU's brand string ([`crate::host::cpu_brand`]), which an x86-64 guest's CPU
|
||||
/// gives as its own (`model-id`); None where the host gives none.
|
||||
pub cpu_brand: Option<String>,
|
||||
/// Whether QEMU's own window can open ([`crate::host::has_screen`]).
|
||||
pub screen: bool,
|
||||
/// Whether the start is headless (`reims-ctl start --headless`): it opens no window, and
|
||||
/// `reims-ctl view` alone shows the guest's screen ([`headless`]).
|
||||
pub headless: bool,
|
||||
/// The option ROM of reims-vgpu's own device, which its `romfile` names
|
||||
/// ([`crate::prebuilt::graphics_rom`]).
|
||||
pub graphics_rom: PathBuf,
|
||||
@@ -221,6 +195,33 @@ pub fn opt(s: &str) -> String {
|
||||
s.replace(',', ",,")
|
||||
}
|
||||
|
||||
/// Compute the qcow2 L2 cache size in MiB needed to cover the full virtual disk
|
||||
/// (`virtual_size / cluster_size * 8` bytes), clamped to `..=32 MiB`, returning `Some(mib)` only
|
||||
/// when the image needs more than QEMU's 8 MiB non-Linux default.
|
||||
fn qcow2_l2_cache_mib(path: &Path) -> Option<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())
|
||||
}
|
||||
@@ -251,20 +252,17 @@ pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result<Invocation> {
|
||||
if library && c.display.borderless {
|
||||
env.push(("REIMS_VGPU_WINDOW_BORDERLESS".into(), "1".into()));
|
||||
}
|
||||
if library && !c.display.capture {
|
||||
env.push(("REIMS_VGPU_WINDOW_CAPTURE".into(), "0".into()));
|
||||
}
|
||||
if library && c.profile.gpu_choice(ctx.host) {
|
||||
let dri_prime = c.gpu.dri_prime()?;
|
||||
if let Some((vendor, device)) = c.gpu.selected()? {
|
||||
// The GPU first, every other GPU and driver kept: Mesa's device-select layer reads
|
||||
// MESA_VK_DEVICE_SELECT, the loader VK_LOADER_DEVICE_SELECT (crate::gpu). A GPU
|
||||
// whose IDs another GPU of the host has is named by its address instead, below:
|
||||
// the library reads MESA_VK_DEVICE_SELECT before DRI_PRIME, and its IDs would name
|
||||
// the first of the two.
|
||||
if dri_prime.is_none() {
|
||||
env.push((
|
||||
"MESA_VK_DEVICE_SELECT".into(),
|
||||
format!("{vendor:04x}:{device:04x}"),
|
||||
));
|
||||
}
|
||||
// MESA_VK_DEVICE_SELECT, the loader VK_LOADER_DEVICE_SELECT (crate::gpu).
|
||||
env.push((
|
||||
"MESA_VK_DEVICE_SELECT".into(),
|
||||
format!("{vendor:04x}:{device:04x}"),
|
||||
));
|
||||
env.push((
|
||||
"VK_LOADER_DEVICE_SELECT".into(),
|
||||
format!("{vendor:#06x}:{device:#06x}"),
|
||||
@@ -278,9 +276,6 @@ pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result<Invocation> {
|
||||
env.push(("VK_LOADER_DEVICE_ID_FILTER".into(), format!("{id:#06x}")));
|
||||
}
|
||||
}
|
||||
if let Some(pci) = dri_prime {
|
||||
env.push(("DRI_PRIME".into(), pci));
|
||||
}
|
||||
}
|
||||
for (k, v) in &c.extra_env {
|
||||
// A name the shell's export takes, so the printed script runs as start does.
|
||||
@@ -289,12 +284,6 @@ pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result<Invocation> {
|
||||
unset.retain(|u| u != k);
|
||||
env.push((k.clone(), v.clone()));
|
||||
}
|
||||
// A headless start keeps the device headless whatever the VM's own variables give.
|
||||
if library && ctx.headless {
|
||||
env.retain(|(k, _)| k != "REIMS_VGPU_WINDOW");
|
||||
unset.retain(|u| u != "REIMS_VGPU_WINDOW");
|
||||
env.push(("REIMS_VGPU_WINDOW".into(), "0".into()));
|
||||
}
|
||||
Ok(Invocation {
|
||||
program: ctx.qemu.clone(),
|
||||
args: a,
|
||||
@@ -341,17 +330,9 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
]);
|
||||
}
|
||||
push(&["-accel", c.profile.accel(ctx.host), "-m", &mem]);
|
||||
// On a host whose CPU lacks AVX2, a VM on reims-ctl's own model runs on a model the host's CPU
|
||||
// is, and the features of reims-ctl's model that the host has and that one lacks follow
|
||||
// reims-ctl's flags, before the VM's own, less those the host lacks
|
||||
// (crate::host::model_without_avx2). A VM's own model stays.
|
||||
let own = ctx
|
||||
.model_without_avx2
|
||||
.as_ref()
|
||||
.filter(|_| q.cpu_model == crate::vm::default_cpu_model());
|
||||
let mut cpu = format!(
|
||||
"{},kvm=on,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on",
|
||||
own.map_or(q.cpu_model.as_str(), |m| m.name)
|
||||
q.cpu_model
|
||||
);
|
||||
// VMX lets the guest run VMs of its own (Hypervisor.framework, Docker). It is given only where
|
||||
// KVM offers it, so `check` never drops it with a warning. It is `vmx=on`, not `+vmx`, so a
|
||||
@@ -365,28 +346,9 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
if ctx.avx512_xstate {
|
||||
cpu.push_str(",x-avx512-xstate=on");
|
||||
}
|
||||
// The host CPU's brand string, which the guest reads as `machdep.cpu.brand_string`; QEMU's
|
||||
// model names its own ("Intel Core Processor (Skylake, IBRS, no TSX)"). It names the CPU and
|
||||
// changes none of its features. `name=value` as well, so a VM's own `model-id=` in
|
||||
// `cpu_flags` replaces it; a comma in it is doubled, as QEMU's option syntax escapes one.
|
||||
if let Some(brand) = &ctx.cpu_brand {
|
||||
cpu.push_str(",model-id=");
|
||||
cpu.push_str(&brand.replace(',', ",,"));
|
||||
}
|
||||
for flag in own.iter().flat_map(|m| &m.flags) {
|
||||
if !q.cpu_flags.trim().is_empty() {
|
||||
cpu.push(',');
|
||||
cpu.push_str(flag);
|
||||
}
|
||||
// The VM's flags, without reims-ctl's own whose feature such a host lacks.
|
||||
let dropped = |f: &str| own.is_some_and(|m| m.drop.iter().any(|d| d == f));
|
||||
for flag in q
|
||||
.cpu_flags
|
||||
.trim()
|
||||
.split(',')
|
||||
.filter(|f| !f.is_empty() && !dropped(f))
|
||||
{
|
||||
cpu.push(',');
|
||||
cpu.push_str(flag);
|
||||
cpu.push_str(q.cpu_flags.trim());
|
||||
}
|
||||
push(&["-cpu", &cpu]);
|
||||
push(&[
|
||||
@@ -418,13 +380,6 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
),
|
||||
]);
|
||||
push(&["-smbios", "type=2"]);
|
||||
// Whether the memory has ECC, as the presented Mac's RAM has it: QEMU's memory array says
|
||||
// multi-bit ECC, which OpenCore copies into the guest's SMBIOS and System Information shows
|
||||
// as "ECC: Enabled", where an iMac20,1's RAM has none. The option is reims-vgpu's QEMU's
|
||||
// alone; another QEMU keeps ECC.
|
||||
if let Some(e) = ctx.smbios_error_correction {
|
||||
push(&["-smbios", &format!("type=16,error_correction={e}")]);
|
||||
}
|
||||
// The memory as the presented Mac has it: iMac20,1 and iMacPro1,1 both ship 2666 MHz DDR4
|
||||
// (OpenCore's model database), where QEMU's memory devices are 0 MHz "RAM". OpenCore copies
|
||||
// both fields into the guest's SMBIOS, and About This Mac shows them ("x86-64 macOS guests:
|
||||
@@ -434,12 +389,6 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
if ctx.smbios_memory_type {
|
||||
memory.push_str(",memory_type=26");
|
||||
}
|
||||
// The memory slots as the presented Mac has them: QEMU's memory array is the one DIMM RAM
|
||||
// fills, which System Information lists as the Mac's single slot, where an iMac20,1 has four
|
||||
// SO-DIMM slots. The options are reims-vgpu's QEMU's alone; another QEMU keeps one slot.
|
||||
if let Some(s) = ctx.smbios_memory_slots {
|
||||
memory.push_str(&format!(",slots={},form_factor={}", s.count, s.form_factor));
|
||||
}
|
||||
push(&["-smbios", &memory]);
|
||||
push(&["-device", "ich9-ahci,id=sata,addr=0x2"]);
|
||||
push(&[
|
||||
@@ -456,14 +405,12 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
c.disk_format.as_str(),
|
||||
optp(&vm.disk())
|
||||
);
|
||||
// The qcow2 image's L2 cache, its table of where each cluster is, up to 32 MiB, which maps
|
||||
// 256 GiB of a disk of 64 KiB clusters (qemu-img's default, which a new disk has). QEMU's own
|
||||
// limit is 32 MiB on Linux and 8 MiB elsewhere, which maps 64 GiB, half a new 128 GiB disk:
|
||||
// on Windows a guest access whose table has left the cache reads it from the image again.
|
||||
// QEMU takes the smaller of this and what the image's size needs (block/qcow2.c,
|
||||
// `read_cache_sizes`), so a smaller disk keeps a smaller cache.
|
||||
if c.disk_format == crate::vm::ImageFormat::Qcow2 {
|
||||
disk.push_str(",l2-cache-size=32M");
|
||||
// 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.
|
||||
@@ -485,9 +432,8 @@ 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),
|
||||
]),
|
||||
// At the first slot no other device takes, with NVMe's `discard=unmap`, and an iothread
|
||||
// of its own (`io0`), which runs the disk's requests and their completions outside QEMU's
|
||||
// main loop.
|
||||
// Pass guest TRIMs (`discard=unmap`) like NVMe and offload block handling to a dedicated
|
||||
// iothread so disk completions do not contend with QEMU's main event loop.
|
||||
DiskController::Virtio => push(&[
|
||||
"-object",
|
||||
"iothread,id=io0",
|
||||
@@ -525,7 +471,7 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
}
|
||||
push(&["-vga", "none"]);
|
||||
let gfx = match graphics {
|
||||
// The displays only above one, and the windows' first sizes only where they are not the
|
||||
// The displays only above one, and the windows' first size only where it is not the
|
||||
// device's own, 1920x1080: a QEMU built before either property refuses it.
|
||||
Graphics::ReimsVgpu => format!(
|
||||
"reims-graphics-pci,id=gfx,bus=pcie.0,addr=0x4,romfile={}{}{}",
|
||||
@@ -534,8 +480,8 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
.qemu_displays()
|
||||
.map_or(String::new(), |n| format!(",displays={n}")),
|
||||
c.display
|
||||
.qemu_resolution()
|
||||
.map_or(String::new(), |r| format!(",resolution={}", opt(&r)))
|
||||
.window_size()
|
||||
.map_or(String::new(), |(w, h)| format!(",resolution={w}x{h}"))
|
||||
),
|
||||
Graphics::VmwareSvga => "vmware-svga,id=gfx,bus=pcie.0,addr=0x4".into(),
|
||||
};
|
||||
@@ -628,9 +574,6 @@ fn vmapple(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
let mut machine = format!("vmapple,uuid=0x{:016x}", v.ecid);
|
||||
if c.profile.memfd_ram(ctx.host) {
|
||||
machine.push_str(",memory-backend=ram,dump-guest-core=off");
|
||||
} else if c.profile.section_ram(ctx.host) {
|
||||
// QEMU on Windows leaves no memory out of a core and refuses `dump-guest-core=off`.
|
||||
machine.push_str(",memory-backend=ram");
|
||||
}
|
||||
push(&["-machine", &machine, "-m", &mem]);
|
||||
if c.profile.memfd_ram(ctx.host) {
|
||||
@@ -638,13 +581,6 @@ fn vmapple(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
"-object",
|
||||
&format!("memory-backend-memfd,id=ram,size={mem},share=on"),
|
||||
]);
|
||||
} else if c.profile.section_ram(ctx.host) {
|
||||
// A pagefile-backed section in reims-vgpu's QEMU on Windows (the profile's section_ram),
|
||||
// as q35's: the library maps its views of guest pages from it.
|
||||
push(&[
|
||||
"-object",
|
||||
&format!("memory-backend-ram,id=ram,size={mem},share=on"),
|
||||
]);
|
||||
}
|
||||
push(&["-smp", &c.cpus.to_string()]);
|
||||
push(&["-bios", &boot.ambrosia.to_string_lossy()]);
|
||||
@@ -683,8 +619,8 @@ fn vmapple(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
.qemu_displays()
|
||||
.map_or(String::new(), |n| format!(",displays={n}")),
|
||||
c.display
|
||||
.qemu_resolution()
|
||||
.map_or(String::new(), |r| format!(",resolution={}", opt(&r)))
|
||||
.window_size()
|
||||
.map_or(String::new(), |(w, h)| format!(",resolution={w}x{h}"))
|
||||
),
|
||||
]);
|
||||
// Sound only under KVM, the one accelerator an arm64 guest has booted with it on
|
||||
@@ -790,29 +726,18 @@ pub fn sound_note(backend: &str, devices: crate::os::SoundDevices) -> Option<Str
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a start of `vm` in `ctx` is headless, with no window to open: a headless start
|
||||
/// ([`Ctx::headless`]), or one on reims-vgpu's own device whose VM's variables give
|
||||
/// `REIMS_VGPU_WINDOW=0`.
|
||||
pub fn headless(vm: &Vm, ctx: &Ctx) -> bool {
|
||||
let env = &vm.config.extra_env;
|
||||
ctx.headless
|
||||
|| (vm.config.graphics().library()
|
||||
&& env.get("REIMS_VGPU_WINDOW").is_some_and(|v| v == "0"))
|
||||
}
|
||||
|
||||
/// Whether a start of `vm` in `ctx` opens a window on the host: none where it is headless
|
||||
/// ([`headless`]); else QEMU's own, GTK's, for VMware SVGA where it can open ([`Ctx::screen`]);
|
||||
/// the library's on reims-vgpu's own device on a Mac, where it is AppKit's, and elsewhere where
|
||||
/// Whether a start of `vm` in `ctx` opens a window on the host: QEMU's own, GTK's, for VMware
|
||||
/// SVGA where it can open ([`Ctx::screen`]); the library's on reims-vgpu's own device unless the
|
||||
/// VM's variables give `REIMS_VGPU_WINDOW=0`, on a Mac, where it is AppKit's, and elsewhere where
|
||||
/// a window can open, without which the library opens none and the guest runs headless
|
||||
/// (crates/reims-vgpu-window/features.md, "On Linux").
|
||||
pub fn opens_window(vm: &Vm, ctx: &Ctx) -> bool {
|
||||
if headless(vm, ctx) {
|
||||
return false;
|
||||
}
|
||||
if !vm.config.graphics().library() {
|
||||
return ctx.screen;
|
||||
}
|
||||
ctx.host.os == Os::Mac || ctx.screen
|
||||
let env = &vm.config.extra_env;
|
||||
let headless = env.get("REIMS_VGPU_WINDOW").is_some_and(|v| v == "0");
|
||||
!headless && (ctx.host.os == Os::Mac || ctx.screen)
|
||||
}
|
||||
|
||||
fn common(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
@@ -821,7 +746,7 @@ fn common(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
if !c.network.enabled {
|
||||
push(&["-nic", "none"]);
|
||||
}
|
||||
let qemu_window = !c.graphics().library() && ctx.screen && !ctx.headless;
|
||||
let qemu_window = !c.graphics().library() && ctx.screen;
|
||||
push(&["-display", if qemu_window { "gtk" } else { "none" }]);
|
||||
if c.logs.enabled {
|
||||
push(&["-serial", &format!("file:{}", vm.serial_log().display())]);
|
||||
@@ -834,18 +759,10 @@ fn common(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
"-qmp",
|
||||
&format!("unix:{},server=on,wait=off", optp(&vm.qmp_socket())),
|
||||
]);
|
||||
push(&["-trace", SHUTDOWN_TRACE]);
|
||||
push(&["-pidfile", &vm.pidfile().to_string_lossy()]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The trace event QEMU writes a line of to its log, `qemu_system_shutdown_request reason=N`, as
|
||||
/// anything asks it to shut the VM down: the guest, its window's close, a QMP `quit`, a signal
|
||||
/// (system/trace-events; N is QAPI's ShutdownCause, qapi/run-state.json). Every QEMU
|
||||
/// scripts/install-ctl.sh builds has the `log` trace backend, meson's default, which writes the
|
||||
/// events `-trace` turns on to QEMU's stderr, the VM's log.
|
||||
pub const SHUTDOWN_TRACE: &str = "qemu_system_shutdown_request";
|
||||
|
||||
impl Invocation {
|
||||
/// A `std::process::Command` running it.
|
||||
pub fn command(&self) -> std::process::Command {
|
||||
@@ -974,14 +891,9 @@ pub(crate) mod tests {
|
||||
input: true,
|
||||
},
|
||||
nested_vmx: false,
|
||||
model_without_avx2: None,
|
||||
avx512_xstate: false,
|
||||
smbios_memory_type: true,
|
||||
smbios_error_correction: Some(3),
|
||||
smbios_memory_slots: None,
|
||||
cpu_brand: None,
|
||||
screen: true,
|
||||
headless: false,
|
||||
graphics_rom: "/d/firmware/ReimsGraphics-0123456789abcdef.rom".into(),
|
||||
arm64: None,
|
||||
}
|
||||
@@ -1061,8 +973,6 @@ pub(crate) mod tests {
|
||||
"none",
|
||||
"-qmp",
|
||||
"unix:/vms/t/qmp.sock,server=on,wait=off",
|
||||
"-trace",
|
||||
"qemu_system_shutdown_request",
|
||||
"-pidfile",
|
||||
"/vms/t/qemu.pid",
|
||||
];
|
||||
@@ -1351,8 +1261,6 @@ pub(crate) mod tests {
|
||||
"-smbios",
|
||||
"type=2",
|
||||
"-smbios",
|
||||
"type=16,error_correction=3",
|
||||
"-smbios",
|
||||
"type=17,speed=2666,memory_type=26",
|
||||
"-device",
|
||||
"ich9-ahci,id=sata,addr=0x2",
|
||||
@@ -1361,7 +1269,7 @@ pub(crate) mod tests {
|
||||
"-device",
|
||||
"ide-hd,bus=sata.2,drive=opencore,bootindex=1",
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,l2-cache-size=32M",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2",
|
||||
"-device",
|
||||
"ide-hd,bus=sata.3,drive=disk,rotation_rate=1",
|
||||
"-netdev",
|
||||
@@ -1397,8 +1305,6 @@ pub(crate) mod tests {
|
||||
"none",
|
||||
"-qmp",
|
||||
"unix:/vms/t/qmp.sock,server=on,wait=off",
|
||||
"-trace",
|
||||
"qemu_system_shutdown_request",
|
||||
"-pidfile",
|
||||
"/vms/t/qemu.pid",
|
||||
];
|
||||
@@ -1452,7 +1358,7 @@ pub(crate) mod tests {
|
||||
&["-device", "ide-hd,bus=sata.2,drive=opencore,bootindex=1"],
|
||||
&[
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,l2-cache-size=32M",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2",
|
||||
"-device",
|
||||
"ide-hd,bus=sata.3,drive=disk,rotation_rate=1",
|
||||
],
|
||||
@@ -1481,7 +1387,6 @@ pub(crate) mod tests {
|
||||
&["-device", "hda-output,bus=hda.0,audiodev=snd0"],
|
||||
&["-display", "none"],
|
||||
&["-qmp", "unix:/vms/t/qmp.sock,server=on,wait=off"],
|
||||
&["-trace", "qemu_system_shutdown_request"],
|
||||
&["-pidfile", "/vms/t/qemu.pid"],
|
||||
] {
|
||||
assert!(has(a, pair), "missing {pair:?} in {a:?}");
|
||||
@@ -1612,40 +1517,6 @@ pub(crate) mod tests {
|
||||
assert!(e.contains(crate::disks::ONLY), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arm64_vm_on_windows_uses_tcg_and_section_ram() {
|
||||
let win = Host {
|
||||
os: Os::Windows,
|
||||
arch: crate::host::Arch::X86_64,
|
||||
};
|
||||
let inv = invocation(&arm64_vm(), &arm64_ctx(win)).unwrap();
|
||||
assert!(
|
||||
has(&inv.args, &["-accel", "tcg,thread=multi"]),
|
||||
"{:?}",
|
||||
inv.args
|
||||
);
|
||||
assert!(
|
||||
inv.args
|
||||
.iter()
|
||||
.any(|x| x.starts_with("vmapple,uuid=") && x.ends_with(",memory-backend=ram")),
|
||||
"{:?}",
|
||||
inv.args
|
||||
);
|
||||
assert!(
|
||||
!inv.args.iter().any(|x| x.contains("dump-guest-core=off")),
|
||||
"{:?}",
|
||||
inv.args
|
||||
);
|
||||
assert!(
|
||||
has(
|
||||
&inv.args,
|
||||
&["-object", "memory-backend-ram,id=ram,size=8192M,share=on"]
|
||||
),
|
||||
"{:?}",
|
||||
inv.args
|
||||
);
|
||||
}
|
||||
|
||||
/// With logs off the library still logs its warnings; with logs on, at their level.
|
||||
#[test]
|
||||
fn the_librarys_warnings_are_logged_with_logs_off() {
|
||||
@@ -1708,125 +1579,6 @@ pub(crate) mod tests {
|
||||
assert!(!cpu(false).contains("vmx"));
|
||||
}
|
||||
|
||||
/// The guest's CPU gives the host CPU's brand string as its own (`model-id`), its commas
|
||||
/// doubled as QEMU's option syntax escapes them, after the flags reims-ctl gives and before
|
||||
/// the VM's own, so a VM's `model-id=` there replaces it; the CPU's model and every flag are
|
||||
/// the line a host with no brand string gets. An arm64 VM's CPU takes none.
|
||||
#[test]
|
||||
fn the_guests_cpu_names_the_hosts_brand() {
|
||||
let cpu = |vm: &Vm, brand: Option<&str>| {
|
||||
let c = Ctx {
|
||||
avx512_xstate: true,
|
||||
cpu_brand: brand.map(String::from),
|
||||
..ctx(linux())
|
||||
};
|
||||
let inv = invocation(vm, &c).unwrap();
|
||||
let i = inv.args.iter().position(|x| x == "-cpu").unwrap();
|
||||
inv.args[i + 1].clone()
|
||||
};
|
||||
let head = format!(
|
||||
"{},kvm=on,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on,x-avx512-xstate=on",
|
||||
default_cpu_model()
|
||||
);
|
||||
let flags = default_cpu_flags();
|
||||
let vm = q35_vm();
|
||||
assert_eq!(cpu(&vm, None), format!("{head},{flags}"));
|
||||
assert_eq!(
|
||||
cpu(&vm, Some("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics")),
|
||||
format!("{head},model-id=AMD Ryzen 7 7840HS w/ Radeon 780M Graphics,{flags}")
|
||||
);
|
||||
assert_eq!(
|
||||
cpu(&vm, Some("Vendor, Model 1")),
|
||||
format!("{head},model-id=Vendor,, Model 1,{flags}")
|
||||
);
|
||||
let mut own = q35_vm();
|
||||
own.config.q35.as_mut().unwrap().cpu_flags = format!("{flags},model-id=Mine");
|
||||
assert_eq!(
|
||||
cpu(&own, Some("13th Gen Intel(R) Core(TM) i9-13900H")),
|
||||
format!("{head},model-id=13th Gen Intel(R) Core(TM) i9-13900H,{flags},model-id=Mine")
|
||||
);
|
||||
let arm = invocation(
|
||||
&arm64_vm(),
|
||||
&Ctx {
|
||||
cpu_brand: Some("AMD Ryzen 7 7840HS".into()),
|
||||
..arm64_ctx(linux())
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
!arm.args.iter().any(|a| a.contains("model-id")),
|
||||
"{:?}",
|
||||
arm.args
|
||||
);
|
||||
}
|
||||
|
||||
/// On a host whose CPU lacks AVX2 (a fake of its CPU's features, which
|
||||
/// crate::host::model_without_avx2 reads), a VM on reims-ctl's own model names the host's
|
||||
/// model, the features it adds come after reims-ctl's flags and the host's brand, and the
|
||||
/// VM's flags follow without those the host lacks: on an Ivy Bridge-EP Xeon, the whole line
|
||||
/// is the one the lane's boot ran (docs/qemu.md, "x86-64 macOS guests: the CPU model"). A VM
|
||||
/// with a model of its own keeps it with nothing added, and a host with AVX2 changes nothing.
|
||||
#[test]
|
||||
fn a_host_without_avx2_names_its_own_model() {
|
||||
let ivy_ep = [
|
||||
"ssse3",
|
||||
"sse4.2",
|
||||
"popcnt",
|
||||
"aes",
|
||||
"pclmulqdq",
|
||||
"arat",
|
||||
"avx",
|
||||
"xsave",
|
||||
"xsaveopt",
|
||||
"rdtscp",
|
||||
"x2apic",
|
||||
"tsc-deadline",
|
||||
"f16c",
|
||||
"rdrand",
|
||||
"fsgsbase",
|
||||
"smep",
|
||||
"erms",
|
||||
"pcid",
|
||||
"spec-ctrl",
|
||||
];
|
||||
let model = |has: &[&str]| crate::host::model_without_avx2(&|f| has.contains(&f));
|
||||
let cpu = |vm: &Vm, model: Option<crate::host::HostModel>| {
|
||||
let c = Ctx {
|
||||
model_without_avx2: model,
|
||||
cpu_brand: Some("Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz".into()),
|
||||
..ctx(linux())
|
||||
};
|
||||
let inv = invocation(vm, &c).unwrap();
|
||||
let i = inv.args.iter().position(|x| x == "-cpu").unwrap();
|
||||
inv.args[i + 1].clone()
|
||||
};
|
||||
let vm = q35_vm();
|
||||
assert_eq!(
|
||||
cpu(&vm, model(&ivy_ep)),
|
||||
"IvyBridge-IBRS,kvm=on,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on,\
|
||||
model-id=Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz,+pcid,+ssse3,+sse4.2,+popcnt,\
|
||||
+avx,+aes,+xsave,+xsaveopt,check"
|
||||
);
|
||||
// No AVX: reims-ctl's +avx is left out.
|
||||
let no_avx: Vec<&str> = ivy_ep.into_iter().filter(|&f| f != "avx").collect();
|
||||
let line = cpu(&vm, model(&no_avx));
|
||||
assert!(line.starts_with("Westmere-IBRS,"), "{line}");
|
||||
assert!(!line.contains("avx"), "{line}");
|
||||
let tail = "kvm=on,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on,\
|
||||
model-id=Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz";
|
||||
let flags = default_cpu_flags();
|
||||
assert_eq!(
|
||||
cpu(&vm, None),
|
||||
format!("{},{tail},{flags}", default_cpu_model())
|
||||
);
|
||||
let mut own = q35_vm();
|
||||
own.config.q35.as_mut().unwrap().cpu_model = "Haswell-noTSX".into();
|
||||
assert_eq!(
|
||||
cpu(&own, model(&ivy_ep)),
|
||||
format!("Haswell-noTSX,{tail},{flags}")
|
||||
);
|
||||
}
|
||||
|
||||
/// QEMU's `x-avx512-xstate` only where each fact holds, asked in their order: KVM, the host's
|
||||
/// AVX-512 state at any layout, AMD's or Intel's, the guest's kexts in the image, then a QEMU
|
||||
/// that knows the property; neither the image nor QEMU is read where a fact before fails.
|
||||
@@ -1873,7 +1625,6 @@ pub(crate) mod tests {
|
||||
let smbios = |smbios_memory_type| {
|
||||
let c = Ctx {
|
||||
smbios_memory_type,
|
||||
smbios_error_correction: None,
|
||||
..ctx(linux())
|
||||
};
|
||||
let inv = invocation(&q35_vm(), &c).unwrap();
|
||||
@@ -1890,84 +1641,6 @@ pub(crate) mod tests {
|
||||
assert_eq!(smbios(false), ["type=2", "type=17,speed=2666"]);
|
||||
}
|
||||
|
||||
/// The memory array's error correction is given where the context has one, the presented
|
||||
/// Mac's, before the memory devices; without it the `-smbios` options are those reims-ctl gave
|
||||
/// before it had the option, byte for byte, as with a QEMU that lacks it.
|
||||
#[test]
|
||||
fn error_correction_only_where_the_context_has_it() {
|
||||
let smbios = |smbios_error_correction| {
|
||||
let c = Ctx {
|
||||
smbios_error_correction,
|
||||
..ctx(linux())
|
||||
};
|
||||
let inv = invocation(&q35_vm(), &c).unwrap();
|
||||
inv.args
|
||||
.windows(2)
|
||||
.filter(|w| w[0] == "-smbios")
|
||||
.map(|w| w[1].clone())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
smbios(Some(3)),
|
||||
[
|
||||
"type=2",
|
||||
"type=16,error_correction=3",
|
||||
"type=17,speed=2666,memory_type=26",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
smbios(Some(6)),
|
||||
[
|
||||
"type=2",
|
||||
"type=16,error_correction=6",
|
||||
"type=17,speed=2666,memory_type=26",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
smbios(None),
|
||||
["type=2", "type=17,speed=2666,memory_type=26"]
|
||||
);
|
||||
}
|
||||
|
||||
/// The memory slots are given where the context has them, the presented Mac's, in the memory
|
||||
/// devices' option; without them the `-smbios` options are those reims-ctl gave before it had
|
||||
/// the options, byte for byte, as with a QEMU that lacks them.
|
||||
#[test]
|
||||
fn memory_slots_only_where_the_context_has_them() {
|
||||
let smbios = |smbios_memory_slots| {
|
||||
let c = Ctx {
|
||||
smbios_memory_slots,
|
||||
..ctx(linux())
|
||||
};
|
||||
let inv = invocation(&q35_vm(), &c).unwrap();
|
||||
inv.args
|
||||
.windows(2)
|
||||
.filter(|w| w[0] == "-smbios")
|
||||
.map(|w| w[1].clone())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let imac = crate::reims_util::MemorySlots {
|
||||
count: 4,
|
||||
form_factor: 13,
|
||||
};
|
||||
assert_eq!(
|
||||
smbios(Some(imac)),
|
||||
[
|
||||
"type=2",
|
||||
"type=16,error_correction=3",
|
||||
"type=17,speed=2666,memory_type=26,slots=4,form_factor=13",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
smbios(None),
|
||||
[
|
||||
"type=2",
|
||||
"type=16,error_correction=3",
|
||||
"type=17,speed=2666,memory_type=26",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// `x-avx512-xstate=on` comes after `vmx=on` and before the VM's `cpu_flags`, so a VM's
|
||||
/// `x-avx512-xstate=off` there takes it away: QEMU applies `name=value` flags in order, the
|
||||
/// last one winning. Without it, the line is the one reims-ctl gave before it had the
|
||||
@@ -2093,7 +1766,7 @@ pub(crate) mod tests {
|
||||
&a,
|
||||
&[
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,l2-cache-size=32M,discard=unmap",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,discard=unmap",
|
||||
"-device",
|
||||
"nvme,drive=disk,serial=reims-ctl,addr=0xa",
|
||||
]
|
||||
@@ -2121,7 +1794,7 @@ pub(crate) mod tests {
|
||||
"-object",
|
||||
"iothread,id=io0",
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,l2-cache-size=32M,discard=unmap",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,discard=unmap",
|
||||
"-device",
|
||||
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
|
||||
]
|
||||
@@ -2151,45 +1824,13 @@ pub(crate) mod tests {
|
||||
"-object",
|
||||
"iothread,id=io0",
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,l2-cache-size=32M,cache.no-flush=on,discard=unmap",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on,discard=unmap",
|
||||
"-device",
|
||||
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
|
||||
]
|
||||
));
|
||||
}
|
||||
|
||||
/// A qcow2 system disk's L2 cache may grow to 32 MiB on every host and controller, the image
|
||||
/// read by no one but QEMU; a raw disk, which has no L2 tables, takes no such option, which
|
||||
/// QEMU's raw driver would refuse.
|
||||
#[test]
|
||||
fn a_qcow2_disk_has_an_l2_cache_of_up_to_32_mib() {
|
||||
let windows = Host {
|
||||
os: Os::Windows,
|
||||
arch: crate::host::Arch::X86_64,
|
||||
};
|
||||
for controller in [
|
||||
DiskController::Ahci,
|
||||
DiskController::Nvme,
|
||||
DiskController::Virtio,
|
||||
] {
|
||||
for host in [linux(), windows] {
|
||||
let mut vm = q35_vm();
|
||||
vm.config.q35.as_mut().unwrap().disk_controller = controller;
|
||||
let a = invocation(&vm, &ctx(host)).unwrap().args;
|
||||
let disk: Vec<&String> = a.iter().filter(|x| x.starts_with("id=disk,")).collect();
|
||||
assert_eq!(disk.len(), 1, "{a:?}");
|
||||
assert!(
|
||||
disk[0].contains(",format=qcow2,") && disk[0].contains(",l2-cache-size=32M"),
|
||||
"{a:?}"
|
||||
);
|
||||
vm.config.disk = "disk.img".into();
|
||||
vm.config.disk_format = ImageFormat::Raw;
|
||||
let a = invocation(&vm, &ctx(host)).unwrap().args;
|
||||
assert!(!a.iter().any(|x| x.contains("l2-cache-size")), "{a:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The system disk drops the guest's flushes while the installer is attached, on SATA and on
|
||||
/// NVMe, and keeps them once it is ejected.
|
||||
#[test]
|
||||
@@ -2200,7 +1841,7 @@ pub(crate) mod tests {
|
||||
&a,
|
||||
&[
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,l2-cache-size=32M"
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2"
|
||||
]
|
||||
));
|
||||
assert!(!a.iter().any(|x| x.contains("no-flush")), "{a:?}");
|
||||
@@ -2210,7 +1851,7 @@ pub(crate) mod tests {
|
||||
&a,
|
||||
&[
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,l2-cache-size=32M,cache.no-flush=on"
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on"
|
||||
]
|
||||
));
|
||||
// Only the system disk: the installer's overlay and OpenCore's image keep theirs.
|
||||
@@ -2225,7 +1866,7 @@ pub(crate) mod tests {
|
||||
&a,
|
||||
&[
|
||||
"-drive",
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,l2-cache-size=32M,cache.no-flush=on,\
|
||||
"id=disk,if=none,format=qcow2,file=/vms/t/disk.qcow2,cache.no-flush=on,\
|
||||
discard=unmap"
|
||||
]
|
||||
));
|
||||
@@ -2285,7 +1926,6 @@ pub(crate) mod tests {
|
||||
driver_file: Some("/icd/nvidia.json".into()),
|
||||
device_id: Some(0x2204),
|
||||
select: Some("10de:2204".into()),
|
||||
pci: None,
|
||||
name: Some("NVIDIA GeForce RTX 3090".into()),
|
||||
};
|
||||
vm.config
|
||||
@@ -2310,38 +1950,6 @@ pub(crate) mod tests {
|
||||
assert!(!inv.unset.contains(&"REIMS_VGPU_LOG".to_string()));
|
||||
}
|
||||
|
||||
/// A GPU whose IDs another GPU of the host has is named by its PCI address, `DRI_PRIME`'s
|
||||
/// `pci-` form, with its IDs to the loader and no `MESA_VK_DEVICE_SELECT`, which the library
|
||||
/// reads first and whose IDs would name the first of the two (crate::gpu).
|
||||
#[test]
|
||||
fn a_gpu_another_of_its_ids_shares_the_host_with_is_named_by_its_address() {
|
||||
let mut vm = q35_vm();
|
||||
vm.config.gpu = Gpu {
|
||||
driver_file: Some("/icd/radeon_icd.x86_64.json".into()),
|
||||
device_id: Some(0x6798),
|
||||
select: Some("1002:6798".into()),
|
||||
pci: Some("0000:06:00.0".into()),
|
||||
name: Some("AMD Radeon R9 200 / HD 7900 Series (RADV TAHITI)".into()),
|
||||
};
|
||||
let env: BTreeMap<_, _> = invocation(&vm, &ctx(linux()))
|
||||
.unwrap()
|
||||
.env
|
||||
.into_iter()
|
||||
.collect();
|
||||
assert_eq!(env["DRI_PRIME"], "pci-0000_06_00_0");
|
||||
assert_eq!(env["VK_LOADER_DEVICE_SELECT"], "0x1002:0x6798");
|
||||
assert!(!env.contains_key("MESA_VK_DEVICE_SELECT"), "{env:?}");
|
||||
assert!(!env.contains_key("VK_DRIVER_FILES"), "{env:?}");
|
||||
vm.config.gpu.pci = None;
|
||||
let env: BTreeMap<_, _> = invocation(&vm, &ctx(linux()))
|
||||
.unwrap()
|
||||
.env
|
||||
.into_iter()
|
||||
.collect();
|
||||
assert_eq!(env["MESA_VK_DEVICE_SELECT"], "1002:6798");
|
||||
assert!(!env.contains_key("DRI_PRIME"), "{env:?}");
|
||||
}
|
||||
|
||||
/// A GPU its settings name by its driver's manifest alone (a CPU implementation, a GPU
|
||||
/// another manifest reaches too, or a manifest given by its path; crate::gpu) limits the
|
||||
/// loader to that driver, keeping the GPU's device ID where the driver drives several. A
|
||||
@@ -2353,7 +1961,6 @@ pub(crate) mod tests {
|
||||
driver_file: Some("/icd/radeon.json".into()),
|
||||
device_id: Some(0x744c),
|
||||
select: None,
|
||||
pci: None,
|
||||
name: Some("AMD Radeon RX 7900 XTX (RADV NAVI31)".into()),
|
||||
};
|
||||
let env: BTreeMap<_, _> = invocation(&vm, &ctx(linux()))
|
||||
@@ -2437,46 +2044,6 @@ pub(crate) mod tests {
|
||||
assert!(!opens_window(&vm, &headless(linux())));
|
||||
}
|
||||
|
||||
/// A headless start (`reims-ctl start --headless`) opens no window on any host: on
|
||||
/// reims-vgpu's own device QEMU gets `REIMS_VGPU_WINDOW=0`, over a value the VM's own
|
||||
/// variables give, and VMware SVGA's QEMU `-display none` where its window could open.
|
||||
#[test]
|
||||
fn a_headless_start_opens_no_window() {
|
||||
let started = |host| Ctx {
|
||||
headless: true,
|
||||
..ctx(host)
|
||||
};
|
||||
let mut vm = q35_vm();
|
||||
for host in [linux(), mac()] {
|
||||
assert!(headless(&vm, &started(host)) && !opens_window(&vm, &started(host)));
|
||||
let inv = invocation(&vm, &started(host)).unwrap();
|
||||
let env: BTreeMap<_, _> = inv.env.iter().cloned().collect();
|
||||
assert_eq!(env["REIMS_VGPU_WINDOW"], "0");
|
||||
assert!(!inv.unset.contains(&"REIMS_VGPU_WINDOW".to_string()));
|
||||
assert!(has(&inv.args, &["-display", "none"]));
|
||||
}
|
||||
assert!(!headless(&vm, &ctx(linux())));
|
||||
vm.config
|
||||
.extra_env
|
||||
.insert("REIMS_VGPU_WINDOW".into(), "1".into());
|
||||
let inv = invocation(&vm, &started(linux())).unwrap();
|
||||
let window: Vec<_> = inv
|
||||
.env
|
||||
.iter()
|
||||
.filter(|(k, _)| k == "REIMS_VGPU_WINDOW")
|
||||
.collect();
|
||||
assert_eq!(
|
||||
window,
|
||||
[&("REIMS_VGPU_WINDOW".to_string(), "0".to_string())]
|
||||
);
|
||||
vm.config.extra_env.clear();
|
||||
vm.config.graphics = Some(Graphics::VmwareSvga);
|
||||
assert!(headless(&vm, &started(linux())) && !opens_window(&vm, &started(linux())));
|
||||
let inv = invocation(&vm, &started(linux())).unwrap();
|
||||
assert!(has(&inv.args, &["-display", "none"]), "{:?}", inv.args);
|
||||
assert!(inv.env.is_empty(), "{:?}", inv.env);
|
||||
}
|
||||
|
||||
/// reims-vgpu's own device, with the ROM reims-ctl carries, on a machine that leaves its BAR
|
||||
/// room below 4 GiB: the default of a VM whose settings name no graphics. The resolution, as
|
||||
/// its window's first size, and borderless reach it; the GPU and the logs are the library's.
|
||||
@@ -2538,41 +2105,31 @@ pub(crate) mod tests {
|
||||
assert!(!a.iter().any(|x| x.contains("max-ram-below-4g")), "{a:?}");
|
||||
}
|
||||
|
||||
/// A resolution of one size per display reaches the device as its `resolution`, the sizes in
|
||||
/// the displays' order with each comma doubled, x86-64 and arm64 alike; one size for every
|
||||
/// display gives the device string reims-ctl gave before a resolution could name several,
|
||||
/// byte for byte, and so do sizes that are all that one size.
|
||||
/// A VM whose capture setting is off gives the library's windows
|
||||
/// `REIMS_VGPU_WINDOW_CAPTURE=0`, x86-64 and arm64 alike; with capture on, the default, the
|
||||
/// variable is left out, and so it is on VMware SVGA, whose window is QEMU's.
|
||||
#[test]
|
||||
fn each_display_s_size_reaches_the_device() {
|
||||
let gfx = |vm: &Vm, c: &Ctx| {
|
||||
let a = invocation(vm, c).unwrap().args;
|
||||
let i = a
|
||||
.iter()
|
||||
.position(|x| x.starts_with("reims-graphics-pci,"))
|
||||
.unwrap();
|
||||
a[i].clone()
|
||||
fn capture_off_reaches_the_library_s_windows() {
|
||||
let capture = |vm: &Vm, c: &Ctx| {
|
||||
invocation(vm, c)
|
||||
.unwrap()
|
||||
.env
|
||||
.into_iter()
|
||||
.find(|(k, _)| k == "REIMS_VGPU_WINDOW_CAPTURE")
|
||||
.map(|(_, v)| v)
|
||||
};
|
||||
let mut vm = q35_vm();
|
||||
vm.config.display.count = 2;
|
||||
let rom = "reims-graphics-pci,id=gfx,bus=pcie.0,addr=0x4,\
|
||||
romfile=/d/firmware/ReimsGraphics-0123456789abcdef.rom,displays=2";
|
||||
vm.config.display.resolution = "2560x1440".into();
|
||||
let one = format!("{rom},resolution=2560x1440");
|
||||
assert_eq!(gfx(&vm, &ctx(linux())), one);
|
||||
vm.config.display.resolution = "2560x1440,2560x1440".into();
|
||||
assert_eq!(gfx(&vm, &ctx(linux())), one);
|
||||
vm.config.display.resolution = "2560x1440,1920x1080".into();
|
||||
assert_eq!(
|
||||
gfx(&vm, &ctx(linux())),
|
||||
format!("{rom},resolution=2560x1440,,1920x1080")
|
||||
);
|
||||
let mut arm = arm64_vm();
|
||||
arm.config.display.count = 2;
|
||||
arm.config.display.resolution = "1920x1080,1280x800".into();
|
||||
assert_eq!(
|
||||
gfx(&arm, &arm64_ctx(mac())),
|
||||
"reims-graphics-pci,id=gfx,displays=2,resolution=1920x1080,,1280x800"
|
||||
);
|
||||
assert!(vm.config.display.capture);
|
||||
assert_eq!(capture(&vm, &ctx(linux())), None);
|
||||
vm.config.display.capture = false;
|
||||
assert_eq!(capture(&vm, &ctx(linux())).as_deref(), Some("0"));
|
||||
assert_eq!(capture(&vm, &ctx(mac())).as_deref(), Some("0"));
|
||||
vm.config.graphics = Some(Graphics::VmwareSvga);
|
||||
assert_eq!(capture(&vm, &ctx(linux())), None);
|
||||
let mut vm = arm64_vm();
|
||||
assert_eq!(capture(&vm, &arm64_ctx(mac())), None);
|
||||
vm.config.display.capture = false;
|
||||
assert_eq!(capture(&vm, &arm64_ctx(mac())).as_deref(), Some("0"));
|
||||
}
|
||||
|
||||
/// A VM of several displays gives reims-vgpu's device their count, and nothing else of the
|
||||
|
||||
@@ -1,476 +0,0 @@
|
||||
//! The TOML files reims-ctl keeps its records in, written so that what another build of reims-ctl
|
||||
//! wrote into them stays as it was ([`text_over`]): each VM's `vm.toml`, the registry
|
||||
//! (`vms.toml`), the install's record (`install.toml`) and the migrations' (`migrations.toml`).
|
||||
//!
|
||||
//! A newer build may add keys to a record, and an older build may save the same file: one still
|
||||
//! open from before an update, or one a switch of channel installed. Re-serialising its own struct
|
||||
//! would drop the keys it does not know. So each save edits the file as it is, with `toml_edit`:
|
||||
//! a key the saving build does not know keeps its place and its form, and so does each key it
|
||||
//! knows whose value it leaves unchanged; only what it changes is written. A record of any type
|
||||
//! that serializes to TOML and reads back as itself can be written this way.
|
||||
//!
|
||||
//! A file this build cannot edit so is never written over: the save is refused ([`Refused`]),
|
||||
//! and the file stays as it is. So is one it cannot read: a save reads the file as it is with
|
||||
//! [`old_text`], which takes only a file that is not there for no file.
|
||||
//!
|
||||
//! A save writes the record's text into a file of its own beside it and renames that over it
|
||||
//! ([`replace`]): a reader never meets the record half-written, and of two saves at once, from
|
||||
//! two processes or two threads, the last rename leaves its whole text, never a mix of the two.
|
||||
|
||||
use anyhow::Result;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::path::{Path, PathBuf};
|
||||
use toml_edit::{ArrayOfTables, DocumentMut, Item, Table, TableLike};
|
||||
|
||||
/// A save refused because its record's file holds what this build cannot keep through it
|
||||
/// ([`text_over`]): the file is left as it is.
|
||||
#[derive(Debug)]
|
||||
pub struct Refused {
|
||||
/// The record's file.
|
||||
pub file: PathBuf,
|
||||
/// Why this build cannot keep what the file holds.
|
||||
pub why: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Refused {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{} was left as it is: {}. Saving over it would drop what it holds that this \
|
||||
reims-ctl doesn't know, which a newer reims-ctl may have written. Update or restart \
|
||||
reims-ctl, or move the file aside and try again",
|
||||
crate::paths::tilde(&self.file),
|
||||
self.why
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Refused {}
|
||||
|
||||
/// `record`'s text written over `old`, the text of its file, `file`, as it is now, where there is
|
||||
/// one: `old` itself, edited in place.
|
||||
/// - A key this build reads is written as `record` has it. Its value is replaced where it
|
||||
/// differs, keeping the old value's place and spacing. The key is removed where `record`
|
||||
/// leaves it out, as a cleared setting is, and added at the end of its table where `old` lacks
|
||||
/// it.
|
||||
/// - Every other key stays where and as it is: one a newer build wrote. The exceptions are the
|
||||
/// `retired` keys, as dotted paths (`display.hidpi`), which an older build wrote and this one
|
||||
/// reads past and drops.
|
||||
/// - A `[[name]]` array's tables are matched to `old`'s by what this build reads of them, so a
|
||||
/// table left as it was keeps its other keys while others are added or removed.
|
||||
///
|
||||
/// `record`'s own text where there is no file. Refused ([`Refused`]) where `old` is not TOML this
|
||||
/// build reads, or not TOML it reads as such a record, as a newer build may write, or where the
|
||||
/// edited text would not read back as `record`, as a key this build reads under another name
|
||||
/// would make it: a write would drop what the file holds.
|
||||
pub fn text_over<T>(record: &T, file: &Path, old: Option<&str>, retired: &[&str]) -> Result<String>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + PartialEq,
|
||||
{
|
||||
let new = toml::to_string_pretty(record)?;
|
||||
let Some(old) = old else {
|
||||
return Ok(new);
|
||||
};
|
||||
edited(record, old, &new, retired).map_err(|why| {
|
||||
Refused {
|
||||
file: file.to_path_buf(),
|
||||
why,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
/// A name for a file or directory written beside `place` and then renamed into it, apart from
|
||||
/// every other writer's: `.<name>.<pid>-<n>.tmp`, `n` counting the names this process gave. Two
|
||||
/// writers sharing one name would write into one file, each truncating what the other wrote,
|
||||
/// and the first rename would install it while the second still writes.
|
||||
pub fn beside(place: &Path) -> PathBuf {
|
||||
static GIVEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = GIVEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut name = std::ffi::OsString::from(".");
|
||||
name.push(place.file_name().unwrap_or_default());
|
||||
name.push(format!(".{}-{n}.tmp", std::process::id()));
|
||||
place.with_file_name(name)
|
||||
}
|
||||
|
||||
/// Writes `bytes` over `file` through a file of its own beside it ([`beside`]), renamed over
|
||||
/// `file` once written, so `file` holds either what it held or all of `bytes`; the file beside
|
||||
/// it is removed where the write or the rename fails.
|
||||
pub fn replace(file: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
let tmp = beside(file);
|
||||
let written = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, file));
|
||||
if written.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
/// The files written beside `place` ([`beside`]) that are there still: none once every save
|
||||
/// ended, as each renames its own or removes it.
|
||||
#[cfg(test)]
|
||||
pub fn left_beside(place: &Path) -> Vec<PathBuf> {
|
||||
let mut head = std::ffi::OsString::from(".");
|
||||
head.push(place.file_name().unwrap_or_default());
|
||||
head.push(".");
|
||||
let head = head.to_string_lossy().into_owned();
|
||||
let Ok(entries) = std::fs::read_dir(place.parent().unwrap_or(Path::new("."))) else {
|
||||
return Vec::new();
|
||||
};
|
||||
(entries.flatten())
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
let name = p.file_name().unwrap_or_default().to_string_lossy();
|
||||
name.starts_with(&head) && name.ends_with(".tmp")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text of `file`, a record's, as it is now, for a save over it ([`text_over`]): `None` where
|
||||
/// there is no file. Refused ([`Refused`]) where there is one this build can't read: one that
|
||||
/// isn't UTF-8, or that a permission or an I/O error keeps from it. A save that took it for no
|
||||
/// file would write its own text over what the file holds.
|
||||
pub fn old_text(file: &Path) -> Result<Option<String>> {
|
||||
match std::fs::read_to_string(file) {
|
||||
Ok(text) => Ok(Some(text)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(Refused {
|
||||
file: file.to_path_buf(),
|
||||
why: format!("this reims-ctl can't read it ({e})"),
|
||||
}
|
||||
.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that `save`, a save of the record whose file is `file`, is refused ([`Refused`], naming
|
||||
/// `file`) where the file is there and this build can't read it, and leaves the file byte for
|
||||
/// byte as it was: one that isn't UTF-8, and on Unix one its mode keeps from the test's user,
|
||||
/// where the mode does (root reads it all the same).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn assert_unreadable_refused(file: &Path, save: &dyn Fn() -> Result<()>) {
|
||||
let refused = |what: &str| {
|
||||
let e = save().expect_err(what);
|
||||
let Some(x) = e.downcast_ref::<Refused>() else {
|
||||
panic!("{what}: not refused: {e:#}");
|
||||
};
|
||||
assert_eq!(x.file, file, "{what}");
|
||||
assert!(
|
||||
x.why.starts_with("this reims-ctl can't read it ("),
|
||||
"{what}: {x}"
|
||||
);
|
||||
};
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
let not_utf8 = b"name = \"\xff\xfe\"\n";
|
||||
std::fs::write(file, not_utf8).unwrap();
|
||||
refused("not UTF-8");
|
||||
assert_eq!(std::fs::read(file).unwrap(), not_utf8);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let text = b"name = \"kept\"\n";
|
||||
std::fs::write(file, text).unwrap();
|
||||
let mode = |m| {
|
||||
let mode = std::fs::Permissions::from_mode(m);
|
||||
std::fs::set_permissions(file, mode).unwrap();
|
||||
};
|
||||
mode(0o000);
|
||||
let kept_from_us = std::fs::read(file).is_err();
|
||||
if kept_from_us {
|
||||
refused("unreadable by its mode");
|
||||
}
|
||||
mode(0o644);
|
||||
assert_eq!(std::fs::read(file).unwrap(), text);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`text_over`]'s edit of `old`, where it can make one that reads back as `record`, whose own
|
||||
/// text is `new`; else why it cannot.
|
||||
fn edited<T>(record: &T, old: &str, new: &str, retired: &[&str]) -> Result<String, String>
|
||||
where
|
||||
T: Serialize + DeserializeOwned + PartialEq,
|
||||
{
|
||||
let mut doc: DocumentMut = old.parse().map_err(|e: toml_edit::TomlError| {
|
||||
format!("it isn't TOML this reims-ctl reads ({})", e.message())
|
||||
})?;
|
||||
let read: T = toml::from_str(old)
|
||||
.map_err(|e| format!("this reims-ctl can't read what it holds ({})", e.message()))?;
|
||||
// What this build reads of the file, as it writes it: the keys it knows.
|
||||
let ours = |r: &T| -> Option<DocumentMut> { toml::to_string_pretty(r).ok()?.parse().ok() };
|
||||
let (Some(known), Some(new)) = (ours(&read), new.parse::<DocumentMut>().ok()) else {
|
||||
return Err("this reims-ctl can't write its record as TOML".into());
|
||||
};
|
||||
merge_table(
|
||||
doc.as_table_mut(),
|
||||
Some(known.as_table() as &dyn TableLike),
|
||||
new.as_table(),
|
||||
"",
|
||||
retired,
|
||||
);
|
||||
let text = doc.to_string();
|
||||
match toml::from_str::<T>(&text) {
|
||||
Ok(r) if r == *record => Ok(text),
|
||||
_ => Err("this reims-ctl can't write its changes around what else it holds".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `new`'s keys into `old`, the table at `path`, whose keys this build knows are
|
||||
/// `known`'s ([`text_over`]).
|
||||
fn merge_table(
|
||||
old: &mut dyn TableLike,
|
||||
known: Option<&dyn TableLike>,
|
||||
new: &dyn TableLike,
|
||||
path: &str,
|
||||
retired: &[&str],
|
||||
) {
|
||||
let at = |key: &str| {
|
||||
if path.is_empty() {
|
||||
key.to_string()
|
||||
} else {
|
||||
format!("{path}.{key}")
|
||||
}
|
||||
};
|
||||
let gone: Vec<String> = old
|
||||
.iter()
|
||||
.map(|(k, _)| k.to_string())
|
||||
.filter(|k| !new.contains_key(k))
|
||||
.filter(|k| known.is_some_and(|t| t.contains_key(k)) || retired.contains(&at(k).as_str()))
|
||||
.collect();
|
||||
for k in gone {
|
||||
old.remove(&k);
|
||||
}
|
||||
for (k, n) in new.iter() {
|
||||
let known = known.and_then(|t| t.get(k));
|
||||
match old.get_mut(k) {
|
||||
Some(o) => merge_item(o, known, n, &at(k), retired),
|
||||
None => {
|
||||
let mut n = n.clone();
|
||||
unplace(&mut n);
|
||||
old.insert(k, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `new` over `old`, the item at `path`, of which this build knows `known`.
|
||||
fn merge_item(old: &mut Item, known: Option<&Item>, new: &Item, path: &str, retired: &[&str]) {
|
||||
if let (Some(o), Some(n)) = (old.as_table_like_mut(), new.as_table_like()) {
|
||||
merge_table(o, known.and_then(Item::as_table_like), n, path, retired);
|
||||
return;
|
||||
}
|
||||
if let (Some(o), Some(n)) = (old.as_array_of_tables_mut(), new.as_array_of_tables()) {
|
||||
merge_tables(
|
||||
o,
|
||||
known.and_then(Item::as_array_of_tables),
|
||||
n,
|
||||
path,
|
||||
retired,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if let (Some(o), Some(n)) = (old.as_value_mut(), new.as_value()) {
|
||||
if read(&Item::Value(o.clone())) != read(&Item::Value(n.clone())) {
|
||||
let decor = o.decor().clone();
|
||||
*o = n.clone();
|
||||
*o.decor_mut() = decor;
|
||||
}
|
||||
return;
|
||||
}
|
||||
*old = new.clone();
|
||||
unplace(old);
|
||||
}
|
||||
|
||||
/// Writes `new`'s tables over `old`'s, the `[[path]]` array of which this build knows `known`:
|
||||
/// each of `new`'s, in its order, is the table of `old`'s that reads as it, with that table's
|
||||
/// other keys, or else as `new` has it.
|
||||
fn merge_tables(
|
||||
old: &mut ArrayOfTables,
|
||||
known: Option<&ArrayOfTables>,
|
||||
new: &ArrayOfTables,
|
||||
path: &str,
|
||||
retired: &[&str],
|
||||
) {
|
||||
let known: Vec<&Table> = known
|
||||
.filter(|k| k.len() == old.len())
|
||||
.map(|k| k.iter().collect())
|
||||
.unwrap_or_default();
|
||||
let known_read: Vec<_> = known
|
||||
.iter()
|
||||
.map(|t| read(&Item::Table((*t).clone())))
|
||||
.collect();
|
||||
// Every table at the place of the first, so they stay together, in the array's order.
|
||||
let place = old.get(0).and_then(Table::position);
|
||||
let mut used = vec![false; known.len()];
|
||||
let mut out = ArrayOfTables::new();
|
||||
for n in new.iter() {
|
||||
let wanted = read(&Item::Table(n.clone()));
|
||||
let found = (0..known.len()).find(|&i| !used[i] && known_read[i] == wanted);
|
||||
let mut t = match (found, found.and_then(|i| old.get(i))) {
|
||||
(Some(i), Some(o)) => {
|
||||
used[i] = true;
|
||||
let mut o = o.clone();
|
||||
merge_table(&mut o, Some(known[i] as &dyn TableLike), n, path, retired);
|
||||
o
|
||||
}
|
||||
_ => {
|
||||
let mut n = n.clone();
|
||||
unplace_table(&mut n);
|
||||
n
|
||||
}
|
||||
};
|
||||
t.set_position(place);
|
||||
out.push(t);
|
||||
}
|
||||
*old = out;
|
||||
}
|
||||
|
||||
/// What `item` reads as, however it is written: its value as a key's, `v`'s. None where it does
|
||||
/// not read.
|
||||
fn read(item: &Item) -> Option<toml::Value> {
|
||||
let mut item = item.clone();
|
||||
unplace(&mut item);
|
||||
let mut doc = DocumentMut::new();
|
||||
doc.insert("v", item);
|
||||
toml::from_str::<toml::Table>(&doc.to_string())
|
||||
.ok()?
|
||||
.remove("v")
|
||||
}
|
||||
|
||||
/// `item`'s tables with no place of their own in a document: one taken from another document
|
||||
/// follows the tables before it in the one it joins.
|
||||
fn unplace(item: &mut Item) {
|
||||
match item {
|
||||
Item::Table(t) => unplace_table(t),
|
||||
Item::ArrayOfTables(a) => a.iter_mut().for_each(unplace_table),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn unplace_table(t: &mut Table) {
|
||||
t.set_position(None);
|
||||
for (_, item) in t.iter_mut() {
|
||||
unplace(item);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Record {
|
||||
n: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
note: Option<String>,
|
||||
inner: Inner,
|
||||
#[serde(default, rename = "item", skip_serializing_if = "Vec::is_empty")]
|
||||
items: Vec<Element>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Inner {
|
||||
a: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Element {
|
||||
id: String,
|
||||
}
|
||||
|
||||
fn record(text: &str) -> Record {
|
||||
toml::from_str(text).unwrap()
|
||||
}
|
||||
|
||||
/// The file the tests' records are written over.
|
||||
fn file() -> &'static Path {
|
||||
Path::new("/r/record.toml")
|
||||
}
|
||||
|
||||
/// A file another build wrote, with keys, a table and comments of its own and values in
|
||||
/// forms this build does not write, is edited where this build's record changes, and stays
|
||||
/// as it was elsewhere: an unchanged value keeps its form, and a changed one its comment.
|
||||
#[test]
|
||||
fn a_record_is_written_over_its_file_as_the_file_is() {
|
||||
let old = "# kept\nn = 0x10 # sixteen\nnote = 'hi'\nlater = [1, 2]\n\n[inner]\na = true\n\
|
||||
b = \"another build's\"\n\n[theirs]\nx = 1\n";
|
||||
let mut r = record(old);
|
||||
assert_eq!(
|
||||
r,
|
||||
Record {
|
||||
n: 16,
|
||||
note: Some("hi".into()),
|
||||
inner: Inner { a: true },
|
||||
items: vec![],
|
||||
}
|
||||
);
|
||||
let same = text_over(&r, file(), Some(old), &[]).unwrap();
|
||||
assert_eq!(same, old);
|
||||
r.n = 17;
|
||||
r.note = None;
|
||||
r.inner.a = false;
|
||||
let edited = text_over(&r, file(), Some(old), &[]).unwrap();
|
||||
assert_eq!(
|
||||
edited,
|
||||
"# kept\nn = 17 # sixteen\nlater = [1, 2]\n\n[inner]\na = false\n\
|
||||
b = \"another build's\"\n\n[theirs]\nx = 1\n"
|
||||
);
|
||||
assert_eq!(record(&edited), r);
|
||||
// Retired keys go.
|
||||
let retired = text_over(&r, file(), Some(&edited), &["later", "inner.b"]).unwrap();
|
||||
assert_eq!(
|
||||
retired,
|
||||
"# kept\nn = 17 # sixteen\n\n[inner]\na = false\n\n[theirs]\nx = 1\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// A `[[item]]` table this build leaves as it was keeps the keys it does not know, while one
|
||||
/// before it is removed and another is added after it.
|
||||
#[test]
|
||||
fn an_array_s_tables_keep_their_keys_as_others_come_and_go() {
|
||||
let old = "n = 1\n\n[inner]\na = true\n\n[[item]]\nid = \"a\"\nspeed = 1\n\n\
|
||||
[[item]]\nid = \"b\"\nspeed = 2\n";
|
||||
let mut r = record(old);
|
||||
r.items.remove(0);
|
||||
r.items.push(Element { id: "c".into() });
|
||||
let text = text_over(&r, file(), Some(old), &[]).unwrap();
|
||||
assert!(
|
||||
text.starts_with("n = 1\n\n[inner]\na = true\n\n[[item]]\nid = \"b\"\nspeed = 2\n"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.ends_with("[[item]]\nid = \"c\"\n"), "{text}");
|
||||
assert!(!text.contains("\"a\""), "{text}");
|
||||
assert_eq!(record(&text), r);
|
||||
}
|
||||
|
||||
/// With no file, the record's own text is written. A file whose keys this build can't keep
|
||||
/// through the save is refused, typed and naming the file, so it is left as it is: one that
|
||||
/// isn't TOML, one this build can't read as the record, as a newer build may write, and one
|
||||
/// whose edit wouldn't read back as the record, as a key this build reads under another name
|
||||
/// makes it.
|
||||
#[test]
|
||||
fn a_file_this_build_cannot_keep_is_refused() {
|
||||
let r = record("n = 1\n[inner]\na = true\n");
|
||||
let own = toml::to_string_pretty(&r).unwrap();
|
||||
assert_eq!(text_over(&r, file(), None, &[]).unwrap(), own);
|
||||
let refused = |e: anyhow::Error| {
|
||||
let x = e.downcast_ref::<Refused>().expect("a Refused");
|
||||
assert_eq!(x.file, file());
|
||||
assert!(x.to_string().contains(" was left as it is: "), "{x}");
|
||||
x.why.clone()
|
||||
};
|
||||
let not_toml = refused(text_over(&r, file(), Some("n = ["), &[]).unwrap_err());
|
||||
assert!(not_toml.starts_with("it isn't TOML"), "{not_toml}");
|
||||
let other = "n = \"one\"\n[inner]\na = true\n";
|
||||
let unread = refused(text_over(&r, file(), Some(other), &[]).unwrap_err());
|
||||
assert!(unread.starts_with("this reims-ctl can't read"), "{unread}");
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Renamed {
|
||||
#[serde(alias = "count")]
|
||||
n: u32,
|
||||
}
|
||||
let e = text_over(&Renamed { n: 2 }, file(), Some("count = 1\n"), &[]).unwrap_err();
|
||||
let around = refused(e);
|
||||
assert!(around.contains("around what else it holds"), "{around}");
|
||||
}
|
||||
}
|
||||
@@ -392,9 +392,8 @@ fn make_opencore(image: &Path, args: &[&str], progress: &mut dyn FnMut(&str)) ->
|
||||
let r = run(&all, progress)?;
|
||||
if let Ok(o) = serde_json::from_value::<OpencoreResult>(r) {
|
||||
progress(&format!(
|
||||
"OpenCore presents the VM as {}; its serial is {}",
|
||||
mac_named(&o.smbios.model),
|
||||
o.smbios.serial
|
||||
"OpenCore presents the VM as an {}, serial {}",
|
||||
o.smbios.model, o.smbios.serial
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
@@ -412,65 +411,7 @@ pub fn model_for(version: &str) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The macOS releases the Mac `model` runs, of those an OpenCore image reims-util makes presents
|
||||
/// ([`model_for`]): the iMac20,1 runs macOS 10.15.6 to 26, and the iMacPro1,1 10.13 to 15. None
|
||||
/// for another model, which reims-ctl knows no releases of.
|
||||
pub fn model_runs(model: &str) -> Option<&'static str> {
|
||||
match model {
|
||||
"iMac20,1" => Some("macOS 10.15.6 to 26"),
|
||||
"iMacPro1,1" => Some("macOS 10.13 to 15"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The SMBIOS Memory Error Correction of the Mac `model`'s RAM, of those an OpenCore image
|
||||
/// reims-util makes presents ([`model_for`]), which System Information shows as the memory's
|
||||
/// "ECC": 3, none, for the iMac20,1, whose DDR4 has no ECC, and 6, multi-bit ECC, for the
|
||||
/// iMacPro1,1, whose DDR4 has ECC. None for another model, whose RAM reims-ctl does not know.
|
||||
pub fn model_memory_error_correction(model: &str) -> Option<u8> {
|
||||
match model {
|
||||
"iMac20,1" => Some(0x03),
|
||||
"iMacPro1,1" => Some(0x06),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The memory slots of the Mac `model`, of those an OpenCore image reims-util makes presents
|
||||
/// ([`model_for`]), which System Information lists: the iMac20,1's four SO-DIMM slots (SMBIOS's
|
||||
/// Form Factor 13). None for another model, whose slots reims-ctl does not know.
|
||||
pub fn model_memory_slots(model: &str) -> Option<MemorySlots> {
|
||||
match model {
|
||||
"iMac20,1" => Some(MemorySlots {
|
||||
count: 4,
|
||||
form_factor: 0x0D,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A Mac's memory slots ([`model_memory_slots`]): how many there are, and their SMBIOS Form Factor.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct MemorySlots {
|
||||
pub count: u16,
|
||||
pub form_factor: u8,
|
||||
}
|
||||
|
||||
/// The Mac `model` as reims-ctl names it, where it says which Mac a VM's image presents: with the
|
||||
/// macOS releases it runs ([`model_runs`]), which the VM's must be, as a kept image's Mac was
|
||||
/// chosen for another macOS.
|
||||
pub fn mac_named(model: &str) -> String {
|
||||
let a = if model.starts_with(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']) {
|
||||
"an"
|
||||
} else {
|
||||
"a"
|
||||
};
|
||||
match model_runs(model) {
|
||||
Some(runs) => format!("{a} {model}, which runs {runs}"),
|
||||
None => format!("{a} {model}, whose macOS releases reims-ctl does not know"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn major(version: &str) -> u32 {
|
||||
fn major(version: &str) -> u32 {
|
||||
version
|
||||
.trim()
|
||||
.split('.')
|
||||
@@ -719,44 +660,6 @@ mod tests {
|
||||
assert_eq!(model_for(""), None);
|
||||
}
|
||||
|
||||
/// The iMac20,1's RAM has no ECC and the iMacPro1,1's has; another model's is unknown.
|
||||
#[test]
|
||||
fn a_macs_memory_has_ecc_as_its_ram_does() {
|
||||
assert_eq!(model_memory_error_correction("iMac20,1"), Some(3));
|
||||
assert_eq!(model_memory_error_correction("iMacPro1,1"), Some(6));
|
||||
assert_eq!(model_memory_error_correction("MacPro7,1"), None);
|
||||
}
|
||||
|
||||
/// The iMac20,1 has four SO-DIMM slots; another model's slots are unknown.
|
||||
#[test]
|
||||
fn a_macs_memory_has_the_slots_the_mac_has() {
|
||||
let imac = MemorySlots {
|
||||
count: 4,
|
||||
form_factor: 13,
|
||||
};
|
||||
assert_eq!(model_memory_slots("iMac20,1"), Some(imac));
|
||||
assert_eq!(model_memory_slots("iMacPro1,1"), None);
|
||||
assert_eq!(model_memory_slots("MacPro7,1"), None);
|
||||
}
|
||||
|
||||
/// Each model an image reims-util makes presents is named with the macOS releases it runs,
|
||||
/// those model_for's choice rests on, and another model as one whose releases are unknown.
|
||||
#[test]
|
||||
fn a_mac_is_named_with_the_macos_it_runs() {
|
||||
assert_eq!(
|
||||
mac_named("iMac20,1"),
|
||||
"an iMac20,1, which runs macOS 10.15.6 to 26"
|
||||
);
|
||||
assert_eq!(
|
||||
mac_named("iMacPro1,1"),
|
||||
"an iMacPro1,1, which runs macOS 10.13 to 15"
|
||||
);
|
||||
assert_eq!(
|
||||
mac_named("MacPro7,1"),
|
||||
"a MacPro7,1, whose macOS releases reims-ctl does not know"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versions_read_reims_utils_list() {
|
||||
let list: Vec<Version> = serde_json::from_str(
|
||||
|
||||
@@ -237,13 +237,12 @@ fn gib(bytes: u64) -> String {
|
||||
|
||||
// ------------------------------------------------------------------ stopping
|
||||
|
||||
/// Set to stop every restore of this process, and every conversion of an x86-64 VM's disk: at
|
||||
/// Ctrl-C ([`stop_at_interrupt`]), or as the interface quits.
|
||||
/// Set to stop every restore of this process: at Ctrl-C ([`stop_at_interrupt`]), or as the
|
||||
/// interface quits.
|
||||
static CANCEL: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// The creates of arm64 VMs running in this process, each from its restore's start to its
|
||||
/// directory's removal where it fails, and of x86-64 VMs whose disk is converted, each from
|
||||
/// taking its directory to that ([`Busy`]).
|
||||
/// directory's removal where it fails ([`Busy`]).
|
||||
static RUNNING: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// The flag a restore watches.
|
||||
@@ -256,13 +255,12 @@ pub fn cancel() {
|
||||
CANCEL.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// The creates running in this process that stop at [`cancel`]: arm64 VMs', and x86-64 VMs'
|
||||
/// whose disk is converted.
|
||||
/// The arm64 creates running in this process.
|
||||
pub fn running() -> usize {
|
||||
RUNNING.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Waits up to `timeout` for every create [`running`] counts to end; whether they did.
|
||||
/// Waits up to `timeout` for every arm64 create to end; whether they did.
|
||||
pub fn wait_stopped(timeout: Duration) -> bool {
|
||||
let end = Instant::now() + timeout;
|
||||
while running() > 0 {
|
||||
@@ -274,8 +272,7 @@ pub fn wait_stopped(timeout: Duration) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Held by an arm64 create while it runs, its restore and its cleanup, and by an x86-64 create
|
||||
/// whose disk is converted, from taking its directory to its cleanup.
|
||||
/// Held by an arm64 create while it runs, its restore and its cleanup.
|
||||
pub struct Busy(());
|
||||
|
||||
impl Busy {
|
||||
@@ -292,9 +289,8 @@ impl Drop for Busy {
|
||||
}
|
||||
|
||||
/// Ctrl-C (SIGINT) and SIGTERM, and Ctrl+Break on Windows, stop the restores of this process,
|
||||
/// the downloads of their IPSWs and the conversions of x86-64 VMs' disks: a restore's or a
|
||||
/// conversion's VM directory is removed, a download keeps its part, and the create says the VM
|
||||
/// was not made.
|
||||
/// and the downloads of their IPSWs: a restore's VM directory is removed, a download keeps its
|
||||
/// part, and the create says the VM was not made.
|
||||
pub fn stop_at_interrupt() {
|
||||
crate::os::set_at_interrupt(&CANCEL);
|
||||
}
|
||||
|
||||
+64
-1890
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,212 +0,0 @@
|
||||
//! What reims-ctl reads of a qcow2 image's internal snapshots (QEMU's docs/interop/qcow2.txt):
|
||||
//! each one's name, and the space it alone holds, which deleting it frees.
|
||||
//!
|
||||
//! An image refers to a cluster from its own L1 table and from each snapshot's: a snapshot made
|
||||
//! by `qemu-img snapshot -c` adds one to the refcount of every L2 table and data cluster the
|
||||
//! image's L1 table reaches (qcow2-refcount.c, `qcow2_update_snapshot_refcount`), and a write
|
||||
//! after it copies what it changes. So a cluster a snapshot's L1 table reaches whose refcount is
|
||||
//! 1 is that snapshot's alone, and an L2 table with a refcount above 1 is shared, as every data
|
||||
//! cluster in it then is. What a snapshot holds is its L1 table's clusters, and the L2 tables
|
||||
//! and data clusters it reaches with a refcount of 1. A compressed cluster, which qemu-img
|
||||
//! writes only when asked to, is counted as held by none.
|
||||
//!
|
||||
//! The images read are those qemu-img makes: no external data file, no extended L2 entries, and
|
||||
//! refcounts of 8 to 64 bits; another is refused. An image over a backing file reads as any
|
||||
//! other: its snapshots' table, their L1 tables and every cluster they count are in its own file,
|
||||
//! and a cluster it never wrote, read from the backing file, is in no L2 entry, so held by none.
|
||||
|
||||
use crate::os::FileExt;
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry as Slot;
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
|
||||
/// Bits 9 to 55 of an L1 or L2 entry, or a refcount table entry: where the table or the cluster
|
||||
/// is in the file.
|
||||
const OFFSET: u64 = 0x00ff_ffff_ffff_fe00;
|
||||
|
||||
/// An L2 entry's flag for a compressed cluster.
|
||||
const COMPRESSED: u64 = 1 << 62;
|
||||
|
||||
/// The most snapshots, and the longest name, an image may have (qcow2.h's QCOW_MAX_SNAPSHOTS,
|
||||
/// and a name's 16-bit length).
|
||||
const MOST_SNAPSHOTS: u32 = 65536;
|
||||
|
||||
/// An internal snapshot: its name (qemu-img's tag) and its L1 table.
|
||||
pub struct Entry {
|
||||
pub name: String,
|
||||
l1_offset: u64,
|
||||
l1_size: u32,
|
||||
}
|
||||
|
||||
pub struct Image {
|
||||
file: File,
|
||||
cluster_bits: u32,
|
||||
refcount_order: u32,
|
||||
refcount_table: Vec<u64>,
|
||||
pub snapshots: Vec<Entry>,
|
||||
}
|
||||
|
||||
fn be32(b: &[u8], o: usize) -> u32 {
|
||||
u32::from_be_bytes(b[o..o + 4].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn be64(b: &[u8], o: usize) -> u64 {
|
||||
u64::from_be_bytes(b[o..o + 8].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn be16(b: &[u8], o: usize) -> u16 {
|
||||
u16::from_be_bytes(b[o..o + 2].try_into().unwrap())
|
||||
}
|
||||
|
||||
impl Image {
|
||||
pub fn open(path: &Path) -> Result<Image> {
|
||||
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
|
||||
Image::of(file).with_context(|| format!("read {}", path.display()))
|
||||
}
|
||||
|
||||
fn of(file: File) -> Result<Image> {
|
||||
let mut h = [0u8; 104];
|
||||
file.read_exact_at(&mut h[..72], 0)?;
|
||||
ensure!(h[..4] == *b"QFI\xfb", "not a qcow2 image");
|
||||
let version = be32(&h, 4);
|
||||
let cluster_bits = be32(&h, 20);
|
||||
ensure!(
|
||||
(9..=21).contains(&cluster_bits),
|
||||
"qcow2 clusters of 2^{cluster_bits} bytes"
|
||||
);
|
||||
let refcount_order = if version >= 3 {
|
||||
file.read_exact_at(&mut h[72..104], 72)?;
|
||||
// An external data file (bit 2) or extended L2 entries (bit 4) lay clusters out
|
||||
// otherwise.
|
||||
ensure!(
|
||||
be64(&h, 72) & (1 << 2 | 1 << 4) == 0,
|
||||
"a qcow2 image with an external data file or extended L2 entries"
|
||||
);
|
||||
be32(&h, 96)
|
||||
} else {
|
||||
4
|
||||
};
|
||||
ensure!(
|
||||
(3..=6).contains(&refcount_order),
|
||||
"a qcow2 image with refcounts of {} bits",
|
||||
1u64 << refcount_order.min(63)
|
||||
);
|
||||
let cluster = 1u64 << cluster_bits;
|
||||
let table_bytes = u64::from(be32(&h, 56)) * cluster;
|
||||
ensure!(
|
||||
table_bytes <= 1 << 30,
|
||||
"a refcount table of {table_bytes} bytes"
|
||||
);
|
||||
let mut table = vec![0u8; table_bytes as usize];
|
||||
file.read_exact_at(&mut table, be64(&h, 48))?;
|
||||
let refcount_table = (table.as_chunks::<8>().0.iter())
|
||||
.map(|e| u64::from_be_bytes(*e))
|
||||
.collect();
|
||||
let count = be32(&h, 60);
|
||||
ensure!(count <= MOST_SNAPSHOTS, "{count} snapshots");
|
||||
let mut snapshots = Vec::with_capacity(count as usize);
|
||||
let mut at = be64(&h, 64);
|
||||
for _ in 0..count {
|
||||
let mut e = [0u8; 40];
|
||||
file.read_exact_at(&mut e, at)?;
|
||||
let extra = u64::from(be32(&e, 36));
|
||||
let (id_len, name_len) = (u64::from(be16(&e, 12)), u64::from(be16(&e, 14)));
|
||||
ensure!(
|
||||
extra <= 1 << 20,
|
||||
"a snapshot with {extra} bytes of extra data"
|
||||
);
|
||||
let mut name = vec![0u8; name_len as usize];
|
||||
file.read_exact_at(&mut name, at + 40 + extra + id_len)?;
|
||||
snapshots.push(Entry {
|
||||
name: String::from_utf8_lossy(&name).into_owned(),
|
||||
l1_offset: be64(&e, 0),
|
||||
l1_size: be32(&e, 8),
|
||||
});
|
||||
at += (40 + extra + id_len + name_len).next_multiple_of(8);
|
||||
}
|
||||
Ok(Image {
|
||||
file,
|
||||
cluster_bits,
|
||||
refcount_order,
|
||||
refcount_table,
|
||||
snapshots,
|
||||
})
|
||||
}
|
||||
|
||||
/// The bytes the snapshot named `name` alone holds: what deleting it frees.
|
||||
pub fn held(&self, name: &str) -> Result<u64> {
|
||||
let s = self
|
||||
.snapshots
|
||||
.iter()
|
||||
.find(|s| s.name == name)
|
||||
.with_context(|| format!("no snapshot named {name}"))?;
|
||||
let cluster = 1u64 << self.cluster_bits;
|
||||
let l1_bytes = u64::from(s.l1_size) * 8;
|
||||
ensure!(l1_bytes <= 1 << 30, "an L1 table of {l1_bytes} bytes");
|
||||
let mut l1 = vec![0u8; l1_bytes as usize];
|
||||
self.file.read_exact_at(&mut l1, s.l1_offset)?;
|
||||
let mut refcounts = Refcounts {
|
||||
image: self,
|
||||
blocks: HashMap::new(),
|
||||
};
|
||||
let mut held = l1_bytes.div_ceil(cluster) * cluster;
|
||||
let mut l2 = vec![0u8; cluster as usize];
|
||||
for e in l1.as_chunks::<8>().0 {
|
||||
let table = u64::from_be_bytes(*e) & OFFSET;
|
||||
if table == 0 || refcounts.of(table)? != 1 {
|
||||
continue;
|
||||
}
|
||||
held += cluster;
|
||||
self.file.read_exact_at(&mut l2, table)?;
|
||||
for e in l2.as_chunks::<8>().0 {
|
||||
let e = u64::from_be_bytes(*e);
|
||||
if e & COMPRESSED != 0 || e & OFFSET == 0 {
|
||||
continue;
|
||||
}
|
||||
if refcounts.of(e & OFFSET)? == 1 {
|
||||
held += cluster;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(held)
|
||||
}
|
||||
}
|
||||
|
||||
/// The refcount blocks read so far, by their index in the refcount table.
|
||||
struct Refcounts<'a> {
|
||||
image: &'a Image,
|
||||
blocks: HashMap<usize, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Refcounts<'_> {
|
||||
/// The refcount of the cluster at `offset` in the file; 0 where no block counts it.
|
||||
fn of(&mut self, offset: u64) -> Result<u64> {
|
||||
let img = self.image;
|
||||
let cluster = 1u64 << img.cluster_bits;
|
||||
let bits = 1u64 << img.refcount_order;
|
||||
let per_block = cluster * 8 / bits;
|
||||
let index = offset >> img.cluster_bits;
|
||||
let block = (index / per_block) as usize;
|
||||
let Some(&at) = img.refcount_table.get(block) else {
|
||||
return Ok(0);
|
||||
};
|
||||
if at & OFFSET == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let b = match self.blocks.entry(block) {
|
||||
Slot::Occupied(e) => e.into_mut(),
|
||||
Slot::Vacant(e) => {
|
||||
let mut b = vec![0u8; cluster as usize];
|
||||
img.file.read_exact_at(&mut b, at & OFFSET)?;
|
||||
e.insert(b)
|
||||
}
|
||||
};
|
||||
let bytes = (bits / 8) as usize;
|
||||
let at = (index % per_block) as usize * bytes;
|
||||
Ok(b[at..at + bytes]
|
||||
.iter()
|
||||
.fold(0u64, |v, &x| v << 8 | u64::from(x)))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -104,30 +104,10 @@ pub fn toml_path(p: &Path) -> String {
|
||||
/// A stand-in program at `path` that runs `script`, a POSIX shell script, and the path to run it
|
||||
/// by: `path` itself, made executable. On Windows, which runs no script by its `#!` line, `path`
|
||||
/// holds the script and `path.cmd` runs it in MSYS2's or Git's `sh`, the path returned.
|
||||
///
|
||||
/// On Unix a child, `sh`, writes it, not this process: a file this process held open for writing
|
||||
/// would be held too by each child another test forks meanwhile, until that child execs, and
|
||||
/// Linux refuses to exec a file open for writing anywhere (ETXTBSY). The child's descriptor ends
|
||||
/// with it, before this returns.
|
||||
#[cfg(unix)]
|
||||
pub fn program(path: &Path, script: &str) -> PathBuf {
|
||||
use std::io::Write;
|
||||
let mut sh = std::process::Command::new("/bin/sh")
|
||||
.args(["-c", "cat > \"$1\" && chmod 755 \"$1\"", "sh"])
|
||||
.arg(path)
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
sh.stdin
|
||||
.take()
|
||||
.unwrap()
|
||||
.write_all(script.as_bytes())
|
||||
.unwrap();
|
||||
assert!(
|
||||
sh.wait().unwrap().success(),
|
||||
"{} not written",
|
||||
path.display()
|
||||
);
|
||||
std::fs::write(path, script).unwrap();
|
||||
crate::os::set_mode(path, 0o755).unwrap();
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
@@ -161,60 +141,3 @@ pub fn program(path: &Path, script: &str) -> PathBuf {
|
||||
.unwrap();
|
||||
cmd
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// A stand-in program runs as soon as it is written while other tests fork: each forked
|
||||
/// child holds this process's descriptors until it execs, and Linux refuses to exec a file
|
||||
/// open for writing anywhere (ETXTBSY). Here eight threads keep forking children that wait 1
|
||||
/// ms before they exec, as a busy test run's do, and each of 100 programs, 256 KiB long so
|
||||
/// that a write takes a while, must run at once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_program_runs_at_once_while_other_tests_fork() {
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let d = std::env::temp_dir().join(format!("reims-ctl-forks-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let done = Arc::new(AtomicBool::new(false));
|
||||
let forkers: Vec<_> = (0..8)
|
||||
.map(|_| {
|
||||
let done = done.clone();
|
||||
std::thread::spawn(move || {
|
||||
while !done.load(Ordering::Relaxed) {
|
||||
let mut c = std::process::Command::new("/bin/sh");
|
||||
c.args(["-c", ":"]);
|
||||
// SAFETY: usleep is async-signal-safe, all a forked child may call.
|
||||
unsafe {
|
||||
c.pre_exec(|| {
|
||||
libc::usleep(1000);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let _ = c.status();
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let script = format!("#!/bin/sh\nexit 0\n{}", "# padding\n".repeat(26 << 10));
|
||||
let mut failed = None;
|
||||
for i in 0..100 {
|
||||
let p = super::program(&d.join(format!("p{i}")), &script);
|
||||
match std::process::Command::new(&p).status() {
|
||||
Ok(s) if s.success() => {}
|
||||
other => {
|
||||
failed = Some(format!("program {i}: {other:?}"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
done.store(true, Ordering::Relaxed);
|
||||
for f in forkers {
|
||||
f.join().unwrap();
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
assert_eq!(failed, None);
|
||||
}
|
||||
}
|
||||
+164
-1053
File diff suppressed because it is too large.
Load diff
@@ -17,8 +17,6 @@ use crate::paths;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// The branches an update can follow.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
|
||||
@@ -83,7 +81,7 @@ pub enum Outcome {
|
||||
/// the install is already the latest commit of that branch ([`current`]), it says so and builds
|
||||
/// nothing; scripts/install-ctl.sh run by hand builds it again.
|
||||
pub fn update(channel: Option<Channel>) -> Result<Outcome> {
|
||||
let i = Install::load()?.with_context(|| {
|
||||
let i = Install::load().with_context(|| {
|
||||
format!(
|
||||
"no install record: run {} in your reims-vgpu checkout once, and reims-ctl update \
|
||||
can use it from then on",
|
||||
@@ -297,82 +295,6 @@ pub fn remove_set_aside(bin: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A program's file as reims-ctl tells one build's from another's at the same path: its length,
|
||||
/// its time of last write and its identity ([`crate::os::file_id`]), the last of which an install
|
||||
/// that writes the new build anew there changes, whatever times it keeps.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BinaryFile {
|
||||
len: u64,
|
||||
modified: Option<SystemTime>,
|
||||
id: Option<(u64, u64)>,
|
||||
}
|
||||
|
||||
impl BinaryFile {
|
||||
pub fn of(path: &Path) -> Option<BinaryFile> {
|
||||
let m = std::fs::metadata(path).ok()?;
|
||||
Some(BinaryFile {
|
||||
len: m.len(),
|
||||
modified: m.modified().ok(),
|
||||
id: crate::os::file_id(path, &m),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// This process's binary as it started ([`note_binary`]): its path, and its file then.
|
||||
static STARTED_FROM: OnceLock<Option<(PathBuf, BinaryFile)>> = OnceLock::new();
|
||||
|
||||
/// Notes this process's binary, its path and its file, as reims-ctl starts, before an update from
|
||||
/// another terminal can install a new one there ([`binary_replaced`]).
|
||||
pub fn note_binary() {
|
||||
STARTED_FROM.get_or_init(|| {
|
||||
let exe = restart_path(std::env::current_exe().ok()?);
|
||||
let file = BinaryFile::of(&exe)?;
|
||||
Some((exe, file))
|
||||
});
|
||||
}
|
||||
|
||||
/// Where this process's binary has been replaced since it started ([`note_binary`]): the path
|
||||
/// that holds another build now, as an update run from another terminal leaves it while this
|
||||
/// interface stays open. None where it was not noted, or its path holds it still, or nothing.
|
||||
pub fn binary_replaced() -> Option<PathBuf> {
|
||||
let (exe, then) = STARTED_FROM.get()?.as_ref()?;
|
||||
replaced(exe, then).then(|| exe.clone())
|
||||
}
|
||||
|
||||
/// Whether the file at `path` is no longer `then`, the file noted there: another file is there
|
||||
/// now. A path that holds nothing now holds no other build, and is not taken for one.
|
||||
fn replaced(path: &Path, then: &BinaryFile) -> bool {
|
||||
BinaryFile::of(path).is_some_and(|now| now != *then)
|
||||
}
|
||||
|
||||
/// Refuses, with [`replaced_note`], where this process's binary was replaced since it started
|
||||
/// ([`binary_replaced`]). What it carries of its own build, the guest's kexts, the device's
|
||||
/// option ROM and an arm64 VM's bundle, is not the build of the QEMU and library the install
|
||||
/// holds now, so it refuses what would pair them: a VM's start, an OpenCore image made with the
|
||||
/// kexts, a VM's create and the QEMU command it prints.
|
||||
pub fn refuse_replaced() -> Result<()> {
|
||||
refuse(binary_replaced())
|
||||
}
|
||||
|
||||
/// [`refuse_replaced`]'s answer where `replaced` is what [`binary_replaced`] found.
|
||||
fn refuse(replaced: Option<PathBuf>) -> Result<()> {
|
||||
match replaced {
|
||||
Some(exe) => bail!("{}", replaced_note(&exe)),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`refuse_replaced`] says where this process's binary, at `exe`, was replaced since it
|
||||
/// started.
|
||||
pub fn replaced_note(exe: &Path) -> String {
|
||||
format!(
|
||||
"reims-ctl was updated since this one started ({} holds another build now): quit it and \
|
||||
run reims-ctl again. This one carries the macOS drivers and option ROM of its own \
|
||||
build, which don't match the installed QEMU and can keep the guest from using its GPU",
|
||||
paths::tilde(exe)
|
||||
)
|
||||
}
|
||||
|
||||
/// The binary to run after an update, from the path this process was started from
|
||||
/// (`std::env::current_exe`), read before the update, which on Windows renames this running
|
||||
/// binary aside ([`remove_set_aside`]). The update installs the new reims-ctl over that path
|
||||
@@ -412,92 +334,6 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A binary another is installed over at its path since it was noted, as an update installs
|
||||
/// the new reims-ctl over the one an open interface runs, is told from the one noted: by its
|
||||
/// file, whether the new one is written beside it and renamed over it, as cargo install
|
||||
/// does, or written in its place, and even where it keeps its length and time of last
|
||||
/// write. The one noted, left as it was, is not; nor is a path that holds nothing now.
|
||||
#[test]
|
||||
fn a_binary_installed_over_the_one_noted_is_seen() {
|
||||
let d = std::env::temp_dir().join(format!("reims-ctl-replaced-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let bin = d.join("reims-ctl");
|
||||
std::fs::write(&bin, "build a").unwrap();
|
||||
let noted = BinaryFile::of(&bin).unwrap();
|
||||
let kept = replaced(&bin, ¬ed);
|
||||
// Written beside it and renamed over it, of the same length and time of last write.
|
||||
let new = d.join("reims-ctl.new");
|
||||
std::fs::write(&new, "build b").unwrap();
|
||||
let f = std::fs::File::options().write(true).open(&new).unwrap();
|
||||
f.set_modified(std::fs::metadata(&bin).unwrap().modified().unwrap())
|
||||
.unwrap();
|
||||
drop(f);
|
||||
std::fs::rename(&new, &bin).unwrap();
|
||||
let renamed_over = replaced(&bin, ¬ed);
|
||||
let noted = BinaryFile::of(&bin).unwrap();
|
||||
// Written in its place.
|
||||
std::fs::write(&bin, "build c, longer").unwrap();
|
||||
let written_over = replaced(&bin, ¬ed);
|
||||
std::fs::remove_file(&bin).unwrap();
|
||||
let gone = replaced(&bin, ¬ed);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
assert_eq!(
|
||||
(kept, renamed_over, written_over, gone),
|
||||
(false, true, true, false),
|
||||
"(kept, renamed over, written over, gone)"
|
||||
);
|
||||
let note = replaced_note(Path::new("/opt/bin/reims-ctl"));
|
||||
// The note shows the path in the host's own separators (`paths::tilde`).
|
||||
let shown = if cfg!(windows) {
|
||||
r"\opt\bin\reims-ctl"
|
||||
} else {
|
||||
"/opt/bin/reims-ctl"
|
||||
};
|
||||
assert!(
|
||||
note.starts_with(&format!(
|
||||
"reims-ctl was updated since this one started ({shown} holds another build now): \
|
||||
quit it and run reims-ctl again."
|
||||
)),
|
||||
"{note}"
|
||||
);
|
||||
}
|
||||
|
||||
/// On Windows the installer sets the running reims-ctl aside before it installs the new one:
|
||||
/// it renames it beside itself (`NAME.old-N`), which the process keeps running, and copies
|
||||
/// it back to its path. The copy has the same bytes, length and time of last write, but it is
|
||||
/// another file, so the binary noted there counts as replaced from then on, before the
|
||||
/// install writes the new build over the copy. The file set aside is still the one noted.
|
||||
/// Until the binary is replaced nothing is refused; after that, what would pair this build's
|
||||
/// kexts and ROM with the install's QEMU is refused with the note.
|
||||
#[test]
|
||||
fn a_binary_set_aside_and_copied_back_is_replaced() {
|
||||
let d = std::env::temp_dir().join(format!("reims-ctl-aside-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let bin = d.join("reims-ctl.exe");
|
||||
std::fs::write(&bin, "build a").unwrap();
|
||||
let noted = BinaryFile::of(&bin).unwrap();
|
||||
let before = refuse(replaced(&bin, ¬ed).then(|| bin.clone())).is_ok();
|
||||
let aside = d.join("reims-ctl.exe.old-0");
|
||||
std::fs::rename(&bin, &aside).unwrap();
|
||||
std::fs::copy(&aside, &bin).unwrap();
|
||||
let f = std::fs::File::options().write(true).open(&bin).unwrap();
|
||||
f.set_modified(std::fs::metadata(&aside).unwrap().modified().unwrap())
|
||||
.unwrap();
|
||||
drop(f);
|
||||
let copied_back = replaced(&bin, ¬ed);
|
||||
let aside_kept = !replaced(&aside, ¬ed);
|
||||
let refused = refuse(copied_back.then(|| bin.clone())).map_err(|e| format!("{e:#}"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
assert_eq!(
|
||||
(before, copied_back, aside_kept),
|
||||
(true, true, true),
|
||||
"(nothing refused before, the copy is another file, the one set aside is the same)"
|
||||
);
|
||||
assert_eq!(refused, Err(replaced_note(&bin)));
|
||||
}
|
||||
|
||||
/// A start removes what the installer set aside, reims-ctl's and reims-util's `NAME.old-N`,
|
||||
/// and leaves the programs themselves and every other file, a near name's among them.
|
||||
#[test]
|
||||
@@ -545,33 +381,8 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let bin = d.join("sleeper");
|
||||
// The running binary is this test binary, copied, idling in install's idle test, as the
|
||||
// prune test's QEMU does: a copy of /bin/sleep ran no sleep where /bin/sleep is uutils'
|
||||
// one binary of every utility (Ubuntu 26.04's coreutils), which picks the utility by its
|
||||
// file's name, whatever argv[0] says ("coreutils: unknown program 'sleeper'", GitHub's
|
||||
// ubuntu-26.04 runner, 2026-12-04).
|
||||
let this = std::env::current_exe().unwrap();
|
||||
std::fs::copy(&this, &bin).unwrap();
|
||||
// The copy's write handle is closed, but another test's child forked while it was open
|
||||
// holds it until that child execs, and an exec of a file open for writing fails with
|
||||
// ETXTBSY: spawn again until that child has let go of it.
|
||||
let busy = std::time::Instant::now();
|
||||
let mut child = loop {
|
||||
let spawned = Command::new(&bin)
|
||||
.args(["--exact", "install::tests::idle_as_a_qemu"])
|
||||
.env("REIMS_CTL_TEST_IDLE", "1")
|
||||
.stdout(std::process::Stdio::null())
|
||||
.spawn();
|
||||
match spawned {
|
||||
Err(e)
|
||||
if e.raw_os_error() == Some(libc::ETXTBSY)
|
||||
&& busy.elapsed() < std::time::Duration::from_secs(10) =>
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
spawned => break spawned.unwrap(),
|
||||
}
|
||||
};
|
||||
std::fs::copy("/bin/sleep", &bin).unwrap();
|
||||
let mut child = Command::new(&bin).arg("30").spawn().unwrap();
|
||||
// spawn returns once the child's exec lets go of this process's memory, which the kernel
|
||||
// does a moment before it names the new binary as the child's exe: wait for that name.
|
||||
let exe = format!("/proc/{}/exe", child.id());
|
||||
@@ -585,7 +396,7 @@ mod tests {
|
||||
}
|
||||
// cargo install --force: the new binary written beside, then renamed over the old.
|
||||
let new = d.join("sleeper.new");
|
||||
std::fs::copy(&this, &new).unwrap();
|
||||
std::fs::copy("/bin/sleep", &new).unwrap();
|
||||
std::fs::rename(&new, &bin).unwrap();
|
||||
let named = std::fs::read_link(format!("/proc/{}/exe", child.id())).unwrap();
|
||||
let _ = child.kill();
|
||||
|
||||
+1
-180
@@ -23,7 +23,6 @@
|
||||
//! udev rule says otherwise: scripts/install-ctl.sh adds one ([`UDEV_RULE`]), which gives USB
|
||||
//! devices other than hubs to the kvm group and to the user at the host's screen.
|
||||
|
||||
use crate::disks::HostDisk;
|
||||
use crate::host::{Host, Os, Profile};
|
||||
use crate::vm::{UsbDevice, Vm, parse_usb_port};
|
||||
use crate::{qmp, runtime};
|
||||
@@ -41,9 +40,6 @@ pub const UDEV_RULE: &str = r#"SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATT
|
||||
|
||||
/// Where Linux lists the host's USB devices, and lsusb's names for them.
|
||||
const SYSFS: &str = "/sys/bus/usb/devices";
|
||||
/// Linux's sysfs, where `block/<disk>` leads to the disk's device, below its bus's and, on USB,
|
||||
/// its USB device's ([`disks_on`]).
|
||||
const SYS: &str = "/sys";
|
||||
const USB_IDS: &str = "/usr/share/hwdata/usb.ids";
|
||||
|
||||
/// A USB device plugged into the host, other than a hub.
|
||||
@@ -465,10 +461,9 @@ pub fn apply(
|
||||
if now.config.usb == old {
|
||||
return Ok((now, vec![format!("{name}: nothing changed")]));
|
||||
}
|
||||
let new: Vec<&UsbDevice> = now.config.usb.iter().filter(|u| !old.contains(u)).collect();
|
||||
refuse_in_use_here(&new)?;
|
||||
now.save()?;
|
||||
let gone: Vec<&UsbDevice> = old.iter().filter(|u| !now.config.usb.contains(u)).collect();
|
||||
let new: Vec<&UsbDevice> = now.config.usb.iter().filter(|u| !old.contains(u)).collect();
|
||||
let label = |u: &UsbDevice| match u.name.as_str() {
|
||||
"" => u.id.clone(),
|
||||
n => n.to_string(),
|
||||
@@ -528,70 +523,6 @@ pub fn apply(
|
||||
Ok((now, said))
|
||||
}
|
||||
|
||||
/// The host's disks on `d`, a USB stick's or a USB disk's: each of `disks` whose device, where
|
||||
/// `sys` (Linux's sysfs) leads `block/<disk>`, lies below `d`'s port.
|
||||
fn disks_on<'a>(d: &HostDevice, sys: &Path, disks: &'a [HostDisk]) -> Vec<&'a HostDisk> {
|
||||
let below = |k: &&HostDisk| {
|
||||
std::fs::canonicalize(sys.join("block").join(&k.kernel))
|
||||
.is_ok_and(|p| p.components().any(|c| c.as_os_str() == d.port.as_str()))
|
||||
};
|
||||
disks.iter().filter(below).collect()
|
||||
}
|
||||
|
||||
/// Why `d` can't be the guest's while the host uses a disk on it (mounted, swap, part of another
|
||||
/// device), a sentence in [`crate::disks::refusal`]'s form; None where it uses none. QEMU takes
|
||||
/// the device from the host's drivers (`libusb_detach_kernel_driver`), and a file system the
|
||||
/// host has mounted on it would lose its disk mid-use, with what the host had not written yet.
|
||||
fn in_use(d: &HostDevice, sys: &Path, disks: &[HostDisk]) -> Option<String> {
|
||||
let k = disks_on(d, sys, disks)
|
||||
.into_iter()
|
||||
.find(|k| !k.uses.is_empty())?;
|
||||
Some(format!(
|
||||
"USB device {} ({}) holds {} ({}), which is this host's: {}. Unmount or eject it on the \
|
||||
host first: a guest given a disk the host uses would destroy it",
|
||||
d.name,
|
||||
d.id(),
|
||||
k.label(),
|
||||
k.path.display(),
|
||||
k.uses.join(", ")
|
||||
))
|
||||
}
|
||||
|
||||
/// Refuses to give a guest any of `chosen` that is plugged in, among `devices`, while the host
|
||||
/// uses a disk on it ([`in_use`]), `disks` the host's disks as `sys` leads to them.
|
||||
fn refuse_in_use(
|
||||
chosen: &[&UsbDevice],
|
||||
devices: &[HostDevice],
|
||||
sys: &Path,
|
||||
disks: &[HostDisk],
|
||||
) -> Result<()> {
|
||||
let found = chosen
|
||||
.iter()
|
||||
.flat_map(|u| devices.iter().filter(|d| d.is(u)))
|
||||
.find_map(|d| in_use(d, sys, disks));
|
||||
match found {
|
||||
Some(why) => bail!("{why}"),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`refuse_in_use`] on this host's USB devices and disks; none where `chosen` is empty.
|
||||
fn refuse_in_use_here(chosen: &[&UsbDevice]) -> Result<()> {
|
||||
if chosen.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let disks = crate::disks::host_disks();
|
||||
refuse_in_use(chosen, &host_devices(), Path::new(SYS), &disks)
|
||||
}
|
||||
|
||||
/// Refuses a start that would give the guest a USB device the host uses a disk on
|
||||
/// ([`in_use`]): one chosen and plugged in. One plugged in while the VM runs is QEMU's to take
|
||||
/// (`usb_host_auto_check`), unseen here.
|
||||
pub fn check_start(vm: &Vm) -> Result<()> {
|
||||
let chosen: Vec<&UsbDevice> = vm.config.usb.iter().collect();
|
||||
refuse_in_use_here(&chosen)
|
||||
}
|
||||
|
||||
/// Why `d` can't be opened, and what lets QEMU open it.
|
||||
pub fn unusable(d: &HostDevice) -> String {
|
||||
format!("you can't open {}: {}", d.file().display(), fix())
|
||||
@@ -738,116 +669,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A USB device holding a disk the host uses (a stick with a partition it has mounted) is
|
||||
/// refused, saying what the host uses it for and to unmount or eject it first; one whose
|
||||
/// disk nothing uses goes through, as does one chosen but not plugged in. Each disk's
|
||||
/// `block` entry leads to its device below its USB device's port, as Linux's sysfs does; a
|
||||
/// disk on another bus is on no USB device, and one behind a hub is on its own device, not
|
||||
/// on another device on that hub.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_usb_device_holding_a_disk_the_host_uses_is_refused() {
|
||||
let f = Sysfs::new("in-use");
|
||||
let (sys, by_id) = (f.0.join("sys"), f.0.join("by-id"));
|
||||
std::fs::create_dir_all(sys.join("block")).unwrap();
|
||||
std::fs::create_dir_all(&by_id).unwrap();
|
||||
// A disk below `device` in sys/devices, with one partition, `block/<name>` leading to it.
|
||||
let disk = |name: &str, device: &str, dev: &str, part: &str| {
|
||||
let d = sys.join("devices").join(device).join("block").join(name);
|
||||
let write = |rel: &str, v: &str| {
|
||||
let p = d.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, format!("{v}\n")).unwrap();
|
||||
};
|
||||
write("dev", dev);
|
||||
write("size", "62530624");
|
||||
write("ro", "0");
|
||||
write("device/model", "Ultra Fit");
|
||||
write(&format!("{name}1/partition"), "1");
|
||||
write(&format!("{name}1/dev"), part);
|
||||
std::os::unix::fs::symlink(&d, sys.join("block").join(name)).unwrap();
|
||||
};
|
||||
let usb = "pci0000:00/0000:00:14.0/usb2";
|
||||
disk(
|
||||
"sdb",
|
||||
&format!("{usb}/2-1/2-1:1.0/host6/6:0:0:0"),
|
||||
"8:16",
|
||||
"8:17",
|
||||
);
|
||||
disk(
|
||||
"sdc",
|
||||
&format!("{usb}/2-2/2-2:1.0/host7/7:0:0:0"),
|
||||
"8:32",
|
||||
"8:33",
|
||||
);
|
||||
// Behind a hub at port 2-3: its path passes the hub's port too.
|
||||
disk(
|
||||
"sdd",
|
||||
&format!("{usb}/2-3/2-3.4/2-3.4:1.0/host8/8:0:0:0"),
|
||||
"8:48",
|
||||
"8:49",
|
||||
);
|
||||
disk(
|
||||
"nvme0n1",
|
||||
"pci0000:00/0000:00:1d.0/nvme/nvme0",
|
||||
"259:0",
|
||||
"259:1",
|
||||
);
|
||||
let used = crate::disks::HostUse {
|
||||
mounts: vec![
|
||||
(Some((8, 17)), "/media/u/STICK".into()),
|
||||
(Some((259, 1)), "/".into()),
|
||||
],
|
||||
swaps: vec![],
|
||||
};
|
||||
let disks = crate::disks::read_disks(&sys, &by_id, &used);
|
||||
assert_eq!(disks.len(), 4, "{disks:?}");
|
||||
let device = |port: &str, product: u16| HostDevice {
|
||||
vendor: 0x0781,
|
||||
product,
|
||||
port: port.into(),
|
||||
bus: 2,
|
||||
address: 3,
|
||||
name: "SanDisk Ultra Fit".into(),
|
||||
kinds: vec!["storage"],
|
||||
};
|
||||
let devices = [
|
||||
device("2-1", 0x5583),
|
||||
device("2-2", 0x5584),
|
||||
device("2-3.1", 0x5585),
|
||||
device("2-3.4", 0x5586),
|
||||
];
|
||||
let mounted = choice_of(&devices[0], &devices);
|
||||
let free = choice_of(&devices[1], &devices);
|
||||
let sdb = disks.iter().find(|k| k.kernel == "sdb").unwrap();
|
||||
let e = refuse_in_use(&[&mounted], &devices, &sys, &disks).unwrap_err();
|
||||
assert_eq!(
|
||||
e.to_string(),
|
||||
format!(
|
||||
"USB device SanDisk Ultra Fit (0781:5583) holds {} (/dev/sdb), which is this \
|
||||
host's: sdb1 mounted at /media/u/STICK. Unmount or eject it on the host first: a \
|
||||
guest given a disk the host uses would destroy it",
|
||||
sdb.label()
|
||||
)
|
||||
);
|
||||
refuse_in_use(&[&free], &devices, &sys, &disks).unwrap();
|
||||
let absent = UsbDevice {
|
||||
id: "1234:5678".into(),
|
||||
port: None,
|
||||
name: String::new(),
|
||||
};
|
||||
refuse_in_use(&[&absent], &devices, &sys, &disks).unwrap();
|
||||
// The host's NVMe disk, mounted at /, is on none. The disk behind the hub is on the
|
||||
// device at 2-3.4 alone, not on the one beside it at 2-3.1.
|
||||
let want: [&[&str]; 4] = [&["sdb"], &["sdc"], &[], &["sdd"]];
|
||||
for (d, want) in devices.iter().zip(want) {
|
||||
let on: Vec<&str> = (disks_on(d, &sys, &disks).iter())
|
||||
.map(|k| k.kernel.as_str())
|
||||
.collect();
|
||||
assert_eq!(on, want, "{}", d.port);
|
||||
}
|
||||
}
|
||||
|
||||
const USB_IDS_TEXT: &str = "# usb.ids\n\
|
||||
0bda Realtek Semiconductor Corp.\n\
|
||||
\t5458 BillBoard Device\n\
|
||||
|
||||
@@ -13,10 +13,8 @@
|
||||
//! - Input is `input-send-event`: the USB tablet's absolute position and buttons, and the USB
|
||||
//! keyboard's keys (keys.rs).
|
||||
//!
|
||||
//! QMP's socket serves one client at a time, so the viewer connects for each exchange, a frame's
|
||||
//! or a batch of input's, and lets the connection go as QEMU answers: `reims-ctl stop`, a
|
||||
//! report's ask for the counts and the interface's probes get in while it runs, also while it
|
||||
//! sends input as a frame is still being drawn.
|
||||
//! QMP's socket serves one client at a time, so the viewer lets its connection go after each
|
||||
//! frame, and `reims-ctl stop` gets in while it runs.
|
||||
//!
|
||||
//! QEMU's USB keyboard queues 16 scancodes, drops a key whose scancodes do not fit, and gives the
|
||||
//! guest one each time it polls the keyboard (hw/input/hid.c). Keys go out at most 12 scancodes
|
||||
@@ -882,29 +880,32 @@ fn take_batch(pending: &mut VecDeque<Vec<Ev>>, queued: &mut f64) -> Vec<Ev> {
|
||||
batch
|
||||
}
|
||||
|
||||
/// Runs `command` on the VM's QMP socket in an exchange of its own: connected for it alone, and
|
||||
/// closed once QEMU answers. QEMU serves the socket one client at a time (qmp.rs), so a
|
||||
/// connection the viewer kept between its exchanges would keep every other client out while it
|
||||
/// views: a report's ask for the counts, a stop's keys and power button, a resume, a USB
|
||||
/// device's attach, the interface's probe for a pause.
|
||||
fn exchange(t: &Target, command: &str, arguments: Value) -> Result<Value> {
|
||||
Qmp::connect(&t.socket, Duration::from_secs(5))?.execute(command, Some(arguments))
|
||||
fn connect<'a>(conn: &'a mut Option<Qmp>, socket: &Path) -> Result<&'a mut Qmp> {
|
||||
if conn.is_none() {
|
||||
*conn = Some(Qmp::connect(socket, Duration::from_secs(5))?);
|
||||
}
|
||||
Ok(conn.as_mut().unwrap())
|
||||
}
|
||||
|
||||
fn send_input(t: &Target, evs: Vec<Ev>) -> Result<()> {
|
||||
fn send_input(conn: &mut Option<Qmp>, t: &Target, evs: Vec<Ev>) -> Result<()> {
|
||||
let mut events = Vec::new();
|
||||
for e in evs {
|
||||
e.json(&mut events);
|
||||
}
|
||||
exchange(
|
||||
t,
|
||||
"input-send-event",
|
||||
t.with_device(json!({ "events": events })),
|
||||
)
|
||||
.map(drop)
|
||||
let r = connect(conn, &t.socket).and_then(|q| {
|
||||
q.execute(
|
||||
"input-send-event",
|
||||
Some(t.with_device(json!({ "events": events }))),
|
||||
)
|
||||
});
|
||||
if r.is_err() {
|
||||
*conn = None;
|
||||
}
|
||||
r.map(|_| ())
|
||||
}
|
||||
|
||||
fn qmp_thread(c: Capture) {
|
||||
let mut conn: Option<Qmp> = None;
|
||||
let mut pending: VecDeque<Vec<Ev>> = VecDeque::new();
|
||||
// Scancodes the guest has yet to take from its queue, by estimate.
|
||||
let mut queued = 0.0f64;
|
||||
@@ -953,7 +954,7 @@ fn qmp_thread(c: Capture) {
|
||||
}
|
||||
pending.retain(|g| !g.iter().any(|e| matches!(e, Ev::Key(_, true))));
|
||||
if !pending.is_empty() {
|
||||
let _ = send_input(&c.target, pending.drain(..).flatten().collect());
|
||||
let _ = send_input(&mut conn, &c.target, pending.drain(..).flatten().collect());
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -966,7 +967,7 @@ fn qmp_thread(c: Capture) {
|
||||
input_at = Some(t);
|
||||
// Show what the input did soon.
|
||||
next = next.min(t + Duration::from_millis(30));
|
||||
if let Err(e) = send_input(&c.target, batch) {
|
||||
if let Err(e) = send_input(&mut conn, &c.target, batch) {
|
||||
if gone() {
|
||||
break;
|
||||
}
|
||||
@@ -978,8 +979,11 @@ fn qmp_thread(c: Capture) {
|
||||
continue;
|
||||
}
|
||||
let t0 = Instant::now();
|
||||
let dumped = exchange(&c.target, "screendump", c.target.screendump(&c.file))
|
||||
let dumped = connect(&mut conn, &c.target.socket)
|
||||
.and_then(|q| q.execute("screendump", Some(c.target.screendump(&c.file))))
|
||||
.and_then(|_| Ok(std::fs::read(&c.file)?));
|
||||
// Between frames QMP's socket is free for other clients.
|
||||
conn = None;
|
||||
let data = match dumped {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
@@ -1086,81 +1090,6 @@ mod tests {
|
||||
assert_eq!(left, (false, true, true), "(killed, running, others)");
|
||||
}
|
||||
|
||||
/// The viewer holds the VM's QMP socket, which QEMU serves one client at a time (qmp.rs),
|
||||
/// only for each of its exchanges: a report's ask for the counts, a stop's keys and power
|
||||
/// button, and the interface's probes get in between them, while the viewer sends input
|
||||
/// as its last frame is still being drawn too.
|
||||
#[test]
|
||||
fn the_viewer_leaves_qmp_to_others_between_its_exchanges() {
|
||||
use std::io::BufRead;
|
||||
let dir = crate::testenv::SocketDir::new("view-qmp");
|
||||
let sock = dir.0.join("qmp.sock");
|
||||
let listener = crate::os::UnixListener::bind(&sock).unwrap();
|
||||
std::thread::spawn(move || {
|
||||
for mut conn in listener.incoming().map_while(Result::ok) {
|
||||
let _ = conn.write_all(b"{\"QMP\": {}}\n");
|
||||
let reader = std::io::BufReader::new(conn.try_clone().unwrap());
|
||||
for _ in reader.lines().map_while(Result::ok) {
|
||||
let _ = conn.write_all(b"{\"return\": {}}\n");
|
||||
}
|
||||
}
|
||||
});
|
||||
let sh = Arc::new(Shared {
|
||||
stop: AtomicBool::new(false),
|
||||
// The frame captured last is still being drawn.
|
||||
busy: AtomicBool::new(true),
|
||||
screen: Mutex::new(Screen {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cell: ASSUMED_CELL,
|
||||
pixel_mouse: false,
|
||||
place: None,
|
||||
latch: Mods::NONE,
|
||||
layout: 0,
|
||||
}),
|
||||
});
|
||||
let (input, rx) = channel();
|
||||
let (enc, _enc_rx) = channel();
|
||||
let (ui, _ui_rx) = channel();
|
||||
let (done, done_rx) = channel();
|
||||
let c = Capture {
|
||||
sh: sh.clone(),
|
||||
target: Target {
|
||||
socket: sock.clone(),
|
||||
device: "gfx",
|
||||
},
|
||||
file: dir.0.join("frame.ppm"),
|
||||
vm: Vm {
|
||||
dir: dir.0.clone(),
|
||||
config: crate::vm::tests::x86_64_config(),
|
||||
},
|
||||
rx,
|
||||
enc,
|
||||
ui,
|
||||
gap: Duration::from_secs_f64(1.0 / 15.0),
|
||||
done,
|
||||
};
|
||||
std::thread::spawn(move || qmp_thread(c));
|
||||
// The mouse moving over the frame, as it does while one waits for a slow app.
|
||||
let moving = std::thread::spawn(move || {
|
||||
for i in 0..100u16 {
|
||||
if input.send(vec![Ev::Abs(i, i)]).is_err() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
});
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
let other = Qmp::connect(&sock, Duration::from_secs(1))
|
||||
.and_then(|mut q| q.execute("qom-set", None))
|
||||
.map(drop)
|
||||
.map_err(|e| format!("{e:#}"));
|
||||
sh.stop.store(true, Ordering::SeqCst);
|
||||
let _ = moving.join();
|
||||
let _ = done_rx.recv_timeout(Duration::from_secs(5));
|
||||
assert_eq!(other, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_toolbar_shows_disconnect_first_and_finds_its_buttons() {
|
||||
let (line, buttons) = toolbar("mac", Mods::CMD);
|
||||
|
||||
+90
-464
@@ -4,9 +4,6 @@
|
||||
//! firmware copies, `qemu.pid` while QEMU runs, the QMP socket where the path is short enough,
|
||||
//! and `logs/`. The registry (`vms.toml` in the config directory) lists each VM by its name and
|
||||
//! directory, so a VM may live anywhere.
|
||||
//!
|
||||
//! A save writes `vm.toml` over the file as it is ([`Vm::save`]), so settings a newer reims-ctl
|
||||
//! added stay, in their place and form, when an older one saves the VM.
|
||||
|
||||
use crate::host::Profile;
|
||||
use crate::paths;
|
||||
@@ -17,17 +14,6 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
pub const CONFIG_FILE: &str = "vm.toml";
|
||||
|
||||
/// The settings an older reims-ctl wrote that this one reads past, and leaves out of a VM's next
|
||||
/// save ([`Vm::save`]): apple-gfx's video acceleration, HiDPI and refresh rate, and an x86-64
|
||||
/// VM's installer kind and SMC key, which settings held before 2026-10-12.
|
||||
pub(crate) const RETIRED: [&str; 5] = [
|
||||
"video_acceleration",
|
||||
"display.hidpi",
|
||||
"display.refresh",
|
||||
"q35.installer_kind",
|
||||
"q35.osk",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct VmConfig {
|
||||
pub name: String,
|
||||
@@ -245,15 +231,14 @@ impl DiskController {
|
||||
}
|
||||
|
||||
/// reims-vgpu's displays, one by default and up to [`DISPLAYS_MAX`], each in a window of its own:
|
||||
/// each window opens at its display's size of the resolution ([`Display::window_sizes`]) and keeps
|
||||
/// the size the person gives it, which its display follows, at the refresh rate of the host
|
||||
/// screen it is on. The guest starts a HiDPI desktop by itself on a display whose window is at
|
||||
/// least 3840 pixels wide, and offers one in its Displays settings from 2880 (the kext's HiDPI
|
||||
/// modes, whose pixels halve exactly: the guest is offered the window's pixels, the width rounded
|
||||
/// down to a multiple of 16 and the height to even). The count an older reims-ctl saved for
|
||||
/// apple-gfx's displays comes back as reims-vgpu's ([`saved_display_count`]); its HiDPI and
|
||||
/// refresh rate are read past, and left out of the next save, as is the `capture` an older
|
||||
/// reims-ctl saved, a setting the windows no longer have.
|
||||
/// every window opens at the resolution's size ([`Display::window_size`]) and keeps the size the
|
||||
/// person gives it, which its display follows, at the refresh rate of the host screen it is on.
|
||||
/// The guest starts a HiDPI desktop by itself on a display whose window is at least 3840 pixels
|
||||
/// wide, and offers one in its Displays settings from 2880 (the kext's HiDPI modes, whose pixels
|
||||
/// halve exactly: the guest is offered the window's pixels, the width rounded down to a multiple
|
||||
/// of 16 and the height to even). The count an older reims-ctl saved for apple-gfx's displays
|
||||
/// comes back as reims-vgpu's ([`saved_display_count`]); its HiDPI and refresh rate are read
|
||||
/// past, and left out of the next save.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Display {
|
||||
@@ -264,13 +249,21 @@ pub struct Display {
|
||||
deserialize_with = "saved_display_count"
|
||||
)]
|
||||
pub count: u32,
|
||||
/// The size each window opens at, `<width>x<height>`: one size for every display, or one for
|
||||
/// each display, comma-separated, in the displays' order.
|
||||
/// The size every window opens at, `<width>x<height>`.
|
||||
pub resolution: String,
|
||||
/// Borderless windows that fill their screens: every display's.
|
||||
pub borderless: bool,
|
||||
/// Whether a click into a window captures the mouse and the keyboard, until the keys its
|
||||
/// title names or the window losing the keyboard let them go; off, the windows never
|
||||
/// capture them (`REIMS_VGPU_WINDOW_CAPTURE=0`, [`crate::qemu`]). Saved only where it is not
|
||||
/// [`DEFAULT_CAPTURE`], so a VM that never chose follows the default.
|
||||
#[serde(skip_serializing_if = "Display::is_default_capture")]
|
||||
pub capture: bool,
|
||||
}
|
||||
|
||||
/// Whether a VM's windows capture the mouse and the keyboard where its settings do not say.
|
||||
pub const DEFAULT_CAPTURE: bool = true;
|
||||
|
||||
/// The most displays reims-vgpu's device takes (the device's `RGFX_DISPLAYS_MAX`, QEMU's
|
||||
/// `displays` property's top).
|
||||
pub const DISPLAYS_MAX: u32 = 4;
|
||||
@@ -294,6 +287,7 @@ impl Default for Display {
|
||||
count: 1,
|
||||
resolution: "1920x1080".into(),
|
||||
borderless: false,
|
||||
capture: DEFAULT_CAPTURE,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -303,46 +297,24 @@ impl Display {
|
||||
*count == 1
|
||||
}
|
||||
|
||||
fn is_default_capture(capture: &bool) -> bool {
|
||||
*capture == DEFAULT_CAPTURE
|
||||
}
|
||||
|
||||
/// The `displays` reims-vgpu's device is given: none for one, the device's own, which a
|
||||
/// QEMU built before the property takes.
|
||||
pub fn qemu_displays(&self) -> Option<u32> {
|
||||
(self.count != 1).then_some(self.count)
|
||||
}
|
||||
|
||||
/// The size each of reims-vgpu's windows opens at, display i's at i, from the resolution: one
|
||||
/// size for every display, or a comma-separated list of one for each. In the host's points (a
|
||||
/// The size each of reims-vgpu's windows opens at, the resolution's, in the host's points (a
|
||||
/// guest point per host point), shrunk to fit the screen, which its guest takes in pixels and
|
||||
/// follows: measured on a Linux desktop at 2.1x, 1280x720 opened 1280x720 points and the
|
||||
/// guest ran 2688x1512. On a headless start, each display's mode. An error for a size that is
|
||||
/// not one, or a list of another count of sizes than the displays.
|
||||
pub fn window_sizes(&self) -> Result<Vec<(u32, u32)>> {
|
||||
let sizes = (self.resolution.split(','))
|
||||
.map(|s| parse_resolution(s.trim()))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let count = self.count.max(1) as usize;
|
||||
match sizes.len() {
|
||||
1 => Ok(vec![sizes[0]; count]),
|
||||
n if n == count => Ok(sizes),
|
||||
n => bail!(
|
||||
"the resolution gives {n} sizes for {count} display{}: give one size for every \
|
||||
display, or one for each display, comma-separated, as 2560x1440,1920x1080",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The device's `resolution`, from [`Display::window_sizes`]: none where every display opens
|
||||
/// at the device's own 1920x1080, as a QEMU built before the property takes; one size where
|
||||
/// every display has it; else each display's, comma-separated, which QEMU's line writes with
|
||||
/// each comma doubled ([`crate::qemu::opt`]). None for a resolution reims-ctl does not take.
|
||||
pub fn qemu_resolution(&self) -> Option<String> {
|
||||
let sizes = self.window_sizes().ok()?;
|
||||
let named = |&(w, h): &(u32, u32)| format!("{w}x{h}");
|
||||
if sizes.iter().all(|s| *s == sizes[0]) {
|
||||
(sizes[0] != (1920, 1080)).then(|| named(&sizes[0]))
|
||||
} else {
|
||||
Some(sizes.iter().map(named).collect::<Vec<_>>().join(","))
|
||||
}
|
||||
/// guest ran 2688x1512. None for the device's own, 1920x1080.
|
||||
pub fn window_size(&self) -> Option<(u32, u32)> {
|
||||
parse_resolution(self.resolution.trim())
|
||||
.ok()
|
||||
.filter(|&size| size != (1920, 1080))
|
||||
}
|
||||
|
||||
/// [`Display::check`], and more than one display refused on VMware SVGA, which has one. A
|
||||
@@ -363,7 +335,7 @@ impl Display {
|
||||
if !(1..=DISPLAYS_MAX).contains(&self.count) {
|
||||
bail!("a VM has 1 to {DISPLAYS_MAX} displays, not {}", self.count);
|
||||
}
|
||||
self.window_sizes().map(|_| ())
|
||||
parse_resolution(self.resolution.trim()).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,8 +361,7 @@ pub fn parse_resolution(s: &str) -> Result<(u32, u32)> {
|
||||
#[serde(default)]
|
||||
pub struct Gpu {
|
||||
/// The Vulkan driver's manifest (ICD JSON) that reaches the GPU. Where [`Gpu::select`] is
|
||||
/// none, the loader is limited to it: `VK_DRIVER_FILES`, and each start finds it again first
|
||||
/// ([`crate::gpu`], "A VM's driver at its start"), as a driver update can move it.
|
||||
/// none, the loader is limited to it: `VK_DRIVER_FILES`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub driver_file: Option<PathBuf>,
|
||||
/// The GPU's PCI device ID, where its driver drives several GPUs: the loader keeps that GPU
|
||||
@@ -403,12 +374,6 @@ pub struct Gpu {
|
||||
/// ([`crate::gpu`]).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub select: Option<String>,
|
||||
/// The GPU's PCI address, `0000:02:00.0`, where another GPU of its vendor and device IDs is
|
||||
/// on the host, which those IDs cannot tell from it: the GPU is then named by its address,
|
||||
/// `DRI_PRIME=pci-0000_02_00_0`, which Mesa's device-select layer and the library read
|
||||
/// ([`crate::gpu`], "Two GPUs of the same IDs").
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pci: Option<String>,
|
||||
/// The GPU's name, for display.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
@@ -430,31 +395,6 @@ impl Gpu {
|
||||
.map(Some)
|
||||
.with_context(|| format!("the GPU's select is vendor:device in hex, not {s:?}"))
|
||||
}
|
||||
|
||||
/// `DRI_PRIME`'s value that names the GPU at [`Gpu::pci`], `pci-0000_02_00_0`, where it has
|
||||
/// an address: its domain, bus, device and function in hex, as `0000:02:00.0` gives them.
|
||||
pub fn dri_prime(&self) -> Result<Option<String>> {
|
||||
let Some(a) = self.pci.as_deref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let hex = |x: &str, len: usize| {
|
||||
let ok = x.len() == len && x.bytes().all(|b| b.is_ascii_hexdigit());
|
||||
ok.then(|| x.to_ascii_lowercase())
|
||||
};
|
||||
let parts = (|| {
|
||||
let (domain, rest) = a.split_once(':')?;
|
||||
let (bus, rest) = rest.split_once(':')?;
|
||||
let (device, function) = rest.split_once('.')?;
|
||||
let p = [(domain, 4), (bus, 2), (device, 2), (function, 1)];
|
||||
p.into_iter()
|
||||
.map(|(x, len)| hex(x, len))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
})();
|
||||
let Some(parts) = parts else {
|
||||
bail!("the GPU's pci is its PCI address, 0000:02:00.0, not {a:?}");
|
||||
};
|
||||
Ok(Some(format!("pci-{}", parts.join("_"))))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -742,7 +682,6 @@ impl VmConfig {
|
||||
}
|
||||
self.display.check()?;
|
||||
self.gpu.selected()?;
|
||||
self.gpu.dri_prime()?;
|
||||
for k in self.extra_env.keys() {
|
||||
check_env_name(k)?;
|
||||
}
|
||||
@@ -819,8 +758,7 @@ impl VmConfig {
|
||||
/// How long `stop` waits for the guest to shut down before it powers the VM off: `None`
|
||||
/// for a timeout of 0, no limit, as an SSH port of 0 is no forward. A stop then waits until
|
||||
/// the guest shuts down, which may ask about unsaved documents for as long as they stay
|
||||
/// open, or until QEMU pauses the VM for a full disk, which ends it with an error; only a
|
||||
/// forced stop powers the VM off.
|
||||
/// open; only a forced stop powers the VM off.
|
||||
pub fn stop_timeout(&self) -> Option<std::time::Duration> {
|
||||
stop_timeout(self.stop_timeout_secs)
|
||||
}
|
||||
@@ -902,14 +840,40 @@ pub fn check_mac(mac: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A locally administered MAC in QEMU's 52:54:00 prefix, its last three bytes from the OS's
|
||||
/// random source (the getrandom crate's, on Windows `ProcessPrng`).
|
||||
/// A locally administered MAC in QEMU's 52:54:00 prefix.
|
||||
pub fn random_mac() -> String {
|
||||
let mut b = [0u8; 3];
|
||||
getrandom::fill(&mut b).expect("the OS's random source");
|
||||
let b = random_bytes::<3>();
|
||||
format!("52:54:00:{:02x}:{:02x}:{:02x}", b[0], b[1], b[2])
|
||||
}
|
||||
|
||||
fn random_bytes<const N: usize>() -> [u8; N] {
|
||||
use std::io::Read;
|
||||
let mut b = [0u8; N];
|
||||
if std::fs::File::open("/dev/urandom")
|
||||
.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()]);
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A size such as `8G`, `8GiB`, `512M` or `1.5T`, in MiB; a bare number is GiB.
|
||||
pub fn parse_size_mib(s: &str) -> Result<u64> {
|
||||
let t = s.trim();
|
||||
@@ -960,18 +924,14 @@ impl Vm {
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes the settings into `vm.toml`, over the file as it is: what another build of
|
||||
/// reims-ctl wrote there and this one does not know stays in its place and form, and the
|
||||
/// keys an older build wrote that this one retired ([`RETIRED`]) go
|
||||
/// ([`crate::record::text_over`]). Refused, with the file left as it is, where this build
|
||||
/// can't read it, or can't keep what it holds through the save ([`crate::record::Refused`]).
|
||||
pub fn save(&self) -> Result<()> {
|
||||
self.config.check()?;
|
||||
let text = toml::to_string_pretty(&self.config)?;
|
||||
let file = self.dir.join(CONFIG_FILE);
|
||||
let old = crate::record::old_text(&file)?;
|
||||
let text = crate::record::text_over(&self.config, &file, old.as_deref(), &RETIRED)?;
|
||||
crate::record::replace(&file, text.as_bytes())
|
||||
.with_context(|| format!("write {}", file.display()))
|
||||
let tmp = self.dir.join(format!(".{CONFIG_FILE}.tmp"));
|
||||
std::fs::write(&tmp, text).with_context(|| format!("write {}", tmp.display()))?;
|
||||
std::fs::rename(&tmp, &file).with_context(|| format!("write {}", file.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
@@ -1095,7 +1055,7 @@ pub fn qmp_socket_in(dir: &Path, name: &str, runtime: &Path, short: &Path) -> Pa
|
||||
|
||||
// ---------------------------------------------------------------- the registry
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Registry {
|
||||
#[serde(default, rename = "vm")]
|
||||
pub vms: Vec<Entry>,
|
||||
@@ -1127,16 +1087,13 @@ impl Registry {
|
||||
Ok(reg)
|
||||
}
|
||||
|
||||
/// Writes the registry over its file as it is, keeping what another build of reims-ctl wrote
|
||||
/// there in its place and form ([`crate::record::text_over`]); refused, with the file left as
|
||||
/// it is, where this build can't read it or keep what it holds ([`crate::record::Refused`]).
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let file = paths::registry_file();
|
||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
||||
let old = crate::record::old_text(&file)?;
|
||||
let text = crate::record::text_over(self, &file, old.as_deref(), &[])?;
|
||||
crate::record::replace(&file, text.as_bytes())
|
||||
.with_context(|| format!("write {}", file.display()))
|
||||
let tmp = file.with_extension("toml.tmp");
|
||||
std::fs::write(&tmp, toml::to_string_pretty(self)?)?;
|
||||
std::fs::rename(&tmp, &file)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn find(&self, name: &str) -> Option<&Entry> {
|
||||
@@ -1181,71 +1138,16 @@ pub(crate) mod tests {
|
||||
resolution: resolution.into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(d("2560x1440").window_sizes().unwrap(), [(2560, 1440)]);
|
||||
assert_eq!(
|
||||
d("2560x1440").qemu_resolution().as_deref(),
|
||||
Some("2560x1440")
|
||||
);
|
||||
assert_eq!(
|
||||
d(" 3840x2160").qemu_resolution().as_deref(),
|
||||
Some("3840x2160")
|
||||
);
|
||||
assert_eq!(d("1920x1080").qemu_resolution(), None);
|
||||
assert_eq!(d("2560x1440").window_size(), Some((2560, 1440)));
|
||||
assert_eq!(d(" 3840x2160").window_size(), Some((3840, 2160)));
|
||||
assert_eq!(d("1920x1080").window_size(), None);
|
||||
assert!(d("2560x1600").check().is_ok());
|
||||
for bad in [
|
||||
"host",
|
||||
"2560",
|
||||
"19x",
|
||||
"0x1080",
|
||||
"70000x10",
|
||||
"",
|
||||
"2560x1440,",
|
||||
] {
|
||||
for bad in ["host", "2560", "19x", "0x1080", "70000x10"] {
|
||||
assert!(d(bad).check().is_err(), "{bad}");
|
||||
assert_eq!(d(bad).qemu_resolution(), None, "{bad}");
|
||||
assert_eq!(d(bad).window_size(), None, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A resolution gives one size for every display, or one for each display, comma-separated:
|
||||
/// each display's window opens at its own, and the device is given them in the displays'
|
||||
/// order. Sizes that are all the same are that one size, and all the device's own none.
|
||||
/// Another count of sizes than the displays is refused, saying what to give.
|
||||
#[test]
|
||||
fn each_display_s_window_opens_at_its_own_size() {
|
||||
let d = |count: u32, resolution: &str| Display {
|
||||
count,
|
||||
resolution: resolution.into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
d(3, "2560x1440").window_sizes().unwrap(),
|
||||
[(2560, 1440), (2560, 1440), (2560, 1440)]
|
||||
);
|
||||
let two = d(2, "2560x1440, 1920x1080");
|
||||
assert_eq!(two.window_sizes().unwrap(), [(2560, 1440), (1920, 1080)]);
|
||||
assert_eq!(
|
||||
two.qemu_resolution().as_deref(),
|
||||
Some("2560x1440,1920x1080")
|
||||
);
|
||||
assert_eq!(
|
||||
d(2, "1280x720,1280x720").qemu_resolution().as_deref(),
|
||||
Some("1280x720")
|
||||
);
|
||||
assert_eq!(d(2, "1920x1080,1920x1080").qemu_resolution(), None);
|
||||
let wrong = d(3, "2560x1440,1920x1080").check().unwrap_err().to_string();
|
||||
assert_eq!(
|
||||
wrong,
|
||||
"the resolution gives 2 sizes for 3 displays: give one size for every display, or one \
|
||||
for each display, comma-separated, as 2560x1440,1920x1080"
|
||||
);
|
||||
let one = d(1, "2560x1440,1920x1080").check().unwrap_err().to_string();
|
||||
assert!(
|
||||
one.starts_with("the resolution gives 2 sizes for 1 display: "),
|
||||
"{one}"
|
||||
);
|
||||
assert!(d(2, "2560x1440,0x1080").check().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes() {
|
||||
assert_eq!(parse_size_mib("8G").unwrap(), 8192);
|
||||
@@ -1392,7 +1294,6 @@ pub(crate) mod tests {
|
||||
driver_file: Some("/usr/share/vulkan/icd.d/nvidia_icd.json".into()),
|
||||
device_id: Some(0x2204),
|
||||
select: Some("10de:2204".into()),
|
||||
pci: None,
|
||||
name: None,
|
||||
},
|
||||
audio: Audio::default(),
|
||||
@@ -1648,257 +1549,6 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A save keeps what a newer reims-ctl wrote into a VM's settings, as an interface open since
|
||||
/// before an update, or an older build a switch of channel installed, saves them. A key of the
|
||||
/// newer build's own, one in a table this build has, and a table of its own stay as written,
|
||||
/// byte for byte, and only the changed setting's line differs. A save that changes nothing
|
||||
/// writes the same bytes.
|
||||
#[test]
|
||||
fn a_save_keeps_what_a_newer_build_wrote() {
|
||||
let env = crate::testenv::Env::new("newer-settings");
|
||||
let dir = env.root.join("t");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join(CONFIG_FILE);
|
||||
Vm {
|
||||
dir: dir.clone(),
|
||||
config: x86_64_config(),
|
||||
}
|
||||
.save()
|
||||
.unwrap();
|
||||
let ours = std::fs::read_to_string(&file).unwrap();
|
||||
let newer = ours
|
||||
.replacen(
|
||||
"stop_timeout_secs = 90\n",
|
||||
"stop_timeout_secs = 90\npacing = \"smooth\"\n",
|
||||
1,
|
||||
)
|
||||
.replacen("[display]\n", "[display]\nhdr = \"pq\"\n", 1)
|
||||
.replacen(
|
||||
"[q35]\n",
|
||||
"[snapshots]\nkeep = 3\nnames = [\"a\", \"b\"]\n\n[q35]\n",
|
||||
1,
|
||||
);
|
||||
for added in ["pacing = ", "hdr = ", "[snapshots]"] {
|
||||
assert!(newer.contains(added), "{added}: {newer}");
|
||||
}
|
||||
std::fs::write(&file, &newer).unwrap();
|
||||
let mut vm = Vm::load(&dir).unwrap();
|
||||
assert_eq!(vm.config, x86_64_config());
|
||||
vm.save().unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), newer);
|
||||
vm.config.memory_mib = 16384;
|
||||
vm.save().unwrap();
|
||||
let edited = newer.replacen("memory_mib = 8192\n", "memory_mib = 16384\n", 1);
|
||||
assert_ne!(edited, newer);
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), edited);
|
||||
}
|
||||
|
||||
/// Every kind of change a save makes keeps what a newer build wrote: a cleared setting's key
|
||||
/// goes, a key is added to a table, a `[[usb]]` table removed beside one kept leaves the kept
|
||||
/// one's own keys, and a `[[host_disk]]` table is added. What an older build wrote and this
|
||||
/// one retired goes ([`RETIRED`]).
|
||||
#[test]
|
||||
fn every_kind_of_change_keeps_what_a_newer_build_wrote() {
|
||||
let env = crate::testenv::Env::new("newer-settings-changes");
|
||||
let dir = env.root.join("t");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join(CONFIG_FILE);
|
||||
let usb = |id: &str, name: &str| UsbDevice {
|
||||
id: id.into(),
|
||||
port: None,
|
||||
name: name.into(),
|
||||
};
|
||||
let mut c = x86_64_config();
|
||||
c.usb = vec![usb("1050:0407", "key"), usb("046d:c52b", "receiver")];
|
||||
Vm {
|
||||
dir: dir.clone(),
|
||||
config: c,
|
||||
}
|
||||
.save()
|
||||
.unwrap();
|
||||
let ours = std::fs::read_to_string(&file).unwrap();
|
||||
let newer = ours
|
||||
.replacen(
|
||||
"stop_timeout_secs = 90\n",
|
||||
"stop_timeout_secs = 90\npacing = \"smooth\"\nvideo_acceleration = false\n",
|
||||
1,
|
||||
)
|
||||
.replacen("[display]\n", "[display]\nhdr = \"pq\"\nhidpi = true\n", 1)
|
||||
.replacen(
|
||||
"id = \"046d:c52b\"\n",
|
||||
"id = \"046d:c52b\"\nspeed = \"high\"\n",
|
||||
1,
|
||||
);
|
||||
assert!(newer.contains("speed = "), "{newer}");
|
||||
std::fs::write(&file, &newer).unwrap();
|
||||
let mut vm = Vm::load(&dir).unwrap();
|
||||
vm.config.q35.as_mut().unwrap().installer = None;
|
||||
vm.config.extra_env.insert("B".into(), "c".into());
|
||||
vm.config.usb.remove(0);
|
||||
vm.config.host_disks.push(HostDiskChoice {
|
||||
path: "/dev/disk/by-id/ata-disk".into(),
|
||||
name: String::new(),
|
||||
});
|
||||
vm.save().unwrap();
|
||||
let saved = std::fs::read_to_string(&file).unwrap();
|
||||
assert_eq!(Vm::load(&dir).unwrap().config, vm.config);
|
||||
for kept in [
|
||||
"pacing = \"smooth\"\n",
|
||||
"[display]\nhdr = \"pq\"\n",
|
||||
"id = \"046d:c52b\"\nspeed = \"high\"\n",
|
||||
"B = \"c\"\n",
|
||||
"[[host_disk]]\n",
|
||||
] {
|
||||
assert!(saved.contains(kept), "{kept}: {saved}");
|
||||
}
|
||||
for gone in ["video_acceleration", "hidpi", "installer = ", "1050:0407"] {
|
||||
assert!(!saved.contains(gone), "{gone}: {saved}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A save over settings this build can't read, here a graphics device a newer build added,
|
||||
/// is refused, naming the file, and leaves the file as it was: a plain write would drop
|
||||
/// what this build doesn't know.
|
||||
#[test]
|
||||
fn a_save_over_settings_this_build_cannot_read_leaves_them() {
|
||||
let env = crate::testenv::Env::new("unreadable-settings");
|
||||
let dir = env.root.join("t");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join(CONFIG_FILE);
|
||||
let vm = Vm {
|
||||
dir: dir.clone(),
|
||||
config: x86_64_config(),
|
||||
};
|
||||
vm.save().unwrap();
|
||||
let newer = format!(
|
||||
"graphics = \"a-newer-device\"\n{}",
|
||||
std::fs::read_to_string(&file).unwrap()
|
||||
);
|
||||
std::fs::write(&file, &newer).unwrap();
|
||||
let e = vm.save().unwrap_err();
|
||||
let refused = e
|
||||
.downcast_ref::<crate::record::Refused>()
|
||||
.unwrap_or_else(|| panic!("not refused: {e:#}"));
|
||||
assert_eq!(refused.file, file);
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), newer);
|
||||
assert_eq!(crate::record::left_beside(&file), Vec::<PathBuf>::new());
|
||||
}
|
||||
|
||||
/// A save over settings whose file is there and this build can't read, as one that isn't
|
||||
/// UTF-8 or that its mode keeps from the user, is refused, naming the file, and leaves the file
|
||||
/// byte for byte: taken for no file, it would be written over with this build's settings.
|
||||
#[test]
|
||||
fn a_save_over_a_settings_file_this_build_cannot_read_leaves_it() {
|
||||
let env = crate::testenv::Env::new("unreadable-settings-file");
|
||||
let dir = env.root.join("t");
|
||||
let vm = Vm {
|
||||
dir: dir.clone(),
|
||||
config: x86_64_config(),
|
||||
};
|
||||
let file = dir.join(CONFIG_FILE);
|
||||
crate::record::assert_unreadable_refused(&file, &|| vm.save());
|
||||
assert_eq!(crate::record::left_beside(&file), Vec::<PathBuf>::new());
|
||||
}
|
||||
|
||||
/// The registry's save over a file this build can't read, as one that isn't UTF-8 or that its
|
||||
/// mode keeps from the user, is refused, naming the file, and leaves the file byte for byte.
|
||||
#[test]
|
||||
fn the_registry_s_save_over_a_file_this_build_cannot_read_leaves_it() {
|
||||
let _env = crate::testenv::Env::new("unreadable-registry");
|
||||
let mut reg = Registry::default();
|
||||
reg.add("a", Path::new("/vms/a")).unwrap();
|
||||
crate::record::assert_unreadable_refused(&paths::registry_file(), &|| reg.save());
|
||||
}
|
||||
|
||||
/// Two saves of the registry at once, as two reims-ctl open make them, here from two threads,
|
||||
/// each saving a list of its own over and over: every read of the file meanwhile is one list
|
||||
/// whole, never a mix of the two or a cut, and every save succeeds; the last rename wins.
|
||||
#[test]
|
||||
fn two_saves_of_the_registry_at_once_leave_one_list_whole() {
|
||||
let _env = crate::testenv::Env::new("registry-two-saves");
|
||||
let list = |name: &str| {
|
||||
let mut reg = Registry::default();
|
||||
// Many VMs, so that a write takes a while.
|
||||
for n in 0..200 {
|
||||
let dir = PathBuf::from(format!("/vms/{name}{n}"));
|
||||
reg.add(&format!("{name}{n}"), &dir).unwrap();
|
||||
}
|
||||
reg
|
||||
};
|
||||
let lists = [list("a"), list("b")];
|
||||
lists[0].save().unwrap();
|
||||
let done = std::sync::atomic::AtomicBool::new(false);
|
||||
let (failed, torn) = std::thread::scope(|s| {
|
||||
let savers = lists.each_ref().map(|reg| {
|
||||
s.spawn(move || {
|
||||
(0..100)
|
||||
.filter_map(|_| reg.save().err().map(|e| format!("{e:#}")))
|
||||
.collect::<Vec<String>>()
|
||||
})
|
||||
});
|
||||
// How many reads were not one list whole, and the first few.
|
||||
let reader = s.spawn(|| {
|
||||
let mut torn = (0, Vec::new());
|
||||
while !done.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
let why = match Registry::load() {
|
||||
Ok(read) if lists.contains(&read) => continue,
|
||||
Ok(read) => format!("a list of {} VMs", read.vms.len()),
|
||||
Err(e) => format!("{e:#}"),
|
||||
};
|
||||
torn.0 += 1;
|
||||
if torn.1.len() < 3 {
|
||||
torn.1.push(why);
|
||||
}
|
||||
}
|
||||
torn
|
||||
});
|
||||
let failed: Vec<String> = savers.into_iter().flat_map(|t| t.join().unwrap()).collect();
|
||||
done.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
(failed, reader.join().unwrap())
|
||||
});
|
||||
assert!(
|
||||
torn.0 == 0 && failed.is_empty(),
|
||||
"{} reads not one list whole, as {:?}; {} saves failed, as {:?}",
|
||||
torn.0,
|
||||
torn.1,
|
||||
failed.len(),
|
||||
failed.first()
|
||||
);
|
||||
assert_eq!(
|
||||
crate::record::left_beside(&paths::registry_file()),
|
||||
Vec::<PathBuf>::new()
|
||||
);
|
||||
}
|
||||
|
||||
/// The registry's save keeps what a newer reims-ctl wrote into it: a key of its own, a key in
|
||||
/// a VM's `[[vm]]` table and a table of its own stay as written, byte for byte, as a VM is
|
||||
/// added, whose table is all that changes.
|
||||
#[test]
|
||||
fn the_registry_s_save_keeps_what_a_newer_build_wrote() {
|
||||
let env = crate::testenv::Env::new("newer-registry");
|
||||
let (a, b) = (env.root.join("a"), env.root.join("b"));
|
||||
let mut reg = Registry::default();
|
||||
reg.add("a", &a).unwrap();
|
||||
reg.save().unwrap();
|
||||
let file = paths::registry_file();
|
||||
let ours = std::fs::read_to_string(&file).unwrap();
|
||||
let pinned = ours.replacen("name = \"a\"\n", "name = \"a\"\npinned = true\n", 1);
|
||||
assert_ne!(pinned, ours);
|
||||
let newer = format!("version = 2\n\n{pinned}\n[groups]\nwork = [\"a\"]\n");
|
||||
std::fs::write(&file, &newer).unwrap();
|
||||
let mut reg = Registry::load().unwrap();
|
||||
reg.add("b", &b).unwrap();
|
||||
reg.save().unwrap();
|
||||
let mut both = Registry::default();
|
||||
both.add("a", &a).unwrap();
|
||||
both.add("b", &b).unwrap();
|
||||
let both = toml::to_string_pretty(&both).unwrap();
|
||||
let b_table = both.strip_prefix(ours.as_str()).unwrap();
|
||||
let want = newer.replacen("\n[groups]", &format!("{b_table}\n[groups]"), 1);
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), want);
|
||||
assert_eq!(Registry::load().unwrap(), reg);
|
||||
}
|
||||
|
||||
/// A VM has 1 to 4 displays, the device's most; any other count saved by hand is refused.
|
||||
#[test]
|
||||
fn a_vm_has_1_to_4_displays() {
|
||||
@@ -1940,20 +1590,22 @@ pub(crate) mod tests {
|
||||
assert!(c.check().is_ok());
|
||||
}
|
||||
|
||||
/// The `capture` an older reims-ctl saved, on or off, is read past with no error, and the
|
||||
/// next save leaves it out: the windows have no such setting.
|
||||
/// Capture input is saved only where it is not [`DEFAULT_CAPTURE`], so a VM whose settings
|
||||
/// never chose follows the default, and the other value is saved and read back.
|
||||
#[test]
|
||||
fn a_saved_capture_is_read_past_and_left_out() {
|
||||
let c = x86_64_config();
|
||||
fn capture_is_saved_only_off_the_default() {
|
||||
let mut c = x86_64_config();
|
||||
assert_eq!(c.display.capture, DEFAULT_CAPTURE);
|
||||
let text = toml::to_string_pretty(&c).unwrap();
|
||||
assert!(!text.contains("capture"), "{text}");
|
||||
for saved in ["capture = false", "capture = true"] {
|
||||
let old = text.replacen("[display]\n", &format!("[display]\n{saved}\n"), 1);
|
||||
assert!(old.contains(saved), "{old}");
|
||||
let read = toml::from_str::<VmConfig>(&old).unwrap();
|
||||
assert_eq!(read, c);
|
||||
assert!(!toml::to_string_pretty(&read).unwrap().contains("capture"));
|
||||
}
|
||||
assert_eq!(toml::from_str::<VmConfig>(&text).unwrap(), c);
|
||||
c.display.capture = !DEFAULT_CAPTURE;
|
||||
let text = toml::to_string_pretty(&c).unwrap();
|
||||
assert!(
|
||||
text.contains(&format!("capture = {}", !DEFAULT_CAPTURE)),
|
||||
"{text}"
|
||||
);
|
||||
assert_eq!(toml::from_str::<VmConfig>(&text).unwrap(), c);
|
||||
}
|
||||
|
||||
/// A VM an earlier create saved with an SSH port of 0 has no forward, as `set --ssh-port 0`
|
||||
@@ -2043,32 +1695,6 @@ pub(crate) mod tests {
|
||||
assert!(e.contains("no [q35] settings"), "{e}");
|
||||
}
|
||||
|
||||
/// A GPU's PCI address is `domain:bus:device.function` in hex, which names it to
|
||||
/// `DRI_PRIME` as `pci-domain_bus_device_function`; the check refuses anything else.
|
||||
#[test]
|
||||
fn a_gpu_s_pci_address_names_it_to_dri_prime() {
|
||||
let mut c = x86_64_config();
|
||||
assert_eq!(c.gpu.dri_prime().unwrap(), None);
|
||||
c.gpu.pci = Some("0000:02:00.0".into());
|
||||
let prime = c.gpu.dri_prime().unwrap();
|
||||
assert_eq!(prime.as_deref(), Some("pci-0000_02_00_0"));
|
||||
c.gpu.pci = Some("0000:C7:1F.7".into());
|
||||
let prime = c.gpu.dri_prime().unwrap();
|
||||
assert_eq!(prime.as_deref(), Some("pci-0000_c7_1f_7"));
|
||||
assert!(c.check().is_ok());
|
||||
for bad in [
|
||||
"",
|
||||
"02:00.0",
|
||||
"0000:02:00",
|
||||
"0000:2:00.0",
|
||||
"0000:02:00.10",
|
||||
"0000_02_00_0",
|
||||
] {
|
||||
c.gpu.pci = Some(bad.into());
|
||||
assert!(c.check().is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A GPU's select names its vendor and device IDs in hex, as `MESA_VK_DEVICE_SELECT` takes
|
||||
/// them; the check refuses anything else.
|
||||
#[test]
|
||||
|
||||
@@ -62,14 +62,9 @@ uuid = { version = "1.29.2", features = ["v4"] }
|
||||
# The IPSW is a zip (ipsw.rs).
|
||||
zip = { version = "9.5.1", default-features = false, features = ["deflate-flate2"] }
|
||||
|
||||
# The space free on a volume, the space a file takes on it, and sparse files (src/sys/windows.rs).
|
||||
# The space free on a volume (src/sys/windows.rs).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_IO",
|
||||
"Win32_System_Ioctl",
|
||||
] }
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# Writes the tests' synthetic IPSWs.
|
||||
|
||||
@@ -247,7 +247,7 @@ The guest can't keep such a policy through a change of its own (`policy_nonce.rs
|
||||
account (opendirectoryd's PlistFile module, when AppleVPKeyStore reports no owners), and at any
|
||||
later LocalPolicy change, the guest begins a local policy nonce update, decodes the current
|
||||
policy in libbootpolicy to re-sign it for the new nonce, and ends the update, which blesses the
|
||||
new nonce and removes the policies named for the old, on 27.0.1 and 27.2.1.
|
||||
new nonce and removes the policies named for the old **[read from code, 27.0.1 and 27.2.1]**.
|
||||
libbootpolicy checks the policy's chain against Apple's roots alone (production, QA and the
|
||||
Hacktivation one), compiled into it in the OS cryptex's dyld shared cache, which the project
|
||||
can't change; it skips a policy it can't decode, the update still ends, and the next boot stops
|
||||
@@ -363,17 +363,6 @@ Data out and has the first boot make it, by EACS:
|
||||
guest wrote (the ean storage's keys among it), then removes the copies. It refuses while the
|
||||
ean storage holds only `aptk`. The next boot unwraps the D-key, unlocks Data (boot mode
|
||||
`_autounlock`) and goes to Setup Assistant **[measured]**.
|
||||
- `mobile_obliterator` clears `/<G>/` in Preboot item by item, the request's `var` among them,
|
||||
and stops at the first item it can't delete. A 27.2.1 (26B131) first boot under TCG on an
|
||||
x86-64 Linux host failed to delete `PreLoginData`, which that boot had made ("Operation not
|
||||
permitted"), left `var/db/.com.apple.eacs`, `Library` and `System`, and still made Data and
|
||||
reset ("EACS completed with warnings"); the next boot ran EACS again from the request and
|
||||
deleted the LocalPolicy `finish_eacs` had put back. That second run's deletion of
|
||||
`PreLoginData` succeeded and it removed the request **[measured, 2026-12-02]**. So
|
||||
`finish_eacs` first reads Preboot for the request (`pipeline::eacs_request_left`): where it is
|
||||
left, it puts the partition and the nonces back as usual but keeps the copies, counts the boot
|
||||
in `eacs-again` and asks for one more first boot, then finishes after it; after 3 boots that
|
||||
leave it, it asks for a new restore.
|
||||
- Its template migration (`templateMigrator`, in the BaseSystem) depends on how the restore left
|
||||
the Update volume. With every volume recording 26A434's OS version and no
|
||||
`Update/Hardware/Battery`, 9 of 16 fresh 14.6.1 restores failed it ("MobileObliteration
|
||||
|
||||
@@ -282,35 +282,14 @@ fn lock(dir: &Path, name: &str) -> Result<File> {
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.with_context(|| format!("open {}", path.display()))?;
|
||||
if !matches!(try_lock_let_go(&f), Ok(true)) {
|
||||
// flock(LOCK_EX | LOCK_NB) on Unix, LockFileEx on Windows; the lock goes when the file is
|
||||
// closed.
|
||||
if f.try_lock().is_err() {
|
||||
bail!("another download of {name} is running");
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// How long [`try_lock_let_go`] waits for a lock another holds before it takes it for a running
|
||||
/// holder's: a few milliseconds is what a forked child holds a lock on for on a busy host.
|
||||
pub const LOCK_LET_GO: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Takes `f`'s lock (flock(LOCK_EX | LOCK_NB) on Unix, LockFileEx on Windows; it goes when the
|
||||
/// file is closed), waiting up to [`LOCK_LET_GO`] where another holds it: `Ok(false)` where it is
|
||||
/// held still, `Err` where the file takes no lock. flock's lock is the open file's, which a fork
|
||||
/// shares: a lock its holder let go of, its file closed or its process ended, is held on by each
|
||||
/// child that another thread of the holder's process forked before, until that child execs.
|
||||
pub fn try_lock_let_go(f: &File) -> std::io::Result<bool> {
|
||||
let since = std::time::Instant::now();
|
||||
loop {
|
||||
match f.try_lock() {
|
||||
Ok(()) => return Ok(true),
|
||||
Err(std::fs::TryLockError::WouldBlock) if since.elapsed() < LOCK_LET_GO => {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(false),
|
||||
Err(std::fs::TryLockError::Error(e)) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hashes the first `have` bytes of the file at `path` into `hash`, opening it to read alone.
|
||||
fn hash_prefix(path: &Path, have: u64, hash: &mut Sha1, cancel: &AtomicBool) -> Result<()> {
|
||||
let f = File::open(path).with_context(|| format!("open {}", path.display()))?;
|
||||
@@ -705,28 +684,6 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A lock its download let go of is held on by a child forked meanwhile, until the child
|
||||
/// execs (flock's lock is the open file's, which the fork shares): the next download waits
|
||||
/// for it rather than say another runs. A clone of the lock's descriptor, let go 100 ms
|
||||
/// after the download's lock, stands in for the child.
|
||||
#[test]
|
||||
fn a_lock_a_forked_child_holds_on_is_waited_out() {
|
||||
let dir = temp_dir("lock-held");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let held = lock(&dir, NAME).unwrap();
|
||||
let child = held.try_clone().unwrap();
|
||||
drop(held);
|
||||
let exec = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
drop(child);
|
||||
});
|
||||
let taken = lock(&dir, NAME);
|
||||
exec.join().unwrap();
|
||||
assert!(taken.is_ok(), "{taken:?}");
|
||||
drop(taken);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// What a download still takes: the CDN's length, less what is here.
|
||||
#[test]
|
||||
fn what_a_download_still_takes() {
|
||||
|
||||
@@ -462,11 +462,8 @@ pub(crate) mod tests {
|
||||
fn a_members_unix_mode_is_kept() {
|
||||
let p = tempfile_path::TempPath::new("zip");
|
||||
let mut w = zip::ZipWriter::new(File::create(&p.0).unwrap());
|
||||
// Made on Unix, as Apple's IPSWs are: the writer marks a member made on Windows as DOS's,
|
||||
// whose mode the reader makes up (0o664), unless the options name the system.
|
||||
let opts = zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Stored)
|
||||
.system(zip::System::Unix)
|
||||
.unix_permissions(0o755);
|
||||
w.start_file("tool", opts).unwrap();
|
||||
w.write_all(b"#!").unwrap();
|
||||
|
||||
@@ -60,8 +60,7 @@ enum Command {
|
||||
ecid: Option<u64>,
|
||||
},
|
||||
/// After a VM's first boot: macOS makes its Data volume at that boot and resets the VM, which
|
||||
/// then doesn't start; this makes it bootable again, for Setup Assistant, or, where that boot
|
||||
/// failed or left its request for the Data volume behind, ready for one more first boot.
|
||||
/// then doesn't start; this makes it bootable again, for Setup Assistant.
|
||||
FinishEacs {
|
||||
/// The VM's directory.
|
||||
dir: PathBuf,
|
||||
@@ -156,9 +155,8 @@ fn restore(ipsw: PathBuf, dir: PathBuf, disk_gib: u64, ecid: Option<u64>) -> Res
|
||||
);
|
||||
println!(
|
||||
"macOS {} makes its Data volume at the VM's first boot, then resets the VM, which \
|
||||
then doesn't start. Once it has, run `reims-restore finish-eacs {}`. Where it says the \
|
||||
VM needs one more first boot, boot it again and finish again; once it finishes, the \
|
||||
next boot goes to Setup Assistant.",
|
||||
then doesn't start. Once it has, run `reims-restore finish-eacs {}`; the next boot \
|
||||
goes to Setup Assistant.",
|
||||
done.version,
|
||||
job.dir.display()
|
||||
);
|
||||
@@ -170,15 +168,7 @@ fn default_cache() -> Result<PathBuf> {
|
||||
if let Some(x) = std::env::var_os("XDG_CACHE_HOME").filter(|x| !x.is_empty()) {
|
||||
return Ok(PathBuf::from(x).join("reims-restore"));
|
||||
}
|
||||
let home = std::env::var_os("HOME")
|
||||
.or_else(|| {
|
||||
if cfg!(windows) {
|
||||
std::env::var_os("USERPROFILE")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.context("HOME is not set: pass --cache")?;
|
||||
let home = std::env::var_os("HOME").context("HOME is not set: pass --cache")?;
|
||||
Ok(PathBuf::from(home).join(".cache/reims-restore"))
|
||||
}
|
||||
|
||||
@@ -337,7 +327,6 @@ fn extract(
|
||||
.create_new(true)
|
||||
.open(out)
|
||||
.with_context(|| format!("create {}", out.display()))?;
|
||||
let _ = reims_restore::sys::set_sparse(&f);
|
||||
f.set_len(src.len())?;
|
||||
let mut buf = vec![0u8; 8 << 20];
|
||||
let mut off = 0u64;
|
||||
|
||||
@@ -88,9 +88,6 @@ pub const EACS_DISK: &str = "disk.pre-eacs";
|
||||
pub const EACS_TRIES: &str = "eacs-tries";
|
||||
/// The first boots a VM gets to make its Data volume by EACS before [`finish_eacs`] gives up.
|
||||
pub const EACS_MAX_TRIES: u32 = 3;
|
||||
/// Until [`finish_eacs`]: how many first boots made the Data volume but left EACS's request on
|
||||
/// Preboot ([`eacs_request_left`]), each readied for one more first boot.
|
||||
pub const EACS_AGAIN: &str = "eacs-again";
|
||||
|
||||
/// The auxiliary storage's size as QEMU attaches it.
|
||||
const AUX_SIZE: u64 = aux::SIZE as u64;
|
||||
@@ -448,7 +445,6 @@ fn check_dir(dir: &Path) -> Result<()> {
|
||||
EACS_AUX,
|
||||
EACS_DISK,
|
||||
EACS_TRIES,
|
||||
EACS_AGAIN,
|
||||
] {
|
||||
ensure!(
|
||||
!dir.join(f).exists(),
|
||||
@@ -479,7 +475,6 @@ impl Files {
|
||||
for (name, size) in [(DISK, disk_size), (AUX_TRIMMED, AUX_SIZE)] {
|
||||
let p = self.part(name);
|
||||
let f = File::create(&p).with_context(|| format!("make {}", p.display()))?;
|
||||
let _ = crate::sys::set_sparse(&f);
|
||||
f.set_len(size)
|
||||
.with_context(|| format!("size {} to {size} bytes", p.display()))?;
|
||||
}
|
||||
@@ -500,19 +495,13 @@ impl Files {
|
||||
/// takes no space, where the file system makes one, else a sparse copy, once the space it
|
||||
/// takes is free. Returns the bytes a copy takes, `None` for a clone.
|
||||
fn keep_disk_for_eacs(&self) -> Result<Option<u64>> {
|
||||
self.keep_disk_for_eacs_with(&clone_file)
|
||||
}
|
||||
|
||||
/// [`Files::keep_disk_for_eacs`], making the clone with `clone`, whose refusal, for any
|
||||
/// reason, falls back to the sparse copy.
|
||||
fn keep_disk_for_eacs_with(&self, clone: &dyn Fn(&Path, &Path) -> bool) -> Result<Option<u64>> {
|
||||
let (from, to) = (self.part(DISK), self.part(EACS_DISK));
|
||||
if clone(&from, &to) {
|
||||
if clone_file(&from, &to) {
|
||||
return Ok(None);
|
||||
}
|
||||
let f = File::open(&from).context("open the disk")?;
|
||||
let m = f.metadata()?;
|
||||
let used = crate::sys::allocated_at(&from, &m);
|
||||
let used = crate::sys::allocated(&m);
|
||||
check_space(&self.dir, free_space(&self.dir)?, used)?;
|
||||
copy_sparse(&f, 0, m.len(), &to, 0)?;
|
||||
Ok(Some(used))
|
||||
@@ -541,9 +530,7 @@ impl Files {
|
||||
if name == EACS_DISK && !p.exists() {
|
||||
continue;
|
||||
}
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&p)
|
||||
File::open(&p)
|
||||
.and_then(|f| f.sync_all())
|
||||
.with_context(|| format!("flush {}", p.display()))?;
|
||||
}
|
||||
@@ -638,7 +625,6 @@ fn clone_file(from: &Path, to: &Path) -> bool {
|
||||
fn copy_sparse(from: &File, at: u64, len: u64, to: &Path, to_at: u64) -> Result<()> {
|
||||
use reims_apfs::file_at::FileAt as _;
|
||||
let out = File::create(to).with_context(|| format!("make {}", to.display()))?;
|
||||
let _ = crate::sys::set_sparse(&out);
|
||||
out.set_len(to_at + len)?;
|
||||
let mut buf = vec![0u8; 1 << 20];
|
||||
let mut done = 0;
|
||||
@@ -666,11 +652,8 @@ fn copy_sparse(from: &File, at: u64, len: u64, to: &Path, to_at: u64) -> Result<
|
||||
/// policy nonces back into NVRAM ([`aux::put_back_policy_entries`]), keeping what the guest
|
||||
/// wrote in the auxiliary storage, its keys in the ean storage among it; then removes the copies.
|
||||
/// Refuses before the guest's keystore has made its keys. After a first boot whose EACS failed
|
||||
/// ([`aux::recovery_boot_mode`]) it starts the VM again instead ([`start_again`]). After one that
|
||||
/// made the Data volume but left EACS's request on Preboot ([`eacs_request_left`]), which would
|
||||
/// have the next boot run EACS again and delete what this puts back, it puts the same back but
|
||||
/// keeps the copies, counts the boot in [`EACS_AGAIN`] and asks for one more first boot; after
|
||||
/// [`EACS_MAX_TRIES`] such boots it leaves the VM as it is. A run cut short can run again.
|
||||
/// ([`aux::recovery_boot_mode`]) it starts the VM again instead ([`start_again`]). A run cut
|
||||
/// short can run again.
|
||||
pub fn finish_eacs(dir: &Path) -> Result<()> {
|
||||
use reims_apfs::file_at::FileAt as _;
|
||||
let (isc, pre_aux) = (dir.join(EACS_ISC), dir.join(EACS_AUX));
|
||||
@@ -694,25 +677,6 @@ pub fn finish_eacs(dir: &Path) -> Result<()> {
|
||||
"the VM's first boot hasn't made its keys yet: boot it once, until macOS has made its \
|
||||
Data volume and reset, then finish"
|
||||
);
|
||||
let left = eacs_request_left(&dir.join(DISK))?;
|
||||
let again = dir.join(EACS_AGAIN);
|
||||
let boots_left_it = match &left {
|
||||
Some(path) => {
|
||||
let n = std::fs::read_to_string(&again)
|
||||
.ok()
|
||||
.and_then(|s| s.trim().parse::<u32>().ok())
|
||||
.unwrap_or(0)
|
||||
+ 1;
|
||||
ensure!(
|
||||
n < EACS_MAX_TRIES,
|
||||
"macOS's first boot made its Data volume but left the request for it on Preboot \
|
||||
({path}) in all {EACS_MAX_TRIES} tries, so every boot makes it again: restore \
|
||||
the VM again"
|
||||
);
|
||||
n
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
let restored =
|
||||
std::fs::read(&pre_aux).with_context(|| format!("read {}", pre_aux.display()))?;
|
||||
aux::put_back_policy_entries(&mut a, &restored)?;
|
||||
@@ -753,20 +717,10 @@ pub fn finish_eacs(dir: &Path) -> Result<()> {
|
||||
}
|
||||
disk.sync_all().context("flush the disk")?;
|
||||
put_aux(dir, &a)?;
|
||||
if let Some(path) = left {
|
||||
std::fs::write(&again, format!("{boots_left_it}\n"))
|
||||
.with_context(|| format!("write {}", again.display()))?;
|
||||
bail!(
|
||||
"macOS's first boot made its Data volume but left the request for it on Preboot \
|
||||
({path}), so the next boot makes it again (try {boots_left_it} of \
|
||||
{EACS_MAX_TRIES}): the VM is ready for that boot, so boot it once more, until macOS \
|
||||
has made its Data volume and reset, then finish again"
|
||||
);
|
||||
}
|
||||
for f in [&isc, &pre_aux] {
|
||||
std::fs::remove_file(f).with_context(|| format!("remove {}", f.display()))?;
|
||||
}
|
||||
for f in [dir.join(EACS_DISK), dir.join(EACS_TRIES), again] {
|
||||
for f in [dir.join(EACS_DISK), dir.join(EACS_TRIES)] {
|
||||
if f.exists() {
|
||||
std::fs::remove_file(&f).with_context(|| format!("remove {}", f.display()))?;
|
||||
}
|
||||
@@ -774,50 +728,10 @@ pub fn finish_eacs(dir: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where the VM's first boot left EACS's request ([`plan::EACS_COOKIE`]) under the volume
|
||||
/// group's directory in the main container's Preboot, its path there; `None` where it is gone.
|
||||
/// `mobile_obliterator` deletes the group's directory there item by item, the request's `var`
|
||||
/// among them, but stops at the first item it can't delete: a 27.2.1 (26B131) first boot under
|
||||
/// TCG on an x86-64 Linux host failed to delete `PreLoginData`, which the boot had made ("Operation
|
||||
/// not permitted"), left `var`, `Library` and `System`, and still made the Data volume and reset.
|
||||
/// The next boot ran EACS again from the request, deleting the macOS LocalPolicy [`finish_eacs`]
|
||||
/// had put back; that boot's deletion of `PreLoginData` succeeded **[measured]**.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The disk's main container, its System or Preboot volume, or a record on the path fails to
|
||||
/// read or check.
|
||||
fn eacs_request_left(disk: &Path) -> Result<Option<String>> {
|
||||
let f = File::open(disk).with_context(|| format!("open {}", disk.display()))?;
|
||||
let c = reims_apfs::open(Arc::new(f)).context("open the disk's main container")?;
|
||||
let group = c
|
||||
.system_volume()
|
||||
.context("find the main container's System volume")?
|
||||
.sb
|
||||
.volume_group_id;
|
||||
let path = format!(
|
||||
"{}/{}",
|
||||
Uuid::from_bytes(group).to_string().to_uppercase(),
|
||||
plan::EACS_COOKIE
|
||||
);
|
||||
let volumes = c.volumes().context("read the main container's volumes")?;
|
||||
let preboot = volumes
|
||||
.iter()
|
||||
.find(|v| v.role() == reims_apfs::ondisk::apfs::ROLE_PREBOOT)
|
||||
.context("the main container has no Preboot volume")?;
|
||||
match preboot.lookup(&path) {
|
||||
Ok(e) if e.is_file() => Ok(Some(path)),
|
||||
// A component that is not there, or not a directory: no request.
|
||||
Ok(_) | Err(reims_apfs::Error::Invalid(_)) => Ok(None),
|
||||
Err(e) => Err(e).with_context(|| format!("look for {path} on Preboot")),
|
||||
}
|
||||
}
|
||||
|
||||
/// After a first boot whose EACS failed: puts the VM back as the restore left it, the disk from
|
||||
/// [`EACS_DISK`] and the auxiliary storage from [`EACS_AUX`], for another first boot, counts the
|
||||
/// failed boot in [`EACS_TRIES`] and starts [`EACS_AGAIN`]'s count over; after
|
||||
/// [`EACS_MAX_TRIES`] failed boots it leaves the VM as it is. Either way it returns an error that
|
||||
/// says which, and what to do next.
|
||||
/// [`EACS_DISK`] and the auxiliary storage from [`EACS_AUX`], for another first boot, and counts
|
||||
/// the failed boot in [`EACS_TRIES`]; after [`EACS_MAX_TRIES`] failed boots it leaves the VM as
|
||||
/// it is. Either way it returns an error that says which, and what to do next.
|
||||
fn start_again(dir: &Path) -> Result<()> {
|
||||
let tries = dir.join(EACS_TRIES);
|
||||
let failed = std::fs::read_to_string(&tries)
|
||||
@@ -845,21 +759,13 @@ fn start_again(dir: &Path) -> Result<()> {
|
||||
let f = File::open(&pre).with_context(|| format!("open {}", pre.display()))?;
|
||||
copy_sparse(&f, 0, f.metadata()?.len(), &part, 0)?;
|
||||
}
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&part)
|
||||
File::open(&part)
|
||||
.and_then(|f| f.sync_all())
|
||||
.with_context(|| format!("flush {}", part.display()))?;
|
||||
std::fs::rename(&part, dir.join(DISK)).context("move the restored disk back into place")?;
|
||||
let restored = std::fs::read(dir.join(EACS_AUX))
|
||||
.with_context(|| format!("read {}", dir.join(EACS_AUX).display()))?;
|
||||
put_aux(dir, &restored)?;
|
||||
// The disk is the restore's again, so no boot since has left EACS's request on it: the count
|
||||
// of those starts over.
|
||||
let again = dir.join(EACS_AGAIN);
|
||||
if again.exists() {
|
||||
std::fs::remove_file(&again).with_context(|| format!("remove {}", again.display()))?;
|
||||
}
|
||||
std::fs::write(&tries, format!("{failed}\n"))
|
||||
.with_context(|| format!("write {}", tries.display()))?;
|
||||
bail!(
|
||||
@@ -878,7 +784,7 @@ fn put_aux(dir: &Path, trimmed: &[u8]) -> Result<()> {
|
||||
let p = dir.join(name);
|
||||
let tmp = dir.join(format!("{name}.part"));
|
||||
std::fs::write(&tmp, bytes).with_context(|| format!("write {}", tmp.display()))?;
|
||||
OpenOptions::new().write(true).open(&tmp)?.sync_all()?;
|
||||
File::open(&tmp)?.sync_all()?;
|
||||
std::fs::rename(&tmp, &p).with_context(|| format!("move {} into place", p.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -972,6 +878,7 @@ mod tests {
|
||||
let isc = table.isc();
|
||||
write_at(&f.part(DISK), isc.offset() + 0x1000, b"the restore's iSC");
|
||||
write_at(&f.part(DISK), isc.offset() + isc.len() - 0x1000, b"its end");
|
||||
write_at(&f.part(DISK), table.main().offset(), b"the main container");
|
||||
let n = Nvram {
|
||||
policy_nonces: [
|
||||
[0x11; 16], [0x22; 16], [3; 16], [4; 16], [5; 16], [6; 16], [7; 16],
|
||||
@@ -979,7 +886,6 @@ mod tests {
|
||||
container: table.main().guid,
|
||||
group: Uuid::from_u128(0xbf30_4653),
|
||||
};
|
||||
write_main(&f.part(DISK), &table, n.group, true);
|
||||
let a = aux::trimmed(&n, b"a ticket of the tests' own").unwrap();
|
||||
std::fs::write(f.part(AUX_TRIMMED), &a).unwrap();
|
||||
f.keep_for_eacs(&table).unwrap();
|
||||
@@ -987,77 +893,15 @@ mod tests {
|
||||
(d, table, n, a)
|
||||
}
|
||||
|
||||
/// A main container of the tests' own at `t`'s main partition of `disk`: a System volume in
|
||||
/// volume group `group`, and a Preboot volume holding the group's `var/db`, with EACS's
|
||||
/// request in it where `request`.
|
||||
fn write_main(disk: &Path, t: &Table, group: Uuid, request: bool) {
|
||||
use reims_apfs::ondisk::apfs::{ROLE_PREBOOT, ROLE_SYSTEM};
|
||||
use reims_apfs::write::{self as w, fsbuild};
|
||||
let item = |path: String, kind| fsbuild::Item {
|
||||
path,
|
||||
kind,
|
||||
mode: 0o755,
|
||||
uid: 0,
|
||||
gid: 0,
|
||||
bsd_flags: 0,
|
||||
xattrs: Vec::new(),
|
||||
};
|
||||
let g = group.to_string().to_uppercase();
|
||||
let mut items = vec![
|
||||
item(g.clone(), fsbuild::Kind::Dir),
|
||||
item(format!("{g}/var"), fsbuild::Kind::Dir),
|
||||
item(format!("{g}/var/db"), fsbuild::Kind::Dir),
|
||||
];
|
||||
let cookie = plan::eacs_cookie(group, t.main().guid);
|
||||
if request {
|
||||
items.push(item(
|
||||
format!("{g}/{}", plan::EACS_COOKIE),
|
||||
fsbuild::Kind::File {
|
||||
len: cookie.len() as u64,
|
||||
},
|
||||
));
|
||||
}
|
||||
let mut system = w::VolumeDef::of(
|
||||
"Macintosh HD",
|
||||
[1; 16],
|
||||
ROLE_SYSTEM,
|
||||
fsbuild::build(&[], true, w::FORMAT_TIME).unwrap(),
|
||||
);
|
||||
system.system = true;
|
||||
system.group = *group.as_bytes();
|
||||
let preboot = w::VolumeDef::of(
|
||||
"Preboot",
|
||||
[2; 16],
|
||||
ROLE_PREBOOT,
|
||||
fsbuild::build(&items, true, w::FORMAT_TIME).unwrap(),
|
||||
);
|
||||
let block = w::geometry::BLOCK_SIZE;
|
||||
let formed = w::container(
|
||||
t.main().len() / block,
|
||||
[3; 16],
|
||||
w::FORMAT_TIME,
|
||||
w::key_os_version("26B131").unwrap(),
|
||||
vec![system, preboot],
|
||||
)
|
||||
.unwrap();
|
||||
let base = t.main().offset();
|
||||
for (addr, b) in &formed.blocks {
|
||||
write_at(disk, base + addr * block, b);
|
||||
}
|
||||
for first in &formed.stream_blocks[1] {
|
||||
write_at(disk, base + first * block, &cookie);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a guest's EACS boot leaves, as far as finishing reads it: other bytes in the iBoot
|
||||
/// system container, the main container without EACS's request, the keystore's entries
|
||||
/// counted in the ean storage, and NVRAM's policy nonces not the restore's.
|
||||
/// system container and the main container, the keystore's entries counted in the ean
|
||||
/// storage, and NVRAM's policy nonces not the restore's.
|
||||
fn boot_by_eacs(d: &Path, t: &Table, n: &Nvram) {
|
||||
let isc = t.isc();
|
||||
let disk = d.join(DISK);
|
||||
write_at(&disk, isc.offset() + 0x1000, &[0; 17]);
|
||||
write_at(&disk, isc.offset() + 0x20_0000, b"the guest's iSC");
|
||||
write_main(&disk, t, n.group, false);
|
||||
write_at(&disk, t.main().offset(), b"the guest's Data");
|
||||
let mut other = n.clone();
|
||||
other.policy_nonces[1] = [0x99; 16];
|
||||
let mut a = aux::trimmed(&other, b"a ticket of the tests' own").unwrap();
|
||||
@@ -1095,8 +939,6 @@ mod tests {
|
||||
boot_by_eacs(&d, &t, &n);
|
||||
std::fs::write(d.join(EACS_DISK), b"the restored disk").unwrap();
|
||||
std::fs::write(d.join(EACS_TRIES), b"1\n").unwrap();
|
||||
std::fs::write(d.join(EACS_AGAIN), b"1\n").unwrap();
|
||||
let main = read_at(&d.join(DISK), t.main().offset(), 0x1_0000);
|
||||
finish_eacs(&d).unwrap();
|
||||
let disk = d.join(DISK);
|
||||
let isc = t.isc();
|
||||
@@ -1109,11 +951,7 @@ mod tests {
|
||||
read_at(&disk, isc.offset() + isc.len() - 0x1000, 7),
|
||||
b"its end"
|
||||
);
|
||||
assert_eq!(
|
||||
read_at(&disk, t.main().offset(), 0x1_0000),
|
||||
main,
|
||||
"the main container stays as the guest left it"
|
||||
);
|
||||
assert_eq!(read_at(&disk, t.main().offset(), 16), b"the guest's Data");
|
||||
let a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
|
||||
assert_eq!(
|
||||
aux::ean_entries(&a[aux::EAN_AT..]),
|
||||
@@ -1134,7 +972,7 @@ mod tests {
|
||||
let vz = std::fs::read(d.join(AUX)).unwrap();
|
||||
assert_eq!(&vz[..aux::HEADER_LEN], &aux::vz_header()[..]);
|
||||
assert_eq!(&vz[aux::HEADER_LEN..], &a[..]);
|
||||
for f in [EACS_ISC, EACS_AUX, EACS_DISK, EACS_TRIES, EACS_AGAIN] {
|
||||
for f in [EACS_ISC, EACS_AUX, EACS_DISK, EACS_TRIES] {
|
||||
assert!(!d.join(f).exists(), "{f} is left");
|
||||
}
|
||||
assert!(finish_eacs(&d).is_err(), "nothing left to finish");
|
||||
@@ -1162,7 +1000,6 @@ mod tests {
|
||||
let mut a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
|
||||
aux::add_system_entry(&mut a, 0, "recovery-boot-mode", b"the guest's");
|
||||
std::fs::write(d.join(AUX_TRIMMED), &a).unwrap();
|
||||
let main = read_at(&d.join(DISK), t.main().offset(), 0x1_0000);
|
||||
let e = finish_eacs(&d).unwrap_err().to_string();
|
||||
assert!(e.contains("failed to make its Data volume"), "{e}");
|
||||
assert_eq!(
|
||||
@@ -1170,91 +1007,14 @@ mod tests {
|
||||
a,
|
||||
"left as it is"
|
||||
);
|
||||
assert_eq!(read_at(&d.join(DISK), t.main().offset(), 0x1_0000), main);
|
||||
assert_eq!(
|
||||
read_at(&d.join(DISK), t.main().offset(), 16),
|
||||
b"the guest's Data"
|
||||
);
|
||||
assert!(d.join(EACS_ISC).exists() && d.join(EACS_AUX).exists());
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restore_for_eacs_leaves_its_request_on_preboot() {
|
||||
let (d, t, n, _) = restored_for_eacs();
|
||||
let path = format!(
|
||||
"{}/{}",
|
||||
n.group.to_string().to_uppercase(),
|
||||
plan::EACS_COOKIE
|
||||
);
|
||||
assert_eq!(eacs_request_left(&d.join(DISK)).unwrap(), Some(path));
|
||||
boot_by_eacs(&d, &t, &n);
|
||||
assert_eq!(eacs_request_left(&d.join(DISK)).unwrap(), None);
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
/// A first boot that made the Data volume but left EACS's request on Preboot, as a 27.2.1
|
||||
/// first boot under TCG did when it failed to delete `PreLoginData` **[measured]**: finishing
|
||||
/// puts the restore's iSC and nonces back for one more first boot, keeps the copies, and
|
||||
/// finishes after a boot that removes the request.
|
||||
#[test]
|
||||
fn finishing_eacs_after_a_boot_that_left_its_request_readies_another() {
|
||||
let (d, t, n, _) = restored_for_eacs();
|
||||
std::fs::write(d.join(EACS_DISK), b"the restored disk").unwrap();
|
||||
for k in 1..EACS_MAX_TRIES {
|
||||
boot_by_eacs(&d, &t, &n);
|
||||
write_main(&d.join(DISK), &t, n.group, true);
|
||||
let e = finish_eacs(&d).unwrap_err().to_string();
|
||||
assert!(e.contains("left the request for it on Preboot"), "{e}");
|
||||
assert!(e.contains(&format!("try {k} of {EACS_MAX_TRIES}")), "{e}");
|
||||
assert_eq!(
|
||||
read_at(&d.join(DISK), t.isc().offset() + 0x1000, 17),
|
||||
b"the restore's iSC"
|
||||
);
|
||||
let a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
|
||||
assert_eq!(aux::ean_entries(&a[aux::EAN_AT..]), Some(3));
|
||||
let parts = aux::read_bank(&a[aux::NVRAM_AT..aux::NVRAM_AT + 0x8_0000]).unwrap();
|
||||
let system = &parts.iter().find(|(p, _)| p == "system").unwrap().1;
|
||||
let nonces = &system
|
||||
.iter()
|
||||
.find(|(k, _)| k == "boop-storage-nonces")
|
||||
.unwrap()
|
||||
.1;
|
||||
assert_eq!(nonces, &n.policy_nonces.concat());
|
||||
for f in [EACS_ISC, EACS_AUX, EACS_DISK] {
|
||||
assert!(d.join(f).is_file(), "{f} is kept for the next boot");
|
||||
}
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(d.join(EACS_AGAIN)).unwrap(),
|
||||
format!("{k}\n")
|
||||
);
|
||||
}
|
||||
boot_by_eacs(&d, &t, &n);
|
||||
finish_eacs(&d).unwrap();
|
||||
for f in [EACS_ISC, EACS_AUX, EACS_DISK, EACS_AGAIN] {
|
||||
assert!(!d.join(f).exists(), "{f} is left");
|
||||
}
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finishing_eacs_gives_up_when_every_boot_leaves_its_request() {
|
||||
let (d, t, n, _) = restored_for_eacs();
|
||||
boot_by_eacs(&d, &t, &n);
|
||||
write_main(&d.join(DISK), &t, n.group, true);
|
||||
let k = EACS_MAX_TRIES - 1;
|
||||
std::fs::write(d.join(EACS_AGAIN), format!("{k}\n")).unwrap();
|
||||
let a = std::fs::read(d.join(AUX_TRIMMED)).unwrap();
|
||||
let e = finish_eacs(&d).unwrap_err().to_string();
|
||||
assert!(e.contains("restore the VM again"), "{e}");
|
||||
assert_eq!(
|
||||
std::fs::read(d.join(AUX_TRIMMED)).unwrap(),
|
||||
a,
|
||||
"left as it is"
|
||||
);
|
||||
assert_eq!(
|
||||
read_at(&d.join(DISK), t.isc().offset() + 0x1000, 17),
|
||||
[0; 17]
|
||||
);
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restore_keeps_its_disk_to_start_again_from() {
|
||||
let d = temp_dir();
|
||||
@@ -1272,24 +1032,6 @@ mod tests {
|
||||
std::fs::remove_dir(&d).unwrap();
|
||||
}
|
||||
|
||||
/// Where the file system makes no clone (ext4), the restore keeps its disk as a sparse copy
|
||||
/// of the same bytes, on any file system the test runs on.
|
||||
#[test]
|
||||
fn a_restore_keeps_a_copy_of_its_disk_where_no_clone_is_made() {
|
||||
let d = temp_dir();
|
||||
let f = Files::new(&d);
|
||||
f.make(1 << 20).unwrap();
|
||||
write_at(&f.part(DISK), 0x1000, b"the restored disk");
|
||||
let copied = f.keep_disk_for_eacs_with(&|_, _| false).unwrap();
|
||||
assert!(copied.is_some(), "a copy, not a clone");
|
||||
let kept = f.part(EACS_DISK);
|
||||
assert_eq!(std::fs::metadata(&kept).unwrap().len(), 1 << 20);
|
||||
assert_eq!(read_at(&kept, 0x1000, 17), b"the restored disk");
|
||||
f.discard();
|
||||
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0);
|
||||
std::fs::remove_dir(&d).unwrap();
|
||||
}
|
||||
|
||||
/// Sets a VM of the tests' small files back to after a first boot whose EACS failed: the
|
||||
/// guest's disk, and the restore's auxiliary storage with NVRAM asking for recoveryOS.
|
||||
fn fail_first_boot(d: &Path, restored: &[u8]) {
|
||||
@@ -1320,8 +1062,6 @@ mod tests {
|
||||
fn finishing_eacs_after_a_failed_first_boot_starts_the_vm_again() {
|
||||
let (d, restored) = failed_first_boot();
|
||||
for t in 1..EACS_MAX_TRIES {
|
||||
// A boot before this one left EACS's request, on the disk the restore's replaces.
|
||||
std::fs::write(d.join(EACS_AGAIN), b"1\n").unwrap();
|
||||
let e = finish_eacs(&d).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("try {t} of {EACS_MAX_TRIES}")), "{e}");
|
||||
assert_eq!(std::fs::read(d.join(DISK)).unwrap(), b"the restored disk");
|
||||
@@ -1332,7 +1072,6 @@ mod tests {
|
||||
for f in [EACS_DISK, EACS_ISC, EACS_AUX] {
|
||||
assert!(d.join(f).is_file(), "{f} is kept for the next try");
|
||||
}
|
||||
assert!(!d.join(EACS_AGAIN).exists(), "its count starts over");
|
||||
fail_first_boot(&d, &restored);
|
||||
}
|
||||
let e = finish_eacs(&d).unwrap_err().to_string();
|
||||
|
||||
@@ -10,23 +10,28 @@
|
||||
//! while another, uninterruptible, runs: the update's first step fails, nothing is rolled or
|
||||
//! removed, and the policy the restore wrote stays the blessed one.
|
||||
//!
|
||||
//! The kext's command for the update begins with two checks of the local update's state, a
|
||||
//! record of bytes. The first reads the state's byte and, unless an update is running, branches
|
||||
//! past the refusal to make the new nonce. The second reads, from the record's fourth byte,
|
||||
//! whether the running update is interruptible, and branches to the refusal unless it is; an
|
||||
//! interruptible one is logged and marked interrupted, and the command goes on to make the new
|
||||
//! nonce. The patch turns the first branch into a `nop`, so the refusal is taken unless a
|
||||
//! running update is interruptible, which only that update's own timer makes it.
|
||||
//! The kext's command for the update begins with
|
||||
//!
|
||||
//! What is matched (`begins_update`) is those six instructions: each check is a byte load from
|
||||
//! the record, a compare with the running value (2) or the interruptible value (1), and a branch
|
||||
//! if not equal, both loads into the same register from the same base register. The kext holds
|
||||
//! that shape in other commands too; the update's beginning is the one whose first branch lands
|
||||
//! eight instructions on, on a move of the proposed nonce, 3, into the first argument register,
|
||||
//! with a store of zero to the record's fourth byte just before it and a call just after. The
|
||||
//! bytes are read from the IPSW's own boot kernel collection at install time, as the anchors
|
||||
//! are, and the restore checks there is one such place, and that its bytes occur once in the
|
||||
//! kext, before it writes the patch.
|
||||
//! ```text
|
||||
//! ldrb wT, [xN] ; the local update's state
|
||||
//! cmp wT, #2 ; one running?
|
||||
//! b.ne new ; no: make the new nonce
|
||||
//! ldrb wT, [xN, #3] ; is it interruptible?
|
||||
//! cmp wT, #1
|
||||
//! b.ne refuse ; no: refuse this one
|
||||
//! ... ; log it, and mark it interrupted:
|
||||
//! strb wzr, [xN, #3]
|
||||
//! new: mov w0, #3 ; the proposed local nonce
|
||||
//! bl ... ; made new
|
||||
//! ```
|
||||
//!
|
||||
//! and the patch makes its first `b.ne` a `nop`, so the refusal is taken unless a running update
|
||||
//! is interruptible, which only that update's own timer makes it. The kext holds the first six
|
||||
//! instructions' shape in other commands too; the update's beginning is the one whose first
|
||||
//! branch lands, eight instructions on, on `mov w0, #3` and a `bl` right after
|
||||
//! `strb wzr, [xN, #3]`. The bytes are read from the IPSW's own boot kernel collection at
|
||||
//! install time, as the anchors are, and the restore checks there is one such place, and that
|
||||
//! its bytes occur once in the kext, before it writes the patch.
|
||||
|
||||
use anyhow::{Result, ensure};
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! What the restore asks the host's OS where Unix (`unix.rs`) and Windows (`windows.rs`) differ:
|
||||
//! the space free on a file system, the space a file takes on it, and sparse files, whose ranges
|
||||
//! never written take no space: the disk images the restore makes are, and NTFS makes a file
|
||||
//! sparse only when asked ([`set_sparse`]). Positioned reads and writes are reims-apfs's
|
||||
//! [`reims_apfs::file_at::FileAt`].
|
||||
//! the space free on a file system, and the space a file takes on it. Positioned reads and writes
|
||||
//! are reims-apfs's [`reims_apfs::file_at::FileAt`].
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix;
|
||||
|
||||
@@ -17,14 +17,8 @@ pub fn free_space(dir: &Path) -> Result<u64> {
|
||||
Ok(u64::from(s.f_bavail) * u64::from(s.f_frsize))
|
||||
}
|
||||
|
||||
/// The space the file at `path`, which `m` describes, takes on its file system: its 512-byte
|
||||
/// blocks, fewer than its length where it is sparse.
|
||||
pub fn allocated_at(_path: &Path, m: &std::fs::Metadata) -> u64 {
|
||||
/// The space the file `m` describes takes on its file system: its 512-byte blocks, fewer than
|
||||
/// its length where it is sparse.
|
||||
pub fn allocated(m: &std::fs::Metadata) -> u64 {
|
||||
m.blocks() * 512
|
||||
}
|
||||
|
||||
/// Nothing: a file here leaves the ranges of it never written unallocated, as holes, wherever
|
||||
/// its file system keeps them, with no flag to set first (NTFS needs one, `windows.rs`).
|
||||
pub fn set_sparse(_file: &std::fs::File) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,19 +1,10 @@
|
||||
//! [`super`] on Windows: the space free on a volume, the space a file takes on it, and sparse
|
||||
//! files. NTFS leaves the ranges of a file never written unallocated only once the file is
|
||||
//! marked sparse (`FSCTL_SET_SPARSE`): a file that is not takes its whole length as it is sized,
|
||||
//! so a VM's new disk, and the copy of it the restore keeps for EACS, would each take the disk's
|
||||
//! whole size at once.
|
||||
//! [`super`] on Windows, where reims-ctl makes no arm64 VM (its host.rs), so no restore runs:
|
||||
//! these answer as reims-ctl's code that the restore shares with x86-64 VMs needs them.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::fs::{File, Metadata};
|
||||
use std::os::windows::ffi::OsStrExt as _;
|
||||
use std::os::windows::io::AsRawHandle as _;
|
||||
use std::path::Path;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
GetCompressedFileSizeW, GetDiskFreeSpaceExW, INVALID_FILE_SIZE,
|
||||
};
|
||||
use windows_sys::Win32::System::IO::DeviceIoControl;
|
||||
use windows_sys::Win32::System::Ioctl::FSCTL_SET_SPARSE;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
|
||||
|
||||
/// The space free to this user on the volume `dir`, which exists, is on.
|
||||
pub fn free_space(dir: &Path) -> Result<u64> {
|
||||
@@ -35,82 +26,8 @@ pub fn free_space(dir: &Path) -> Result<u64> {
|
||||
Ok(free)
|
||||
}
|
||||
|
||||
/// Marks `file`, open for writing, sparse, so that the ranges of it never written stay
|
||||
/// unallocated: those `set_len` adds, and the all-zero blocks the restore's copies leave
|
||||
/// unwritten. A volume that keeps no sparse files (FAT32, exFAT) refuses, and the file then
|
||||
/// takes its whole length.
|
||||
pub fn set_sparse(file: &File) -> std::io::Result<()> {
|
||||
let mut returned = 0u32;
|
||||
// SAFETY: the handle is open for the call, which takes no input or output buffer and runs
|
||||
// synchronously, on a handle opened without overlapped I/O.
|
||||
let ok = unsafe {
|
||||
DeviceIoControl(
|
||||
file.as_raw_handle(),
|
||||
FSCTL_SET_SPARSE,
|
||||
std::ptr::null(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut returned,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if ok == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The space the file at `path`, which `m` describes, takes on its volume: its allocated
|
||||
/// clusters (`GetCompressedFileSizeW`), fewer than its length where it is sparse or compressed;
|
||||
/// its length where the call fails.
|
||||
pub fn allocated_at(path: &Path, m: &Metadata) -> u64 {
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let mut high = 0u32;
|
||||
// SAFETY: a NUL-terminated path, and one out-pointer the call fills.
|
||||
let low = unsafe { GetCompressedFileSizeW(wide.as_ptr(), &mut high) };
|
||||
// INVALID_FILE_SIZE is a size's low half too: the call's last error, NO_ERROR where it
|
||||
// succeeded, tells the two apart.
|
||||
if low == INVALID_FILE_SIZE && std::io::Error::last_os_error().raw_os_error() != Some(0) {
|
||||
return m.len();
|
||||
}
|
||||
(u64::from(high) << 32) | u64::from(low)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A file marked sparse and sized to 1 GiB takes under 1 MiB of its volume, as
|
||||
/// `allocated_at` reads it; on a volume that keeps no sparse files the test has nothing to
|
||||
/// check.
|
||||
#[test]
|
||||
fn sparse_file_does_not_allocate_virtual_length_on_ntfs() {
|
||||
let dir = std::env::temp_dir().join(format!("reims-restore-sparse-{}", std::process::id()));
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let path = dir.join("disk.img");
|
||||
let f = File::create(&path).unwrap();
|
||||
if set_sparse(&f).is_err() {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
return;
|
||||
}
|
||||
f.set_len(1u64 << 30).unwrap();
|
||||
drop(f);
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap()
|
||||
.sync_all()
|
||||
.unwrap();
|
||||
let m = std::fs::metadata(&path).unwrap();
|
||||
let alloc = allocated_at(&path, &m);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
assert_eq!(m.len(), 1u64 << 30);
|
||||
assert!(
|
||||
alloc < (1u64 << 20),
|
||||
"expected sparse allocation < 1 MiB, got {alloc}"
|
||||
);
|
||||
}
|
||||
/// The space the file `m` describes takes on its volume, counted as its length: a sparse file's
|
||||
/// holes count as written, so a check of room for its copy asks for more than the copy takes.
|
||||
pub fn allocated(m: &std::fs::Metadata) -> u64 {
|
||||
m.len()
|
||||
}
|
||||
@@ -9,50 +9,10 @@
|
||||
//! dist` names the dylib it installs `@rpath/libreims_vgpu.dylib` (`xtask/src/dist/macos.rs`).
|
||||
//! Linux needs nothing: a cdylib built here has no soname, and a host linked to it records its
|
||||
//! file name.
|
||||
//!
|
||||
//! On every host: stamps the library with the commit its tree is at (`src/build_stamp.rs`).
|
||||
|
||||
#[path = "src/build_stamp.rs"]
|
||||
mod build_stamp;
|
||||
|
||||
/// The library's crates and the workspace's manifest, whose change the stamp is read again for
|
||||
/// (`src/build_stamp.rs`): a tree changed since the last read is marked dirty.
|
||||
const SOURCES: [&str; 7] = [
|
||||
"Cargo.toml",
|
||||
"crates/reims-vgpu",
|
||||
"crates/reims-vgpu-c",
|
||||
"crates/reims-vgpu-graphics",
|
||||
"crates/reims-vgpu-video",
|
||||
"crates/reims-vgpu-vulkan",
|
||||
"crates/reims-vgpu-window",
|
||||
];
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
stamp();
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "macos") {
|
||||
println!("cargo:rustc-cdylib-link-arg=-Wl,-install_name,@rpath/libreims_vgpu_c.dylib");
|
||||
}
|
||||
}
|
||||
|
||||
/// Stamps the library with the commit its tree is at (`src/build_stamp.rs`), as
|
||||
/// `RVG_BUILD_STAMP`, read again where the checkout's HEAD or index moves or a source of the
|
||||
/// library changes.
|
||||
fn stamp() {
|
||||
let crate_dir =
|
||||
std::path::PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
|
||||
let root = crate_dir.join("../..");
|
||||
println!(
|
||||
"cargo:rustc-env=RVG_BUILD_STAMP={}",
|
||||
build_stamp::read(&root)
|
||||
);
|
||||
for file in build_stamp::git_files(&root) {
|
||||
println!("cargo:rerun-if-changed={}", file.display());
|
||||
}
|
||||
for source in SOURCES {
|
||||
let path = root.join(source);
|
||||
if path.exists() {
|
||||
println!("cargo:rerun-if-changed={}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,8 +59,7 @@
|
||||
|
||||
// The host refused the memory, a pipe, a thread or the GPU device the call needs: the graphics
|
||||
// device's region, its threads, or its GPU device, where the host has none the library can use
|
||||
// or its driver refused it, or the pool's host memory, which the GPU refused
|
||||
// (rvg_graphics_device_create).
|
||||
// or its driver refused it (rvg_graphics_device_create).
|
||||
#define RVG_ERR_HOST_RESOURCES 5
|
||||
|
||||
// The left button, in an RvgWindowPointerFn's `buttons`.
|
||||
@@ -196,36 +195,21 @@ typedef void (*RvgDestroyFn)(void *ctx);
|
||||
// (`reims-vgpu.graphics-queue-<id>`) or one of its lane's threads, which walk and commit its
|
||||
// command buffers (`reims-vgpu.graphics-lane-<id>`), a pipeline compile's thread
|
||||
// (`reims-vgpu.graphics-compile-<n>`), a thread that makes IOSurfaces' and pages blocks' views
|
||||
// (`reims-vgpu.graphics-surfaces-<i>`, and `reims-vgpu.graphics-views-<i>` for a pages block's
|
||||
// view made after its answer), a thread that makes indirect command buffers
|
||||
// (`reims-vgpu.graphics-surfaces-<i>`), a thread that makes indirect command buffers
|
||||
// (`reims-vgpu.icb-create-<i>`), a thread that lets go of a closed process's objects and answers
|
||||
// its close (`reims-vgpu.graphics-closes-<i>`), a thread that moves a staged copy of a surface's
|
||||
// device cache into its pages and answers what waited for it
|
||||
// (`reims-vgpu.graphics-into-pages-<i>`), the thread that paces releases' copies of their
|
||||
// surfaces' device caches into their pages, which answers a BLOCK_RELEASE as its turn comes
|
||||
// (`reims-vgpu.graphics-release-pace`), the thread that tries again the EVENT_SIGNALLED to a
|
||||
// shared event's other holders that their rings had no room for
|
||||
// (`reims-vgpu.graphics-shared-events`), a take worker of the guest's Shared pool or of its
|
||||
// Private blocks, which answers a POOL_TAKE or a PRIVATE_TAKE
|
||||
// (`reims-vgpu.graphics-pool-take`, `reims-vgpu.graphics-private-take`), the windows' UI thread,
|
||||
// which tells the guest of the host's pointer and scrolling (POINTER_OVER, POINTER_MOTION and
|
||||
// SCROLL; on macOS the process's main thread, on Linux and Windows `reims-vgpu.ui`), a video
|
||||
// session's picture landing thread, which posts a decode's completion as the decode is done
|
||||
// (`reims-vgpu.graphics-video-land`), or the platform's thread that runs a command buffer's
|
||||
// scheduled or completed handler; or the host's own, inside
|
||||
// rvg_graphics_device_mmio_write_taking or rvg_graphics_device_doorbell_write.
|
||||
// (`reims-vgpu.graphics-into-pages-<i>`), a video session's picture landing thread, which posts
|
||||
// a decode's completion as the decode is done (`reims-vgpu.graphics-video-land`), or the
|
||||
// platform's thread that runs a command buffer's scheduled or completed handler; or the host's
|
||||
// own, inside rvg_graphics_device_mmio_write_taking.
|
||||
// Never inside another call of the host's into the library. The library may hold locks of its
|
||||
// own around it (docs/api.md section 5 names them), but none that a function it may call waits
|
||||
// for, directly or through a thread of the library's, so it may call them at once. It may wait
|
||||
// for a lock the host holds while it calls the device (QEMU's BQL), but not for one the host
|
||||
// holds while it calls rvg_graphics_device_mmio_write_taking or
|
||||
// rvg_graphics_device_doorbell_write, nor, on any thread, for one the host holds around
|
||||
// rvg_graphics_device_reset or a write of 0 to STATUS: those wait for the platform's completed
|
||||
// handlers while the GPU work before them completes, and at most 30 s for locks of the library's
|
||||
// it may hold around this (docs/api.md section 5). May call: rvg_status_message and the
|
||||
// rvg_graphics_device_* functions, except the release of its own device; a reset called here waits
|
||||
// for none of the GPU work committed before it (rvg_graphics_device_reset). Without it the guest
|
||||
// gets no interrupt.
|
||||
// holds while it calls rvg_graphics_device_mmio_write_taking. May call: rvg_status_message and
|
||||
// the rvg_graphics_device_* functions, except the release of its own device. Without it the
|
||||
// guest gets no interrupt.
|
||||
typedef void (*RvgGraphicsRaiseFn)(void *ctx, uint32_t vector);
|
||||
|
||||
// A position or size in pixels.
|
||||
@@ -356,9 +340,7 @@ typedef void (*RvgCursorMoveAtFn)(void *ctx, uint32_t display);
|
||||
// Thread: the device's pool thread (`reims-vgpu.graphics-pool`), never inside a call of the
|
||||
// host's, with no lock of the library's held. It must not wait for a lock the host holds while
|
||||
// it calls the device (QEMU's BQL): QEMU queues the add for its main loop. One piece at a time,
|
||||
// in the order the device places them, each before its pool_remove. Not called once
|
||||
// rvg_graphics_device_release has closed the pool, at its start; a call the pool thread began
|
||||
// before that may still be running, and the release waits for it. May call: nothing of the
|
||||
// in the order the device places them, each before its pool_remove. May call: nothing of the
|
||||
// library's. Needed with a pool.
|
||||
typedef void (*RvgGraphicsPoolAddFn)(void *ctx,
|
||||
uint64_t physical_address,
|
||||
@@ -376,9 +358,8 @@ typedef void (*RvgGraphicsPoolAddFn)(void *ctx,
|
||||
// block back, never inside a call of the host's, with no lock of the library's held. It must not
|
||||
// wait for a lock the host holds while it calls the device (QEMU queues the remove for its main
|
||||
// loop). Once a piece, after its pool_add. Not called once rvg_graphics_device_release has
|
||||
// closed the pool, at its start; a call the pool thread began before that may still be running,
|
||||
// and the release waits for it. The host removes every piece it added before it releases the
|
||||
// device. May call: nothing of the library's. Needed with a pool.
|
||||
// begun: the host removes every piece it added before it releases the device. May call: nothing
|
||||
// of the library's. Needed with a pool.
|
||||
typedef void (*RvgGraphicsPoolRemoveFn)(void *ctx, uint64_t physical_address, uint64_t length);
|
||||
|
||||
// The graphics device's callbacks.
|
||||
@@ -609,14 +590,13 @@ typedef struct {
|
||||
uint32_t struct_size;
|
||||
// NULL is a table with every callback absent.
|
||||
const RvgGraphicsCallbacks *callbacks;
|
||||
// NULL is no window: the display offers its headless mode (`headless_modes`, else
|
||||
// `headless_mode_width` x `headless_mode_height`) at 60 Hz and shows nothing. Otherwise the
|
||||
// library opens a window for the display, with its input as the window's callbacks, sized
|
||||
// for its mode (1920 x 1080 where it has none). The window keeps its size: the display
|
||||
// offers the guest one mode, the window's size in pixels at the refresh rate of the host
|
||||
// screen it opens on, and tells the guest when the person resizes it. The guest's scanout is
|
||||
// blitted out of the region into the window's drawables on the GPU at each of the display's
|
||||
// refreshes, at the screen's rate, while the display shows no presented surface.
|
||||
// NULL is no window: the display offers 1920 x 1080 at 60 Hz and shows nothing. Otherwise
|
||||
// the library opens a window for the display, with its input as the window's callbacks,
|
||||
// sized for its mode (1920 x 1080 where it has none). The window keeps its size: the
|
||||
// display offers the guest one mode, the window's size in pixels at the refresh rate of the
|
||||
// host screen it opens on, and tells the guest when the person resizes it. The guest's
|
||||
// scanout is blitted out of the region into the window's drawables on the GPU at each of the
|
||||
// display's refreshes, at the screen's rate, while the display shows no presented surface.
|
||||
const RvgWindowConfig *window;
|
||||
// The guest's RAM, or NULL. With it, where the host's page is the guest's 4 KiB, or 16 KiB
|
||||
// for a guest that lays its pages out in 16 KiB (`RGFX_FEATURE_PAGES_16K`), the GPU uses an
|
||||
@@ -626,8 +606,7 @@ typedef struct {
|
||||
// down to 16 KiB, or the host GPU's answer where that is less; with no map, and on a GPU of
|
||||
// its own memory, the host GPU's. The map's pages stay the guest's RAM, mapped, until the
|
||||
// process exits (`RvgMemoryRange`): a host that discards guest RAM (a balloon, virtio-mem,
|
||||
// hot-unplug) passes NULL. Its ranges may not overlap: a map whose ranges overlap, or one
|
||||
// of whose ranges runs past the address space, is refused (RVG_ERR_INVALID_ARGUMENT).
|
||||
// hot-unplug) passes NULL. Its ranges may not overlap.
|
||||
const RvgMemoryMap *memory_map;
|
||||
// With `memory_map`: the files behind its ranges, NULL for none, one entry per range, each
|
||||
// duplicated during the create. Refused (RVG_ERR_INVALID_ARGUMENT), in this order: files
|
||||
@@ -691,34 +670,6 @@ typedef struct {
|
||||
uint64_t pool_physical_address;
|
||||
// The range's length in bytes, the most the pool may take: 0 for none.
|
||||
uint64_t pool_physical_length;
|
||||
// A fact of the host's, which it finds by asking its hypervisor and sets from nothing else:
|
||||
// 1 where the hypervisor takes no cacheable mapping of the GPU's own memory as guest memory,
|
||||
// as QEMU finds under Linux's KVM on arm64 where the VM does not answer
|
||||
// KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED (KVM then refuses a cacheable VM_PFNMAP mapping as a
|
||||
// memory slot); 0 where it takes one, every other host, and a host built before this field.
|
||||
// At 1 each of the pool's blocks is ordinary memory of the library's own (on Linux a memfd
|
||||
// it maps shared) that the GPU imports as a dma-buf, which pool_add then maps; at 0 the
|
||||
// GPU's own memory. Nothing without a pool. Refused (RVG_ERR_INVALID_ARGUMENT): any other
|
||||
// value, and 1 on a platform that makes no such blocks (macOS and Windows); refused
|
||||
// (RVG_ERR_HOST_RESOURCES): 1 where the GPU refuses host memory as a dma-buf (NVIDIA's
|
||||
// driver, or a Linux host without udmabuf), which the create finds by importing one block.
|
||||
uint32_t pool_host_memory;
|
||||
// Where `window` is NULL, the mode each display offers the guest first, in pixels, as a
|
||||
// window config's `mode_width` gives the mode its window opens for: its width rounded down
|
||||
// to a multiple of 16 and its height to even, at 60 Hz (no host screen shows the display,
|
||||
// so none sets its rate), sized to each display's scanout room on a device of several. 0 in
|
||||
// either is 1920 x 1080, as a host built before this field, whose `struct_size` ends before
|
||||
// it, has. Unread where `window` is given: the window's size is then the mode.
|
||||
uint16_t headless_mode_width;
|
||||
// As `headless_mode_width`.
|
||||
uint16_t headless_mode_height;
|
||||
// Where `window` is NULL, each display's own first mode, in place of `headless_mode_width`
|
||||
// x `headless_mode_height` for every display: an array of `display_count` sizes (one where
|
||||
// it is 0), display i's at i, its `x` the width and `y` the height, each taken as
|
||||
// `headless_mode_width` and `headless_mode_height` are (a 0 in either is 1920 x 1080). NULL
|
||||
// is those two for every display, as a host built before this field, whose `struct_size`
|
||||
// ends before it, has. Unread where `window` is given.
|
||||
const RvgDisplayCoord *headless_modes;
|
||||
} RvgGraphicsDeviceConfig;
|
||||
|
||||
#ifdef __cplusplus
|
||||
@@ -734,9 +685,8 @@ const char *rvg_status_message(RvgStatus status);
|
||||
// tables, before any table is the library's: a struct_size refusal runs no destroy, and a later
|
||||
// refusal runs each, the windows' first, display 0's first. Refusals: RVG_ERR_INVALID_ARGUMENT,
|
||||
// RVG_ERR_UNSUPPORTED, RVG_ERR_HOST_RESOURCES (the host refused the region's memory, a pipe or
|
||||
// a thread, or has no GPU device the library can use: none, or one its driver refused; or
|
||||
// the GPU refused the pool's host memory, `pool_host_memory`). Calls back: never, but a
|
||||
// refusal's destroys.
|
||||
// a thread, or has no GPU device the library can use: none, or one its driver refused). Calls
|
||||
// back: never, but a refusal's destroys.
|
||||
//
|
||||
// # Safety
|
||||
// `config` is NULL or a live config; `device` is NULL or writable.
|
||||
@@ -749,7 +699,7 @@ RvgStatus rvg_graphics_device_create(const RvgGraphicsDeviceConfig *config,
|
||||
// host's lock (QEMU's BQL) held or not: waits for nothing. Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is NULL or a live graphics device handle.
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_pool_added(RvgGraphicsDevice *device, uint64_t physical_address);
|
||||
|
||||
// The host took the pool's piece at `physical_address` out of the guest's address space, and no
|
||||
@@ -760,7 +710,7 @@ RvgStatus rvg_graphics_device_pool_added(RvgGraphicsDevice *device, uint64_t phy
|
||||
// Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is NULL or a live graphics device handle.
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_pool_removed(RvgGraphicsDevice *device, uint64_t physical_address);
|
||||
|
||||
// Asks for at least `length` more bytes of the guest's Shared pool now, ahead of the guest's own
|
||||
@@ -771,7 +721,7 @@ RvgStatus rvg_graphics_device_pool_removed(RvgGraphicsDevice *device, uint64_t p
|
||||
// for nothing. Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is NULL or a live graphics device handle.
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_pool_grow(RvgGraphicsDevice *device, uint64_t length);
|
||||
|
||||
// The range of guest physical addresses the device's Shared pool took, of those its config gave
|
||||
@@ -788,20 +738,17 @@ RvgStatus rvg_graphics_device_pool_grow(RvgGraphicsDevice *device, uint64_t leng
|
||||
// `device` is a live graphics device handle; `length` is NULL or writable.
|
||||
uint64_t rvg_graphics_device_pool_range(const RvgGraphicsDevice *device, uint64_t *length);
|
||||
|
||||
// Drops the host's reference; the last one closes the device's pool first, waiting for a pool_add
|
||||
// or pool_remove the pool's thread began, then closes the window, waiting for nothing, and ends
|
||||
// the device's threads without waiting for them: the callbacks' destroy runs once both have ended,
|
||||
// possibly after this returns, and the region stays mapped until then and until the window's GPU
|
||||
// work has let it go. The release of the process's last graphics device then waits, at most 5 s,
|
||||
// for its threads, its objects and their GPU work to let go of the GPU device, and lets go of
|
||||
// every GPU device the library keeps for the process, so that none is live as the process exits:
|
||||
// on NVIDIA's driver an exit with one live can end in SIGSEGV inside the driver's exit handler. A
|
||||
// device callback still running holds the wait up, one that waits for a lock the host holds around
|
||||
// this call for the whole 5 s; past them the library keeps the GPU device for the process, and
|
||||
// logs a warning saying what held it. A device created after it runs on a new GPU device. The host
|
||||
// unmaps BAR 2 from the guest first. Calls back: the window table's destroy, on the calling
|
||||
// thread unless a window callback is running then, and the device table's where this call drops
|
||||
// the last of its closures, as it does for a table with no functions; no other callback.
|
||||
// Drops the host's reference; the last one closes the window, waiting for nothing, and ends the
|
||||
// device's threads without waiting for them: the callbacks' destroy runs once both have ended,
|
||||
// possibly after this returns, and the region stays mapped until then and until the window's
|
||||
// GPU work has let it go. The release of the process's last graphics device then waits, at most
|
||||
// 5 s, for its threads, its objects and their GPU work to let go of the GPU device, and lets go
|
||||
// of every GPU device the library keeps for the process, so that none is live as the process
|
||||
// exits: on NVIDIA's driver an exit with one live can end in SIGSEGV inside the driver's exit
|
||||
// handler. A device callback still running holds the wait up, one that waits for a lock the host
|
||||
// holds around this call for the whole 5 s; past them the library keeps the GPU device for the
|
||||
// process, and logs a warning saying what held it. A device created after it runs on a new GPU
|
||||
// device. The host unmaps BAR 2 from the guest first. Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is NULL or a live graphics device handle, not used again.
|
||||
@@ -832,15 +779,10 @@ bool rvg_quiesce_for_exit(uint64_t timeout_ms);
|
||||
// Writes the library's degradation counts on stderr now, as a device's reset and the process's
|
||||
// exit do: `reims-vgpu: degradation counts: <code> <n>, ...`, every kind counted since the process
|
||||
// began, where any was and where the line changed since the library last wrote it, then the log's
|
||||
// count of its repeated lines. Then two lines only the ask writes: the library's build,
|
||||
// `reims-vgpu: build <commit> on metal2vulkan <commit>`, and, where the ask before this one was 2
|
||||
// to 60 s earlier, the pacing line of the span between the two: presents a second, the GPU's time
|
||||
// a frame and the CPU time of the guest's vCPU threads, of the library's by role and of the rest
|
||||
// of the process (docs/conventions.md). For a host asked for them while its guest runs, so that a
|
||||
// log read then has them: QEMU calls it for its device's `x-write-counts` property, which
|
||||
// `reims-ctl report` sets twice, 10 s apart. It takes no handle: the counts are the process's. It
|
||||
// reads each of the process's threads' CPU time, and waits for no thread of the library's. Calls
|
||||
// back: never.
|
||||
// count of its repeated lines. For a host asked for them while its guest runs, so that a log read
|
||||
// then has them: QEMU calls it for its device's `x-write-counts` property, which `reims-ctl
|
||||
// report` sets. It takes no handle: the counts are the process's. It waits for no thread of the
|
||||
// library's. Calls back: never.
|
||||
void rvg_write_counts(void);
|
||||
|
||||
// The device's region: its first byte, page-aligned, and, through `size` where it is not NULL,
|
||||
@@ -863,8 +805,7 @@ uint32_t rvg_graphics_device_mmio_read(RvgGraphicsDevice *device, uint64_t offse
|
||||
// A 32-bit write of BAR 0 at `offset`, below RVG_GRAPHICS_MSIX_OFFSET: STATUS, and DOORBELL
|
||||
// where the host's ioeventfd did not take the write; other offsets are ignored. A write of 0 to
|
||||
// STATUS resets the device, and waits for the command the device is taking, which waits for
|
||||
// nothing of the host's, and then for the GPU work committed before it, as
|
||||
// rvg_graphics_device_reset does.
|
||||
// nothing of the host's.
|
||||
//
|
||||
// A write to RVG_GRAPHICS_REG_DOORBELL of a command queue's ring (any value but
|
||||
// RVG_GRAPHICS_DOORBELL_CONTROL) wakes the queue's thread, and may answer the queue's next
|
||||
@@ -881,10 +822,7 @@ uint32_t rvg_graphics_device_mmio_read(RvgGraphicsDevice *device, uint64_t offse
|
||||
// already and the control thread sleeps with every earlier message carried out (each lock
|
||||
// tried, nothing allocated); else the control thread takes it. What the guest sees is the same
|
||||
// either way but for when the event comes. On any thread, the vCPU's included. Calls back:
|
||||
// raise_interrupt, as above; and on the calling thread route_doorbell and route_doorbell_page,
|
||||
// dropping the routes of the queues a STATUS write of 0 ends, and route_doorbell_page,
|
||||
// dropping the routes on a doorbell page a DOORBELL_PAGE_BIND write binds to another
|
||||
// context (docs/api.md section 5).
|
||||
// raise_interrupt, as above.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
@@ -916,7 +854,7 @@ void rvg_graphics_device_doorbell_write(RvgGraphicsDevice *device, uint64_t offs
|
||||
// Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is NULL or a live graphics device handle.
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_set_doorbell(RvgGraphicsDevice *device, int32_t fd);
|
||||
#endif
|
||||
|
||||
@@ -930,31 +868,16 @@ RvgStatus rvg_graphics_device_set_doorbell(RvgGraphicsDevice *device, int32_t fd
|
||||
// already. Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is NULL or a live graphics device handle.
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_set_doorbell(RvgGraphicsDevice *device, void *event);
|
||||
#endif
|
||||
|
||||
// The guest's bus reset: as a write of 0 to STATUS, the device is as one just made. It takes no
|
||||
// command until the guest writes 1, its rings are as new, the display keeps its scanout but has no
|
||||
// cursor image or VBLANK, its panel is on, and the device drops every object the guest's processes
|
||||
// made, on its control thread before it takes the guest's next command. Waits for the command the
|
||||
// device is taking, and for a take of a queue's ring or a post onto one under way. Then it waits,
|
||||
// within 30 s, for each walk of a queue's command buffer begun before it to end, its work
|
||||
// committed, and until every command buffer committed to the host's GPU before it has completed
|
||||
// and run its completed handlers, so none of the guest's work from before the reset writes the
|
||||
// guest's memory after this returns, as a GPU's reset stops its DMA: while that work completes,
|
||||
// each command buffer within 30 s of the one before, and 10 min at most in all. Of the device's
|
||||
// threads it waits only for those walks, which call back only raise_interrupt, and within 30 s
|
||||
// for the locks of the library's it takes. Waiting 2 s on for the GPU, it writes a line on stderr
|
||||
// that it waits, and one once it is done (docs/api.md, "The reset's lines"). A walk still running
|
||||
// after 30 s, a GPU that completes none of that work for 30 s or runs it past 10 min, or such a
|
||||
// lock still held after 30 s, is one no driver recovered, and the process ends there. Called
|
||||
// inside raise_interrupt, it is the one reset that waits for none of that work,
|
||||
// which may then write the guest's memory after it returns: the raise's thread may hold those
|
||||
// locks, and the work it raises for began before the reset and ends only once this returns. QEMU's
|
||||
// raise_interrupt never resets the device. Calls back: route_doorbell and route_doorbell_page, on
|
||||
// the calling thread, dropping the routes of the queues it ends (docs/api.md section 5); no other
|
||||
// callback.
|
||||
// command until the guest writes 1, its rings are as new, the display keeps its scanout but has
|
||||
// no cursor image or VBLANK, its panel is on, and the device drops every object the guest's
|
||||
// processes made, on its control thread before it takes the guest's next command. Waits for the
|
||||
// command the device is taking, and for a take of a queue's ring or a post onto one under way.
|
||||
// Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
@@ -976,8 +899,8 @@ void rvg_graphics_device_reset(RvgGraphicsDevice *device);
|
||||
// and the mode is only asked. One read runs at a time. On any thread. Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is NULL or a live graphics device handle; `dst` is NULL or holds `dst_length`
|
||||
// writable bytes; `width` and `height` are each NULL or writable.
|
||||
// `device` is a live graphics device handle; `dst` is NULL or holds `dst_length` writable bytes;
|
||||
// `width` and `height` are each NULL or writable.
|
||||
RvgStatus rvg_graphics_device_read_display(RvgGraphicsDevice *device,
|
||||
uint8_t *dst,
|
||||
size_t dst_length,
|
||||
@@ -1000,8 +923,8 @@ RvgDisplayCoord rvg_graphics_device_cursor_position(const RvgGraphicsDevice *dev
|
||||
// Reads of one display run one at a time. On any thread. Calls back: never.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is NULL or a live graphics device handle; `dst` is NULL or holds `dst_length`
|
||||
// writable bytes; `width` and `height` are each NULL or writable.
|
||||
// `device` is a live graphics device handle; `dst` is NULL or holds `dst_length` writable bytes;
|
||||
// `width` and `height` are each NULL or writable.
|
||||
RvgStatus rvg_graphics_device_read_display_at(RvgGraphicsDevice *device,
|
||||
uint32_t display,
|
||||
uint8_t *dst,
|
||||
@@ -1019,6 +942,45 @@ RvgStatus rvg_graphics_device_read_display_at(RvgGraphicsDevice *device,
|
||||
RvgDisplayCoord rvg_graphics_device_cursor_position_at(const RvgGraphicsDevice *device,
|
||||
uint32_t display);
|
||||
|
||||
// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
|
||||
// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
|
||||
// and waits for GPU idle.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_quiesce(RvgGraphicsDevice *device);
|
||||
|
||||
// Resumes VBLANK and ring threads after a snapshot finishes or fails.
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle.
|
||||
RvgStatus rvg_graphics_device_unquiesce(RvgGraphicsDevice *device);
|
||||
|
||||
// Serializes the full graphics device state into a heap-allocated buffer owned by the caller
|
||||
// and released with [`rvg_graphics_snapshot_free`].
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers.
|
||||
RvgStatus rvg_graphics_device_snapshot_save(RvgGraphicsDevice *device,
|
||||
uint8_t **out_data,
|
||||
size_t *out_len);
|
||||
|
||||
// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`].
|
||||
//
|
||||
// # Safety
|
||||
// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not
|
||||
// be freed more than once.
|
||||
void rvg_graphics_snapshot_free(uint8_t *data, size_t len);
|
||||
|
||||
// Restores the full graphics device state from a snapshot buffer produced by
|
||||
// [`rvg_graphics_device_snapshot_save`].
|
||||
//
|
||||
// # Safety
|
||||
// `device` is a live graphics device handle; `data` points to `len` readable bytes.
|
||||
RvgStatus rvg_graphics_device_snapshot_load(RvgGraphicsDevice *device,
|
||||
const uint8_t *data,
|
||||
size_t len);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif // __cplusplus
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
//! The library's build stamp, which the crate's build script reads at each build (`build.rs`) and
|
||||
//! the library's first call hands on (`crate::ffi::export`, `reims_vgpu_vulkan::stamp`): the
|
||||
//! commit the tree is at, `git rev-parse HEAD`, with `-dirty` where a tracked file of the tree
|
||||
//! differs from it or git cannot say, and `unknown` for a build outside a checkout (no git, or no
|
||||
//! commit), which never fails the build. Left aside as the tree is compared: submodules,
|
||||
//! `crates/reims-ctl` (a workspace of its own, linking nothing of the library), and `Cargo.lock`,
|
||||
//! which is committed without metal2vulkan's git `source` lines and which every build writes them
|
||||
//! back into. A diagnostic: nothing decides on it.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// The stamp of a tree whose `git rev-parse HEAD` answered `head` and whose status
|
||||
/// ([`STATUS`]) answered `status`, each `None` where git failed (the module doc).
|
||||
pub fn stamp(head: Option<&str>, status: Option<&str>) -> String {
|
||||
let Some(head) = head.map(str::trim).filter(|h| !h.is_empty()) else {
|
||||
return "unknown".to_owned();
|
||||
};
|
||||
match status {
|
||||
Some(status) if status.trim().is_empty() => head.to_owned(),
|
||||
_ => format!("{head}-dirty"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The status the stamp reads: the tracked files that differ from HEAD, but those the module doc
|
||||
/// leaves aside.
|
||||
pub const STATUS: [&str; 8] = [
|
||||
"status",
|
||||
"--porcelain",
|
||||
"--untracked-files=no",
|
||||
"--ignore-submodules",
|
||||
"--",
|
||||
".",
|
||||
":(exclude)crates/reims-ctl",
|
||||
":(exclude)Cargo.lock",
|
||||
];
|
||||
|
||||
/// What `git -C <dir> <args>` writes on its stdout, where it runs and succeeds.
|
||||
pub fn git(dir: &Path, args: &[&str]) -> Option<String> {
|
||||
let out = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(dir)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
out.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// The stamp of the tree at `root`, read from git.
|
||||
pub fn read(root: &Path) -> String {
|
||||
let head = git(root, &["rev-parse", "HEAD"]);
|
||||
let status = head.as_ref().and_then(|_| git(root, &STATUS));
|
||||
stamp(head.as_deref(), status.as_deref())
|
||||
}
|
||||
|
||||
/// The files of the checkout at `root` whose change moves HEAD or the index: its HEAD and index,
|
||||
/// the branch's ref HEAD names, and the packed refs, those that exist (Cargo runs a build script
|
||||
/// again at every build for a path that does not).
|
||||
pub fn git_files(root: &Path) -> Vec<PathBuf> {
|
||||
let dir = |args: &[&str]| git(root, args).map(|d| PathBuf::from(d.trim()));
|
||||
let mut files = Vec::new();
|
||||
if let Some(own) = dir(&["rev-parse", "--absolute-git-dir"]) {
|
||||
files.push(own.join("HEAD"));
|
||||
files.push(own.join("index"));
|
||||
}
|
||||
if let Some(common) = dir(&["rev-parse", "--path-format=absolute", "--git-common-dir"]) {
|
||||
if let Some(branch) = git(root, &["symbolic-ref", "-q", "HEAD"]) {
|
||||
files.push(common.join(branch.trim()));
|
||||
}
|
||||
files.push(common.join("packed-refs"));
|
||||
}
|
||||
files.retain(|f| f.exists());
|
||||
files
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const HEAD: &str = "41f0bba449c1e1f1b2e5d3c4a5b6c7d8e9f00112";
|
||||
|
||||
/// A clean tree's stamp is its commit.
|
||||
#[test]
|
||||
fn a_clean_tree_is_stamped_with_its_commit() {
|
||||
assert_eq!(stamp(Some(&format!("{HEAD}\n")), Some("")), HEAD);
|
||||
}
|
||||
|
||||
/// A tree with a tracked file changed, or whose status git could not give, is marked dirty.
|
||||
#[test]
|
||||
fn a_changed_tree_is_stamped_dirty() {
|
||||
let dirty = format!("{HEAD}-dirty");
|
||||
assert_eq!(
|
||||
stamp(Some(HEAD), Some(" M crates/reims-vgpu/src/graphics.rs\n")),
|
||||
dirty
|
||||
);
|
||||
assert_eq!(stamp(Some(HEAD), None), dirty);
|
||||
}
|
||||
|
||||
/// A build outside a checkout, where git answers no commit, is stamped unknown.
|
||||
#[test]
|
||||
fn a_build_outside_a_checkout_is_unknown() {
|
||||
assert_eq!(stamp(None, None), "unknown");
|
||||
assert_eq!(stamp(Some("\n"), Some("")), "unknown");
|
||||
let nowhere = std::env::temp_dir().join("reims-vgpu-c-no-checkout-here");
|
||||
assert_eq!(git(&nowhere, &["rev-parse", "HEAD"]), None);
|
||||
assert_eq!(read(&nowhere), "unknown");
|
||||
assert!(git_files(&nowhere).is_empty());
|
||||
}
|
||||
|
||||
/// The build stamped the library with this checkout's commit, the one the tests run at.
|
||||
#[test]
|
||||
fn the_library_carries_its_build_s_stamp() {
|
||||
let built = env!("RVG_BUILD_STAMP");
|
||||
// Read at run time, so the test names no worktree (docs/development.md).
|
||||
let manifest = std::env::var_os("CARGO_MANIFEST_DIR").unwrap();
|
||||
let root = Path::new(&manifest).join("../..");
|
||||
match git(&root, &["rev-parse", "HEAD"]) {
|
||||
Some(head) => assert!(built.starts_with(head.trim()), "{built} {head}"),
|
||||
None => assert_eq!(built, "unknown"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,8 @@
|
||||
//! and [`host_call`] around every call of a host function.
|
||||
//!
|
||||
//! **Into the library.** Every `rvg_` function is `extern "C"`: nothing unwinds out of it into
|
||||
//! the host. Its body runs inside [`export`], which first installs the library's panic hook, hands
|
||||
//! on the library's build stamp (`build.rs`, `reims_vgpu_vulkan::stamp`), and then marks the
|
||||
//! thread as the library's for the call, so a panic anywhere under an export ends
|
||||
//! the host. Its body runs inside [`export`], which first installs the library's panic hook and
|
||||
//! then marks the thread as the library's for the call, so a panic anywhere under an export ends
|
||||
//! the process in the hook, before any frame unwinds and before any drop runs (architecture 6.5).
|
||||
//! The `extern "C"` frame is only the backstop: an unwind that reached it would end the process
|
||||
//! too, but only after the frames in between had run their drops, a table's `destroy(ctx)` among
|
||||
@@ -30,8 +29,6 @@ pub(crate) fn export<R>(body: impl FnOnce() -> R) -> R {
|
||||
if !std::thread::panicking() {
|
||||
reims_vgpu::singleton::install_panic_hook();
|
||||
}
|
||||
// The commit the library was built from, which its log lines name (`build.rs`).
|
||||
reims_vgpu_vulkan::stamp::set_commit(env!("RVG_BUILD_STAMP"));
|
||||
let _ours = enter_ours();
|
||||
body()
|
||||
}
|
||||
|
||||
@@ -126,10 +126,6 @@ fn a_panic_in_a_callback_of_the_first_export_ends_in_the_hook() {
|
||||
display_windows: std::ptr::null(),
|
||||
pool_physical_address: 0,
|
||||
pool_physical_length: 0,
|
||||
pool_host_memory: 0,
|
||||
headless_mode_width: 0,
|
||||
headless_mode_height: 0,
|
||||
headless_modes: std::ptr::null(),
|
||||
};
|
||||
// SAFETY: a live config; a NULL out-pointer, which the create refuses.
|
||||
let _ =
|
||||
|
||||
+217
-176
@@ -124,36 +124,21 @@ const _: () = {
|
||||
/// (`reims-vgpu.graphics-queue-<id>`) or one of its lane's threads, which walk and commit its
|
||||
/// command buffers (`reims-vgpu.graphics-lane-<id>`), a pipeline compile's thread
|
||||
/// (`reims-vgpu.graphics-compile-<n>`), a thread that makes IOSurfaces' and pages blocks' views
|
||||
/// (`reims-vgpu.graphics-surfaces-<i>`, and `reims-vgpu.graphics-views-<i>` for a pages block's
|
||||
/// view made after its answer), a thread that makes indirect command buffers
|
||||
/// (`reims-vgpu.graphics-surfaces-<i>`), a thread that makes indirect command buffers
|
||||
/// (`reims-vgpu.icb-create-<i>`), a thread that lets go of a closed process's objects and answers
|
||||
/// its close (`reims-vgpu.graphics-closes-<i>`), a thread that moves a staged copy of a surface's
|
||||
/// device cache into its pages and answers what waited for it
|
||||
/// (`reims-vgpu.graphics-into-pages-<i>`), the thread that paces releases' copies of their
|
||||
/// surfaces' device caches into their pages, which answers a BLOCK_RELEASE as its turn comes
|
||||
/// (`reims-vgpu.graphics-release-pace`), the thread that tries again the EVENT_SIGNALLED to a
|
||||
/// shared event's other holders that their rings had no room for
|
||||
/// (`reims-vgpu.graphics-shared-events`), a take worker of the guest's Shared pool or of its
|
||||
/// Private blocks, which answers a POOL_TAKE or a PRIVATE_TAKE
|
||||
/// (`reims-vgpu.graphics-pool-take`, `reims-vgpu.graphics-private-take`), the windows' UI thread,
|
||||
/// which tells the guest of the host's pointer and scrolling (POINTER_OVER, POINTER_MOTION and
|
||||
/// SCROLL; on macOS the process's main thread, on Linux and Windows `reims-vgpu.ui`), a video
|
||||
/// session's picture landing thread, which posts a decode's completion as the decode is done
|
||||
/// (`reims-vgpu.graphics-video-land`), or the platform's thread that runs a command buffer's
|
||||
/// scheduled or completed handler; or the host's own, inside
|
||||
/// rvg_graphics_device_mmio_write_taking or rvg_graphics_device_doorbell_write.
|
||||
/// (`reims-vgpu.graphics-into-pages-<i>`), a video session's picture landing thread, which posts
|
||||
/// a decode's completion as the decode is done (`reims-vgpu.graphics-video-land`), or the
|
||||
/// platform's thread that runs a command buffer's scheduled or completed handler; or the host's
|
||||
/// own, inside rvg_graphics_device_mmio_write_taking.
|
||||
/// Never inside another call of the host's into the library. The library may hold locks of its
|
||||
/// own around it (docs/api.md section 5 names them), but none that a function it may call waits
|
||||
/// for, directly or through a thread of the library's, so it may call them at once. It may wait
|
||||
/// for a lock the host holds while it calls the device (QEMU's BQL), but not for one the host
|
||||
/// holds while it calls rvg_graphics_device_mmio_write_taking or
|
||||
/// rvg_graphics_device_doorbell_write, nor, on any thread, for one the host holds around
|
||||
/// rvg_graphics_device_reset or a write of 0 to STATUS: those wait for the platform's completed
|
||||
/// handlers while the GPU work before them completes, and at most 30 s for locks of the library's
|
||||
/// it may hold around this (docs/api.md section 5). May call: rvg_status_message and the
|
||||
/// rvg_graphics_device_* functions, except the release of its own device; a reset called here waits
|
||||
/// for none of the GPU work committed before it (rvg_graphics_device_reset). Without it the guest
|
||||
/// gets no interrupt.
|
||||
/// holds while it calls rvg_graphics_device_mmio_write_taking. May call: rvg_status_message and
|
||||
/// the rvg_graphics_device_* functions, except the release of its own device. Without it the
|
||||
/// guest gets no interrupt.
|
||||
pub type RvgGraphicsRaiseFn = Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, vector: u32)>;
|
||||
|
||||
/// `route_doorbell(ctx, route, ring_id, bell)`: with `bell` 0 or more, route a command queue's
|
||||
@@ -230,9 +215,7 @@ pub type RvgGraphicsRouteDoorbellPageFn = Option<
|
||||
/// Thread: the device's pool thread (`reims-vgpu.graphics-pool`), never inside a call of the
|
||||
/// host's, with no lock of the library's held. It must not wait for a lock the host holds while
|
||||
/// it calls the device (QEMU's BQL): QEMU queues the add for its main loop. One piece at a time,
|
||||
/// in the order the device places them, each before its pool_remove. Not called once
|
||||
/// rvg_graphics_device_release has closed the pool, at its start; a call the pool thread began
|
||||
/// before that may still be running, and the release waits for it. May call: nothing of the
|
||||
/// in the order the device places them, each before its pool_remove. May call: nothing of the
|
||||
/// library's. Needed with a pool.
|
||||
pub type RvgGraphicsPoolAddFn = Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
@@ -254,9 +237,8 @@ pub type RvgGraphicsPoolAddFn = Option<
|
||||
/// block back, never inside a call of the host's, with no lock of the library's held. It must not
|
||||
/// wait for a lock the host holds while it calls the device (QEMU queues the remove for its main
|
||||
/// loop). Once a piece, after its pool_add. Not called once rvg_graphics_device_release has
|
||||
/// closed the pool, at its start; a call the pool thread began before that may still be running,
|
||||
/// and the release waits for it. The host removes every piece it added before it releases the
|
||||
/// device. May call: nothing of the library's. Needed with a pool.
|
||||
/// begun: the host removes every piece it added before it releases the device. May call: nothing
|
||||
/// of the library's. Needed with a pool.
|
||||
pub type RvgGraphicsPoolRemoveFn =
|
||||
Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, physical_address: u64, length: u64)>;
|
||||
|
||||
@@ -343,14 +325,13 @@ pub struct RvgGraphicsDeviceConfig {
|
||||
pub struct_size: u32,
|
||||
/// NULL is a table with every callback absent.
|
||||
pub callbacks: *const RvgGraphicsCallbacks,
|
||||
/// NULL is no window: the display offers its headless mode (`headless_modes`, else
|
||||
/// `headless_mode_width` x `headless_mode_height`) at 60 Hz and shows nothing. Otherwise the
|
||||
/// library opens a window for the display, with its input as the window's callbacks, sized
|
||||
/// for its mode (1920 x 1080 where it has none). The window keeps its size: the display
|
||||
/// offers the guest one mode, the window's size in pixels at the refresh rate of the host
|
||||
/// screen it opens on, and tells the guest when the person resizes it. The guest's scanout is
|
||||
/// blitted out of the region into the window's drawables on the GPU at each of the display's
|
||||
/// refreshes, at the screen's rate, while the display shows no presented surface.
|
||||
/// NULL is no window: the display offers 1920 x 1080 at 60 Hz and shows nothing. Otherwise
|
||||
/// the library opens a window for the display, with its input as the window's callbacks,
|
||||
/// sized for its mode (1920 x 1080 where it has none). The window keeps its size: the
|
||||
/// display offers the guest one mode, the window's size in pixels at the refresh rate of the
|
||||
/// host screen it opens on, and tells the guest when the person resizes it. The guest's
|
||||
/// scanout is blitted out of the region into the window's drawables on the GPU at each of the
|
||||
/// display's refreshes, at the screen's rate, while the display shows no presented surface.
|
||||
pub window: *const RvgWindowConfig,
|
||||
/// The guest's RAM, or NULL. With it, where the host's page is the guest's 4 KiB, or 16 KiB
|
||||
/// for a guest that lays its pages out in 16 KiB (`RGFX_FEATURE_PAGES_16K`), the GPU uses an
|
||||
@@ -360,8 +341,7 @@ pub struct RvgGraphicsDeviceConfig {
|
||||
/// down to 16 KiB, or the host GPU's answer where that is less; with no map, and on a GPU of
|
||||
/// its own memory, the host GPU's. The map's pages stay the guest's RAM, mapped, until the
|
||||
/// process exits (`RvgMemoryRange`): a host that discards guest RAM (a balloon, virtio-mem,
|
||||
/// hot-unplug) passes NULL. Its ranges may not overlap: a map whose ranges overlap, or one
|
||||
/// of whose ranges runs past the address space, is refused (RVG_ERR_INVALID_ARGUMENT).
|
||||
/// hot-unplug) passes NULL. Its ranges may not overlap.
|
||||
pub memory_map: *const RvgMemoryMap,
|
||||
/// With `memory_map`: the files behind its ranges, NULL for none, one entry per range, each
|
||||
/// duplicated during the create. Refused (RVG_ERR_INVALID_ARGUMENT), in this order: files
|
||||
@@ -425,34 +405,6 @@ pub struct RvgGraphicsDeviceConfig {
|
||||
pub pool_physical_address: u64,
|
||||
/// The range's length in bytes, the most the pool may take: 0 for none.
|
||||
pub pool_physical_length: u64,
|
||||
/// A fact of the host's, which it finds by asking its hypervisor and sets from nothing else:
|
||||
/// 1 where the hypervisor takes no cacheable mapping of the GPU's own memory as guest memory,
|
||||
/// as QEMU finds under Linux's KVM on arm64 where the VM does not answer
|
||||
/// KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED (KVM then refuses a cacheable VM_PFNMAP mapping as a
|
||||
/// memory slot); 0 where it takes one, every other host, and a host built before this field.
|
||||
/// At 1 each of the pool's blocks is ordinary memory of the library's own (on Linux a memfd
|
||||
/// it maps shared) that the GPU imports as a dma-buf, which pool_add then maps; at 0 the
|
||||
/// GPU's own memory. Nothing without a pool. Refused (RVG_ERR_INVALID_ARGUMENT): any other
|
||||
/// value, and 1 on a platform that makes no such blocks (macOS and Windows); refused
|
||||
/// (RVG_ERR_HOST_RESOURCES): 1 where the GPU refuses host memory as a dma-buf (NVIDIA's
|
||||
/// driver, or a Linux host without udmabuf), which the create finds by importing one block.
|
||||
pub pool_host_memory: u32,
|
||||
/// Where `window` is NULL, the mode each display offers the guest first, in pixels, as a
|
||||
/// window config's `mode_width` gives the mode its window opens for: its width rounded down
|
||||
/// to a multiple of 16 and its height to even, at 60 Hz (no host screen shows the display,
|
||||
/// so none sets its rate), sized to each display's scanout room on a device of several. 0 in
|
||||
/// either is 1920 x 1080, as a host built before this field, whose `struct_size` ends before
|
||||
/// it, has. Unread where `window` is given: the window's size is then the mode.
|
||||
pub headless_mode_width: u16,
|
||||
/// As `headless_mode_width`.
|
||||
pub headless_mode_height: u16,
|
||||
/// Where `window` is NULL, each display's own first mode, in place of `headless_mode_width`
|
||||
/// x `headless_mode_height` for every display: an array of `display_count` sizes (one where
|
||||
/// it is 0), display i's at i, its `x` the width and `y` the height, each taken as
|
||||
/// `headless_mode_width` and `headless_mode_height` are (a 0 in either is 1920 x 1080). NULL
|
||||
/// is those two for every display, as a host built before this field, whose `struct_size`
|
||||
/// ends before it, has. Unread where `window` is given.
|
||||
pub headless_modes: *const RvgDisplayCoord,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; pointers and u32s.
|
||||
@@ -491,9 +443,8 @@ unsafe fn live<'a>(device: *const RvgGraphicsDevice, call: &'static str) -> &'a
|
||||
/// tables, before any table is the library's: a struct_size refusal runs no destroy, and a later
|
||||
/// refusal runs each, the windows' first, display 0's first. Refusals: RVG_ERR_INVALID_ARGUMENT,
|
||||
/// RVG_ERR_UNSUPPORTED, RVG_ERR_HOST_RESOURCES (the host refused the region's memory, a pipe or
|
||||
/// a thread, or has no GPU device the library can use: none, or one its driver refused; or
|
||||
/// the GPU refused the pool's host memory, `pool_host_memory`). Calls back: never, but a
|
||||
/// refusal's destroys.
|
||||
/// a thread, or has no GPU device the library can use: none, or one its driver refused). Calls
|
||||
/// back: never, but a refusal's destroys.
|
||||
///
|
||||
/// # Safety
|
||||
/// `config` is NULL or a live config; `device` is NULL or writable.
|
||||
@@ -602,17 +553,6 @@ unsafe fn create(
|
||||
1 => true,
|
||||
_ => return refuse(RVG_ERR_INVALID_ARGUMENT),
|
||||
};
|
||||
let pool_host_memory = match c.pool_host_memory {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => return refuse(RVG_ERR_INVALID_ARGUMENT),
|
||||
};
|
||||
// Each display's own headless mode, one for each of the `count` displays checked above.
|
||||
let headless_modes = (window.is_none() && !c.headless_modes.is_null()).then(|| {
|
||||
// SAFETY: the config's contract: `display_count` readable sizes, one where it is 0.
|
||||
let modes = unsafe { std::slice::from_raw_parts(c.headless_modes, count as usize) };
|
||||
modes.iter().map(|m| (m.x, m.y)).collect()
|
||||
});
|
||||
// SAFETY: the config's contract: NULL or a live map, and NULL or its files.
|
||||
let memory_map = match unsafe { memory_map(c.memory_map, c.memory_files) } {
|
||||
Ok(m) => m,
|
||||
@@ -686,9 +626,6 @@ unsafe fn create(
|
||||
guest_arch,
|
||||
doorbell_pages,
|
||||
pool,
|
||||
pool_host_memory,
|
||||
headless_mode: Some((c.headless_mode_width, c.headless_mode_height)),
|
||||
headless_modes,
|
||||
};
|
||||
match GraphicsDevice::with_platform(<Plat as reims_vgpu::ApiPlatform>::process(), config) {
|
||||
Ok(d) => {
|
||||
@@ -736,7 +673,7 @@ fn pool_remove(table: &Arc<Table>, f: RvgGraphicsPoolRemoveFn) -> Option<PoolRem
|
||||
/// host's lock (QEMU's BQL) held or not: waits for nothing. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle.
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_pool_added(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
@@ -744,7 +681,11 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_added(
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { pool_call(device, |d| d.pool_added(physical_address)) }
|
||||
unsafe {
|
||||
pool_call(device, "rvg_graphics_device_pool_added", |d| {
|
||||
d.pool_added(physical_address)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -756,7 +697,7 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_added(
|
||||
/// Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle.
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_pool_removed(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
@@ -764,7 +705,11 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_removed(
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { pool_call(device, |d| d.pool_removed(physical_address)) }
|
||||
unsafe {
|
||||
pool_call(device, "rvg_graphics_device_pool_removed", |d| {
|
||||
d.pool_removed(physical_address)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -776,7 +721,7 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_removed(
|
||||
/// for nothing. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle.
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_pool_grow(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
@@ -784,7 +729,11 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_grow(
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { pool_call(device, |d| d.pool_grow(length)) }
|
||||
unsafe {
|
||||
pool_call(device, "rvg_graphics_device_pool_grow", |d| {
|
||||
d.pool_grow(length)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -816,39 +765,34 @@ pub unsafe extern "C" fn rvg_graphics_device_pool_range(
|
||||
}
|
||||
|
||||
/// The body of the pool's functions inside their `ffi::export`: `call` on the device, its answer
|
||||
/// as a status; RVG_ERR_INVALID_ARGUMENT for a NULL `device`, as for every function that answers
|
||||
/// a status.
|
||||
/// as a status.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle.
|
||||
/// `device` is a live graphics device handle.
|
||||
unsafe fn pool_call(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
name: &'static str,
|
||||
call: impl FnOnce(&GraphicsDevice<Plat>) -> Result<(), reims_vgpu::Error>,
|
||||
) -> RvgStatus {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(d) = (unsafe { handle::get(device) }) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
let d = unsafe { live(device, name) };
|
||||
match call(&d.device) {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the host's reference; the last one closes the device's pool first, waiting for a pool_add
|
||||
/// or pool_remove the pool's thread began, then closes the window, waiting for nothing, and ends
|
||||
/// the device's threads without waiting for them: the callbacks' destroy runs once both have ended,
|
||||
/// possibly after this returns, and the region stays mapped until then and until the window's GPU
|
||||
/// work has let it go. The release of the process's last graphics device then waits, at most 5 s,
|
||||
/// for its threads, its objects and their GPU work to let go of the GPU device, and lets go of
|
||||
/// every GPU device the library keeps for the process, so that none is live as the process exits:
|
||||
/// on NVIDIA's driver an exit with one live can end in SIGSEGV inside the driver's exit handler. A
|
||||
/// device callback still running holds the wait up, one that waits for a lock the host holds around
|
||||
/// this call for the whole 5 s; past them the library keeps the GPU device for the process, and
|
||||
/// logs a warning saying what held it. A device created after it runs on a new GPU device. The host
|
||||
/// unmaps BAR 2 from the guest first. Calls back: the window table's destroy, on the calling
|
||||
/// thread unless a window callback is running then, and the device table's where this call drops
|
||||
/// the last of its closures, as it does for a table with no functions; no other callback.
|
||||
/// Drops the host's reference; the last one closes the window, waiting for nothing, and ends the
|
||||
/// device's threads without waiting for them: the callbacks' destroy runs once both have ended,
|
||||
/// possibly after this returns, and the region stays mapped until then and until the window's
|
||||
/// GPU work has let it go. The release of the process's last graphics device then waits, at most
|
||||
/// 5 s, for its threads, its objects and their GPU work to let go of the GPU device, and lets go
|
||||
/// of every GPU device the library keeps for the process, so that none is live as the process
|
||||
/// exits: on NVIDIA's driver an exit with one live can end in SIGSEGV inside the driver's exit
|
||||
/// handler. A device callback still running holds the wait up, one that waits for a lock the host
|
||||
/// holds around this call for the whole 5 s; past them the library keeps the GPU device for the
|
||||
/// process, and logs a warning saying what held it. A device created after it runs on a new GPU
|
||||
/// device. The host unmaps BAR 2 from the guest first. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle, not used again.
|
||||
@@ -858,11 +802,8 @@ pub unsafe extern "C" fn rvg_graphics_device_release(device: *mut RvgGraphicsDev
|
||||
if device.is_null() {
|
||||
return;
|
||||
}
|
||||
// A block's release that a display hold let go of here answers is posted, and raised
|
||||
// for, by the device's control thread: the device's release calls nothing of the host's
|
||||
// back.
|
||||
// SAFETY: the caller's contract.
|
||||
reims_vgpu_graphics::raise_elsewhere(|| unsafe { handle::release(device) });
|
||||
unsafe { handle::release(device) };
|
||||
// Where that ended the process's last device, the GPU devices go: the Rust API decides
|
||||
// and logs (`GraphicsDevice::let_go_of_gpu`).
|
||||
let _ = GraphicsDevice::<Plat>::let_go_of_gpu(reims_vgpu::LET_GO_BOUND);
|
||||
@@ -899,15 +840,10 @@ pub extern "C" fn rvg_quiesce_for_exit(timeout_ms: u64) -> bool {
|
||||
/// Writes the library's degradation counts on stderr now, as a device's reset and the process's
|
||||
/// exit do: `reims-vgpu: degradation counts: <code> <n>, ...`, every kind counted since the process
|
||||
/// began, where any was and where the line changed since the library last wrote it, then the log's
|
||||
/// count of its repeated lines. Then two lines only the ask writes: the library's build,
|
||||
/// `reims-vgpu: build <commit> on metal2vulkan <commit>`, and, where the ask before this one was 2
|
||||
/// to 60 s earlier, the pacing line of the span between the two: presents a second, the GPU's time
|
||||
/// a frame and the CPU time of the guest's vCPU threads, of the library's by role and of the rest
|
||||
/// of the process (docs/conventions.md). For a host asked for them while its guest runs, so that a
|
||||
/// log read then has them: QEMU calls it for its device's `x-write-counts` property, which
|
||||
/// `reims-ctl report` sets twice, 10 s apart. It takes no handle: the counts are the process's. It
|
||||
/// reads each of the process's threads' CPU time, and waits for no thread of the library's. Calls
|
||||
/// back: never.
|
||||
/// count of its repeated lines. For a host asked for them while its guest runs, so that a log read
|
||||
/// then has them: QEMU calls it for its device's `x-write-counts` property, which `reims-ctl
|
||||
/// report` sets. It takes no handle: the counts are the process's. It waits for no thread of the
|
||||
/// library's. Calls back: never.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn rvg_write_counts() {
|
||||
ffi::export(|| {
|
||||
@@ -958,8 +894,7 @@ pub unsafe extern "C" fn rvg_graphics_device_mmio_read(
|
||||
/// A 32-bit write of BAR 0 at `offset`, below RVG_GRAPHICS_MSIX_OFFSET: STATUS, and DOORBELL
|
||||
/// where the host's ioeventfd did not take the write; other offsets are ignored. A write of 0 to
|
||||
/// STATUS resets the device, and waits for the command the device is taking, which waits for
|
||||
/// nothing of the host's, and then for the GPU work committed before it, as
|
||||
/// rvg_graphics_device_reset does.
|
||||
/// nothing of the host's.
|
||||
///
|
||||
/// A write to RVG_GRAPHICS_REG_DOORBELL of a command queue's ring (any value but
|
||||
/// RVG_GRAPHICS_DOORBELL_CONTROL) wakes the queue's thread, and may answer the queue's next
|
||||
@@ -976,10 +911,7 @@ pub unsafe extern "C" fn rvg_graphics_device_mmio_read(
|
||||
/// already and the control thread sleeps with every earlier message carried out (each lock
|
||||
/// tried, nothing allocated); else the control thread takes it. What the guest sees is the same
|
||||
/// either way but for when the event comes. On any thread, the vCPU's included. Calls back:
|
||||
/// raise_interrupt, as above; and on the calling thread route_doorbell and route_doorbell_page,
|
||||
/// dropping the routes of the queues a STATUS write of 0 ends, and route_doorbell_page,
|
||||
/// dropping the routes on a doorbell page a DOORBELL_PAGE_BIND write binds to another
|
||||
/// context (docs/api.md section 5).
|
||||
/// raise_interrupt, as above.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
@@ -1032,7 +964,7 @@ pub unsafe extern "C" fn rvg_graphics_device_doorbell_write(
|
||||
/// Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle.
|
||||
/// `device` is a live graphics device handle.
|
||||
#[cfg(not(windows))]
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_set_doorbell(
|
||||
@@ -1054,7 +986,7 @@ pub unsafe extern "C" fn rvg_graphics_device_set_doorbell(
|
||||
/// already. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle.
|
||||
/// `device` is a live graphics device handle.
|
||||
#[cfg(windows)]
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_set_doorbell(
|
||||
@@ -1068,16 +1000,13 @@ pub unsafe extern "C" fn rvg_graphics_device_set_doorbell(
|
||||
}
|
||||
|
||||
/// The body of `rvg_graphics_device_set_doorbell` on each OS, inside its `ffi::export`:
|
||||
/// `doorbell` is its `fd`, or on Windows its `event`; RVG_ERR_INVALID_ARGUMENT for a NULL
|
||||
/// `device`, as for every function that answers a status.
|
||||
/// `doorbell` is its `fd`, or on Windows its `event`.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle.
|
||||
/// `device` is a live graphics device handle.
|
||||
unsafe fn set_doorbell(device: *mut RvgGraphicsDevice, doorbell: RawDoorbell) -> RvgStatus {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(d) = (unsafe { handle::get(device) }) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
let d = unsafe { live(device, "rvg_graphics_device_set_doorbell") };
|
||||
if d.device.set_doorbell(doorbell) {
|
||||
RVG_OK
|
||||
} else {
|
||||
@@ -1086,26 +1015,11 @@ unsafe fn set_doorbell(device: *mut RvgGraphicsDevice, doorbell: RawDoorbell) ->
|
||||
}
|
||||
|
||||
/// The guest's bus reset: as a write of 0 to STATUS, the device is as one just made. It takes no
|
||||
/// command until the guest writes 1, its rings are as new, the display keeps its scanout but has no
|
||||
/// cursor image or VBLANK, its panel is on, and the device drops every object the guest's processes
|
||||
/// made, on its control thread before it takes the guest's next command. Waits for the command the
|
||||
/// device is taking, and for a take of a queue's ring or a post onto one under way. Then it waits,
|
||||
/// within 30 s, for each walk of a queue's command buffer begun before it to end, its work
|
||||
/// committed, and until every command buffer committed to the host's GPU before it has completed
|
||||
/// and run its completed handlers, so none of the guest's work from before the reset writes the
|
||||
/// guest's memory after this returns, as a GPU's reset stops its DMA: while that work completes,
|
||||
/// each command buffer within 30 s of the one before, and 10 min at most in all. Of the device's
|
||||
/// threads it waits only for those walks, which call back only raise_interrupt, and within 30 s
|
||||
/// for the locks of the library's it takes. Waiting 2 s on for the GPU, it writes a line on stderr
|
||||
/// that it waits, and one once it is done (docs/api.md, "The reset's lines"). A walk still running
|
||||
/// after 30 s, a GPU that completes none of that work for 30 s or runs it past 10 min, or such a
|
||||
/// lock still held after 30 s, is one no driver recovered, and the process ends there. Called
|
||||
/// inside raise_interrupt, it is the one reset that waits for none of that work,
|
||||
/// which may then write the guest's memory after it returns: the raise's thread may hold those
|
||||
/// locks, and the work it raises for began before the reset and ends only once this returns. QEMU's
|
||||
/// raise_interrupt never resets the device. Calls back: route_doorbell and route_doorbell_page, on
|
||||
/// the calling thread, dropping the routes of the queues it ends (docs/api.md section 5); no other
|
||||
/// callback.
|
||||
/// command until the guest writes 1, its rings are as new, the display keeps its scanout but has
|
||||
/// no cursor image or VBLANK, its panel is on, and the device drops every object the guest's
|
||||
/// processes made, on its control thread before it takes the guest's next command. Waits for the
|
||||
/// command the device is taking, and for a take of a queue's ring or a post onto one under way.
|
||||
/// Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
@@ -1135,8 +1049,8 @@ pub unsafe extern "C" fn rvg_graphics_device_reset(device: *mut RvgGraphicsDevic
|
||||
/// and the mode is only asked. One read runs at a time. On any thread. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle; `dst` is NULL or holds `dst_length`
|
||||
/// writable bytes; `width` and `height` are each NULL or writable.
|
||||
/// `device` is a live graphics device handle; `dst` is NULL or holds `dst_length` writable bytes;
|
||||
/// `width` and `height` are each NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_read_display(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
@@ -1147,7 +1061,15 @@ pub unsafe extern "C" fn rvg_graphics_device_read_display(
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { read_display(device, 0, (dst, dst_length), (width, height)) }
|
||||
unsafe {
|
||||
read_display(
|
||||
"rvg_graphics_device_read_display",
|
||||
device,
|
||||
0,
|
||||
(dst, dst_length),
|
||||
(width, height),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1178,8 +1100,8 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position(
|
||||
/// Reads of one display run one at a time. On any thread. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live graphics device handle; `dst` is NULL or holds `dst_length`
|
||||
/// writable bytes; `width` and `height` are each NULL or writable.
|
||||
/// `device` is a live graphics device handle; `dst` is NULL or holds `dst_length` writable bytes;
|
||||
/// `width` and `height` are each NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_read_display_at(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
@@ -1191,33 +1113,33 @@ pub unsafe extern "C" fn rvg_graphics_device_read_display_at(
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { read_display(device, display, (dst, dst_length), (width, height)) }
|
||||
unsafe {
|
||||
read_display(
|
||||
"rvg_graphics_device_read_display_at",
|
||||
device,
|
||||
display,
|
||||
(dst, dst_length),
|
||||
(width, height),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The body of `rvg_graphics_device_read_display` and `rvg_graphics_device_read_display_at`,
|
||||
/// inside their `ffi::export`: display `display` into `dst` and its length, its size out through
|
||||
/// `size`'s width and height. For a NULL `device`, RVG_ERR_INVALID_ARGUMENT, as for every
|
||||
/// function that answers a status, with nothing written to `dst` and a size of 0 by 0, as for a
|
||||
/// display past the device's count.
|
||||
/// The body of `rvg_graphics_device_read_display` and `rvg_graphics_device_read_display_at`
|
||||
/// (`call`), inside their `ffi::export`: display `display` into `dst` and its length, its size
|
||||
/// out through `size`'s width and height.
|
||||
///
|
||||
/// # Safety
|
||||
/// As rvg_graphics_device_read_display_at's.
|
||||
unsafe fn read_display(
|
||||
call: &'static str,
|
||||
device: *mut RvgGraphicsDevice,
|
||||
display: u32,
|
||||
(dst, dst_length): (*mut u8, usize),
|
||||
(width, height): (*mut u32, *mut u32),
|
||||
) -> RvgStatus {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(d) = (unsafe { handle::get(device) }) else {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe {
|
||||
handle::write_out(width, 0);
|
||||
handle::write_out(height, 0);
|
||||
}
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
let d = unsafe { live(device, call) };
|
||||
let mut none: [u8; 0] = [];
|
||||
let dst: &mut [u8] = if dst.is_null() {
|
||||
&mut none
|
||||
@@ -1258,5 +1180,124 @@ pub unsafe extern "C" fn rvg_graphics_device_cursor_position_at(
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/// Quiesces the graphics device prior to VM RAM & state snapshotting: pauses VBLANK/rings,
|
||||
/// drains pending compiles/workers, flushes dirty device-cached IOSurfaces back to Guest RAM,
|
||||
/// and waits for GPU idle.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_quiesce(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, "rvg_graphics_device_quiesce") };
|
||||
match d.device.quiesce() {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Resumes VBLANK and ring threads after a snapshot finishes or fails.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_unquiesce(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, "rvg_graphics_device_unquiesce") };
|
||||
d.device.unquiesce();
|
||||
RVG_OK
|
||||
})
|
||||
}
|
||||
|
||||
/// Serializes the full graphics device state into a heap-allocated buffer owned by the caller
|
||||
/// and released with [`rvg_graphics_snapshot_free`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle; `out_data` and `out_len` are valid non-null pointers.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_snapshot_save(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
out_data: *mut *mut u8,
|
||||
out_len: *mut usize,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
if out_data.is_null() || out_len.is_null() {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, "rvg_graphics_device_snapshot_save") };
|
||||
match d.device.snapshot_save() {
|
||||
Ok(bytes) => {
|
||||
let mut boxed = bytes.into_boxed_slice();
|
||||
let len = boxed.len();
|
||||
let ptr = boxed.as_mut_ptr();
|
||||
std::mem::forget(boxed);
|
||||
// SAFETY: non-null checked above.
|
||||
unsafe {
|
||||
*out_data = ptr;
|
||||
*out_len = len;
|
||||
}
|
||||
RVG_OK
|
||||
}
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Frees a snapshot buffer returned by [`rvg_graphics_device_snapshot_save`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `data` and `len` must come from a single [`rvg_graphics_device_snapshot_save`] call and not
|
||||
/// be freed more than once.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_snapshot_free(data: *mut u8, len: usize) {
|
||||
ffi::export(|| {
|
||||
if !data.is_null() {
|
||||
// SAFETY: matches Box::<[u8]>::into_raw layout above.
|
||||
unsafe {
|
||||
let _ = Box::from_raw(std::ptr::slice_from_raw_parts_mut(data, len));
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Restores the full graphics device state from a snapshot buffer produced by
|
||||
/// [`rvg_graphics_device_snapshot_save`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live graphics device handle; `data` points to `len` readable bytes.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_graphics_device_snapshot_load(
|
||||
device: *mut RvgGraphicsDevice,
|
||||
data: *const u8,
|
||||
len: usize,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
if data.is_null() && len > 0 {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(device, "rvg_graphics_device_snapshot_load") };
|
||||
let slice = if len == 0 {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: caller's contract.
|
||||
unsafe { std::slice::from_raw_parts(data, len) }
|
||||
};
|
||||
match d.device.snapshot_load(slice) {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -43,10 +43,6 @@ fn config(callbacks: &RvgGraphicsCallbacks) -> RvgGraphicsDeviceConfig {
|
||||
display_windows: std::ptr::null(),
|
||||
pool_physical_address: 0,
|
||||
pool_physical_length: 0,
|
||||
pool_host_memory: 0,
|
||||
headless_mode_width: 0,
|
||||
headless_mode_height: 0,
|
||||
headless_modes: std::ptr::null(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,44 +120,6 @@ fn a_headless_graphics_device_lives_and_ends() {
|
||||
|
||||
/// A config the library refuses for its size runs no destroy; NULL config and out-pointer are
|
||||
/// refused
|
||||
/// A NULL device is RVG_ERR_INVALID_ARGUMENT from every function that answers a status, as the
|
||||
/// header's preamble says (a function without a status ends the process instead,
|
||||
/// `c_harness_null_handle_aborts`): the pool's functions, the doorbell's, and the display reads,
|
||||
/// which write nothing to the destination and a size of 0 by 0
|
||||
#[test]
|
||||
fn a_null_device_is_an_invalid_argument_where_a_status_answers() {
|
||||
let d = std::ptr::null_mut();
|
||||
let (_, open, _kept) = doorbells();
|
||||
let mut dst = [0u8; 16];
|
||||
// SAFETY: a NULL device, which each takes, and a live destination, sizes and doorbell.
|
||||
unsafe {
|
||||
assert_eq!(
|
||||
rvg_graphics_device_pool_added(d, 0),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_graphics_device_pool_removed(d, 0),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_graphics_device_pool_grow(d, 1 << 21),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_graphics_device_set_doorbell(d, open),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
let (mut w, mut h) = (7, 7);
|
||||
let read = rvg_graphics_device_read_display(d, dst.as_mut_ptr(), dst.len(), &mut w, &mut h);
|
||||
assert_eq!((read, w, h), (RVG_ERR_INVALID_ARGUMENT, 0, 0));
|
||||
let (mut w, mut h) = (7, 7);
|
||||
let read =
|
||||
rvg_graphics_device_read_display_at(d, 1, dst.as_mut_ptr(), dst.len(), &mut w, &mut h);
|
||||
assert_eq!((read, w, h), (RVG_ERR_INVALID_ARGUMENT, 0, 0));
|
||||
}
|
||||
assert_eq!(dst, [0; 16]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_graphics_configs() {
|
||||
let cb = callbacks();
|
||||
@@ -188,14 +146,14 @@ fn refused_graphics_configs() {
|
||||
rvg_graphics_device_create(&c, &mut device),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
// A config 8 bytes longer than the library's, aligned as the config is, with a byte set
|
||||
// past the library's size.
|
||||
let ours = size_of::<RvgGraphicsDeviceConfig>();
|
||||
let mut big = [0u64; size_of::<RvgGraphicsDeviceConfig>() / 8 + 1];
|
||||
let bytes = big.as_mut_ptr().cast::<u8>();
|
||||
std::ptr::copy_nonoverlapping(std::ptr::from_ref(&config(&cb)).cast::<u8>(), bytes, ours);
|
||||
bytes.cast::<u32>().write(u32::try_from(ours + 8).unwrap());
|
||||
bytes.add(ours).write(1);
|
||||
let mut big = [0u8; 96];
|
||||
std::ptr::copy_nonoverlapping(
|
||||
std::ptr::from_ref(&config(&cb)).cast::<u8>(),
|
||||
big.as_mut_ptr(),
|
||||
size_of::<RvgGraphicsDeviceConfig>(),
|
||||
);
|
||||
big[0] = 96;
|
||||
big[88] = 1;
|
||||
assert_eq!(
|
||||
rvg_graphics_device_create(big.as_ptr().cast(), &mut device),
|
||||
RVG_ERR_UNSUPPORTED
|
||||
@@ -406,71 +364,6 @@ fn the_display_count_makes_the_displays() {
|
||||
assert_eq!(reads[1], past);
|
||||
}
|
||||
|
||||
/// A device with no window offers its config's headless mode, its width rounded down to a
|
||||
/// multiple of 16 and its height to even, as each display's read answers it, a share of the
|
||||
/// scanout's room on a device of several; 0 in either is 1920 x 1080, as it is for a config whose
|
||||
/// `struct_size` ends before the fields
|
||||
#[test]
|
||||
fn a_headless_device_offers_the_configs_headless_mode() {
|
||||
let cb = RvgGraphicsCallbacks {
|
||||
destroy: None,
|
||||
..callbacks()
|
||||
};
|
||||
let mut c = config(&cb);
|
||||
let read = |c: &RvgGraphicsDeviceConfig| displays_of(c).1[0];
|
||||
for ((w, h), size) in [
|
||||
((2560, 1441), (2560, 1440)),
|
||||
((1366, 768), (1360, 768)),
|
||||
((3840, 0), (1920, 1080)),
|
||||
((0, 0), (1920, 1080)),
|
||||
] {
|
||||
(c.headless_mode_width, c.headless_mode_height) = (w, h);
|
||||
assert_eq!(
|
||||
read(&c),
|
||||
(RVG_ERR_INVALID_ARGUMENT, size.0, size.1),
|
||||
"{w}x{h}"
|
||||
);
|
||||
}
|
||||
// Two displays share the room, each offered the same mode where it fits.
|
||||
(c.headless_mode_width, c.headless_mode_height) = (2560, 1440);
|
||||
c.display_count = 2;
|
||||
let (_, reads, _) = displays_of(&c);
|
||||
assert_eq!(reads[0], reads[1]);
|
||||
// A host built before the fields offers 1920 x 1080 whatever lies past its size.
|
||||
c.display_count = 0;
|
||||
c.struct_size = std::mem::offset_of!(RvgGraphicsDeviceConfig, headless_mode_width) as u32;
|
||||
assert_eq!(read(&c), (RVG_ERR_INVALID_ARGUMENT, 1920, 1080));
|
||||
}
|
||||
|
||||
/// Each display of a device without a window offers its own of the config's `headless_modes`, in
|
||||
/// place of `headless_mode_width` x `headless_mode_height` for every display; NULL keeps those
|
||||
/// for every display, as a config whose `struct_size` ends before the field does whatever lies
|
||||
/// past its size
|
||||
#[test]
|
||||
fn each_headless_display_offers_its_own_of_the_configs_modes() {
|
||||
let cb = RvgGraphicsCallbacks {
|
||||
destroy: None,
|
||||
..callbacks()
|
||||
};
|
||||
let mut c = config(&cb);
|
||||
(c.headless_mode_width, c.headless_mode_height) = (2560, 1440);
|
||||
c.display_count = 2;
|
||||
let one = displays_of(&c).1;
|
||||
let modes = [
|
||||
RvgDisplayCoord { x: 1920, y: 1080 },
|
||||
RvgDisplayCoord { x: 1366, y: 768 },
|
||||
];
|
||||
c.headless_modes = modes.as_ptr();
|
||||
let reads = displays_of(&c).1;
|
||||
assert_eq!(reads[0], (RVG_ERR_INVALID_ARGUMENT, 1920, 1080));
|
||||
assert_eq!(reads[1], (RVG_ERR_INVALID_ARGUMENT, 1360, 768));
|
||||
c.struct_size = std::mem::offset_of!(RvgGraphicsDeviceConfig, headless_modes) as u32;
|
||||
assert_eq!(displays_of(&c).1, one);
|
||||
// Past that size the field is not read: not even a pointer no array of sizes can start at.
|
||||
c.headless_modes = std::ptr::without_provenance(1);
|
||||
assert_eq!(displays_of(&c).1, one);
|
||||
}
|
||||
|
||||
/// A display count past `RVG_GRAPHICS_DISPLAYS_MAX`, and display windows not given exactly where
|
||||
/// display 0's window is, are refused once the tables are the library's, running their destroys
|
||||
#[test]
|
||||
@@ -671,51 +564,6 @@ unsafe extern "C-unwind" fn pool_remove(_ctx: *mut c_void, physical_address: u64
|
||||
POOL_ASKS.lock().push((false, physical_address, length));
|
||||
}
|
||||
|
||||
/// A host says its hypervisor takes no cacheable mapping of the GPU's own memory as guest memory
|
||||
/// with `pool_host_memory` 1, and says nothing with 0, as a config whose `struct_size` ends before
|
||||
/// the field does, whatever lies past it; any other value is refused. On the testkit's platform,
|
||||
/// whose pool's blocks are the process's own memory, host memory already, a device with a pool
|
||||
/// takes either, on every OS, the pool then answering its range; on the rt platform, which of the
|
||||
/// pool's blocks the word picks is `reims_vgpu`'s (`graphics::pool_source`).
|
||||
#[test]
|
||||
fn a_pool_s_host_memory_blocks_are_the_host_s_ask() {
|
||||
const BASE: u64 = 52 << 30;
|
||||
let with_pool = RvgGraphicsCallbacks {
|
||||
pool_add: Some(pool_add),
|
||||
pool_remove: Some(pool_remove),
|
||||
destroy: None,
|
||||
..callbacks()
|
||||
};
|
||||
let config = |host_memory: u32, struct_size: usize| RvgGraphicsDeviceConfig {
|
||||
struct_size: struct_size as u32,
|
||||
pool_physical_address: BASE,
|
||||
pool_physical_length: 2 << 20,
|
||||
pool_host_memory: host_memory,
|
||||
..config(&with_pool)
|
||||
};
|
||||
let whole = size_of::<RvgGraphicsDeviceConfig>();
|
||||
let before = std::mem::offset_of!(RvgGraphicsDeviceConfig, pool_host_memory);
|
||||
let made = |host_memory, size| {
|
||||
let c = config(host_memory, size);
|
||||
let mut device = std::ptr::null_mut();
|
||||
// SAFETY: a live config and out-pointer; then a live device, released.
|
||||
unsafe {
|
||||
let status = rvg_graphics_device_create(&c, &mut device);
|
||||
if status == RVG_OK {
|
||||
let mut length = 0;
|
||||
assert_eq!(rvg_graphics_device_pool_range(device, &mut length), BASE);
|
||||
assert_eq!(length, 2 << 20);
|
||||
rvg_graphics_device_release(device);
|
||||
}
|
||||
status
|
||||
}
|
||||
};
|
||||
assert_eq!(made(0, whole), RVG_OK);
|
||||
assert_eq!(made(7, before), RVG_OK, "a size before the field: 0");
|
||||
assert_eq!(made(2, whole), RVG_ERR_INVALID_ARGUMENT);
|
||||
assert_eq!(made(1, whole), RVG_OK);
|
||||
}
|
||||
|
||||
/// A pool needs both of its callbacks and a range of whole 2 MiB; a device without one refuses
|
||||
/// the pool's calls and answers no range; a device with one takes as much of the range as the
|
||||
/// GPU's memory heaps hold, in whole 2 MiB, at most all of it, grows on the host's ask, on its
|
||||
@@ -839,9 +687,8 @@ fn a_quiesce_ahead_of_the_exit_with_nothing_to_stop_answers_true() {
|
||||
}
|
||||
|
||||
/// The write of the counts takes no handle and writes the process's degradation counts on stderr
|
||||
/// before it returns, again only where they changed since, and the library's build line at each
|
||||
/// write; and the pacing line at a write from 2 to 60 s after the one before it, over the span
|
||||
/// between the two, none sooner: in a child, since the counts are the process's
|
||||
/// before it returns, again only where they changed since: in a child, since the counts are the
|
||||
/// process's
|
||||
#[test]
|
||||
fn a_write_of_the_counts_writes_their_line_before_it_returns() {
|
||||
const CODE: &str = "test-c-api-write-counts";
|
||||
@@ -855,9 +702,6 @@ fn a_write_of_the_counts_writes_their_line_before_it_returns() {
|
||||
reims_vgpu_vulkan::answer::count_kind(CODE);
|
||||
rvg_write_counts();
|
||||
eprintln!("third write returned");
|
||||
std::thread::sleep(std::time::Duration::from_millis(2_100));
|
||||
rvg_write_counts();
|
||||
eprintln!("fourth write returned");
|
||||
return;
|
||||
}
|
||||
let test = "graphics::tests::a_write_of_the_counts_writes_their_line_before_it_returns";
|
||||
@@ -875,27 +719,9 @@ fn a_write_of_the_counts_writes_their_line_before_it_returns() {
|
||||
assert!(
|
||||
matches!(
|
||||
seen[..],
|
||||
[one, "first write returned", "second write returned", two, "third write returned",
|
||||
"fourth write returned"]
|
||||
[one, "first write returned", "second write returned", two, "third write returned"]
|
||||
if counted(one, 1) && counted(two, 2)
|
||||
),
|
||||
"{stderr}"
|
||||
);
|
||||
let builds = (stderr.lines())
|
||||
.filter(|l| l.starts_with("reims-vgpu: build "))
|
||||
.count();
|
||||
assert_eq!(builds, 4, "{stderr}");
|
||||
let pacing: Vec<&str> = (stderr.lines())
|
||||
.filter(|l| l.starts_with("reims-vgpu: pacing") || l.ends_with("returned"))
|
||||
.collect();
|
||||
assert!(
|
||||
matches!(
|
||||
pacing[..],
|
||||
[.., "third write returned", line, "fourth write returned"]
|
||||
if line.starts_with("reims-vgpu: pacing over 2.")
|
||||
&& line.contains(" s: presents 0.0/s; gpu ")
|
||||
&& line.contains("; cpu vcpu 0% (no threads), ours ")
|
||||
),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
@@ -30,8 +30,6 @@ pub mod window;
|
||||
|
||||
pub mod graphics;
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_stamp;
|
||||
mod ffi;
|
||||
mod handle;
|
||||
mod sized;
|
||||
|
||||
@@ -34,8 +34,7 @@ pub const RVG_ERR_GPU: u32 = 4;
|
||||
|
||||
/// The host refused the memory, a pipe, a thread or the GPU device the call needs: the graphics
|
||||
/// device's region, its threads, or its GPU device, where the host has none the library can use
|
||||
/// or its driver refused it, or the pool's host memory, which the GPU refused
|
||||
/// (rvg_graphics_device_create).
|
||||
/// or its driver refused it (rvg_graphics_device_create).
|
||||
pub const RVG_ERR_HOST_RESOURCES: u32 = 5;
|
||||
|
||||
/// The status of a Rust API error.
|
||||
|
||||
@@ -138,7 +138,7 @@ static void check_graphics(void) {
|
||||
NULL,
|
||||
NULL};
|
||||
RvgGraphicsDeviceConfig c = {
|
||||
sizeof c, &cb, NULL, NULL, NULL, RVG_GUEST_ARCH_X86_64, 2, 0, NULL, 0, 0, 0, 0, 0, NULL};
|
||||
sizeof c, &cb, NULL, NULL, NULL, RVG_GUEST_ARCH_X86_64, 2, 0, NULL, 0, 0};
|
||||
RvgGraphicsDevice *d = NULL;
|
||||
graphics_destroyed = 0;
|
||||
graphics_raised = 0;
|
||||
@@ -241,6 +241,11 @@ static void check_graphics(void) {
|
||||
CHECK(wait_for(&graphics_moved, 2));
|
||||
at = rvg_graphics_device_cursor_position(d);
|
||||
CHECK(at.x == 0 && at.y == 0);
|
||||
CHECK_STATUS(rvg_graphics_device_quiesce(d), RVG_OK);
|
||||
CHECK_STATUS(rvg_graphics_device_snapshot_save(d, NULL, NULL), RVG_ERR_INVALID_ARGUMENT);
|
||||
CHECK_STATUS(rvg_graphics_device_snapshot_load(d, NULL, 1), RVG_ERR_INVALID_ARGUMENT);
|
||||
rvg_graphics_snapshot_free(NULL, 0);
|
||||
CHECK_STATUS(rvg_graphics_device_unquiesce(d), RVG_OK);
|
||||
rvg_graphics_device_release(d);
|
||||
#if defined(_WIN32)
|
||||
CloseHandle(bell);
|
||||
@@ -265,7 +270,7 @@ static void check_displays(void) {
|
||||
cb.ctx = &displays_destroyed;
|
||||
cb.destroy = on_graphics_destroy;
|
||||
RvgGraphicsDeviceConfig c = {
|
||||
sizeof c, &cb, NULL, NULL, NULL, RVG_GUEST_ARCH_X86_64, 0, 2, NULL, 0, 0, 0, 0, 0, NULL};
|
||||
sizeof c, &cb, NULL, NULL, NULL, RVG_GUEST_ARCH_X86_64, 0, 2, NULL, 0, 0};
|
||||
RvgGraphicsDevice *d = NULL;
|
||||
displays_destroyed = 0;
|
||||
CHECK_STATUS(rvg_graphics_device_create(&c, &d), RVG_OK);
|
||||
@@ -404,7 +409,7 @@ static void check_memory_files(void) {
|
||||
cb.ctx = &files_destroyed;
|
||||
cb.destroy = on_graphics_destroy;
|
||||
RvgGraphicsDeviceConfig c = {
|
||||
sizeof c, &cb, NULL, &map, &file, RVG_GUEST_ARCH_X86_64, 0, 0, NULL, 0, 0, 0, 0, 0, NULL};
|
||||
sizeof c, &cb, NULL, &map, &file, RVG_GUEST_ARCH_X86_64, 0, 0, NULL, 0, 0};
|
||||
files_destroyed = 0;
|
||||
RvgGraphicsDevice *d = NULL;
|
||||
CHECK_STATUS(rvg_graphics_device_create(&c, &d), RVG_OK);
|
||||
|
||||
@@ -242,7 +242,7 @@ fn c_harness_calls_every_function() {
|
||||
// A function with a form of each OS's (Windows's under `#if defined(_WIN32)`, the others'
|
||||
// under `#if !defined(_WIN32)`) is declared once per form, one after the other.
|
||||
declared.dedup();
|
||||
assert_eq!(declared.len(), 19, "{declared:?}");
|
||||
assert_eq!(declared.len(), 24, "{declared:?}");
|
||||
let missing: Vec<&str> = declared
|
||||
.iter()
|
||||
.copied()
|
||||
|
||||
@@ -145,7 +145,6 @@ include = [
|
||||
"RgfxHeapOverHostMemory",
|
||||
"RgfxHeapOverPages",
|
||||
"RgfxHeapTextureSizeAndAlign",
|
||||
"RgfxHiddenPlaces",
|
||||
"RgfxIcbBuffer",
|
||||
"RgfxIcbBufferStride",
|
||||
"RgfxIcbCreate",
|
||||
@@ -287,7 +286,6 @@ include = [
|
||||
"RgfxPipelineAnswersQuery",
|
||||
"RgfxPipelineLibrary",
|
||||
"RgfxPipelineReflection",
|
||||
"RgfxPointerLook",
|
||||
"RgfxPointerMotion",
|
||||
"RgfxPointerOver",
|
||||
"RgfxPoolBlock",
|
||||
@@ -336,16 +334,10 @@ include = [
|
||||
"RgfxSharedEventSetValue",
|
||||
"RgfxSharedEventUnname",
|
||||
"RgfxSharedEventValue",
|
||||
"RgfxSharedTexture",
|
||||
"RgfxSharedTextureCreate",
|
||||
"RgfxSharedTextureImport",
|
||||
"RgfxSharedTextureName",
|
||||
"RgfxSharedTextureUnname",
|
||||
"RgfxSizeAndAlign",
|
||||
"RgfxStencilDescriptor",
|
||||
"RgfxSurfaceDownload",
|
||||
"RgfxSurfaceFacts",
|
||||
"RgfxSurfaceHoldLowered",
|
||||
"RgfxSurfaceOrderWait",
|
||||
"RgfxSurfacePages",
|
||||
"RgfxSurfacePagesCache",
|
||||
|
||||
@@ -1835,159 +1835,13 @@
|
||||
// `POOL_LENGTH_HI`, RO: as [`RGFX_REG_POOL_LENGTH_LO`], its high 32 bits.
|
||||
#define RGFX_REG_POOL_LENGTH_HI 80
|
||||
|
||||
// `GUEST_BUNDLE`, WO: what the guest's accelerator found of its Metal bundle as WindowServer
|
||||
// opened the display, once a boot, so the host can tell its user why a desktop runs without
|
||||
// Metal: in bits 0 to 7 an `RGFX_GUEST_BUNDLE_*` (ours, another version's, none, or RgfxGate's
|
||||
// install still under way), in bits 8 to 15 the wire version another version's bundle's marker
|
||||
// names (0 where it names none the kext knows), in bits 16 to 23 RgfxGate's install pass, an
|
||||
// `RGFX_GATE_*`, and in bits 24 to 31 the error its failed write gave (`errno`, 0 for none). It
|
||||
// reads 0. A host that does not know it ignores the write, as at any offset it does not know, and
|
||||
// the guest acts on nothing of it, so it needs no feature: a kext built before it never writes
|
||||
// it, and a host then says nothing of the bundle.
|
||||
#define RGFX_REG_GUEST_BUNDLE 84
|
||||
|
||||
// `FEATURES_EXT`, RO: feature bits 64 to 95 the host offers. The guest uses each with no take,
|
||||
// but those [`RGFX_REG_DRIVER_FEATURES_EXT`] takes ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]): a guest
|
||||
// that sees one of the others may send the messages it names, and the host carries out nothing
|
||||
// else for a guest that does, so a guest that never reads it gets the wire it had before. It
|
||||
// reads [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`] and [`RGFX_FEATURE_EXT_SURFACE_HOLD`] where the
|
||||
// host offers them; 0 from a host older than it, as at any offset a host does not know. A write
|
||||
// is ignored. Bit 1 is offered by no host: hosts built before the hold word left the block's
|
||||
// header offered `SURFACE_HOLD` there, with the word in the header, and kexts built before it
|
||||
// take it; a write of it takes nothing, so such a kext and this host, or this kext and such a
|
||||
// host, take no hold.
|
||||
#define RGFX_REG_FEATURES_EXT 88
|
||||
|
||||
// `DRIVER_FEATURES_EXT`, RW: the feature bits 64 to 95 the guest's driver took of those
|
||||
// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]). A write takes the
|
||||
// bits written that `FEATURES_EXT` offers and that are taken, and a read answers the bits taken.
|
||||
// As at `DRIVER_FEATURES_LO`, a write while `STATUS` reads [`RGFX_STATUS_DRIVER_READY`] is
|
||||
// ignored, and a reset clears it. A guest that never writes it (the option ROM, a kext built
|
||||
// before it) gets the wire it had before; a host older than it reads 0 there and ignores a
|
||||
// write, as at any offset it does not know.
|
||||
#define RGFX_REG_DRIVER_FEATURES_EXT 92
|
||||
|
||||
// `FEATURES_EXT` bit 0, feature bit 64, `SHARED_TEXTURE_NAMES`: ring 0 carries
|
||||
// [`RGFX_CMD_SHARED_TEXTURE_CREATE`], a process's texture another process may open
|
||||
// (`newSharedTextureWithDescriptor:`), and the messages the accelerator kext posts for its handle:
|
||||
// [`RGFX_CMD_SHARED_TEXTURE_NAME`], which names it device-wide, [`RGFX_CMD_SHARED_TEXTURE_IMPORT`],
|
||||
// by which another process's new texture is the same host texture, and
|
||||
// [`RGFX_CMD_SHARED_TEXTURE_UNNAME`]. Every host offers it.
|
||||
#define RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES (1 << 0)
|
||||
|
||||
// `FEATURES_EXT` bit 2, feature bit 66, `SURFACE_HOLD`, taken in
|
||||
// [`RGFX_REG_DRIVER_FEATURES_EXT`]. A host whose GPU's memory is its own (a device of one
|
||||
// memory) may make an image in place over guest pages it imports by their pointer by copying the
|
||||
// bytes under the image out and back around the image's first layout move, so a CPU write of
|
||||
// those bytes between the two copies is lost. Where the guest took it:
|
||||
// - **A cached surface's hold word.** The block of a surface with a device cache
|
||||
// ([`RGFX_SURFACE_PAGES_CACHED`]) holds a 32-bit word in its own part, which no process maps:
|
||||
// the first of the [`RGFX_SURFACE_HOLD_ROOM`] bytes right before its runs, at region offset
|
||||
// `runs_offset - RGFX_SURFACE_HOLD_ROOM`, which the kext stores 0 into as it caches the block.
|
||||
// So only the kext and the host write it. Before such a make over the block's pages the host
|
||||
// raises it ([`RGFX_SURFACE_HOLD_RAISED`]), and after a full fence reads the surface's CPU
|
||||
// generation in the block's header again: where it moved since the host decided on the make,
|
||||
// the host lowers the word and makes nothing in place. Once the bytes are back it stores 0
|
||||
// there. A block whose word would lie in its first [`RGFX_SURFACE_HOLD_ROOM`] bytes, where
|
||||
// its header lies (its runs less than twice that past its start), has none, and gets no image
|
||||
// made so over its pages. A read-write CPU lock stores the new generation, and after a full
|
||||
// fence reads the word: while it is raised, the lock sets [`RGFX_SURFACE_HOLD_WAITED`] beside
|
||||
// it and waits, looking again at the device's next vector or within 1 ms. So either the host
|
||||
// reads the lock's generation and makes nothing in place, or the lock goes on once the bytes
|
||||
// are back. A read-only lock waits for nothing.
|
||||
// - **Answered creates over pages.** A [`RGFX_CMD_TEXTURE_FROM_BUFFER`] or
|
||||
// [`RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER`] over a buffer a [`RGFX_CMD_BUFFER_OVER_PAGES`]
|
||||
// made (the host's refusal of it among them) is answered by an [`RGFX_EVT_COMPLETE`] of
|
||||
// [`RGFX_STATUS_OK`] once carried out, the texture made or refused, and the guest's create
|
||||
// waits for that answer, so the creating thread writes the buffer only after the make. Every
|
||||
// such create is answered: the host answers a pages block before it imports the block's
|
||||
// pages, and on Linux the import alone finds whether it goes by the pages' pointer, the kind
|
||||
// of import a make copies out and back.
|
||||
//
|
||||
// A guest that does not take it gets no image made so over a cached surface's pages, and no
|
||||
// answer. The host offers it where its GPU's memory is its own. The x86-64 and arm64e kexts
|
||||
// take it.
|
||||
#define RGFX_FEATURE_EXT_SURFACE_HOLD (1 << 2)
|
||||
|
||||
// The bytes of a cached surface's block right before its runs that hold its hold word
|
||||
// ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), a `u32` at their start: a page of the block's own part,
|
||||
// past the part its processes map, which no process maps.
|
||||
#define RGFX_SURFACE_HOLD_ROOM 4096
|
||||
|
||||
// The hold word's bit the host raises around a make that copies the pages' bytes out and back
|
||||
// ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]).
|
||||
#define RGFX_SURFACE_HOLD_RAISED (1 << 0)
|
||||
|
||||
// The hold word's bit a read-write CPU lock sets beside [`RGFX_SURFACE_HOLD_RAISED`] while it
|
||||
// waits ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), which the host counts.
|
||||
#define RGFX_SURFACE_HOLD_WAITED (1 << 1)
|
||||
|
||||
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the kext's own version's bundle is on disk,
|
||||
// and the accelerator registered for it.
|
||||
#define RGFX_GUEST_BUNDLE_OURS 1
|
||||
|
||||
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the bundle's executable is there without the
|
||||
// marker of the kext's version, so the accelerator stays unregistered for the boot.
|
||||
#define RGFX_GUEST_BUNDLE_OTHER_VERSION 2
|
||||
|
||||
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: no bundle's executable is there, so the
|
||||
// accelerator stays unregistered for the boot.
|
||||
#define RGFX_GUEST_BUNDLE_ABSENT 3
|
||||
|
||||
// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: RgfxGate's install pass had not ended, so the
|
||||
// accelerator stays unregistered for the boot.
|
||||
#define RGFX_GUEST_BUNDLE_GATE_BUSY 4
|
||||
|
||||
// Where a [`RGFX_REG_GUEST_BUNDLE`] value's other version starts: bits 8 to 15.
|
||||
#define RGFX_GUEST_BUNDLE_VERSION_SHIFT 8
|
||||
|
||||
// Where a [`RGFX_REG_GUEST_BUNDLE`] value's `RGFX_GATE_*` starts: bits 16 to 23.
|
||||
#define RGFX_GUEST_BUNDLE_GATE_SHIFT 16
|
||||
|
||||
// Where a [`RGFX_REG_GUEST_BUNDLE`] value's `errno` starts: bits 24 to 31.
|
||||
#define RGFX_GUEST_BUNDLE_ERRNO_SHIFT 24
|
||||
|
||||
// RgfxGate's install pass, as [`RGFX_REG_GUEST_BUNDLE`] gives it: no RgfxGate published one.
|
||||
#define RGFX_GATE_NONE 0
|
||||
|
||||
// RgfxGate's install pass: under way still.
|
||||
#define RGFX_GATE_RUNNING 1
|
||||
|
||||
// RgfxGate's install pass: ended without saying how, as an RgfxGate built before
|
||||
// `RgfxGateInstallResult` does.
|
||||
#define RGFX_GATE_UNTOLD 2
|
||||
|
||||
// RgfxGate's install pass: its own bundle was there already, written and tagged.
|
||||
#define RGFX_GATE_PRESENT 3
|
||||
|
||||
// RgfxGate's install pass: it wrote its own bundle and tagged it.
|
||||
#define RGFX_GATE_INSTALLED 4
|
||||
|
||||
// RgfxGate's install pass: its own bundle was there, and it tagged it.
|
||||
#define RGFX_GATE_TAGGED 5
|
||||
|
||||
// RgfxGate's install pass: a write or the rename of its bundle failed, with the `errno`.
|
||||
#define RGFX_GATE_FAILED 6
|
||||
|
||||
// RgfxGate's install pass: the Data volume did not mount while it waited, about 60 s.
|
||||
#define RGFX_GATE_NO_DATA_VOLUME 7
|
||||
|
||||
// RgfxGate's install pass: none, in the installer or Recovery.
|
||||
#define RGFX_GATE_SKIPPED 8
|
||||
|
||||
// RgfxGate's install pass: it could not start one (no thread, no VFS context, or on arm64 a
|
||||
// kernel whose vnode layout it does not know).
|
||||
#define RGFX_GATE_REFUSED 9
|
||||
|
||||
// What `MAGIC` reads: "RGFX", little-endian.
|
||||
#define RGFX_MAGIC 1481000786
|
||||
|
||||
// What `VERSION` reads: the wire's version, which every change a guest built before it would
|
||||
// misread moves on, a record's size among them: `include/reims_graphics_wire_sizes.h` pins each
|
||||
// record's size to it (docs/graphics-kext/design.md, "The wire's version"). The kext and the
|
||||
// option ROM leave a device of any other version, and the kext registers its accelerator only for
|
||||
// a bundle of its own.
|
||||
#define RGFX_VERSION 3
|
||||
// misread moves on (docs/graphics-kext/design.md, "The wire's version"). The kext and the option
|
||||
// ROM leave a device of any other version.
|
||||
#define RGFX_VERSION 2
|
||||
|
||||
// `STATUS`: the device is reset, and takes no message.
|
||||
#define RGFX_STATUS_RESET 0
|
||||
@@ -2178,10 +2032,6 @@
|
||||
// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
|
||||
#define RGFX_CMD_SCROLL_DEVICES 11
|
||||
|
||||
// Command `HIDDEN_PLACES` ([`RgfxHiddenPlaces`]), where the guest took
|
||||
// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
|
||||
#define RGFX_CMD_HIDDEN_PLACES 12
|
||||
|
||||
// Event `COMPLETE` ([`RgfxComplete`]): a command's answer, with its `seqno`.
|
||||
#define RGFX_EVT_COMPLETE 256
|
||||
|
||||
@@ -2209,12 +2059,6 @@
|
||||
// own devices scroll as far.
|
||||
#define RGFX_EVT_SCROLL 262
|
||||
|
||||
// Event `POINTER_LOOK` ([`RgfxPointerLook`]), sent only to a guest whose last `HIDDEN_PLACES`
|
||||
// since its last start ([`RGFX_CMD_HIDDEN_PLACES`]) said it reports them: the host's pointer
|
||||
// moved the guest's tablet while the guest hides its cursor, and the guest reports where its
|
||||
// hidden cursor goes.
|
||||
#define RGFX_EVT_POINTER_LOOK 263
|
||||
|
||||
// `COMPLETE`'s status: the command was done.
|
||||
#define RGFX_STATUS_OK 0
|
||||
|
||||
@@ -2625,48 +2469,6 @@
|
||||
// buffer lies there. Makes nothing.
|
||||
#define RGFX_CMD_PAGES_BUFFER_ADDRESS 573
|
||||
|
||||
// Command `SHARED_TEXTURE_CREATE` ([`RgfxSharedTextureCreate`]), where the host offers
|
||||
// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: a texture of shape `desc` that other processes may
|
||||
// open (`newSharedTextureWithDescriptor:`), with the guest-picked `resource_id`. The host makes
|
||||
// the texture's storage itself, at an address and a resource index of its own, which no context
|
||||
// holds, and the sender's texture `obj_id` over all of it at `resource_id`; each process that
|
||||
// opens it later has its own texture over the same storage at its own index
|
||||
// ([`RGFX_CMD_SHARED_TEXTURE_IMPORT`]). So the storage outlives the context that made it while
|
||||
// another process's texture or a name holds it, and no context's addresses or indices are held
|
||||
// past its close. Its storage mode is Private: a create of any other is refused. Not answered;
|
||||
// a create the host refuses stands for a refused object, as a `TEXTURE_CREATE`'s does.
|
||||
// `OBJECT_DESTROY` drops the sender's texture; the storage goes with its last texture and its
|
||||
// last name.
|
||||
#define RGFX_CMD_SHARED_TEXTURE_CREATE 574
|
||||
|
||||
// Command `SHARED_TEXTURE_NAME` ([`RgfxSharedTextureName`]), which the accelerator kext posts for
|
||||
// a process's handle of its shared texture `obj_id` (`newSharedTextureHandle`), where the host
|
||||
// offers [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: the texture's storage is named `name`
|
||||
// device-wide, so another process may open it ([`RGFX_CMD_SHARED_TEXTURE_IMPORT`]), until the kext
|
||||
// lets go of the name ([`RGFX_CMD_SHARED_TEXTURE_UNNAME`]). A name holds the storage as a texture
|
||||
// over it does. Answered by [`RGFX_EVT_COMPLETE`]: [`RGFX_STATUS_OK`], or
|
||||
// [`RGFX_STATUS_NOT_FOUND`] where the sender holds no shared texture of that id (one whose
|
||||
// create the host refused among them), and [`RGFX_STATUS_INVALID_ARGUMENT`] for a name of 0. The
|
||||
// kext builds the message: `name` is the kext's, never the process's.
|
||||
#define RGFX_CMD_SHARED_TEXTURE_NAME 575
|
||||
|
||||
// Command `SHARED_TEXTURE_IMPORT` ([`RgfxSharedTextureImport`]), which the accelerator kext posts
|
||||
// for a process that opens a handle another process's `SHARED_TEXTURE_NAME` named
|
||||
// (`newSharedTextureWithHandle:`), where the host offers
|
||||
// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: the process's new texture `obj_id` lies over all of
|
||||
// the storage `name` names, in the shape it was made in, at the guest-picked `resource_id`.
|
||||
// Answered by [`RGFX_EVT_SHARED_TEXTURE`] with the shape, which the process's texture answers,
|
||||
// or [`RGFX_STATUS_NOT_FOUND`] where the name was let go of or never given, and
|
||||
// [`RGFX_STATUS_INVALID_ARGUMENT`] for another context's id or a resource index the sender does
|
||||
// not hold; nothing is made then. `OBJECT_DESTROY` drops it, as any texture.
|
||||
#define RGFX_CMD_SHARED_TEXTURE_IMPORT 576
|
||||
|
||||
// Command `SHARED_TEXTURE_UNNAME` ([`RgfxSharedTextureUnname`]), which the accelerator kext posts
|
||||
// once nothing but the kext holds the handle a `SHARED_TEXTURE_NAME` named, where the host offers
|
||||
// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: no process can open the name from then on, and the
|
||||
// storage goes once no texture lies over it. Context 0's, which no process is. Not answered.
|
||||
#define RGFX_CMD_SHARED_TEXTURE_UNNAME 577
|
||||
|
||||
// `CONTEXT_CLOSE` ([`RgfxContextClose`]), on ring 0 from the accelerator kext: the process that
|
||||
// held context `context` closed the device or died. The host ends the context's command queues
|
||||
// and drops every object whose id lies in its range ([`RGFX_CONTEXT_OBJ_ID_SHIFT`]), then answers
|
||||
@@ -3036,18 +2838,6 @@
|
||||
// `gpu_address` and `length`; otherwise each 0.
|
||||
#define RGFX_EVT_PRIVATE_BLOCK 1041
|
||||
|
||||
// Event `SHARED_TEXTURE` ([`RgfxSharedTexture`], on the control completion ring), with a
|
||||
// [`RGFX_CMD_SHARED_TEXTURE_IMPORT`]'s `seqno`: its answer. `status` [`RGFX_STATUS_OK`] with the
|
||||
// shape the storage was made in; otherwise the shape is zeros.
|
||||
#define RGFX_EVT_SHARED_TEXTURE 1042
|
||||
|
||||
// Event `SURFACE_HOLD_LOWERED` ([`RgfxSurfaceHoldLowered`], on the control completion ring,
|
||||
// `seqno` 0), where the guest took [`RGFX_FEATURE_EXT_SURFACE_HOLD`]: the host lowered the hold
|
||||
// word of the cached surface's block at `block_offset` after a read-write CPU lock set
|
||||
// [`RGFX_SURFACE_HOLD_WAITED`] beside it, so the lock looks at the word again. Posted with no
|
||||
// wait: one the ring has no room for is dropped, and the lock looks again within 1 ms.
|
||||
#define RGFX_EVT_SURFACE_HOLD_LOWERED 1043
|
||||
|
||||
// A command buffer's status in [`RgfxCbComplete`]: finished with no error.
|
||||
#define RGFX_CB_OK 0
|
||||
|
||||
@@ -5689,24 +5479,6 @@ typedef struct {
|
||||
RgfxTextureDescriptor desc;
|
||||
} RgfxHeapTextureSizeAndAlign;
|
||||
|
||||
// `HIDDEN_PLACES`: whether the guest reports where its hidden cursor goes (`reports` 1, else 0),
|
||||
// which its driver sends once its mouse ([`RGFX_FEATURE_POINTER_MOTION`]) is up after each start.
|
||||
// A guest that reports them is sent [`RGFX_EVT_POINTER_LOOK`] when the host's pointer moves its
|
||||
// tablet while it hides its cursor, and answers with a `MOVE_CURSOR` of the cursor still hidden
|
||||
// (`visible` 0) at each new place it reads for a while after; the device then counts a hide as a
|
||||
// game's only once its hidden cursor has followed the tablet (docs/graphics-kext/design.md, "A
|
||||
// pointer for games", "The hidden cursor's place"). A guest that sends none, or 0, is never sent
|
||||
// `POINTER_LOOK`, and each hide of its counts as a game's as before, until the next reset. The
|
||||
// x86-64 kext sends it; the arm64e kext, whose cursor is a layer of its swaps, sends none.
|
||||
typedef struct {
|
||||
// [`RGFX_CMD_HIDDEN_PLACES`].
|
||||
RgfxMsgHeader header;
|
||||
// 1 where the guest reports where its hidden cursor goes, else 0.
|
||||
uint32_t reports;
|
||||
// 0.
|
||||
uint32_t reserved_14;
|
||||
} RgfxHiddenPlaces;
|
||||
|
||||
// The body of a buffer's setter.
|
||||
typedef struct {
|
||||
// The buffer, 0 for nil.
|
||||
@@ -7492,21 +7264,6 @@ typedef struct {
|
||||
uint32_t flags;
|
||||
} RgfxPipelineReflection;
|
||||
|
||||
// `POINTER_LOOK`: the host's pointer, over display `display`'s window, moved the guest's tablet
|
||||
// while the guest hides its cursor on every display: the guest looks where its hidden cursor
|
||||
// goes for a while, and reports each new place in a `MOVE_CURSOR` of the cursor still hidden
|
||||
// (`visible` 0). Sent only to a guest whose [`RGFX_CMD_HIDDEN_PLACES`] said it reports them,
|
||||
// while the hide has not shown its hidden cursor following the tablet, one at most every 50 ms;
|
||||
// one that finds the ring held or full is not sent, and the next move sends it.
|
||||
typedef struct {
|
||||
// [`RGFX_EVT_POINTER_LOOK`], `seqno` 0.
|
||||
RgfxMsgHeader header;
|
||||
// The display whose window the host's pointer is over.
|
||||
uint32_t display;
|
||||
// 0.
|
||||
uint32_t reserved_14;
|
||||
} RgfxPointerLook;
|
||||
|
||||
// `POINTER_MOTION`: the host's pointing device moved by (`dx`, `dy`), right and down, in its own
|
||||
// counts, as no acceleration has changed them, turned its wheel `wheel` notches up (away from the
|
||||
// person), and holds the `RGFX_POINTER_BUTTON_*` `buttons` after it. The guest's driver hands it
|
||||
@@ -8452,67 +8209,6 @@ typedef struct {
|
||||
uint64_t value;
|
||||
} RgfxSharedEventValue;
|
||||
|
||||
// `SHARED_TEXTURE`: a `SHARED_TEXTURE_IMPORT`'s answer, with its `seqno`: the shape the storage
|
||||
// was made in, which the new texture answers.
|
||||
typedef struct {
|
||||
// [`RGFX_EVT_SHARED_TEXTURE`], with the import's `seqno`.
|
||||
RgfxMsgHeader header;
|
||||
// An `RGFX_STATUS_*`: [`RGFX_STATUS_OK`] where the texture is made.
|
||||
uint32_t status;
|
||||
// Pads to a multiple of 8; 0.
|
||||
uint32_t reserved_14;
|
||||
// The storage's shape; zeros where the texture was not made.
|
||||
RgfxTextureDescriptor desc;
|
||||
} RgfxSharedTexture;
|
||||
|
||||
// `SHARED_TEXTURE_CREATE`: the sender's texture `obj_id`, of shape `desc`, over storage the host
|
||||
// makes for it, which other processes may open.
|
||||
typedef struct {
|
||||
// [`RGFX_CMD_SHARED_TEXTURE_CREATE`].
|
||||
RgfxMsgHeader header;
|
||||
// The new texture's guest-picked id.
|
||||
uint64_t obj_id;
|
||||
// The texture's guest-picked resource id.
|
||||
uint64_t resource_id;
|
||||
// The texture's shape: Private storage.
|
||||
RgfxTextureDescriptor desc;
|
||||
} RgfxSharedTextureCreate;
|
||||
|
||||
// `SHARED_TEXTURE_IMPORT`: the sender's new texture `obj_id` over the storage named `name`, at
|
||||
// `resource_id`. The kext builds the message from the handle the process holds.
|
||||
typedef struct {
|
||||
// [`RGFX_CMD_SHARED_TEXTURE_IMPORT`].
|
||||
RgfxMsgHeader header;
|
||||
// The sender's new texture's guest-picked id.
|
||||
uint64_t obj_id;
|
||||
// The name the storage was given ([`RgfxSharedTextureName::name`]).
|
||||
uint64_t name;
|
||||
// The new texture's guest-picked resource id.
|
||||
uint64_t resource_id;
|
||||
} RgfxSharedTextureImport;
|
||||
|
||||
// `SHARED_TEXTURE_NAME`: the storage of the sender's shared texture `obj_id` named `name`
|
||||
// device-wide. The kext builds the message: `name` is the kext's, never the process's.
|
||||
typedef struct {
|
||||
// [`RGFX_CMD_SHARED_TEXTURE_NAME`].
|
||||
RgfxMsgHeader header;
|
||||
// The sender's shared texture, or a texture it opened from another's name.
|
||||
uint64_t obj_id;
|
||||
// Its name, unique to the device from the kext's start: never 0.
|
||||
uint64_t name;
|
||||
} RgfxSharedTextureName;
|
||||
|
||||
// `SHARED_TEXTURE_UNNAME`: the name `name` is no longer the kext's to give out.
|
||||
typedef struct {
|
||||
// [`RGFX_CMD_SHARED_TEXTURE_UNNAME`].
|
||||
RgfxMsgHeader header;
|
||||
// 0: the message is context 0's, which no process is, so it waits for no process's
|
||||
// messages.
|
||||
uint64_t reserved_10;
|
||||
// The name ([`RgfxSharedTextureName::name`]).
|
||||
uint64_t name;
|
||||
} RgfxSharedTextureUnname;
|
||||
|
||||
// `SIZE_AND_ALIGN`: a `HEAP_TEXTURE_SIZE_AND_ALIGN`'s answer. `status` is [`RGFX_STATUS_OK`]
|
||||
// with the device's `size` and `align` (a size of 0 for a shape no texture has, as Metal answers
|
||||
// it), or [`RGFX_STATUS_REFUSED`], with both 0, where the device gave no answer.
|
||||
@@ -8569,15 +8265,6 @@ typedef struct {
|
||||
uint32_t reserved_24;
|
||||
} RgfxSurfaceFacts;
|
||||
|
||||
// `SURFACE_HOLD_LOWERED`: the host lowered a cached surface's hold word that a lock waited on
|
||||
// ([`RGFX_EVT_SURFACE_HOLD_LOWERED`]).
|
||||
typedef struct {
|
||||
// [`RGFX_EVT_SURFACE_HOLD_LOWERED`], `seqno` 0.
|
||||
RgfxMsgHeader header;
|
||||
// The region offset of the surface's block.
|
||||
uint64_t block_offset;
|
||||
} RgfxSurfaceHoldLowered;
|
||||
|
||||
// One command buffer an [`RGFX_OP_SURFACE_ORDER`]'s buffer runs after, or an
|
||||
// [`RGFX_OP_COMMIT_ORDER`]'s is committed after: the one at `seqno` on the submission ring of
|
||||
// queue `queue_obj_id`, and the queue's buffers before it.
|
||||
|
||||
@@ -1,405 +0,0 @@
|
||||
/*
|
||||
* reims_graphics_wire_sizes.h: the size of each record of the reims-graphics device's wire
|
||||
* (reims_graphics_wire.h) at the wire's version RGFX_WIRE_SIZES_VERSION, one
|
||||
* RGFX_WIRE_SIZE(record, bytes) row a record, which the includer defines. The wire crate's tests
|
||||
* (crates/reims-vgpu-graphics/tests/wire_sizes.rs) and the guest's (guest/kext/tests/
|
||||
* wire_sizes_test.cpp) check each row against the header as each side compiles it, and that
|
||||
* RGFX_WIRE_SIZES_VERSION is RGFX_VERSION.
|
||||
*
|
||||
* A record's size changes only with the version (docs/graphics-kext/design.md, "The wire's
|
||||
* version"): a guest built at a version lays out and reads each record at the size this table
|
||||
* gives it. A change that alters a size moves RGFX_VERSION on by one, and this table to the new
|
||||
* version with the new sizes, in the same commit; a record that must carry more under the same
|
||||
* version takes a record of its own after it, under a feature the guest takes. A new record adds
|
||||
* its row at the version it lands in.
|
||||
*
|
||||
* The same holds for each register of BAR 0, one RGFX_WIRE_REGISTER(register, offset) row a
|
||||
* register: a register that moves moves RGFX_VERSION on, and a new register, at an offset no
|
||||
* register of an earlier version had, adds its row at the version it lands in.
|
||||
*/
|
||||
|
||||
#define RGFX_WIRE_SIZES_VERSION 3
|
||||
|
||||
#ifdef RGFX_WIRE_SIZE
|
||||
RGFX_WIRE_SIZE(RgfxArgumentDescriptor, 24)
|
||||
RGFX_WIRE_SIZE(RgfxArgumentLayoutQuery, 80)
|
||||
RGFX_WIRE_SIZE(RgfxArgumentLayoutRecord, 24)
|
||||
RGFX_WIRE_SIZE(RgfxArgumentLayoutReply, 16)
|
||||
RGFX_WIRE_SIZE(RgfxArgumentMemberRecord, 48)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyBufferToBuffer, 40)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyBufferToTexture, 104)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyBufferToTextureOptions, 112)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyIndirectCommandBuffer, 40)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureRegion, 120)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureRegionOptions, 128)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureSlices, 64)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureToBuffer, 104)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpCopyTextureToBufferOptions, 112)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpFillBuffer, 32)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpFillBufferPattern4, 32)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpFillTexture, 80)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpFillTextureColor, 112)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpGenerateMipmaps, 8)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpInvalidateCompressedTexture, 8)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpInvalidateCompressedTextureSlice, 24)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeForCpu, 8)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeForCpuSlice, 24)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeForGpu, 8)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeForGpuSlice, 24)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpOptimizeIndirectCommandBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpResetCommandsInBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpSynchronizeResource, 16)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpSynchronizeTexture, 24)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpUpdateFence, 8)
|
||||
RGFX_WIRE_SIZE(RgfxBlitOpWaitForFence, 8)
|
||||
RGFX_WIRE_SIZE(RgfxBlockGrant, 40)
|
||||
RGFX_WIRE_SIZE(RgfxBlockRelease, 40)
|
||||
RGFX_WIRE_SIZE(RgfxBufferAtOffset, 56)
|
||||
RGFX_WIRE_SIZE(RgfxBufferBinding, 16)
|
||||
RGFX_WIRE_SIZE(RgfxBufferCreate, 48)
|
||||
RGFX_WIRE_SIZE(RgfxBufferDidModifyRange, 40)
|
||||
RGFX_WIRE_SIZE(RgfxBufferEscaped, 32)
|
||||
RGFX_WIRE_SIZE(RgfxBufferManagedAtOffset, 64)
|
||||
RGFX_WIRE_SIZE(RgfxBufferOverHostMemory, 56)
|
||||
RGFX_WIRE_SIZE(RgfxBufferOverPages, 72)
|
||||
RGFX_WIRE_SIZE(RgfxBufferOverSurfacePages, 56)
|
||||
RGFX_WIRE_SIZE(RgfxBufferStrideBinding, 24)
|
||||
RGFX_WIRE_SIZE(RgfxCbComplete, 48)
|
||||
RGFX_WIRE_SIZE(RgfxCbScheduled, 24)
|
||||
RGFX_WIRE_SIZE(RgfxCbSubmitted, 24)
|
||||
RGFX_WIRE_SIZE(RgfxColorAttachmentDesc, 40)
|
||||
RGFX_WIRE_SIZE(RgfxColorEntry, 16)
|
||||
RGFX_WIRE_SIZE(RgfxCommandBuffer, 40)
|
||||
RGFX_WIRE_SIZE(RgfxCommandBufferInRegion, 32)
|
||||
RGFX_WIRE_SIZE(RgfxCommandBufferPart, 56)
|
||||
RGFX_WIRE_SIZE(RgfxComplete, 24)
|
||||
RGFX_WIRE_SIZE(RgfxComputeBufferBinding, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeBufferStrideBinding, 24)
|
||||
RGFX_WIRE_SIZE(RgfxComputeHeapBinding, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpDispatchThreadgroups, 48)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpDispatchThreadgroupsIndirect, 40)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpDispatchThreads, 48)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpDispatchThreadsIndirect, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpEncodeStartIf, 32)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpEncodeStartWhile, 32)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpExecuteCommandsInBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpExecuteCommandsIndirect, 24)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpMemoryBarrierResources, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpMemoryBarrierScope, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetBufferOffset, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetBufferOffsetAttributeStride, 24)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetBuffers, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetBuffersAttributeStrides, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetComputePipelineState, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetImageblockWidth, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetSamplerStates, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetSamplerStatesLodClamps, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetStageInRegion, 48)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetStageInRegionIndirect, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetTexture, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetTextures, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetThreadgroupMemoryLength, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetVisibleFunctionTable, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpSetVisibleFunctionTables, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpUpdateFence, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpUseHeaps, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpUseResources, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeOpWaitForFence, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputePassDesc, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputePipelineCreate, 96)
|
||||
RGFX_WIRE_SIZE(RgfxComputeResourceRef, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeSamplerBinding, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputeSamplerLodBinding, 16)
|
||||
RGFX_WIRE_SIZE(RgfxComputeTextureBinding, 8)
|
||||
RGFX_WIRE_SIZE(RgfxComputeVisibleFunctionTableBinding, 8)
|
||||
RGFX_WIRE_SIZE(RgfxContextClose, 24)
|
||||
RGFX_WIRE_SIZE(RgfxCursorColor, 288)
|
||||
RGFX_WIRE_SIZE(RgfxCursorCurve, 32)
|
||||
RGFX_WIRE_SIZE(RgfxDepthStencilCreate, 80)
|
||||
RGFX_WIRE_SIZE(RgfxDeviceInfo, 11672)
|
||||
RGFX_WIRE_SIZE(RgfxDisplayBounds, 40)
|
||||
RGFX_WIRE_SIZE(RgfxDisplayChanged, 24)
|
||||
RGFX_WIRE_SIZE(RgfxDisplayColor, 40)
|
||||
RGFX_WIRE_SIZE(RgfxDisplayEntry, 16)
|
||||
RGFX_WIRE_SIZE(RgfxDisplayScale, 8)
|
||||
RGFX_WIRE_SIZE(RgfxDisplays, 24)
|
||||
RGFX_WIRE_SIZE(RgfxDynamicLibraryCreate, 32)
|
||||
RGFX_WIRE_SIZE(RgfxEventSignalled, 32)
|
||||
RGFX_WIRE_SIZE(RgfxFormatAnswers, 64)
|
||||
RGFX_WIRE_SIZE(RgfxFunctionConstant, 40)
|
||||
RGFX_WIRE_SIZE(RgfxFunctionHandleCreate, 80)
|
||||
RGFX_WIRE_SIZE(RgfxFunctionPointerState, 48)
|
||||
RGFX_WIRE_SIZE(RgfxFunctionTableCreate, 40)
|
||||
RGFX_WIRE_SIZE(RgfxFunctionTableSet, 40)
|
||||
RGFX_WIRE_SIZE(RgfxGetDisplays, 16)
|
||||
RGFX_WIRE_SIZE(RgfxHeapBinding, 8)
|
||||
RGFX_WIRE_SIZE(RgfxHeapCreate, 48)
|
||||
RGFX_WIRE_SIZE(RgfxHeapOverHostMemory, 56)
|
||||
RGFX_WIRE_SIZE(RgfxHeapOverPages, 64)
|
||||
RGFX_WIRE_SIZE(RgfxHeapTextureSizeAndAlign, 72)
|
||||
RGFX_WIRE_SIZE(RgfxHiddenPlaces, 24)
|
||||
RGFX_WIRE_SIZE(RgfxIcbBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxIcbBufferStride, 32)
|
||||
RGFX_WIRE_SIZE(RgfxIcbComputeSlot, 88)
|
||||
RGFX_WIRE_SIZE(RgfxIcbCreate, 88)
|
||||
RGFX_WIRE_SIZE(RgfxIcbDispatch, 24)
|
||||
RGFX_WIRE_SIZE(RgfxIcbDraw, 24)
|
||||
RGFX_WIRE_SIZE(RgfxIcbDrawIndexed, 40)
|
||||
RGFX_WIRE_SIZE(RgfxIcbDrawIndexedPatches, 72)
|
||||
RGFX_WIRE_SIZE(RgfxIcbDrawPatches, 56)
|
||||
RGFX_WIRE_SIZE(RgfxIcbImageblock, 8)
|
||||
RGFX_WIRE_SIZE(RgfxIcbObject, 8)
|
||||
RGFX_WIRE_SIZE(RgfxIcbRange, 8)
|
||||
RGFX_WIRE_SIZE(RgfxIcbRecord, 8)
|
||||
RGFX_WIRE_SIZE(RgfxIcbRegion, 24)
|
||||
RGFX_WIRE_SIZE(RgfxIcbRenderSlot, 104)
|
||||
RGFX_WIRE_SIZE(RgfxIcbSlotBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxIcbSlotPagesRun, 48)
|
||||
RGFX_WIRE_SIZE(RgfxIcbSlotRun, 32)
|
||||
RGFX_WIRE_SIZE(RgfxIcbSlots, 32)
|
||||
RGFX_WIRE_SIZE(RgfxIcbState, 32)
|
||||
RGFX_WIRE_SIZE(RgfxIcbThreadgroupMemory, 8)
|
||||
RGFX_WIRE_SIZE(RgfxIcbWrite, 24)
|
||||
RGFX_WIRE_SIZE(RgfxLibraryCreate, 72)
|
||||
RGFX_WIRE_SIZE(RgfxLibraryFromRegion, 112)
|
||||
RGFX_WIRE_SIZE(RgfxLibraryLookup, 64)
|
||||
RGFX_WIRE_SIZE(RgfxLinearTextureFromBuffer, 112)
|
||||
RGFX_WIRE_SIZE(RgfxLinkedFunction, 48)
|
||||
RGFX_WIRE_SIZE(RgfxManagedBufferCreate, 56)
|
||||
RGFX_WIRE_SIZE(RgfxManagedBufferZero, 8)
|
||||
RGFX_WIRE_SIZE(RgfxManagedTextureCreate, 112)
|
||||
RGFX_WIRE_SIZE(RgfxMeshPipelineReflection, 24)
|
||||
RGFX_WIRE_SIZE(RgfxMeshRenderPipelineCreate, 512)
|
||||
RGFX_WIRE_SIZE(RgfxModeEntry, 12)
|
||||
RGFX_WIRE_SIZE(RgfxMoveCursor, 32)
|
||||
RGFX_WIRE_SIZE(RgfxMsgHeader, 16)
|
||||
RGFX_WIRE_SIZE(RgfxObjectCreate, 24)
|
||||
RGFX_WIRE_SIZE(RgfxObjectDestroy, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpDispatchThreadsPerTile, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpDispatchThreadsPerTileInRegion, 72)
|
||||
RGFX_WIRE_SIZE(RgfxOpDispatchThreadsPerTileInRegionIndex, 80)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPatches, 72)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPatchesIndirect, 56)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPrimitives, 40)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPrimitivesBase, 64)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPrimitivesIndirect, 48)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawIndexedPrimitivesInstances, 48)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawMeshThreadgroups, 72)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawMeshThreadgroupsIndirect, 64)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawMeshThreads, 72)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawPatches, 56)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawPatchesIndirect, 40)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawPrimitives, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawPrimitivesBase, 40)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawPrimitivesIndirect, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpDrawPrimitivesInstances, 32)
|
||||
RGFX_WIRE_SIZE(RgfxOpEvent, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpExecuteCommandsInBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpExecuteCommandsIndirect, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpGuestTimes, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpHeader, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpMemoryBarrierWithScope, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpQueueBarrier, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetAlphaTestReferenceValue, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetBlendColorRed, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetColorResolveTexture, 48)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetColorStoreAction, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetColorStoreActionOptions, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetCullMode, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetDepthBias, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetDepthClipModeSpi, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetDepthResolveTexture, 40)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetDepthStencilState, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetDepthStoreAction, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetDepthStoreActionOptions, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetFragmentBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetFragmentBufferOffset, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetFragmentBuffers, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetFragmentSamplerStates, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetFragmentSamplerStatesLodClamps, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetFragmentTexture, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetFragmentTextures, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetFrontFacingWinding, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetLineWidth, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetMeshBufferOffset, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetMeshBuffers, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetMeshSamplerStates, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetMeshSamplerStatesLodClamps, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetMeshTextures, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetObjectBufferOffset, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetObjectBuffers, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetObjectSamplerStates, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetObjectSamplerStatesLodClamps, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetObjectTextures, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetObjectThreadgroupMemoryLength, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetPointSize, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetPrimitiveRestartEnabled, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetProvokingVertexMode, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetRenderPipelineState, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetScissorRect, 32)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetScissorRects, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetStencilFrontReferenceValue, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetStencilResolveTexture, 40)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetStencilStoreAction, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetStencilStoreActionOptions, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetTessellationFactorBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetTessellationFactorScale, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetThreadgroupMemoryLength, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetTileBufferOffset, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetTileBuffers, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetTileSamplerStates, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetTileSamplerStatesLodClamps, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetTileTextures, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetTriangleFillMode, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexAmplificationCount, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexAmplificationMode, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexBuffer, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexBufferOffset, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexBufferOffsetAttributeStride, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexBuffers, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexBuffersAttributeStrides, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexSamplerStates, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexSamplerStatesLodClamps, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVertexTextures, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetViewport, 48)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetViewportTransformEnabled, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetViewports, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpSetVisibilityResultMode, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpSurfaceUse, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpUpdateFence, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpUseHeaps, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpUseHeapsStages, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpUseResources, 16)
|
||||
RGFX_WIRE_SIZE(RgfxOpUseResourcesStages, 24)
|
||||
RGFX_WIRE_SIZE(RgfxOpVideoPass, 8)
|
||||
RGFX_WIRE_SIZE(RgfxOpWaitForFence, 16)
|
||||
RGFX_WIRE_SIZE(RgfxPageRun, 16)
|
||||
RGFX_WIRE_SIZE(RgfxPagesAnswer, 32)
|
||||
RGFX_WIRE_SIZE(RgfxPagesBufferAddress, 24)
|
||||
RGFX_WIRE_SIZE(RgfxPipelineAnswersQuery, 24)
|
||||
RGFX_WIRE_SIZE(RgfxPipelineLibrary, 16)
|
||||
RGFX_WIRE_SIZE(RgfxPipelineReflection, 80)
|
||||
RGFX_WIRE_SIZE(RgfxPointerLook, 24)
|
||||
RGFX_WIRE_SIZE(RgfxPointerMotion, 32)
|
||||
RGFX_WIRE_SIZE(RgfxPointerOver, 32)
|
||||
RGFX_WIRE_SIZE(RgfxPoolBlock, 48)
|
||||
RGFX_WIRE_SIZE(RgfxPoolGive, 40)
|
||||
RGFX_WIRE_SIZE(RgfxPoolTake, 32)
|
||||
RGFX_WIRE_SIZE(RgfxPresentSurface, 32)
|
||||
RGFX_WIRE_SIZE(RgfxPresentSurfaceGen, 8)
|
||||
RGFX_WIRE_SIZE(RgfxPrivateBlock, 40)
|
||||
RGFX_WIRE_SIZE(RgfxPrivateGive, 40)
|
||||
RGFX_WIRE_SIZE(RgfxPrivateTake, 32)
|
||||
RGFX_WIRE_SIZE(RgfxQueueCreate, 56)
|
||||
RGFX_WIRE_SIZE(RgfxQueueCreateFlags, 8)
|
||||
RGFX_WIRE_SIZE(RgfxRateMapAnswer, 48)
|
||||
RGFX_WIRE_SIZE(RgfxRateMapCreate, 64)
|
||||
RGFX_WIRE_SIZE(RgfxRateMapLayer, 16)
|
||||
RGFX_WIRE_SIZE(RgfxRateMapQuery, 56)
|
||||
RGFX_WIRE_SIZE(RgfxRateMapState, 104)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPassColorAttachment, 88)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPassDepthAttachment, 64)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPassDesc, 152)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPassRateMap, 8)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPassSamplePositions, 136)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPassStencilAttachment, 64)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPassVisibility, 16)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPipelineCreate, 496)
|
||||
RGFX_WIRE_SIZE(RgfxRenderPipelinePrivateState, 24)
|
||||
RGFX_WIRE_SIZE(RgfxResourceBinding, 16)
|
||||
RGFX_WIRE_SIZE(RgfxResourceIdChunk, 24)
|
||||
RGFX_WIRE_SIZE(RgfxRingHeader, 256)
|
||||
RGFX_WIRE_SIZE(RgfxSamplerBinding, 8)
|
||||
RGFX_WIRE_SIZE(RgfxSamplerCreate, 72)
|
||||
RGFX_WIRE_SIZE(RgfxSamplerCreateExt, 8)
|
||||
RGFX_WIRE_SIZE(RgfxSamplerLodBinding, 16)
|
||||
RGFX_WIRE_SIZE(RgfxSamplerState, 32)
|
||||
RGFX_WIRE_SIZE(RgfxScheduledAsk, 32)
|
||||
RGFX_WIRE_SIZE(RgfxScissorRectElem, 32)
|
||||
RGFX_WIRE_SIZE(RgfxScroll, 32)
|
||||
RGFX_WIRE_SIZE(RgfxScrollDevices, 24)
|
||||
RGFX_WIRE_SIZE(RgfxSetCursor, 48)
|
||||
RGFX_WIRE_SIZE(RgfxSetDisplayPower, 24)
|
||||
RGFX_WIRE_SIZE(RgfxSetScanout, 40)
|
||||
RGFX_WIRE_SIZE(RgfxSetVblank, 24)
|
||||
RGFX_WIRE_SIZE(RgfxSharedEventCreate, 32)
|
||||
RGFX_WIRE_SIZE(RgfxSharedEventImport, 40)
|
||||
RGFX_WIRE_SIZE(RgfxSharedEventName, 40)
|
||||
RGFX_WIRE_SIZE(RgfxSharedEventSetValue, 32)
|
||||
RGFX_WIRE_SIZE(RgfxSharedEventUnname, 32)
|
||||
RGFX_WIRE_SIZE(RgfxSharedEventValue, 32)
|
||||
RGFX_WIRE_SIZE(RgfxSharedTexture, 72)
|
||||
RGFX_WIRE_SIZE(RgfxSharedTextureCreate, 80)
|
||||
RGFX_WIRE_SIZE(RgfxSharedTextureImport, 40)
|
||||
RGFX_WIRE_SIZE(RgfxSharedTextureName, 32)
|
||||
RGFX_WIRE_SIZE(RgfxSharedTextureUnname, 32)
|
||||
RGFX_WIRE_SIZE(RgfxSizeAndAlign, 40)
|
||||
RGFX_WIRE_SIZE(RgfxStencilDescriptor, 24)
|
||||
RGFX_WIRE_SIZE(RgfxSurfaceDownload, 24)
|
||||
RGFX_WIRE_SIZE(RgfxSurfaceFacts, 40)
|
||||
RGFX_WIRE_SIZE(RgfxSurfaceHoldLowered, 24)
|
||||
RGFX_WIRE_SIZE(RgfxSurfaceOrderWait, 16)
|
||||
RGFX_WIRE_SIZE(RgfxSurfacePages, 56)
|
||||
RGFX_WIRE_SIZE(RgfxSurfacePagesCache, 8)
|
||||
RGFX_WIRE_SIZE(RgfxSurfacePagesLayout, 136)
|
||||
RGFX_WIRE_SIZE(RgfxSurfacePlaneLayout, 32)
|
||||
RGFX_WIRE_SIZE(RgfxSurfaceWriter, 16)
|
||||
RGFX_WIRE_SIZE(RgfxSurfaceWriters, 64)
|
||||
RGFX_WIRE_SIZE(RgfxTextureBinding, 8)
|
||||
RGFX_WIRE_SIZE(RgfxTextureCreate, 104)
|
||||
RGFX_WIRE_SIZE(RgfxTextureDescriptor, 48)
|
||||
RGFX_WIRE_SIZE(RgfxTextureDidModifyData, 24)
|
||||
RGFX_WIRE_SIZE(RgfxTextureFromBuffer, 104)
|
||||
RGFX_WIRE_SIZE(RgfxTextureFromIOSurface, 120)
|
||||
RGFX_WIRE_SIZE(RgfxTextureReplaceRegion, 56)
|
||||
RGFX_WIRE_SIZE(RgfxTextureView, 72)
|
||||
RGFX_WIRE_SIZE(RgfxUploadWritten, 16)
|
||||
RGFX_WIRE_SIZE(RgfxVblank, 40)
|
||||
RGFX_WIRE_SIZE(RgfxVertexAttribute, 16)
|
||||
RGFX_WIRE_SIZE(RgfxVertexBufferLayout, 16)
|
||||
RGFX_WIRE_SIZE(RgfxVideoCaps, 1552)
|
||||
RGFX_WIRE_SIZE(RgfxVideoCodecCaps, 48)
|
||||
RGFX_WIRE_SIZE(RgfxVideoDecodeCaps, 16)
|
||||
RGFX_WIRE_SIZE(RgfxVideoEncodeCaps, 16)
|
||||
RGFX_WIRE_SIZE(RgfxVideoEncodeResult, 32)
|
||||
RGFX_WIRE_SIZE(RgfxVideoEncodeSettings, 96)
|
||||
RGFX_WIRE_SIZE(RgfxVideoOpDecodeH264, 48)
|
||||
RGFX_WIRE_SIZE(RgfxVideoOpDecodeH265, 48)
|
||||
RGFX_WIRE_SIZE(RgfxVideoOpEncode, 72)
|
||||
RGFX_WIRE_SIZE(RgfxVideoOutputLayout, 16)
|
||||
RGFX_WIRE_SIZE(RgfxVideoSessionCreate, 32)
|
||||
RGFX_WIRE_SIZE(RgfxViewMapping, 8)
|
||||
RGFX_WIRE_SIZE(RgfxViewportElem, 48)
|
||||
RGFX_WIRE_SIZE(RgfxVtHostMessage, 24)
|
||||
RGFX_WIRE_SIZE(RgfxVtMessage, 72)
|
||||
RGFX_WIRE_SIZE(RgfxVtRing, 24)
|
||||
RGFX_WIRE_SIZE(RgfxVtStatus, 24)
|
||||
RGFX_WIRE_SIZE(RgfxVtSurface, 88)
|
||||
RGFX_WIRE_SIZE(RgfxVtSurfacePlane, 24)
|
||||
#endif
|
||||
|
||||
#ifdef RGFX_WIRE_REGISTER
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_MAGIC, 0x000)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_VERSION, 0x004)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_FEATURES_LO, 0x008)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_FEATURES_HI, 0x00c)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_STATUS, 0x010)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_REGION_SIZE_LO, 0x014)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_REGION_SIZE_HI, 0x018)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_DOORBELL, 0x020)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_DRIVER_FEATURES_LO, 0x024)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_DRIVER_FEATURES_HI, 0x028)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_CONSUMED, 0x02c)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_DEFERRED_BUDGET_LO, 0x030)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_DEFERRED_BUDGET_HI, 0x034)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_HOST_TIME_LO, 0x038)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_HOST_TIME_HI, 0x03c)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_DOORBELL_PAGE_BIND, 0x040)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_POOL_BASE_LO, 0x044)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_POOL_BASE_HI, 0x048)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_POOL_LENGTH_LO, 0x04c)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_POOL_LENGTH_HI, 0x050)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_GUEST_BUNDLE, 0x054)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_FEATURES_EXT, 0x058)
|
||||
RGFX_WIRE_REGISTER(RGFX_REG_DRIVER_FEATURES_EXT, 0x05c)
|
||||
#endif
|
||||
@@ -11,7 +11,7 @@ use zerocopy::{FromBytes, IntoBytes};
|
||||
|
||||
use crate::device::{CursorShape, Shared};
|
||||
use crate::display::cursor_color::CursorColor;
|
||||
use crate::display::{CursorImage, Scanout, offered_modes, straight_rgba};
|
||||
use crate::display::{CursorImage, Scanout, straight_rgba};
|
||||
use crate::ring::{Message, set_size, sized};
|
||||
use crate::wire::*;
|
||||
|
||||
@@ -32,12 +32,11 @@ pub(crate) fn answer(shared: &Shared, message: &Message) -> Option<Vec<u8>> {
|
||||
&& let Some(display) = shared.seen_display(command.display)
|
||||
{
|
||||
// The device knows first, so a window the move reaches asks it of a cursor
|
||||
// shown or hidden already. A move of a cursor hidden already, which shows
|
||||
// nothing, is the device's alone (`Shared::cursor_visible`).
|
||||
let visible = command.visible != 0;
|
||||
if !shared.cursor_visible(command.display, command.x, command.y, visible) {
|
||||
display.screen.cursor_moved(command.x, command.y, visible);
|
||||
}
|
||||
// shown or hidden already.
|
||||
shared.cursor_visible(command.display, command.visible != 0);
|
||||
display
|
||||
.screen
|
||||
.cursor_moved(command.x, command.y, command.visible != 0);
|
||||
if command.visible != 0 {
|
||||
shared.cursor_shown_on(command.display, command.x, command.y);
|
||||
}
|
||||
@@ -60,12 +59,6 @@ pub(crate) fn answer(shared: &Shared, message: &Message) -> Option<Vec<u8>> {
|
||||
}
|
||||
return None;
|
||||
}
|
||||
RGFX_CMD_HIDDEN_PLACES => {
|
||||
if let Some(command) = read::<RgfxHiddenPlaces>(message) {
|
||||
shared.hidden_places(command.reports != 0);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
RGFX_CMD_SET_VBLANK => read(message).map_or(RGFX_STATUS_INVALID_ARGUMENT, |command| {
|
||||
set_vblank(shared, &command)
|
||||
}),
|
||||
@@ -193,9 +186,7 @@ fn lifecycle(shared: &Shared, message: &Message, epoch: u64) -> Option<Vec<u8>>
|
||||
}
|
||||
RGFX_CMD_VT_MESSAGE => {
|
||||
// A guest that took no VT_MESSAGES sends none; one it sends anyway is answered as
|
||||
// one the device could not read, as is one whose runs or length do not hold. The
|
||||
// lends such a message names go back first, where the guest took VT_MESSAGES: the
|
||||
// kext holds each lend of a message it posted until a `rels` names it.
|
||||
// one the device could not read, as is one whose runs or length do not hold.
|
||||
let read = shared
|
||||
.driver_took(RGFX_FEATURE_VT_MESSAGES)
|
||||
.then(|| crate::device::vt_read(message))
|
||||
@@ -209,12 +200,7 @@ fn lifecycle(shared: &Shared, message: &Message, epoch: u64) -> Option<Vec<u8>>
|
||||
);
|
||||
None
|
||||
}
|
||||
None => {
|
||||
if let Some(release) = crate::device::vt_unread_release(message) {
|
||||
shared.vt_link(epoch).send(&release);
|
||||
}
|
||||
Some(crate::device::vt_status(seqno, RGFX_VT_STATUS_MALFORMED))
|
||||
}
|
||||
None => Some(crate::device::vt_status(seqno, RGFX_VT_STATUS_MALFORMED)),
|
||||
}
|
||||
}
|
||||
RGFX_CMD_SURFACE_DOWNLOAD => match read::<RgfxSurfaceDownload>(message) {
|
||||
@@ -392,11 +378,9 @@ pub(crate) fn complete(seqno: u64, status: u32) -> Vec<u8> {
|
||||
|
||||
/// `GET_DISPLAYS`' answer: each display the guest sees (`Shared::displays_seen`: display 0
|
||||
/// alone where it did not take [`RGFX_FEATURE_MULTI_DISPLAY`]), in order of id, connected, with
|
||||
/// the modes it offers ([`offered_modes`]): first the mode `Shared::offered_mode` gives, which it
|
||||
/// prefers, then its smaller modes; and, where the guest took [`RGFX_FEATURE_DISPLAY_SCALE`], its
|
||||
/// screen's scale between the display's record and its modes. The record's count is the modes
|
||||
/// that follow it. The guest is told each display's first mode from now on (`device`'s
|
||||
/// refresh), which the smaller modes follow.
|
||||
/// the mode it offers (`Shared::offered_mode`) as its one mode, which it prefers, and, where the
|
||||
/// guest took [`RGFX_FEATURE_DISPLAY_SCALE`], its screen's scale between the display's record and
|
||||
/// its mode. The guest is told each display's mode from now on (`device`'s refresh).
|
||||
fn displays(shared: &Shared, seqno: u64) -> Vec<u8> {
|
||||
let seen = shared.displays_seen();
|
||||
let mut bytes = RgfxMsgHeader {
|
||||
@@ -408,35 +392,28 @@ fn displays(shared: &Shared, seqno: u64) -> Vec<u8> {
|
||||
.to_vec();
|
||||
bytes.extend_from_slice(&seen.to_le_bytes());
|
||||
for (id, display) in (0..seen).zip(shared.displays.iter()) {
|
||||
let modes = offered_modes(display.screen.mode(), shared.display_count());
|
||||
let first = modes[0];
|
||||
display.state.lock().told = Some(first);
|
||||
let mut records = Vec::new();
|
||||
let mut mode_count = 0;
|
||||
for mode in &modes {
|
||||
let record = RgfxModeEntry {
|
||||
width: mode.width,
|
||||
height: mode.height,
|
||||
refresh_mhz: mode.refresh_mhz,
|
||||
};
|
||||
records.extend_from_slice(record.as_bytes());
|
||||
mode_count += 1;
|
||||
}
|
||||
let mode = shared.offered_mode(display);
|
||||
display.state.lock().told = Some(mode);
|
||||
let entry = RgfxDisplayEntry {
|
||||
id,
|
||||
connected: 1,
|
||||
preferred_mode: 0,
|
||||
mode_count,
|
||||
mode_count: 1,
|
||||
};
|
||||
bytes.extend_from_slice(entry.as_bytes());
|
||||
if shared.driver_took(RGFX_FEATURE_DISPLAY_SCALE) {
|
||||
let scale = RgfxDisplayScale {
|
||||
scale_120ths: first.scale_120ths,
|
||||
scale_120ths: mode.scale_120ths,
|
||||
reserved_4: 0,
|
||||
};
|
||||
bytes.extend_from_slice(scale.as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(&records);
|
||||
let mode = RgfxModeEntry {
|
||||
width: mode.width,
|
||||
height: mode.height,
|
||||
refresh_mhz: mode.refresh_mhz,
|
||||
};
|
||||
bytes.extend_from_slice(mode.as_bytes());
|
||||
}
|
||||
bytes.resize(bytes.len().next_multiple_of(8), 0);
|
||||
set_size(&mut bytes);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
//! The guest's desktop as a drag of the host's pointer crosses it (docs/graphics-kext/design.md,
|
||||
//! The guest's desktop as the host's captured pointer crosses it (docs/graphics-kext/design.md,
|
||||
//! "Multiple displays", "A drag across displays"): each display's rectangle in WindowServer's
|
||||
//! global space, in points, as the guest's `DISPLAY_BOUNDS` gave it, beside the display's
|
||||
//! scanout, whose pixels lie over that rectangle as the kext places `POINTER_OVER`'s point
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
//! What the device sees of the guest's drivers being of another build than the host
|
||||
//! (docs/graphics-kext/design.md, "The guest's bundle, told to the host"), which it tells the host
|
||||
//! once a boot, so the host can tell its user why the guest's desktop runs without Metal:
|
||||
//! - A kext of another wire version leaves the device at `VERSION`. Every kext since the version
|
||||
//! check reads `MAGIC` and `VERSION` first, and on another version reads `VERSION` once more for
|
||||
//! its log line and writes nothing; a kext of the host's version reads `REGION_SIZE_HI` right
|
||||
//! after (`guest/kext/tests/start_order_test.cpp` holds that order). The option ROM and
|
||||
//! Ambrosia's module read `VERSION` before they reset the device. So a read of `VERSION` while
|
||||
//! the device is started, which no other register access follows in [`LEFT_AFTER`], is a driver
|
||||
//! that left at its version check ([`VersionWatch`]).
|
||||
//! - The accelerator of a kext of the host's version writes `GUEST_BUNDLE` once a boot, with what
|
||||
//! it found of its Metal bundle and RgfxGate's install pass ([`GuestBundle`]).
|
||||
|
||||
use crate::wire::{
|
||||
RGFX_GUEST_BUNDLE_ERRNO_SHIFT, RGFX_GUEST_BUNDLE_GATE_SHIFT, RGFX_GUEST_BUNDLE_VERSION_SHIFT,
|
||||
};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
/// How long after a read of `VERSION` while the device is started no other register access must
|
||||
/// come for the reader to count as a driver that left the device at its version check. A kext of
|
||||
/// the host's version touches `REGION_SIZE_HI` next, with no wait between in its start
|
||||
/// (`start_order_test.cpp`); each boot logs the gap at info ([`VersionWatch::other_access`]).
|
||||
/// Measured in seven healthy boots of x86-64 macOS 26.7.2 under KVM (docs/qemu.md, "x86-64
|
||||
/// macOS guests: drivers of another build"): 65 ms at most, the framebuffer's, whose PAT
|
||||
/// rendezvous runs between the two reads, and 8 us at most for the accelerator's; under TCG, in a
|
||||
/// boot of arm64 macOS 26 on Ambrosia, 38 and 35 us, the kexts starting 70 s in. The margin is
|
||||
/// wide on purpose: a driver called old on a healthy guest is worse than none called, and the
|
||||
/// line comes a minute into a boot whose desktop takes longer to show.
|
||||
pub(crate) const LEFT_AFTER: Duration = Duration::from_secs(60);
|
||||
|
||||
/// The watch for a driver that leaves at `VERSION` (the module doc).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct VersionWatch {
|
||||
/// The device's clock at a read of `VERSION` while the device was started, which no other
|
||||
/// register access has followed since; 0 for none.
|
||||
read_at: AtomicU64,
|
||||
/// The reset count at which a leave was told, plus 1; 0 for none.
|
||||
told: AtomicU64,
|
||||
}
|
||||
|
||||
impl VersionWatch {
|
||||
/// A read of `VERSION` at `now`, the device `started` (`STATUS` 1) or not: one while started
|
||||
/// begins the watch, unless a leave was told since the last reset (`epoch`).
|
||||
pub(crate) fn version_read(&self, started: bool, epoch: u64, now: u64) {
|
||||
if started && self.told.load(Ordering::Acquire) != epoch + 1 {
|
||||
self.read_at.store(now.max(1), Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
/// Any other register access, a read but of `MAGIC` and `VERSION`, or any write, at `now()`,
|
||||
/// which is asked only where a read is watched: the reader did not leave. The time since a
|
||||
/// watched read of `VERSION` where this ends one. Where none is watched it costs a load.
|
||||
pub(crate) fn other_access(&self, now: impl FnOnce() -> u64) -> Option<u64> {
|
||||
if self.read_at.load(Ordering::Relaxed) == 0 {
|
||||
return None;
|
||||
}
|
||||
let at = self.read_at.swap(0, Ordering::AcqRel);
|
||||
(at != 0).then(|| now().saturating_sub(at))
|
||||
}
|
||||
|
||||
/// Whether, at `now`, a watched read of `VERSION` has had no other register access for
|
||||
/// [`LEFT_AFTER`] while the device stayed `started` at reset count `epoch`: true once, and
|
||||
/// then not again until a reset.
|
||||
pub(crate) fn left(&self, started: bool, epoch: u64, now: u64) -> bool {
|
||||
let at = self.read_at.load(Ordering::Acquire);
|
||||
let after = u64::try_from(LEFT_AFTER.as_nanos()).unwrap_or(u64::MAX);
|
||||
if at == 0 || !started || now.saturating_sub(at) < after {
|
||||
return false;
|
||||
}
|
||||
if self
|
||||
.read_at
|
||||
.compare_exchange(at, 0, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.told.swap(epoch + 1, Ordering::AcqRel) != epoch + 1
|
||||
}
|
||||
|
||||
/// The device's reset: a watched read ends with it.
|
||||
pub(crate) fn reset(&self) {
|
||||
self.read_at.store(0, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `GUEST_BUNDLE` write: what the guest's accelerator found of its Metal bundle as WindowServer
|
||||
/// opened the display, and RgfxGate's install pass (`RGFX_REG_GUEST_BUNDLE`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct GuestBundle {
|
||||
/// What it found: an `RGFX_GUEST_BUNDLE_*`.
|
||||
pub found: u32,
|
||||
/// The wire version another version's bundle's marker names; 0 where it names none the kext
|
||||
/// knows.
|
||||
pub version: u32,
|
||||
/// RgfxGate's install pass: an `RGFX_GATE_*`.
|
||||
pub gate: u32,
|
||||
/// The `errno` of RgfxGate's failed write or rename; 0 for none.
|
||||
pub errno: u32,
|
||||
}
|
||||
|
||||
impl GuestBundle {
|
||||
/// The fields of a `GUEST_BUNDLE` write of `value`.
|
||||
#[must_use]
|
||||
pub fn from_register(value: u32) -> GuestBundle {
|
||||
let byte = |shift: u32| (value >> shift) & 0xff;
|
||||
GuestBundle {
|
||||
found: byte(0),
|
||||
version: byte(RGFX_GUEST_BUNDLE_VERSION_SHIFT),
|
||||
gate: byte(RGFX_GUEST_BUNDLE_GATE_SHIFT),
|
||||
errno: byte(RGFX_GUEST_BUNDLE_ERRNO_SHIFT),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1035,6 +1035,19 @@ impl Lanes {
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until no lane is running or has queued jobs (or the device ends).
|
||||
pub(super) fn wait_idle(&self) {
|
||||
let mut state = self.state.lock();
|
||||
while !state.ended
|
||||
&& state
|
||||
.lanes
|
||||
.values()
|
||||
.any(|lane| lane.running.is_some() || !lane.jobs.is_empty())
|
||||
{
|
||||
self.moved.wait(&mut state);
|
||||
}
|
||||
}
|
||||
|
||||
/// The device ended: the lanes' threads go at their next look, and so do those that wait for
|
||||
/// a lane.
|
||||
pub(super) fn end(&self) {
|
||||
|
||||
@@ -605,12 +605,10 @@ fn present_surface_asks_the_host_and_answers_its_word() {
|
||||
}
|
||||
|
||||
/// A host whose interrupt resets the device, as a host's `raise_interrupt` may (it may call the
|
||||
/// device), and which answers a present at once, inside [`Host::present_surface`]; it counts the
|
||||
/// settles the device's resets ask of it ([`Host::reset_settles`]).
|
||||
/// device), and which answers a present at once, inside [`Host::present_surface`].
|
||||
struct ResettingHost {
|
||||
shared: Arc<OnceLock<Weak<Shared>>>,
|
||||
resets: Arc<AtomicU32>,
|
||||
settles: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
impl Host for ResettingHost {
|
||||
@@ -620,9 +618,6 @@ impl Host for ResettingHost {
|
||||
self.resets.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
fn reset_settles(&self) {
|
||||
self.settles.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
fn present_surface(
|
||||
&self,
|
||||
_display: u32,
|
||||
@@ -643,7 +638,6 @@ fn a_present_answered_at_once_raises_with_no_lock_held() {
|
||||
let mut rig = Rig::with_host(Box::new(ResettingHost {
|
||||
shared: Arc::clone(&shared),
|
||||
resets: Arc::clone(&resets),
|
||||
settles: Arc::default(),
|
||||
}));
|
||||
shared.set(Arc::downgrade(&rig.device.shared)).unwrap();
|
||||
rig.start();
|
||||
@@ -661,47 +655,15 @@ fn a_present_answered_at_once_raises_with_no_lock_held() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A reset made inside the device's raise asks the host for no settle ([`Host::reset_settles`]):
|
||||
/// the host may hold around its raise what its settle takes, and the work the raise is part of
|
||||
/// began before the reset and ends only once the reset returns. A reset made outside one, the
|
||||
/// host's and the guest's `STATUS` 0, asks for it, once each
|
||||
#[test]
|
||||
fn a_reset_inside_a_raise_asks_for_no_settle() {
|
||||
let shared = Arc::new(OnceLock::new());
|
||||
let resets = Arc::new(AtomicU32::new(0));
|
||||
let settles = Arc::new(AtomicU32::new(0));
|
||||
let mut rig = Rig::with_host(Box::new(ResettingHost {
|
||||
shared: Arc::clone(&shared),
|
||||
resets: Arc::clone(&resets),
|
||||
settles: Arc::clone(&settles),
|
||||
}));
|
||||
shared.set(Arc::downgrade(&rig.device.shared)).unwrap();
|
||||
rig.start();
|
||||
rig.arm();
|
||||
rig.send(present_surface(0, HELD_SURFACE));
|
||||
eventually(|| resets.load(Ordering::SeqCst) != 0);
|
||||
assert_eq!(resets.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
settles.load(Ordering::SeqCst),
|
||||
0,
|
||||
"the reset inside the raise asked for a settle"
|
||||
);
|
||||
rig.device.reset();
|
||||
assert_eq!(settles.load(Ordering::SeqCst), 1);
|
||||
rig.device.mmio_write(RGFX_REG_STATUS.into(), 0);
|
||||
assert_eq!(settles.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// The registers read as the wire says, and `STATUS` follows the guest's writes
|
||||
#[test]
|
||||
fn the_registers_read_as_the_wire_says() {
|
||||
let rig = Rig::new();
|
||||
let read = |offset: u32| rig.device.mmio_read(offset.into());
|
||||
assert_eq!(read(RGFX_REG_MAGIC), 0x5846_4752);
|
||||
assert_eq!(read(RGFX_REG_VERSION), 3);
|
||||
assert_eq!(read(RGFX_REG_VERSION), 2);
|
||||
assert_eq!(read(RGFX_REG_FEATURES_LO), 0);
|
||||
assert_eq!(read(RGFX_REG_FEATURES_HI), 0);
|
||||
assert_eq!(read(RGFX_REG_FEATURES_EXT), 0, "a host that offers none");
|
||||
assert_eq!(read(RGFX_REG_STATUS), 0);
|
||||
assert_eq!(
|
||||
read(RGFX_REG_REGION_SIZE_LO),
|
||||
@@ -721,109 +683,25 @@ fn the_registers_read_as_the_wire_says() {
|
||||
assert_eq!(read(RGFX_REG_STATUS), 0);
|
||||
}
|
||||
|
||||
/// `FEATURES_EXT` reads the host's bits 64 to 95 with no take, before the driver starts and
|
||||
/// after, across a reset, and a write there changes nothing
|
||||
#[test]
|
||||
fn features_ext_reads_the_host_s_bits_with_no_take() {
|
||||
struct Ext;
|
||||
impl Host for Ext {
|
||||
fn raise_interrupt(&self, _vector: u32) {}
|
||||
fn features_ext(&self) -> u32 {
|
||||
RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES
|
||||
}
|
||||
}
|
||||
let rig = Rig::with_host(Box::new(Ext));
|
||||
let read = || rig.device.mmio_read(RGFX_REG_FEATURES_EXT.into());
|
||||
assert_eq!(read(), RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
|
||||
rig.device.mmio_write(RGFX_REG_FEATURES_EXT.into(), 0);
|
||||
assert_eq!(read(), RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_DRIVER_READY);
|
||||
assert_eq!(read(), RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
|
||||
assert_eq!(read(), RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
|
||||
}
|
||||
|
||||
/// A guest built before `FEATURES_EXT`, which never reads it, meets a host that offers shared
|
||||
/// textures there as it meets one that offers nothing there: every register it reads, and every
|
||||
/// feature it takes, read the same on both, before its start, after it and after a reset
|
||||
#[test]
|
||||
fn an_old_guest_reads_the_same_device_where_features_ext_offers_more() {
|
||||
struct Ext;
|
||||
impl Host for Ext {
|
||||
fn raise_interrupt(&self, _vector: u32) {}
|
||||
fn features_ext(&self) -> u32 {
|
||||
RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES
|
||||
}
|
||||
}
|
||||
struct Plain;
|
||||
impl Host for Plain {
|
||||
fn raise_interrupt(&self, _vector: u32) {}
|
||||
}
|
||||
// An old guest's start: its reads of the registers it knows, its take of every offered bit,
|
||||
// then the reads again after the device starts and after a reset.
|
||||
let walk = |rig: &Rig| -> Vec<u32> {
|
||||
let read = |at: u32| rig.device.mmio_read(at.into());
|
||||
let known = [
|
||||
RGFX_REG_MAGIC,
|
||||
RGFX_REG_VERSION,
|
||||
RGFX_REG_FEATURES_LO,
|
||||
RGFX_REG_FEATURES_HI,
|
||||
RGFX_REG_STATUS,
|
||||
RGFX_REG_REGION_SIZE_LO,
|
||||
RGFX_REG_REGION_SIZE_HI,
|
||||
RGFX_REG_DRIVER_FEATURES_LO,
|
||||
RGFX_REG_DRIVER_FEATURES_HI,
|
||||
];
|
||||
let mut seen: Vec<u32> = known.iter().map(|&at| read(at)).collect();
|
||||
rig.device.mmio_write(
|
||||
RGFX_REG_DRIVER_FEATURES_LO.into(),
|
||||
read(RGFX_REG_FEATURES_LO),
|
||||
);
|
||||
rig.device.mmio_write(
|
||||
RGFX_REG_DRIVER_FEATURES_HI.into(),
|
||||
read(RGFX_REG_FEATURES_HI),
|
||||
);
|
||||
rig.start();
|
||||
seen.extend(known.iter().map(|&at| read(at)));
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
|
||||
seen.extend(known.iter().map(|&at| read(at)));
|
||||
seen
|
||||
};
|
||||
let ext = Rig::with_host(Box::new(Ext));
|
||||
let plain = Rig::with_host(Box::new(Plain));
|
||||
assert_eq!(walk(&ext), walk(&plain));
|
||||
assert_eq!(plain.device.mmio_read(RGFX_REG_FEATURES_EXT.into()), 0);
|
||||
}
|
||||
|
||||
/// `GET_DISPLAYS` answers display 0, connected, with the screen's mode first, which it prefers,
|
||||
/// then its smaller modes (`display::offered_modes`), each at the screen's rate; the interrupt is
|
||||
/// raised only where the guest armed the ring, and clears `armed`
|
||||
/// `GET_DISPLAYS` answers display 0, connected, with the screen's mode as its one, preferred
|
||||
/// mode; the interrupt is raised only where the guest armed the ring, and clears `armed`
|
||||
#[test]
|
||||
fn get_displays_answers_the_screen_s_mode() {
|
||||
let mut rig = Rig::new();
|
||||
rig.start();
|
||||
let seqno = rig.send(get_displays());
|
||||
let bytes = rig.event().unwrap();
|
||||
assert_eq!(bytes.len(), 88);
|
||||
assert_eq!(bytes.len(), 48);
|
||||
let header = RgfxMsgHeader::read_from_prefix(&bytes).unwrap().0;
|
||||
assert_eq!(
|
||||
(header.r#type, header.size, header.seqno),
|
||||
(RGFX_EVT_DISPLAYS, 88, seqno)
|
||||
(RGFX_EVT_DISPLAYS, 48, seqno)
|
||||
);
|
||||
let words: Vec<u32> = bytes[16..]
|
||||
.chunks(4)
|
||||
.map(|c| u32::from_le_bytes(c.try_into().unwrap()))
|
||||
.collect();
|
||||
let n = NEVER_MHZ;
|
||||
assert_eq!(
|
||||
words,
|
||||
[
|
||||
1, 0, 1, 0, 4, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n, 0
|
||||
]
|
||||
);
|
||||
assert_eq!(words, [1, 0, 1, 0, 1, 1280, 800, NEVER_MHZ]);
|
||||
assert_eq!(rig.interrupts.load(Ordering::SeqCst), 0, "not armed");
|
||||
rig.arm();
|
||||
rig.send(get_displays());
|
||||
@@ -837,7 +715,7 @@ fn get_displays_answers_the_screen_s_mode() {
|
||||
}
|
||||
|
||||
/// A guest that took `DISPLAY_SCALE` is told the screen's scale between the display's record and
|
||||
/// its modes; one that did not gets the answer without it (`get_displays_answers_the_screen_s_mode`)
|
||||
/// its mode; one that did not gets the answer without it (`get_displays_answers_the_screen_s_mode`)
|
||||
#[test]
|
||||
fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
|
||||
struct Scales;
|
||||
@@ -858,19 +736,13 @@ fn a_guest_that_took_display_scale_is_told_the_screen_s_scale() {
|
||||
let header = RgfxMsgHeader::read_from_prefix(&bytes).unwrap().0;
|
||||
assert_eq!(
|
||||
(header.r#type, header.size, header.seqno),
|
||||
(RGFX_EVT_DISPLAYS, 96, seqno)
|
||||
(RGFX_EVT_DISPLAYS, 56, seqno)
|
||||
);
|
||||
let words: Vec<u32> = bytes[16..92]
|
||||
let words: Vec<u32> = bytes[16..56]
|
||||
.chunks(4)
|
||||
.map(|c| u32::from_le_bytes(c.try_into().unwrap()))
|
||||
.collect();
|
||||
let n = NEVER_MHZ;
|
||||
assert_eq!(
|
||||
words,
|
||||
[
|
||||
1, 0, 1, 0, 4, 240, 0, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n
|
||||
]
|
||||
);
|
||||
assert_eq!(words, [1, 0, 1, 0, 1, 240, 0, 1280, 800, NEVER_MHZ]);
|
||||
}
|
||||
|
||||
/// A post whose guest took the record and armed the ring again before the post cleared `armed`
|
||||
@@ -2110,88 +1982,6 @@ fn a_command_queue_gets_its_own_ring_loop() {
|
||||
assert_eq!(*seen.closed.lock(), vec![7]);
|
||||
}
|
||||
|
||||
/// A host that records, in order, the messages it is handed, each with the id at its offset 16
|
||||
/// (an object's, or a command buffer's queue), and the contexts it closes, and holds a
|
||||
/// `COMMAND_BUFFER` while its gate is shut.
|
||||
#[derive(Default)]
|
||||
struct CloseOrderHost {
|
||||
log: Arc<Mutex<Vec<(u32, u64)>>>,
|
||||
gate: Arc<AtomicBool>,
|
||||
in_buffer: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Host for CloseOrderHost {
|
||||
fn raise_interrupt(&self, _vector: u32) {}
|
||||
fn context_closed(&self, context: u32, answer: CompleteAnswer) {
|
||||
self.log
|
||||
.lock()
|
||||
.push((RGFX_CMD_CONTEXT_CLOSE, u64::from(context)));
|
||||
answer.answer(RGFX_STATUS_OK);
|
||||
}
|
||||
fn stage3_message(&self, _completion: &CompletionPoster, message: &[u8]) {
|
||||
let (header, _) = RgfxMsgHeader::read_from_prefix(message).unwrap();
|
||||
let id = RgfxObjectDestroy::read_from_prefix(message).map_or(0, |(m, _)| m.obj_id);
|
||||
self.log.lock().push((header.r#type, id));
|
||||
if header.r#type == RGFX_CMD_COMMAND_BUFFER {
|
||||
self.in_buffer.store(true, Ordering::SeqCst);
|
||||
while !self.gate.load(Ordering::SeqCst) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A queue's service thread hands the host the queue's `OBJECT_DESTROY` before its context's
|
||||
/// `CONTEXT_CLOSE` reaches the host, or not at all: a thread held in a command buffer while the
|
||||
/// guest destroys the queue and its process closes hands none after the close, which the host
|
||||
/// carries out dropping the queue with the context's objects. So no late destroy reaches a later
|
||||
/// process's queue of the same id once the kext gives the context's number out again
|
||||
#[test]
|
||||
fn a_closed_context_s_queue_hands_no_destroy_after_the_close() {
|
||||
let host = CloseOrderHost::default();
|
||||
let (log, gate, in_buffer) = (
|
||||
Arc::clone(&host.log),
|
||||
Arc::clone(&host.gate),
|
||||
Arc::clone(&host.in_buffer),
|
||||
);
|
||||
let mut rig = Rig::with_host(Box::new(host));
|
||||
rig.start();
|
||||
const QUEUE: u64 = (7 << RGFX_CONTEXT_OBJ_ID_SHIFT) | 1;
|
||||
let seqno = send_queue_create(&mut rig, QUEUE);
|
||||
assert_eq!(rig.complete(), (seqno, RGFX_STATUS_OK));
|
||||
wait_queue_idle(&rig);
|
||||
// Its thread in a command buffer the host holds.
|
||||
publish_command_buffer(&rig, QUEUE, 100, 55, true);
|
||||
assert!(
|
||||
eventually(|| in_buffer.load(Ordering::SeqCst)),
|
||||
"the buffer never reached the host"
|
||||
);
|
||||
// The guest destroys the queue, and its process closes: the close is carried out, and
|
||||
// answered, while the queue's thread is still in the buffer.
|
||||
rig.send(object_message(RGFX_CMD_OBJECT_DESTROY, QUEUE));
|
||||
let seqno = rig.send(context_close(7));
|
||||
assert_eq!(rig.complete(), (seqno, RGFX_STATUS_OK));
|
||||
assert_eq!(
|
||||
rig.device.queues_serving(),
|
||||
1,
|
||||
"the queue's thread is still in the buffer"
|
||||
);
|
||||
// The thread goes on, and ends.
|
||||
gate.store(true, Ordering::SeqCst);
|
||||
assert!(
|
||||
eventually(|| rig.device.queues_serving() == 0),
|
||||
"the queue's thread never ended"
|
||||
);
|
||||
let log = log.lock().clone();
|
||||
let closed = (log.iter())
|
||||
.position(|&e| e == (RGFX_CMD_CONTEXT_CLOSE, 7))
|
||||
.expect("the context closed");
|
||||
assert!(
|
||||
!log[closed..].contains(&(RGFX_CMD_OBJECT_DESTROY, QUEUE)),
|
||||
"a destroy handed after the close: {log:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A `COMMAND_BUFFER_IN_REGION` hands the host the whole `COMMAND_BUFFER` message in the block it
|
||||
/// names, with the reference's seqno, and the completion names that seqno; a reference to no
|
||||
/// block its process holds (none granted, another process's, its own once released), or to bytes
|
||||
@@ -5903,7 +5693,6 @@ fn the_host_is_told_each_time_the_driver_takes_the_pool() {
|
||||
#[derive(Clone, Default)]
|
||||
struct ReadyHost {
|
||||
ready: Arc<Mutex<Vec<u64>>>,
|
||||
ready_ext: Arc<Mutex<Vec<u32>>>,
|
||||
}
|
||||
|
||||
impl Host for ReadyHost {
|
||||
@@ -5911,12 +5700,8 @@ impl Host for ReadyHost {
|
||||
fn features(&self) -> u64 {
|
||||
RGFX_FEATURE_MANAGED_AT_COPY | RGFX_FEATURE_POOL
|
||||
}
|
||||
fn driver_ready(&self, taken: u64, taken_ext: u32) {
|
||||
fn driver_ready(&self, taken: u64) {
|
||||
self.ready.lock().push(taken);
|
||||
self.ready_ext.lock().push(taken_ext);
|
||||
}
|
||||
fn features_ext(&self) -> u32 {
|
||||
RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES | RGFX_FEATURE_EXT_SURFACE_HOLD
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5953,84 +5738,6 @@ fn the_host_is_told_the_driver_s_features_as_it_becomes_ready() {
|
||||
);
|
||||
}
|
||||
|
||||
/// `DRIVER_FEATURES_EXT` takes, before the driver is ready, the bits written that
|
||||
/// `FEATURES_EXT` offers and that are taken (`SURFACE_HOLD`, bit 2), never one used with no take
|
||||
/// (`SHARED_TEXTURE_NAMES`) nor one the host does not offer (bit 1, `SURFACE_HOLD` with its word
|
||||
/// in the block's header, which kexts built before the word moved take); a read answers the bits
|
||||
/// taken; a write while ready is ignored; the host is told them as the driver becomes ready
|
||||
/// ([`Host::driver_ready`]); a reset clears them
|
||||
#[test]
|
||||
fn driver_features_ext_takes_the_offered_taken_bits() {
|
||||
let host = ReadyHost::default();
|
||||
let rig = Rig::with_host(Box::new(host.clone()));
|
||||
let read = || rig.device.mmio_read(RGFX_REG_DRIVER_FEATURES_EXT.into());
|
||||
let write = |bits: u32| {
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_DRIVER_FEATURES_EXT.into(), bits);
|
||||
};
|
||||
assert_eq!(read(), 0);
|
||||
write(u32::MAX);
|
||||
assert_eq!(read(), RGFX_FEATURE_EXT_SURFACE_HOLD, "the taken bit alone");
|
||||
write(RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES);
|
||||
assert_eq!(read(), 0, "a bit used with no take is not taken");
|
||||
assert_eq!(RGFX_FEATURE_EXT_SURFACE_HOLD, 1 << 2);
|
||||
write(1 << 1);
|
||||
assert_eq!(
|
||||
read(),
|
||||
0,
|
||||
"the hold in the block's header, which an older kext takes: none"
|
||||
);
|
||||
write(RGFX_FEATURE_EXT_SURFACE_HOLD);
|
||||
rig.start();
|
||||
assert_eq!(*host.ready_ext.lock(), vec![RGFX_FEATURE_EXT_SURFACE_HOLD]);
|
||||
write(0);
|
||||
assert_eq!(read(), RGFX_FEATURE_EXT_SURFACE_HOLD, "fixed while ready");
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
|
||||
assert_eq!(read(), 0, "a reset clears it");
|
||||
rig.start();
|
||||
assert_eq!(
|
||||
*host.ready_ext.lock(),
|
||||
vec![RGFX_FEATURE_EXT_SURFACE_HOLD, 0]
|
||||
);
|
||||
|
||||
// A host that offers nothing there takes nothing.
|
||||
let plain = Rig::new();
|
||||
plain
|
||||
.device
|
||||
.mmio_write(RGFX_REG_DRIVER_FEATURES_EXT.into(), u32::MAX);
|
||||
assert_eq!(
|
||||
plain.device.mmio_read(RGFX_REG_DRIVER_FEATURES_EXT.into()),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
/// The hold's waker posts a `SURFACE_HOLD_LOWERED` of the block onto the control completion
|
||||
/// ring, `seqno` 0, once the driver is ready, and nothing before (`HoldWaker::lowered`)
|
||||
#[test]
|
||||
fn the_hold_waker_posts_the_block_s_lowered_hold() {
|
||||
let mut rig = Rig::new();
|
||||
let waker = rig.device.hold_waker();
|
||||
waker.lowered(0x4000);
|
||||
rig.start();
|
||||
waker.lowered(0x8000);
|
||||
let event = rig.event().expect("a SURFACE_HOLD_LOWERED");
|
||||
let lowered = RgfxSurfaceHoldLowered::read_from_bytes(&event).unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
lowered.header.r#type,
|
||||
lowered.header.size,
|
||||
lowered.header.seqno
|
||||
),
|
||||
(RGFX_EVT_SURFACE_HOLD_LOWERED, 24, 0)
|
||||
);
|
||||
assert_eq!(
|
||||
lowered.block_offset, 0x8000,
|
||||
"the one posted once ready alone"
|
||||
);
|
||||
assert!(rig.quiet_for(200));
|
||||
}
|
||||
|
||||
/// A `POOL_TAKE`'s `POOL_BLOCK` on `rig`: its status, offset, length and GPU address.
|
||||
fn pool_block(rig: &mut Rig, bytes: Vec<u8>) -> (u32, u64, u64, u64) {
|
||||
let seqno = rig.send(bytes);
|
||||
@@ -6306,160 +6013,3 @@ fn private_messages_go_to_the_decoder_where_the_driver_did_not_take_private_bloc
|
||||
[(RGFX_CMD_PRIVATE_TAKE, 0, 0), (RGFX_CMD_PRIVATE_GIVE, 0, 0)]
|
||||
);
|
||||
}
|
||||
|
||||
/// A host that records what the device tells it of the guest's drivers: how many drivers left at
|
||||
/// `VERSION` ([`Host::guest_driver_left`]) and each `GUEST_BUNDLE` ([`Host::guest_bundle`]).
|
||||
#[derive(Clone, Default)]
|
||||
struct DriversHost {
|
||||
left: Arc<AtomicU32>,
|
||||
bundles: Arc<Mutex<Vec<GuestBundle>>>,
|
||||
}
|
||||
|
||||
impl Host for DriversHost {
|
||||
fn raise_interrupt(&self, _vector: u32) {}
|
||||
fn guest_driver_left(&self) {
|
||||
self.left.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
fn guest_bundle(&self, bundle: GuestBundle) {
|
||||
self.bundles.lock().push(bundle);
|
||||
}
|
||||
}
|
||||
|
||||
/// `secs` seconds after now, on the device's clock.
|
||||
fn secs_on(secs: u64) -> u64 {
|
||||
now_ns() + secs * 1_000_000_000
|
||||
}
|
||||
|
||||
/// A driver that reads `VERSION` after the firmware started the device (`STATUS` 1), and reads
|
||||
/// or writes no other register in the 60 s after, left at its version check, as a kext of another
|
||||
/// wire version does: it reads `MAGIC`, `VERSION`, and `VERSION` again for its log line. The host
|
||||
/// is told on display 0's refresh once those 60 s have passed, not before, and once a reset: the
|
||||
/// next boot's, after the host's reset of the device and the firmware's start, is told again.
|
||||
#[test]
|
||||
fn a_driver_that_leaves_at_version_is_told_once_a_reset() {
|
||||
let host = DriversHost::default();
|
||||
let rig = Rig::with_host(Box::new(host.clone()));
|
||||
let left = || host.left.load(Ordering::SeqCst);
|
||||
let read = |offset: u32| rig.device.mmio_read(offset.into());
|
||||
let refresh = |secs: u64| rig.device.shared.refresh(0, secs_on(secs));
|
||||
// The option ROM: its reads come before its reset and start.
|
||||
read(RGFX_REG_MAGIC);
|
||||
read(RGFX_REG_VERSION);
|
||||
read(RGFX_REG_REGION_SIZE_LO);
|
||||
rig.start();
|
||||
// The old kext's framebuffer and accelerator.
|
||||
for _ in 0..2 {
|
||||
read(RGFX_REG_MAGIC);
|
||||
read(RGFX_REG_VERSION);
|
||||
read(RGFX_REG_VERSION);
|
||||
}
|
||||
refresh(59);
|
||||
assert_eq!(left(), 0, "not before 60 s");
|
||||
refresh(61);
|
||||
assert_eq!(left(), 1);
|
||||
refresh(200);
|
||||
read(RGFX_REG_VERSION);
|
||||
refresh(61);
|
||||
assert_eq!(left(), 1, "once a reset");
|
||||
// The guest's reboot: QEMU resets the device, and the firmware starts it again.
|
||||
rig.device.reset();
|
||||
rig.start();
|
||||
read(RGFX_REG_MAGIC);
|
||||
read(RGFX_REG_VERSION);
|
||||
refresh(61);
|
||||
assert_eq!(left(), 2);
|
||||
assert!(host.bundles.lock().is_empty());
|
||||
}
|
||||
|
||||
/// A driver of the host's version goes on after `VERSION`, its framebuffer reading
|
||||
/// `REGION_SIZE_HI` and its accelerator `REGION_SIZE_HI` too, as each one's start does
|
||||
/// (`start_order_test.cpp`), and is never told as one that left, however long the refreshes run;
|
||||
/// nor is a read of `VERSION` while the device is not started, as the option ROM's and Ambrosia's
|
||||
/// module's are, before their reset, nor one the host's reset of the device ends.
|
||||
#[test]
|
||||
fn a_driver_that_goes_on_after_version_is_not_told() {
|
||||
let host = DriversHost::default();
|
||||
let rig = Rig::with_host(Box::new(host.clone()));
|
||||
let left = || host.left.load(Ordering::SeqCst);
|
||||
let read = |offset: u32| rig.device.mmio_read(offset.into());
|
||||
let refresh = |secs: u64| rig.device.shared.refresh(0, secs_on(secs));
|
||||
// Not started: the firmware's reads.
|
||||
read(RGFX_REG_MAGIC);
|
||||
read(RGFX_REG_VERSION);
|
||||
refresh(120);
|
||||
assert_eq!(left(), 0);
|
||||
rig.start();
|
||||
// The framebuffer: on at once to the region's size, then its reset and start.
|
||||
read(RGFX_REG_MAGIC);
|
||||
read(RGFX_REG_VERSION);
|
||||
read(RGFX_REG_REGION_SIZE_HI);
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
|
||||
rig.start();
|
||||
// The accelerator, after the framebuffer's start.
|
||||
read(RGFX_REG_MAGIC);
|
||||
read(RGFX_REG_VERSION);
|
||||
read(RGFX_REG_REGION_SIZE_HI);
|
||||
refresh(120);
|
||||
assert_eq!(left(), 0);
|
||||
// A write after the read counts as going on as well, and so does a doorbell.
|
||||
read(RGFX_REG_VERSION);
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_GUEST_BUNDLE.into(), RGFX_GUEST_BUNDLE_OURS);
|
||||
read(RGFX_REG_VERSION);
|
||||
rig.device
|
||||
.mmio_write_taking(RGFX_REG_DOORBELL.into(), RGFX_CONTROL_RING_ID);
|
||||
refresh(120);
|
||||
assert_eq!(left(), 0);
|
||||
// The host's reset ends a watched read: the device is no longer started.
|
||||
read(RGFX_REG_VERSION);
|
||||
rig.device.reset();
|
||||
refresh(120);
|
||||
assert_eq!(left(), 0);
|
||||
}
|
||||
|
||||
/// `GUEST_BUNDLE` hands the host what the accelerator found, each field from its bits, at each
|
||||
/// write, and reads 0.
|
||||
#[test]
|
||||
fn guest_bundle_tells_the_host_what_the_accelerator_found() {
|
||||
let host = DriversHost::default();
|
||||
let rig = Rig::with_host(Box::new(host.clone()));
|
||||
let write = |value: u32| {
|
||||
rig.device.mmio_write(RGFX_REG_GUEST_BUNDLE.into(), value);
|
||||
};
|
||||
write(
|
||||
RGFX_GUEST_BUNDLE_OTHER_VERSION
|
||||
| 2 << RGFX_GUEST_BUNDLE_VERSION_SHIFT
|
||||
| RGFX_GATE_NO_DATA_VOLUME << RGFX_GUEST_BUNDLE_GATE_SHIFT,
|
||||
);
|
||||
write(
|
||||
RGFX_GUEST_BUNDLE_OTHER_VERSION
|
||||
| RGFX_GATE_FAILED << RGFX_GUEST_BUNDLE_GATE_SHIFT
|
||||
| 28 << RGFX_GUEST_BUNDLE_ERRNO_SHIFT,
|
||||
);
|
||||
write(RGFX_GUEST_BUNDLE_OURS | RGFX_GATE_PRESENT << RGFX_GUEST_BUNDLE_GATE_SHIFT);
|
||||
assert_eq!(
|
||||
*host.bundles.lock(),
|
||||
[
|
||||
GuestBundle {
|
||||
found: RGFX_GUEST_BUNDLE_OTHER_VERSION,
|
||||
version: 2,
|
||||
gate: RGFX_GATE_NO_DATA_VOLUME,
|
||||
errno: 0,
|
||||
},
|
||||
GuestBundle {
|
||||
found: RGFX_GUEST_BUNDLE_OTHER_VERSION,
|
||||
version: 0,
|
||||
gate: RGFX_GATE_FAILED,
|
||||
errno: 28,
|
||||
},
|
||||
GuestBundle {
|
||||
found: RGFX_GUEST_BUNDLE_OURS,
|
||||
version: 0,
|
||||
gate: RGFX_GATE_PRESENT,
|
||||
errno: 0,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(rig.device.mmio_read(RGFX_REG_GUEST_BUNDLE.into()), 0);
|
||||
}
|
||||
@@ -191,14 +191,8 @@ fn a_guest_that_did_not_take_multi_display_sees_display_0_alone() {
|
||||
rig.start();
|
||||
rig.send(get_displays());
|
||||
let bytes = rig.event().unwrap();
|
||||
assert_eq!(bytes.len(), 88);
|
||||
let n = NEVER_MHZ;
|
||||
assert_eq!(
|
||||
words(&bytes),
|
||||
[
|
||||
1, 0, 1, 0, 4, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n, 0
|
||||
]
|
||||
);
|
||||
assert_eq!(bytes.len(), 48);
|
||||
assert_eq!(words(&bytes), [1, 0, 1, 0, 1, 1280, 800, NEVER_MHZ]);
|
||||
let room = scanout_room(3);
|
||||
let image = RGFX_ALLOCATIONS_OFFSET + 0x1000;
|
||||
rig.region().write(image, &[0, 0, 0, 255]);
|
||||
@@ -250,8 +244,7 @@ fn a_guest_that_did_not_take_multi_display_sees_display_0_alone() {
|
||||
}
|
||||
|
||||
/// A guest that took `MULTI_DISPLAY` is told every display, ids 0 up, each connected, with the
|
||||
/// modes its own screen offers: its screen's first, preferred, then its smaller modes, at its
|
||||
/// own screen's rate
|
||||
/// mode its own screen offers as its one, preferred mode
|
||||
#[test]
|
||||
fn a_guest_that_took_multi_display_is_told_every_display_s_own_mode() {
|
||||
let mut rig = Rig::of_displays(3);
|
||||
@@ -270,136 +263,16 @@ fn a_guest_that_took_multi_display_is_told_every_display_s_own_mode() {
|
||||
rig.start();
|
||||
rig.send(get_displays());
|
||||
let bytes = rig.event().unwrap();
|
||||
assert_eq!(bytes.len(), 248);
|
||||
let n = NEVER_MHZ;
|
||||
let m = 60_000;
|
||||
assert_eq!(bytes.len(), 104);
|
||||
assert_eq!(
|
||||
words(&bytes),
|
||||
[
|
||||
3, //
|
||||
0, 1, 0, 4, 1280, 800, n, 1120, 700, n, 992, 620, n, 960, 600, n, //
|
||||
1, 1, 0, 5, 1920, 1080, m, 1680, 944, m, 1504, 846, m, 1440, 810, m, 1280, 720,
|
||||
m, //
|
||||
2, 1, 0, 6, 2560, 1440, n, 2240, 1260, n, 2000, 1124, n, 1920, 1080, n, 1696, 954,
|
||||
n, //
|
||||
1280, 720, n,
|
||||
3, 0, 1, 0, 1, 1280, 800, NEVER_MHZ, 1, 1, 0, 1, 1920, 1080, 60_000, 2, 1, 0, 1, 2560,
|
||||
1440, NEVER_MHZ
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The modes of each display in `bytes`, a `DISPLAYS` answer whose records carry a scale where
|
||||
/// `scaled`, read as the guest's kext reads them (`RgfxDisplayTable.hpp`, `rgfxListDisplays`):
|
||||
/// each display's id, its scale (0 where there is none) and the mode records its count says
|
||||
/// follow it. The records end at the answer's padding, under 8 bytes of zeros.
|
||||
fn listed(bytes: &[u8], scaled: bool) -> Vec<(u32, u32, Vec<[u32; 3]>)> {
|
||||
let words = words(bytes);
|
||||
let mut at = 1;
|
||||
let mut displays = Vec::new();
|
||||
for _ in 0..words[0] {
|
||||
let (id, connected, preferred, count) =
|
||||
(words[at], words[at + 1], words[at + 2], words[at + 3]);
|
||||
assert_eq!((connected, preferred), (1, 0), "display {id}");
|
||||
at += 4;
|
||||
let scale = if scaled {
|
||||
at += 2;
|
||||
words[at - 2]
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let modes = (0..count as usize)
|
||||
.map(|i| {
|
||||
[
|
||||
words[at + 3 * i],
|
||||
words[at + 3 * i + 1],
|
||||
words[at + 3 * i + 2],
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
at += 3 * count as usize;
|
||||
displays.push((id, scale, modes));
|
||||
}
|
||||
assert!(
|
||||
words.len() - at < 2,
|
||||
"{} words past the records",
|
||||
words.len() - at
|
||||
);
|
||||
assert!(words[at..].iter().all(|&w| w == 0), "the padding is zeros");
|
||||
displays
|
||||
}
|
||||
|
||||
/// Each display's mode count is the mode records that follow it, which are the modes it offers
|
||||
/// (`display::offered_modes`) at its screen's rate, after its scale where the guest took
|
||||
/// `DISPLAY_SCALE`, on devices of one to four displays: the guest's walk of the records ends at
|
||||
/// the answer's end
|
||||
#[test]
|
||||
fn each_display_s_mode_count_is_the_records_that_follow_it() {
|
||||
struct Scales;
|
||||
impl Host for Scales {
|
||||
fn raise_interrupt(&self, _vector: u32) {}
|
||||
fn features(&self) -> u64 {
|
||||
RGFX_FEATURE_DISPLAY_SCALE
|
||||
}
|
||||
}
|
||||
let screens = [
|
||||
Mode {
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
refresh_mhz: 120_000,
|
||||
scale_120ths: 240,
|
||||
},
|
||||
Mode {
|
||||
width: 1280,
|
||||
height: 720,
|
||||
refresh_mhz: 59_940,
|
||||
scale_120ths: 120,
|
||||
},
|
||||
Mode {
|
||||
width: 3072,
|
||||
height: 1920,
|
||||
refresh_mhz: 60_000,
|
||||
scale_120ths: 180,
|
||||
},
|
||||
Mode {
|
||||
width: 7680,
|
||||
height: 4320,
|
||||
refresh_mhz: 144_000,
|
||||
scale_120ths: 120,
|
||||
},
|
||||
];
|
||||
for count in 1..=4 {
|
||||
for scaled in [false, true] {
|
||||
let mut rig = Rig::with_displays(Box::new(Scales), Lanes::default(), count);
|
||||
*rig.mode.lock() = screens[0];
|
||||
for (i, (mode, _)) in rig.more.iter().enumerate() {
|
||||
*mode.lock() = screens[i + 1];
|
||||
}
|
||||
let mut took = 0;
|
||||
if count > 1 {
|
||||
took |= RGFX_FEATURE_MULTI_DISPLAY;
|
||||
}
|
||||
if scaled {
|
||||
took |= RGFX_FEATURE_DISPLAY_SCALE;
|
||||
}
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_DRIVER_FEATURES_HI.into(), (took >> 32) as u32);
|
||||
rig.start();
|
||||
rig.send(get_displays());
|
||||
let listed = listed(&rig.event().unwrap(), scaled);
|
||||
assert_eq!(listed.len(), count, "{count} displays");
|
||||
for (i, (id, scale, modes)) in listed.into_iter().enumerate() {
|
||||
let offered = crate::display::offered_modes(screens[i], count as u32);
|
||||
assert_eq!(id, i as u32);
|
||||
assert_eq!(scale, if scaled { screens[i].scale_120ths } else { 0 });
|
||||
let want: Vec<[u32; 3]> = (offered.iter())
|
||||
.map(|m| [m.width, m.height, screens[i].refresh_mhz])
|
||||
.collect();
|
||||
assert_eq!(modes, want, "display {i} of {count}, scaled {scaled}");
|
||||
assert!(modes.len() > 1, "display {i} of {count}: smaller modes");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each display's scanout, cursor and panel reach its own screen alone, and its state is its own
|
||||
#[test]
|
||||
fn each_display_s_commands_reach_its_own_screen() {
|
||||
@@ -512,8 +385,8 @@ fn a_display_offers_the_largest_mode_its_room_holds() {
|
||||
four.start();
|
||||
four.send(get_displays());
|
||||
let words = words(&four.event().unwrap());
|
||||
assert_eq!(words[4..8], [4, 1280, 800, NEVER_MHZ]);
|
||||
assert_eq!(words[20..24], [7, 3840, 2160, NEVER_MHZ]);
|
||||
assert_eq!(words[5..8], [1280, 800, NEVER_MHZ]);
|
||||
assert_eq!(words[12..15], [3840, 2160, NEVER_MHZ]);
|
||||
}
|
||||
|
||||
/// Each display's `VBLANK`s and `DISPLAY_CHANGED` carry its id, its `VBLANK`s on while the guest
|
||||
@@ -976,7 +849,7 @@ fn placed(scale: u32, x1: i32, y1: i32) -> Rig {
|
||||
rig
|
||||
}
|
||||
|
||||
/// A drag's pointer held at an edge of display 0's window where the guest's desktop puts
|
||||
/// The captured pointer held at an edge of display 0's window where the guest's desktop puts
|
||||
/// display 1 goes on onto display 1, as the guest arranged them, its moves scaled as over display
|
||||
/// 0's window, and comes back across the same edge; edges no display meets hold it
|
||||
#[test]
|
||||
|
||||
@@ -199,170 +199,6 @@ fn a_guest_that_sees_one_display_hides_its_cursor_there() {
|
||||
assert!(link.cursor_hidden_for().is_some());
|
||||
}
|
||||
|
||||
/// A `HIDDEN_PLACES` saying the guest reports where its hidden cursor goes (`reports`), or not,
|
||||
/// carried out: it carries out the answered `GET_DISPLAYS` after it.
|
||||
fn hidden_places(rig: &mut Rig, reports: bool) {
|
||||
let command = RgfxHiddenPlaces {
|
||||
header: RgfxMsgHeader {
|
||||
r#type: RGFX_CMD_HIDDEN_PLACES,
|
||||
..Default::default()
|
||||
},
|
||||
reports: u32::from(reports),
|
||||
reserved_14: 0,
|
||||
};
|
||||
moved(rig, command.as_bytes().to_vec());
|
||||
}
|
||||
|
||||
/// The next event, as a `POINTER_LOOK`: its display.
|
||||
fn look(rig: &mut Rig) -> u32 {
|
||||
let l = RgfxPointerLook::read_from_bytes(&rig.event().expect("a POINTER_LOOK")).unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
l.header.r#type,
|
||||
l.header.size,
|
||||
l.header.seqno,
|
||||
l.reserved_14
|
||||
),
|
||||
(RGFX_EVT_POINTER_LOOK, 24, 0, 0)
|
||||
);
|
||||
l.display
|
||||
}
|
||||
|
||||
/// A guest that reports where its hidden cursor goes (`HIDDEN_PLACES`) has a hide counted as a
|
||||
/// game's only once it reports its hidden cursor at a new place (a `MOVE_CURSOR` of the cursor
|
||||
/// still hidden): the tablet's moves of a game's hidden cursor move it (lane sharecur, potluck
|
||||
/// jobs m3-max-78716 and m3-max-78811). Until then the window's pointer is the tablet's, and each
|
||||
/// move of it over the window sends `POINTER_LOOK`, one every 50 ms at most, which has the guest
|
||||
/// read where its hidden cursor went; none goes while the cursor shows, nor once it followed.
|
||||
/// A show, and the next hide, count afresh
|
||||
#[test]
|
||||
fn a_hide_whose_cursor_follows_the_tablet_is_a_games() {
|
||||
let mut rig = motion_rig(1);
|
||||
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
|
||||
let link = rig.device.pointer_link();
|
||||
hidden_places(&mut rig, true);
|
||||
link.tablet_moved(0);
|
||||
assert!(
|
||||
rig.quiet_for(20),
|
||||
"no look before the guest moved its cursor"
|
||||
);
|
||||
moved(&mut rig, cursor_of(0, 100, 100, true));
|
||||
link.tablet_moved(0);
|
||||
assert!(rig.quiet_for(20), "no look while it shows");
|
||||
moved(&mut rig, cursor_of(0, 100, 100, false));
|
||||
assert_eq!(
|
||||
link.cursor_hidden_for(),
|
||||
None,
|
||||
"a hide the tablet has not moved"
|
||||
);
|
||||
link.tablet_moved(0);
|
||||
assert_eq!(look(&mut rig), 0);
|
||||
link.tablet_moved(0);
|
||||
assert!(rig.quiet_for(20), "one look every 50 ms at most");
|
||||
moved(&mut rig, cursor_of(0, 100, 100, false));
|
||||
assert_eq!(
|
||||
link.cursor_hidden_for(),
|
||||
None,
|
||||
"reported where the hide left it"
|
||||
);
|
||||
moved(&mut rig, cursor_of(0, 130, 115, false));
|
||||
assert!(
|
||||
link.cursor_hidden_for().is_some(),
|
||||
"reported where the tablet put it: a game's"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(60));
|
||||
link.tablet_moved(0);
|
||||
assert!(rig.quiet_for(20), "no look once it followed");
|
||||
moved(&mut rig, cursor_of(0, 140, 120, true));
|
||||
assert_eq!(link.cursor_hidden_for(), None, "shown");
|
||||
moved(&mut rig, cursor_of(0, 140, 120, false));
|
||||
assert_eq!(link.cursor_hidden_for(), None, "a new hide counts afresh");
|
||||
link.tablet_moved(0);
|
||||
assert_eq!(look(&mut rig), 0, "and looks at its first move");
|
||||
}
|
||||
|
||||
/// A hide whose cursor stays where the hide left it while the tablet moves is a system
|
||||
/// recording's: macOS draws the cursor into the recording and leaves the hidden cursor's place
|
||||
/// alone (lane sharecur, potluck job m3-max-78811, x86-64 26.7.2). It is never counted a game's,
|
||||
/// so the window's pointer stays the tablet's, absolute, and the guest is asked again every 50 ms
|
||||
/// while the tablet moves
|
||||
#[test]
|
||||
fn a_hide_whose_cursor_stays_put_under_the_tablet_is_no_games() {
|
||||
let mut rig = motion_rig(1);
|
||||
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
|
||||
let link = rig.device.pointer_link();
|
||||
hidden_places(&mut rig, true);
|
||||
moved(&mut rig, cursor_of(0, 2922, 1952, true));
|
||||
moved(&mut rig, cursor_of(0, 2922, 1952, false));
|
||||
for _ in 0..3 {
|
||||
link.tablet_moved(0);
|
||||
assert_eq!(look(&mut rig), 0);
|
||||
assert_eq!(link.cursor_hidden_for(), None, "never a game's");
|
||||
std::thread::sleep(Duration::from_millis(60));
|
||||
}
|
||||
}
|
||||
|
||||
/// A guest that reports no hidden places (a kext built before `HIDDEN_PLACES`, which sends none,
|
||||
/// or one that says 0) hides as before: its hide counts from the hide, and it is sent no
|
||||
/// `POINTER_LOOK`; a reset forgets a guest's report, until it sends another
|
||||
#[test]
|
||||
fn a_guest_that_reports_no_hidden_places_hides_as_before() {
|
||||
let mut rig = motion_rig(1);
|
||||
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
|
||||
let link = rig.device.pointer_link();
|
||||
moved(&mut rig, cursor_of(0, 100, 100, true));
|
||||
moved(&mut rig, cursor_of(0, 100, 100, false));
|
||||
assert!(link.cursor_hidden_for().is_some(), "no HIDDEN_PLACES");
|
||||
link.tablet_moved(0);
|
||||
assert!(rig.quiet_for(20), "no look");
|
||||
hidden_places(&mut rig, false);
|
||||
moved(&mut rig, cursor_of(0, 120, 110, true));
|
||||
moved(&mut rig, cursor_of(0, 120, 110, false));
|
||||
assert!(link.cursor_hidden_for().is_some(), "HIDDEN_PLACES of 0");
|
||||
link.tablet_moved(0);
|
||||
assert!(rig.quiet_for(20), "no look");
|
||||
hidden_places(&mut rig, true);
|
||||
rig.device
|
||||
.mmio_write(RGFX_REG_STATUS.into(), RGFX_STATUS_RESET);
|
||||
(rig.produced, rig.consumed, rig.seqno) = (0, 0, 0);
|
||||
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
|
||||
moved(&mut rig, cursor_of(0, 130, 115, true));
|
||||
moved(&mut rig, cursor_of(0, 130, 115, false));
|
||||
assert!(
|
||||
link.cursor_hidden_for().is_some(),
|
||||
"the reset forgot the report"
|
||||
);
|
||||
link.tablet_moved(0);
|
||||
assert!(rig.quiet_for(20), "no look");
|
||||
}
|
||||
|
||||
/// A move of a cursor the guest hid already shows nothing: it is the device's alone (the guest's
|
||||
/// report of its hidden cursor), and the display's screen is told of the hide and the show, not
|
||||
/// of the moves between
|
||||
#[test]
|
||||
fn a_hidden_cursors_moves_are_not_the_screens() {
|
||||
let mut rig = motion_rig(1);
|
||||
take_and_start(&rig, RGFX_FEATURE_POINTER_MOTION);
|
||||
moved(&mut rig, cursor_of(0, 100, 100, true));
|
||||
moved(&mut rig, cursor_of(0, 100, 100, false));
|
||||
moved(&mut rig, cursor_of(0, 130, 115, false));
|
||||
moved(&mut rig, cursor_of(0, 160, 130, false));
|
||||
moved(&mut rig, cursor_of(0, 170, 135, true));
|
||||
let moves: Vec<Told> = rig
|
||||
.told()
|
||||
.into_iter()
|
||||
.filter(|told| matches!(told, Told::Moved(..)))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
moves,
|
||||
[
|
||||
Told::Moved(100, 100, true),
|
||||
Told::Moved(100, 100, false),
|
||||
Told::Moved(170, 135, true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Each `POINTER_MOTION` the window sends reaches the guest that took it as it was sent: motion,
|
||||
/// wheel and buttons
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
read MAGIC = 0x58464752
|
||||
read VERSION = 0x3
|
||||
read VERSION = 0x2
|
||||
read REGION_SIZE_HI = 0x0
|
||||
read REGION_SIZE_LO = 0x40000000
|
||||
read FEATURES_LO = 0x7
|
||||
@@ -15,7 +15,7 @@ arm ring0 recheck empty
|
||||
post ring0 GET_DISPLAYS seqno=1 size=16
|
||||
write DOORBELL = 0x0
|
||||
interrupt 0
|
||||
take ring0 DISPLAYS seqno=1 size=88 0x1 0x1 0x50000000004 0x100000320 0x2bc00000460 0x3e000000001 0x10000026c 0x258000003c0 0x1
|
||||
take ring0 DISPLAYS seqno=1 size=48 0x1 0x1 0x50000000001 0x100000320
|
||||
arm ring0 recheck empty
|
||||
post ring0 0x7777 seqno=2 size=24 0x0
|
||||
write DOORBELL = 0x0
|
||||
@@ -23,7 +23,7 @@ interrupt 0
|
||||
take ring0 COMPLETE seqno=2 size=24 0x1
|
||||
arm ring0 recheck empty
|
||||
header ring0.submit +0x00=0x28 +0x40=0x28 +0x80=0x1
|
||||
header ring0.complete +0x00=0x70 +0x40=0x70 +0xc0=0x1
|
||||
header ring0.complete +0x00=0x48 +0x40=0x48 +0xc0=0x1
|
||||
header queue.submit
|
||||
header queue.complete
|
||||
post ring0 BLOCK_GRANT seqno=3 size=40 0x7 0x8400000 0x10100
|
||||
@@ -37,7 +37,7 @@ take ring0 COMPLETE seqno=5 size=24 0x0
|
||||
arm ring0 recheck empty
|
||||
arm queueA recheck empty
|
||||
header ring0.submit +0x00=0xb0 +0x40=0xb0 +0x80=0x1
|
||||
header ring0.complete +0x00=0x88 +0x40=0x88 +0xc0=0x1
|
||||
header ring0.complete +0x00=0x60 +0x40=0x60 +0xc0=0x1
|
||||
header queue.submit +0x80=0x1
|
||||
header queue.complete +0xc0=0x1
|
||||
post queueA COMMAND_BUFFER seqno=1 size=40 0x70000000001 0x100 0x0
|
||||
@@ -53,7 +53,7 @@ take queueA CB_COMPLETE seqno=2 size=48 0x101 0x0 0x0 0x0
|
||||
take queueA CB_COMPLETE seqno=3 size=48 0x102 0x0 0x0 0x0
|
||||
arm queueA recheck empty
|
||||
header ring0.submit +0x00=0xb0 +0x40=0xb0 +0x80=0x1
|
||||
header ring0.complete +0x00=0x88 +0x40=0x88 +0xc0=0x1
|
||||
header ring0.complete +0x00=0x60 +0x40=0x60 +0xc0=0x1
|
||||
header queue.submit +0x00=0x78 +0x40=0x78 +0x80=0x1
|
||||
header queue.complete +0x00=0x90 +0x08=0x3 +0x40=0x90 +0xc0=0x1
|
||||
post ring0 OBJECT_DESTROY seqno=6 size=24 0x70000000001
|
||||
@@ -61,10 +61,10 @@ write DOORBELL = 0x0
|
||||
post ring0 GET_DISPLAYS seqno=7 size=16
|
||||
write DOORBELL = 0x0
|
||||
interrupt 0
|
||||
take ring0 DISPLAYS seqno=7 size=88 0x1 0x1 0x50000000004 0x100000320 0x2bc00000460 0x3e000000001 0x10000026c 0x258000003c0 0x1
|
||||
take ring0 DISPLAYS seqno=7 size=48 0x1 0x1 0x50000000001 0x100000320
|
||||
arm ring0 recheck empty
|
||||
header ring0.submit +0x00=0xd8 +0x40=0xd8 +0x80=0x1
|
||||
header ring0.complete +0x00=0xe0 +0x40=0xe0 +0xc0=0x1
|
||||
header ring0.complete +0x00=0x90 +0x40=0x90 +0xc0=0x1
|
||||
header queue.submit +0x00=0x78 +0x40=0x78 +0x80=0x1
|
||||
header queue.complete +0x00=0x90 +0x08=0x3 +0x40=0x90 +0xc0=0x1
|
||||
post ring0 QUEUE_CREATE seqno=8 size=56 0x70000000002 0x8400000 0x8500000 0x1000000010000 0x300000002
|
||||
@@ -74,7 +74,7 @@ take ring0 COMPLETE seqno=8 size=24 0x0
|
||||
arm ring0 recheck empty
|
||||
arm queueB recheck empty
|
||||
header ring0.submit +0x00=0x110 +0x40=0x110 +0x80=0x1
|
||||
header ring0.complete +0x00=0xf8 +0x40=0xf8 +0xc0=0x1
|
||||
header ring0.complete +0x00=0xa8 +0x40=0xa8 +0xc0=0x1
|
||||
header queue.submit +0x80=0x1
|
||||
header queue.complete +0xc0=0x1
|
||||
post queueB COMMAND_BUFFER seqno=1 size=40 0x70000000002 0x200 0x0
|
||||
@@ -83,7 +83,7 @@ interrupt 3
|
||||
take queueB CB_COMPLETE seqno=1 size=48 0x200 0x0 0x0 0x0
|
||||
arm queueB recheck empty
|
||||
header ring0.submit +0x00=0x110 +0x40=0x110 +0x80=0x1
|
||||
header ring0.complete +0x00=0xf8 +0x40=0xf8 +0xc0=0x1
|
||||
header ring0.complete +0x00=0xa8 +0x40=0xa8 +0xc0=0x1
|
||||
header queue.submit +0x00=0x28 +0x40=0x28 +0x80=0x1
|
||||
header queue.complete +0x00=0x30 +0x08=0x1 +0x40=0x30 +0xc0=0x1
|
||||
post ring0 CONTEXT_CLOSE seqno=9 size=24 0x7
|
||||
@@ -92,7 +92,7 @@ interrupt 0
|
||||
take ring0 COMPLETE seqno=9 size=24 0x0
|
||||
arm ring0 recheck empty
|
||||
header ring0.submit +0x00=0x128 +0x40=0x128 +0x80=0x1
|
||||
header ring0.complete +0x00=0x110 +0x40=0x110 +0xc0=0x1
|
||||
header ring0.complete +0x00=0xc0 +0x40=0xc0 +0xc0=0x1
|
||||
header queue.submit +0x00=0x28 +0x40=0x28 +0x80=0x1
|
||||
header queue.complete +0x00=0x30 +0x08=0x1 +0x40=0x30 +0xc0=0x1
|
||||
write STATUS = 0x0
|
||||
|
||||
@@ -195,32 +195,6 @@ fn an_unreadable_vt_message_is_answered_malformed() {
|
||||
assert!(handed.lock().is_empty() && taken_handed.lock().is_empty());
|
||||
}
|
||||
|
||||
/// An unreadable `VT_MESSAGE` whose struct reads gives back the lends it names, as a `rels` before
|
||||
/// its `VT_STATUS`: the guest's kext holds each lend of a message it posted until a `rels` names
|
||||
/// it, and the host never sees this one. One that names none gets no `rels`, and neither does a
|
||||
/// guest that did not take `VT_MESSAGES`, which sends none
|
||||
#[test]
|
||||
fn an_unreadable_vt_message_gives_back_the_lends_it_names() {
|
||||
let (mut rig, handed) = vt_rig();
|
||||
take_and_start(&rig, RGFX_FEATURE_VT_MESSAGES);
|
||||
let seqno = rig.send(vt_message(0x4001, &[(0x4000, 0x4000)], &[7, 9]));
|
||||
let mut release = 24u32.to_be_bytes().to_vec();
|
||||
release.extend_from_slice(b"rels");
|
||||
release.extend_from_slice(&7u64.to_be_bytes());
|
||||
release.extend_from_slice(&9u64.to_be_bytes());
|
||||
assert_eq!(vt_event(&mut rig), release);
|
||||
assert_eq!(status(&mut rig), (seqno, RGFX_VT_STATUS_MALFORMED));
|
||||
let seqno = rig.send(vt_message(0x4001, &[(0x4000, 0x4000)], &[]));
|
||||
assert_eq!(status(&mut rig), (seqno, RGFX_VT_STATUS_MALFORMED));
|
||||
|
||||
let (mut untaken, untaken_handed) = vt_rig();
|
||||
untaken.start();
|
||||
let seqno = untaken.send(vt_message(64, &[(0x4000, 0x4000)], &[7]));
|
||||
assert_eq!(status(&mut untaken), (seqno, RGFX_VT_STATUS_MALFORMED));
|
||||
assert!(untaken.quiet_for(20));
|
||||
assert!(handed.lock().is_empty() && untaken_handed.lock().is_empty());
|
||||
}
|
||||
|
||||
/// A host message is dropped for a guest that did not take `VT_MESSAGES` and once the device is
|
||||
/// reset, and a link made before the reset says it is stale.
|
||||
#[test]
|
||||
|
||||
@@ -110,32 +110,6 @@ impl VtLink {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `rels` box that gives back the lends a `VT_MESSAGE` the device could not read names
|
||||
/// ([`read_message`]), where its struct reads and names any: its big-endian size, `rels`, then
|
||||
/// each nonzero lend of its first `surface_count` (at most [`RGFX_VT_MESSAGE_SURFACES`]),
|
||||
/// big-endian. The guest's kext holds each lend of a message it posted until a `rels` names it,
|
||||
/// so a message the host never sees would hold them to the kext's stop. `None` where the struct
|
||||
/// does not read or names no lend.
|
||||
pub(crate) fn unread_lends_release(message: &Message) -> Option<Vec<u8>> {
|
||||
let (command, _) = RgfxVtMessage::read_from_prefix(&message.bytes).ok()?;
|
||||
let lends: Vec<u64> = (command.surfaces.iter())
|
||||
.take(command.surface_count as usize)
|
||||
.copied()
|
||||
.filter(|&lend| lend != 0)
|
||||
.collect();
|
||||
if lends.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let size = u32::try_from(8 + 8 * lends.len()).ok()?;
|
||||
let mut release = Vec::with_capacity(size as usize);
|
||||
release.extend_from_slice(&size.to_be_bytes());
|
||||
release.extend_from_slice(b"rels");
|
||||
for lend in lends {
|
||||
release.extend_from_slice(&lend.to_be_bytes());
|
||||
}
|
||||
Some(release)
|
||||
}
|
||||
|
||||
/// A `VT_MESSAGE`'s answer: `VT_STATUS` with `status`.
|
||||
pub(crate) fn vt_status(seqno: u64, status: i32) -> Vec<u8> {
|
||||
RgfxVtStatus {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
//! The device's display as the guest drives it, and [`Screen`], what shows it on the host: the
|
||||
//! window of `reims-vgpu`'s glue, or a fixed mode with nothing shown ([`FixedScreen`]).
|
||||
//!
|
||||
//! **Modes.** The display offers first, and prefers, the screen's size and refresh rate
|
||||
//! ([`Screen::mode`]), which for a window is its size in pixels at its host screen's rate, with
|
||||
//! the host screen's scale, which a guest that took `DISPLAY_SCALE` is told after the display's
|
||||
//! record (`RgfxDisplayScale`). After it come the smaller modes of its ratio at a Mac's steps
|
||||
//! ([`offered_modes`]), each at the same rate: the guest runs at the host screen's rate whichever
|
||||
//! it picks, and a window keeps its size at a smaller mode and shows it scaled to fill it
|
||||
//! (`reims-vgpu`'s `graphics::sink`). When the screen's mode changes (the window resized, or
|
||||
//! moved to a screen of another scale), the device tells the guest with `DISPLAY_CHANGED`, and
|
||||
//! the guest asks `GET_DISPLAYS` again (`refresh`); the smaller modes follow the first.
|
||||
//! **Modes.** The display offers one mode: the screen's size and refresh rate ([`Screen::mode`]),
|
||||
//! which for a window is its size in pixels at its host screen's rate, with the host screen's
|
||||
//! scale, which a guest that took `DISPLAY_SCALE` is told after the display's record
|
||||
//! (`RgfxDisplayScale`). The guest runs at the host screen's rate. When the screen's mode changes
|
||||
//! (the window resized, or moved to a screen of another scale), the device tells the guest with
|
||||
//! `DISPLAY_CHANGED`, and the guest asks `GET_DISPLAYS` again (`refresh`).
|
||||
//!
|
||||
//! **Scanout.** `SET_SCANOUT` names the pixels the display shows, in the scanout's room of the
|
||||
//! region (`RGFX_SCANOUT_SPAN` bytes at `RGFX_ALLOCATIONS_OFFSET`, before the processes' blocks,
|
||||
@@ -34,9 +31,8 @@
|
||||
//! each with a [`Screen`] of its own (docs/graphics-kext/design.md, "Multiple displays"). Each
|
||||
//! display's scanout lies in a room of its own: the scanout's room split evenly among them
|
||||
//! ([`scanout_room`], [`scanout_room_at`]), so one display keeps the whole room, as before any
|
||||
//! display had a room of its own. On a device of more than one display each display offers first
|
||||
//! display had a room of its own. On a device of more than one display each display offers only
|
||||
//! a mode whose scanout fits its room ([`offered_in_room`]); with one, the screen's mode as it is.
|
||||
//! Each smaller mode is offered only where its scanout fits the room.
|
||||
|
||||
pub(crate) mod cursor_color;
|
||||
|
||||
@@ -102,77 +98,6 @@ pub fn offered_in_room(mode: Mode, count: u32) -> Mode {
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps of a display's smaller modes, largest first: each a fraction of its first mode's
|
||||
/// width, so that a 3840 × 2160 screen is offered 3360 × 1890, 3008 × 1692, 2880 × 1620,
|
||||
/// 2560 × 1440, 1920 × 1080 and 1440 × 810 below its own. They come from two sources:
|
||||
/// - 7/8, 3/4, 1/2 and 3/8 are steps of the modes of its own ratio a Mac's built-in panel lists
|
||||
/// below its native one: CoreGraphics lists the 3072 × 1920 panel of a MacBook Pro 16-inch
|
||||
/// (2019, macOS 26.7.1) at 2688 × 1680, 2304 × 1440, 1536 × 960, 1440 × 900, 1280 × 800 and
|
||||
/// 1152 × 720 below it (`CGDisplayCopyAllDisplayModes`, measured 2026-12-02);
|
||||
/// - 47/60 and 2/3 are the steps of 3008 × 1692 and 2560 × 1440, which a Mac lists for an
|
||||
/// external 3840 × 2160 screen, taken from a user's report and from what is known of that
|
||||
/// list; they were not read on a Mac of ours.
|
||||
///
|
||||
/// That panel's 15/32 and 5/12 (1440 × 900 and 1280 × 800) are left out as near twins of 1/2,
|
||||
/// and so are the 1650 × 1050 it lists, of another ratio, and the 3584 × 2240 above its native
|
||||
/// mode.
|
||||
const SMALLER_MODE_STEPS: [(u64, u64); 6] = [(7, 8), (47, 60), (3, 4), (2, 3), (1, 2), (3, 8)];
|
||||
|
||||
/// The smallest smaller mode a display offers, its longer side then its shorter: the smallest a
|
||||
/// Mac takes for its desktop. On that MacBook Pro CoreGraphics lists 800 × 600 usable for the
|
||||
/// desktop and 840 × 524 and 640 × 480 not (`CGDisplayModeIsUsableForDesktopGUI`); a portrait
|
||||
/// screen's modes take the floor turned.
|
||||
const SMALLER_MODE_FLOOR: (u32, u32) = (800, 600);
|
||||
|
||||
// A host-side bound: the guest reads each display's count from the answer, so cbindgen leaves it out of
|
||||
// the wire header.
|
||||
/// The most modes a display offers, its first among them.
|
||||
/// cbindgen:ignore
|
||||
pub const MODES_MAX: usize = 8;
|
||||
|
||||
// The first mode and one for each step fit.
|
||||
const _: () = assert!(SMALLER_MODE_STEPS.len() < MODES_MAX);
|
||||
|
||||
/// The modes a display whose screen offers `mode` offers its guest on a device of `count`
|
||||
/// displays, at most [`MODES_MAX`]: first the mode [`offered_in_room`] gives, which the guest
|
||||
/// prefers, then each smaller mode of its ratio at [`SMALLER_MODE_STEPS`] that is at least
|
||||
/// [`SMALLER_MODE_FLOOR`] and whose scanout fits the display's room ([`scanout_room`], rows laid
|
||||
/// out as [`laid_out`] says), largest first. A smaller mode is a multiple of 16 pixels wide and an
|
||||
/// even number high (the steps of a window's offered modes, `reims-vgpu-window`'s
|
||||
/// `geometry::offered_mode`): its width is the step's fraction of the first mode's, rounded down
|
||||
/// to a multiple of 16, and its height the first mode's ratio of that width, rounded down to
|
||||
/// even. Every mode has the first's refresh rate and scale.
|
||||
pub fn offered_modes(mode: Mode, count: u32) -> Vec<Mode> {
|
||||
let first = offered_in_room(mode, count);
|
||||
let mut modes = vec![first];
|
||||
let (w, h) = (u64::from(first.width), u64::from(first.height));
|
||||
if w == 0 || h == 0 {
|
||||
return modes;
|
||||
}
|
||||
let room = scanout_room(count);
|
||||
for (numerator, denominator) in SMALLER_MODE_STEPS {
|
||||
let width = (w * numerator / denominator) & !15;
|
||||
let height = (width * h / w) & !1;
|
||||
let (Ok(width), Ok(height)) = (u32::try_from(width), u32::try_from(height)) else {
|
||||
continue;
|
||||
};
|
||||
let (longer, shorter) = (width.max(height), width.min(height));
|
||||
if longer < SMALLER_MODE_FLOOR.0
|
||||
|| shorter < SMALLER_MODE_FLOOR.1
|
||||
|| laid_out(width, height) > room
|
||||
|| modes.iter().any(|m| (m.width, m.height) == (width, height))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
modes.push(Mode {
|
||||
width,
|
||||
height,
|
||||
..first
|
||||
});
|
||||
}
|
||||
modes
|
||||
}
|
||||
|
||||
/// A display mode: pixels each way and a refresh rate, and the scale of the host screen that
|
||||
/// shows it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -240,9 +165,8 @@ pub struct CursorImage {
|
||||
/// (the control thread and the refresh thread, never inside a call of the host's) and must not
|
||||
/// wait for the device.
|
||||
pub trait Screen: Send + Sync + 'static {
|
||||
/// The mode the display offers first now, which the guest prefers: for a window, its size in
|
||||
/// pixels at its host screen's refresh rate, with that screen's scale. Asked at
|
||||
/// `GET_DISPLAYS`, where the smaller modes follow from it ([`offered_modes`]), and at each
|
||||
/// The one mode the display offers now: for a window, its size in pixels at its host
|
||||
/// screen's refresh rate, with that screen's scale. Asked at `GET_DISPLAYS`, and at each
|
||||
/// refresh, where a change is told to the guest.
|
||||
fn mode(&self) -> Mode;
|
||||
|
||||
@@ -403,182 +327,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The modes a display offers for a screen of `width` x `height` on a device of `count`
|
||||
/// displays, as sizes.
|
||||
fn sizes(width: u32, height: u32, count: u32) -> Vec<(u32, u32)> {
|
||||
let mode = Mode {
|
||||
width,
|
||||
height,
|
||||
refresh_mhz: 59_940,
|
||||
scale_120ths: 240,
|
||||
};
|
||||
offered_modes(mode, count)
|
||||
.iter()
|
||||
.map(|m| (m.width, m.height))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A 4K screen is offered the modes a Mac lists for an external 4K screen, its own first; a
|
||||
/// screen of the Mac panel four of the steps were read from is offered that panel's modes at
|
||||
/// those steps, and two of the external screen's steps between them
|
||||
#[test]
|
||||
fn a_display_offers_its_screen_s_ratio_at_a_mac_s_steps() {
|
||||
assert_eq!(
|
||||
sizes(3840, 2160, 1),
|
||||
[
|
||||
(3840, 2160),
|
||||
(3360, 1890),
|
||||
(3008, 1692),
|
||||
(2880, 1620),
|
||||
(2560, 1440),
|
||||
(1920, 1080),
|
||||
(1440, 810)
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
sizes(3072, 1920, 1),
|
||||
[
|
||||
(3072, 1920),
|
||||
(2688, 1680),
|
||||
(2400, 1500),
|
||||
(2304, 1440),
|
||||
(2048, 1280),
|
||||
(1536, 960),
|
||||
(1152, 720)
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
sizes(2560, 1440, 2),
|
||||
[
|
||||
(2560, 1440),
|
||||
(2240, 1260),
|
||||
(2000, 1124),
|
||||
(1920, 1080),
|
||||
(1696, 954),
|
||||
(1280, 720)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Every mode a display offers carries its first mode's refresh rate and scale, the guest
|
||||
/// running at the host screen's rate whichever it picks; a smaller mode is a multiple of 16
|
||||
/// pixels wide and even high, smaller each way than the first, and of its ratio to within
|
||||
/// those steps; there are at most `MODES_MAX`
|
||||
#[test]
|
||||
fn every_mode_has_the_screen_s_rate_and_steps() {
|
||||
for (w, h) in [
|
||||
(3840, 2160),
|
||||
(3456, 2234),
|
||||
(1712, 1148),
|
||||
(1366, 768),
|
||||
(1001, 777),
|
||||
(2160, 3840),
|
||||
(5120, 1440),
|
||||
(7680, 4320),
|
||||
] {
|
||||
for count in 1..=crate::wire::RGFX_DISPLAYS_MAX {
|
||||
let mode = Mode {
|
||||
width: w,
|
||||
height: h,
|
||||
refresh_mhz: 143_912,
|
||||
scale_120ths: 180,
|
||||
};
|
||||
let modes = offered_modes(mode, count);
|
||||
assert!(modes.len() <= MODES_MAX, "{w}x{h} on {count}");
|
||||
assert_eq!(modes[0], offered_in_room(mode, count));
|
||||
let (fw, fh) = (u64::from(modes[0].width), u64::from(modes[0].height));
|
||||
for m in &modes[1..] {
|
||||
assert_eq!((m.refresh_mhz, m.scale_120ths), (143_912, 180));
|
||||
assert_eq!((m.width % 16, m.height % 2), (0, 0), "{m:?} of {w}x{h}");
|
||||
assert!(m.width < modes[0].width && m.height < modes[0].height);
|
||||
assert!(laid_out(m.width, m.height) <= scanout_room(count));
|
||||
// The first mode's height for the width, less under two rows.
|
||||
let exact = u64::from(m.width) * fh / fw;
|
||||
assert!(exact - u64::from(m.height) < 2, "{m:?} of {w}x{h}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sizes of odd pixels, a fixed screen's (`resolution=`), take the steps too, each smaller
|
||||
/// mode on even pixels; and a portrait screen's modes are its own ratio, the floor turned
|
||||
#[test]
|
||||
fn odd_and_portrait_screens_offer_their_own_ratio() {
|
||||
assert_eq!(sizes(1366, 768, 1), [(1366, 768), (1184, 664)]);
|
||||
assert_eq!(sizes(1001, 777, 1), [(1001, 777), (864, 670)]);
|
||||
assert_eq!(
|
||||
sizes(1080, 1920, 1),
|
||||
[
|
||||
(1080, 1920),
|
||||
(944, 1678),
|
||||
(832, 1478),
|
||||
(800, 1422),
|
||||
(720, 1280)
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
sizes(1440, 2560, 1),
|
||||
[
|
||||
(1440, 2560),
|
||||
(1248, 2218),
|
||||
(1120, 1990),
|
||||
(1072, 1904),
|
||||
(960, 1706),
|
||||
(720, 1280)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// No smaller mode is below 800 x 600, the smallest a Mac takes for its desktop (960 x 600
|
||||
/// is at it); a screen's own mode is offered whatever its size, and alone where no step
|
||||
/// reaches the floor
|
||||
#[test]
|
||||
fn no_smaller_mode_is_below_the_floor() {
|
||||
assert_eq!(
|
||||
sizes(1280, 800, 1),
|
||||
[(1280, 800), (1120, 700), (992, 620), (960, 600)]
|
||||
);
|
||||
assert_eq!(
|
||||
sizes(1920, 1080, 1),
|
||||
[
|
||||
(1920, 1080),
|
||||
(1680, 944),
|
||||
(1504, 846),
|
||||
(1440, 810),
|
||||
(1280, 720)
|
||||
]
|
||||
);
|
||||
assert_eq!(sizes(1024, 768, 1), [(1024, 768), (896, 672), (800, 600)]);
|
||||
assert_eq!(sizes(800, 600, 1), [(800, 600)]);
|
||||
assert_eq!(sizes(640, 480, 1), [(640, 480)]);
|
||||
assert_eq!(sizes(0, 0, 1), [(0, 0)]);
|
||||
}
|
||||
|
||||
/// The first mode is sized to the display's room on a device of several, and the smaller
|
||||
/// modes follow it; on a device of one a screen too large for the room is offered as it is,
|
||||
/// and of its smaller modes only those whose scanout the room holds
|
||||
#[test]
|
||||
fn smaller_modes_keep_to_the_display_s_room() {
|
||||
assert_eq!(sizes(7680, 4320, 4), sizes(3840, 2160, 4));
|
||||
assert_eq!(
|
||||
sizes(7680, 4320, 2),
|
||||
[
|
||||
(5440, 3060),
|
||||
(4752, 2672),
|
||||
(4256, 2394),
|
||||
(4080, 2294),
|
||||
(3616, 2034),
|
||||
(2720, 1530),
|
||||
(2032, 1142)
|
||||
]
|
||||
);
|
||||
// 7168 x 7168, 6416 x 6416 and 6144 x 6144 miss the room's 128 MiB.
|
||||
assert_eq!(
|
||||
sizes(8192, 8192, 1),
|
||||
[(8192, 8192), (5456, 5456), (4096, 4096), (3072, 3072)]
|
||||
);
|
||||
}
|
||||
|
||||
/// A scanout's range runs from its first row's start to its last row's end
|
||||
#[test]
|
||||
fn a_scanout_s_range_ends_at_its_last_pixel() {
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
//! nothing to do.
|
||||
//! - [`clock`] is the device's clock, `HOST_TIME`'s, and [`clock::runtime`] places the
|
||||
//! platform's GPU times on it before they reach the guest.
|
||||
//! - [`threads`] is what each thread the device starts runs first, which the host sets.
|
||||
//! - [`trip`] times a command buffer's completion's trip down to the guest and the guest's next
|
||||
//! buffer's up, by stage: a diagnostic, off unless reims-vgpu turns it on.
|
||||
|
||||
@@ -32,8 +31,8 @@ pub mod keep;
|
||||
pub mod managed;
|
||||
pub mod ops;
|
||||
pub mod region;
|
||||
pub mod snapshot;
|
||||
mod ring;
|
||||
pub mod threads;
|
||||
// The trip line's histograms are a host diagnostic: cbindgen leaves the module out of the wire header.
|
||||
/// cbindgen:ignore
|
||||
pub mod trip;
|
||||
@@ -41,10 +40,9 @@ mod wake;
|
||||
pub mod wire;
|
||||
|
||||
pub use device::{
|
||||
CompleteAnswer, CompletionPoster, Device, DoorbellAt, GuestBundle, HoldWaker, Host,
|
||||
PointerLink, PoolAnswer, PresentAnswer, PrivateAnswer, QueueClaim, REGION_SIZE,
|
||||
RingDegradation, SLOW_ANSWER_NS, Spot, Then, VtAnswer, VtLink, VtMessage, VtSurface,
|
||||
raise_elsewhere,
|
||||
CompleteAnswer, CompletionPoster, Device, DoorbellAt, Host, PointerLink, PoolAnswer,
|
||||
PresentAnswer, PrivateAnswer, QueueClaim, REGION_SIZE, RingDegradation, SLOW_ANSWER_NS, Spot,
|
||||
Then, VtAnswer, VtLink, VtMessage, VtSurface,
|
||||
};
|
||||
pub use display::{CursorImage, FixedScreen, Mode, Scanout, Screen};
|
||||
pub use wake::RawDoorbell;
|
||||
@@ -60,6 +60,19 @@ pub struct Region {
|
||||
}
|
||||
|
||||
/// A block's size and who holds it.
|
||||
/// Serializable snapshot of a granted or shared BAR2 region block.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RegionBlockSnapshot {
|
||||
/// Byte offset inside BAR2.
|
||||
pub offset: u64,
|
||||
/// Block size in bytes.
|
||||
pub size: u64,
|
||||
/// Context IDs holding this block.
|
||||
pub holders: Vec<u32>,
|
||||
/// Whether this block was shared (`BLOCK_SHARE`).
|
||||
pub shared: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct Held {
|
||||
size: u64,
|
||||
@@ -213,6 +226,37 @@ impl Region {
|
||||
}
|
||||
|
||||
/// No block is anyone's any more (the device's reset): the kext grants them again.
|
||||
/// Exports all currently granted/shared BAR2 blocks for checkpointing.
|
||||
pub fn export_blocks(&self) -> Vec<RegionBlockSnapshot> {
|
||||
let blocks = self.blocks.lock();
|
||||
blocks
|
||||
.iter()
|
||||
.map(|(&offset, held)| RegionBlockSnapshot {
|
||||
offset,
|
||||
size: held.size,
|
||||
holders: held.holders.clone(),
|
||||
shared: held.shared,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Replaces the BAR2 block ledger from a checkpoint.
|
||||
pub fn import_blocks(&self, snap: &[RegionBlockSnapshot]) {
|
||||
let mut blocks = self.blocks.lock();
|
||||
blocks.clear();
|
||||
for b in snap {
|
||||
blocks.insert(
|
||||
b.offset,
|
||||
Held {
|
||||
size: b.size,
|
||||
holders: b.holders.clone(),
|
||||
shared: b.shared,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Revokes all active BAR2 region grants prior to snapshot restore.
|
||||
pub fn revoke_all(&self) {
|
||||
self.blocks.lock().clear();
|
||||
}
|
||||
@@ -386,14 +430,6 @@ impl Region {
|
||||
.then(|| self.atomic_u64(offset).load(Ordering::Acquire))
|
||||
}
|
||||
|
||||
/// Swaps the `u32` the guest keeps at `offset` for `value`, atomically and in the order of
|
||||
/// every sequentially consistent access (`SeqCst`), as the guest reads and writes it: the
|
||||
/// value it held. `None`, swapping nothing, where it is not 4-aligned and inside the region.
|
||||
pub fn swap_u32(&self, offset: u64, value: u32) -> Option<u32> {
|
||||
(offset.is_multiple_of(4) && self.contains(offset, 4))
|
||||
.then(|| self.atomic_u32(offset).swap(value, Ordering::SeqCst))
|
||||
}
|
||||
|
||||
/// The `u64` at `offset`, which is 8-aligned and inside the region, as an atomic.
|
||||
pub(crate) fn atomic_u64(&self, offset: u64) -> &AtomicU64 {
|
||||
assert!(
|
||||
|
||||
@@ -202,6 +202,11 @@ impl Consumer {
|
||||
self.count
|
||||
}
|
||||
|
||||
/// Restores the host's consumed byte count from a checkpoint (BAR2 already holds header).
|
||||
pub(crate) fn set_count(&mut self, count: u64) {
|
||||
self.count = count;
|
||||
}
|
||||
|
||||
/// The guest's published count (the ring's producer), read with an acquire load.
|
||||
pub(crate) fn published_count(&self, region: &Region) -> u64 {
|
||||
region
|
||||
@@ -555,6 +560,16 @@ impl Producer {
|
||||
}
|
||||
|
||||
/// Back to a ring nothing has passed through ([`RingAt::initialize`]), `consumer_idle` 0.
|
||||
/// Returns the host's published byte count.
|
||||
pub(crate) fn produced(&self) -> u64 {
|
||||
self.count
|
||||
}
|
||||
|
||||
/// Restores the host's published byte count from a checkpoint (BAR2 already holds header).
|
||||
pub(crate) fn set_count(&mut self, count: u64) {
|
||||
self.count = count;
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&mut self, region: &Region) {
|
||||
self.count = 0;
|
||||
self.at.initialize(region, false);
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Binary snapshot codec for [`Device`](crate::Device) state (Layer B).
|
||||
|
||||
use crate::display::{CursorImage, Mode, Scanout};
|
||||
use crate::region::RegionBlockSnapshot;
|
||||
|
||||
/// Serializable display state.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DisplaySnapshot {
|
||||
/// Active BAR2 scanout, if any.
|
||||
pub scanout: Option<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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
//! What each thread the device starts runs first ([`on_start`]): the host's, set once. reims-vgpu
|
||||
//! sets it to keep the thread's whole name for its pacing line where the OS cuts the name it
|
||||
//! gives the thread (Linux, at 15 bytes: every `reims-vgpu.graphics-…` name reads
|
||||
//! `reims-vgpu.grap` there). A diagnostic: what it does is free under the contract.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// The host's function.
|
||||
static ON_START: OnceLock<fn()> = OnceLock::new();
|
||||
|
||||
/// Each thread the device starts from now on calls `f` first: the control and refresh threads,
|
||||
/// ring 0's lanes and each queue's service thread. The first given wins.
|
||||
pub fn on_start(f: fn()) {
|
||||
let _ = ON_START.set(f);
|
||||
}
|
||||
|
||||
/// The calling thread, one the device started, calls the host's function, where it set one.
|
||||
pub(crate) fn started() {
|
||||
if let Some(f) = ON_START.get() {
|
||||
f();
|
||||
}
|
||||
}
|
||||
@@ -712,133 +712,12 @@ pub const RGFX_REG_POOL_BASE_HI: u32 = 0x048;
|
||||
pub const RGFX_REG_POOL_LENGTH_LO: u32 = 0x04c;
|
||||
/// `POOL_LENGTH_HI`, RO: as [`RGFX_REG_POOL_LENGTH_LO`], its high 32 bits.
|
||||
pub const RGFX_REG_POOL_LENGTH_HI: u32 = 0x050;
|
||||
/// `GUEST_BUNDLE`, WO: what the guest's accelerator found of its Metal bundle as WindowServer
|
||||
/// opened the display, once a boot, so the host can tell its user why a desktop runs without
|
||||
/// Metal: in bits 0 to 7 an `RGFX_GUEST_BUNDLE_*` (ours, another version's, none, or RgfxGate's
|
||||
/// install still under way), in bits 8 to 15 the wire version another version's bundle's marker
|
||||
/// names (0 where it names none the kext knows), in bits 16 to 23 RgfxGate's install pass, an
|
||||
/// `RGFX_GATE_*`, and in bits 24 to 31 the error its failed write gave (`errno`, 0 for none). It
|
||||
/// reads 0. A host that does not know it ignores the write, as at any offset it does not know, and
|
||||
/// the guest acts on nothing of it, so it needs no feature: a kext built before it never writes
|
||||
/// it, and a host then says nothing of the bundle.
|
||||
pub const RGFX_REG_GUEST_BUNDLE: u32 = 0x054;
|
||||
/// `FEATURES_EXT`, RO: feature bits 64 to 95 the host offers. The guest uses each with no take,
|
||||
/// but those [`RGFX_REG_DRIVER_FEATURES_EXT`] takes ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]): a guest
|
||||
/// that sees one of the others may send the messages it names, and the host carries out nothing
|
||||
/// else for a guest that does, so a guest that never reads it gets the wire it had before. It
|
||||
/// reads [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`] and [`RGFX_FEATURE_EXT_SURFACE_HOLD`] where the
|
||||
/// host offers them; 0 from a host older than it, as at any offset a host does not know. A write
|
||||
/// is ignored. Bit 1 is offered by no host: hosts built before the hold word left the block's
|
||||
/// header offered `SURFACE_HOLD` there, with the word in the header, and kexts built before it
|
||||
/// take it; a write of it takes nothing, so such a kext and this host, or this kext and such a
|
||||
/// host, take no hold.
|
||||
pub const RGFX_REG_FEATURES_EXT: u32 = 0x058;
|
||||
/// `DRIVER_FEATURES_EXT`, RW: the feature bits 64 to 95 the guest's driver took of those
|
||||
/// `FEATURES_EXT` offers that are taken ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]). A write takes the
|
||||
/// bits written that `FEATURES_EXT` offers and that are taken, and a read answers the bits taken.
|
||||
/// As at `DRIVER_FEATURES_LO`, a write while `STATUS` reads [`RGFX_STATUS_DRIVER_READY`] is
|
||||
/// ignored, and a reset clears it. A guest that never writes it (the option ROM, a kext built
|
||||
/// before it) gets the wire it had before; a host older than it reads 0 there and ignores a
|
||||
/// write, as at any offset it does not know.
|
||||
pub const RGFX_REG_DRIVER_FEATURES_EXT: u32 = 0x05c;
|
||||
/// `FEATURES_EXT` bit 0, feature bit 64, `SHARED_TEXTURE_NAMES`: ring 0 carries
|
||||
/// [`RGFX_CMD_SHARED_TEXTURE_CREATE`], a process's texture another process may open
|
||||
/// (`newSharedTextureWithDescriptor:`), and the messages the accelerator kext posts for its handle:
|
||||
/// [`RGFX_CMD_SHARED_TEXTURE_NAME`], which names it device-wide, [`RGFX_CMD_SHARED_TEXTURE_IMPORT`],
|
||||
/// by which another process's new texture is the same host texture, and
|
||||
/// [`RGFX_CMD_SHARED_TEXTURE_UNNAME`]. Every host offers it.
|
||||
pub const RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES: u32 = 1 << 0;
|
||||
/// `FEATURES_EXT` bit 2, feature bit 66, `SURFACE_HOLD`, taken in
|
||||
/// [`RGFX_REG_DRIVER_FEATURES_EXT`]. A host whose GPU's memory is its own (a device of one
|
||||
/// memory) may make an image in place over guest pages it imports by their pointer by copying the
|
||||
/// bytes under the image out and back around the image's first layout move, so a CPU write of
|
||||
/// those bytes between the two copies is lost. Where the guest took it:
|
||||
/// - **A cached surface's hold word.** The block of a surface with a device cache
|
||||
/// ([`RGFX_SURFACE_PAGES_CACHED`]) holds a 32-bit word in its own part, which no process maps:
|
||||
/// the first of the [`RGFX_SURFACE_HOLD_ROOM`] bytes right before its runs, at region offset
|
||||
/// `runs_offset - RGFX_SURFACE_HOLD_ROOM`, which the kext stores 0 into as it caches the block.
|
||||
/// So only the kext and the host write it. Before such a make over the block's pages the host
|
||||
/// raises it ([`RGFX_SURFACE_HOLD_RAISED`]), and after a full fence reads the surface's CPU
|
||||
/// generation in the block's header again: where it moved since the host decided on the make,
|
||||
/// the host lowers the word and makes nothing in place. Once the bytes are back it stores 0
|
||||
/// there. A block whose word would lie in its first [`RGFX_SURFACE_HOLD_ROOM`] bytes, where
|
||||
/// its header lies (its runs less than twice that past its start), has none, and gets no image
|
||||
/// made so over its pages. A read-write CPU lock stores the new generation, and after a full
|
||||
/// fence reads the word: while it is raised, the lock sets [`RGFX_SURFACE_HOLD_WAITED`] beside
|
||||
/// it and waits, looking again at the device's next vector or within 1 ms. So either the host
|
||||
/// reads the lock's generation and makes nothing in place, or the lock goes on once the bytes
|
||||
/// are back. A read-only lock waits for nothing.
|
||||
/// - **Answered creates over pages.** A [`RGFX_CMD_TEXTURE_FROM_BUFFER`] or
|
||||
/// [`RGFX_CMD_LINEAR_TEXTURE_FROM_BUFFER`] over a buffer a [`RGFX_CMD_BUFFER_OVER_PAGES`]
|
||||
/// made (the host's refusal of it among them) is answered by an [`RGFX_EVT_COMPLETE`] of
|
||||
/// [`RGFX_STATUS_OK`] once carried out, the texture made or refused, and the guest's create
|
||||
/// waits for that answer, so the creating thread writes the buffer only after the make. Every
|
||||
/// such create is answered: the host answers a pages block before it imports the block's
|
||||
/// pages, and on Linux the import alone finds whether it goes by the pages' pointer, the kind
|
||||
/// of import a make copies out and back.
|
||||
///
|
||||
/// A guest that does not take it gets no image made so over a cached surface's pages, and no
|
||||
/// answer. The host offers it where its GPU's memory is its own. The x86-64 and arm64e kexts
|
||||
/// take it.
|
||||
pub const RGFX_FEATURE_EXT_SURFACE_HOLD: u32 = 1 << 2;
|
||||
/// The bytes of a cached surface's block right before its runs that hold its hold word
|
||||
/// ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), a `u32` at their start: a page of the block's own part,
|
||||
/// past the part its processes map, which no process maps.
|
||||
pub const RGFX_SURFACE_HOLD_ROOM: u64 = 0x1000;
|
||||
/// The hold word's bit the host raises around a make that copies the pages' bytes out and back
|
||||
/// ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]).
|
||||
pub const RGFX_SURFACE_HOLD_RAISED: u32 = 1 << 0;
|
||||
/// The hold word's bit a read-write CPU lock sets beside [`RGFX_SURFACE_HOLD_RAISED`] while it
|
||||
/// waits ([`RGFX_FEATURE_EXT_SURFACE_HOLD`]), which the host counts.
|
||||
pub const RGFX_SURFACE_HOLD_WAITED: u32 = 1 << 1;
|
||||
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the kext's own version's bundle is on disk,
|
||||
/// and the accelerator registered for it.
|
||||
pub const RGFX_GUEST_BUNDLE_OURS: u32 = 1;
|
||||
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: the bundle's executable is there without the
|
||||
/// marker of the kext's version, so the accelerator stays unregistered for the boot.
|
||||
pub const RGFX_GUEST_BUNDLE_OTHER_VERSION: u32 = 2;
|
||||
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: no bundle's executable is there, so the
|
||||
/// accelerator stays unregistered for the boot.
|
||||
pub const RGFX_GUEST_BUNDLE_ABSENT: u32 = 3;
|
||||
/// A [`RGFX_REG_GUEST_BUNDLE`] value's bundle field: RgfxGate's install pass had not ended, so the
|
||||
/// accelerator stays unregistered for the boot.
|
||||
pub const RGFX_GUEST_BUNDLE_GATE_BUSY: u32 = 4;
|
||||
/// Where a [`RGFX_REG_GUEST_BUNDLE`] value's other version starts: bits 8 to 15.
|
||||
pub const RGFX_GUEST_BUNDLE_VERSION_SHIFT: u32 = 8;
|
||||
/// Where a [`RGFX_REG_GUEST_BUNDLE`] value's `RGFX_GATE_*` starts: bits 16 to 23.
|
||||
pub const RGFX_GUEST_BUNDLE_GATE_SHIFT: u32 = 16;
|
||||
/// Where a [`RGFX_REG_GUEST_BUNDLE`] value's `errno` starts: bits 24 to 31.
|
||||
pub const RGFX_GUEST_BUNDLE_ERRNO_SHIFT: u32 = 24;
|
||||
/// RgfxGate's install pass, as [`RGFX_REG_GUEST_BUNDLE`] gives it: no RgfxGate published one.
|
||||
pub const RGFX_GATE_NONE: u32 = 0;
|
||||
/// RgfxGate's install pass: under way still.
|
||||
pub const RGFX_GATE_RUNNING: u32 = 1;
|
||||
/// RgfxGate's install pass: ended without saying how, as an RgfxGate built before
|
||||
/// `RgfxGateInstallResult` does.
|
||||
pub const RGFX_GATE_UNTOLD: u32 = 2;
|
||||
/// RgfxGate's install pass: its own bundle was there already, written and tagged.
|
||||
pub const RGFX_GATE_PRESENT: u32 = 3;
|
||||
/// RgfxGate's install pass: it wrote its own bundle and tagged it.
|
||||
pub const RGFX_GATE_INSTALLED: u32 = 4;
|
||||
/// RgfxGate's install pass: its own bundle was there, and it tagged it.
|
||||
pub const RGFX_GATE_TAGGED: u32 = 5;
|
||||
/// RgfxGate's install pass: a write or the rename of its bundle failed, with the `errno`.
|
||||
pub const RGFX_GATE_FAILED: u32 = 6;
|
||||
/// RgfxGate's install pass: the Data volume did not mount while it waited, about 60 s.
|
||||
pub const RGFX_GATE_NO_DATA_VOLUME: u32 = 7;
|
||||
/// RgfxGate's install pass: none, in the installer or Recovery.
|
||||
pub const RGFX_GATE_SKIPPED: u32 = 8;
|
||||
/// RgfxGate's install pass: it could not start one (no thread, no VFS context, or on arm64 a
|
||||
/// kernel whose vnode layout it does not know).
|
||||
pub const RGFX_GATE_REFUSED: u32 = 9;
|
||||
/// What `MAGIC` reads: "RGFX", little-endian.
|
||||
pub const RGFX_MAGIC: u32 = 0x5846_4752;
|
||||
/// What `VERSION` reads: the wire's version, which every change a guest built before it would
|
||||
/// misread moves on, a record's size among them: `include/reims_graphics_wire_sizes.h` pins each
|
||||
/// record's size to it (docs/graphics-kext/design.md, "The wire's version"). The kext and the
|
||||
/// option ROM leave a device of any other version, and the kext registers its accelerator only for
|
||||
/// a bundle of its own.
|
||||
pub const RGFX_VERSION: u32 = 3;
|
||||
/// misread moves on (docs/graphics-kext/design.md, "The wire's version"). The kext and the option
|
||||
/// ROM leave a device of any other version.
|
||||
pub const RGFX_VERSION: u32 = 2;
|
||||
/// `STATUS`: the device is reset, and takes no message.
|
||||
pub const RGFX_STATUS_RESET: u32 = 0;
|
||||
/// `STATUS`: the guest's driver has read the rings' headers; the device takes its messages.
|
||||
@@ -1053,9 +932,6 @@ pub const RGFX_CMD_CURSOR_COLOR: u32 = 10;
|
||||
/// Command `SCROLL_DEVICES` ([`RgfxScrollDevices`]), where the guest took
|
||||
/// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
|
||||
pub const RGFX_CMD_SCROLL_DEVICES: u32 = 11;
|
||||
/// Command `HIDDEN_PLACES` ([`RgfxHiddenPlaces`]), where the guest took
|
||||
/// [`RGFX_FEATURE_POINTER_MOTION`]: not answered.
|
||||
pub const RGFX_CMD_HIDDEN_PLACES: u32 = 12;
|
||||
/// Event `COMPLETE` ([`RgfxComplete`]): a command's answer, with its `seqno`.
|
||||
pub const RGFX_EVT_COMPLETE: u32 = 0x100;
|
||||
/// Event `DISPLAYS` ([`RgfxDisplays`]): `GET_DISPLAYS`'s answer, with its `seqno`.
|
||||
@@ -1076,11 +952,6 @@ pub const RGFX_EVT_POINTER_MOTION: u32 = 0x105;
|
||||
/// ([`RGFX_CMD_SCROLL_DEVICES`]) take it: the host's wheel or trackpad scrolled, and the guest's
|
||||
/// own devices scroll as far.
|
||||
pub const RGFX_EVT_SCROLL: u32 = 0x106;
|
||||
/// Event `POINTER_LOOK` ([`RgfxPointerLook`]), sent only to a guest whose last `HIDDEN_PLACES`
|
||||
/// since its last start ([`RGFX_CMD_HIDDEN_PLACES`]) said it reports them: the host's pointer
|
||||
/// moved the guest's tablet while the guest hides its cursor, and the guest reports where its
|
||||
/// hidden cursor goes.
|
||||
pub const RGFX_EVT_POINTER_LOOK: u32 = 0x107;
|
||||
|
||||
/// `COMPLETE`'s status: the command was done.
|
||||
pub const RGFX_STATUS_OK: u32 = 0;
|
||||
@@ -1437,44 +1308,6 @@ pub const RGFX_CMD_HEAP_OVER_POOL: u32 = 0x23c;
|
||||
/// create among them, which waits for its block's view's address: the answer comes once the
|
||||
/// buffer lies there. Makes nothing.
|
||||
pub const RGFX_CMD_PAGES_BUFFER_ADDRESS: u32 = 0x23d;
|
||||
/// Command `SHARED_TEXTURE_CREATE` ([`RgfxSharedTextureCreate`]), where the host offers
|
||||
/// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: a texture of shape `desc` that other processes may
|
||||
/// open (`newSharedTextureWithDescriptor:`), with the guest-picked `resource_id`. The host makes
|
||||
/// the texture's storage itself, at an address and a resource index of its own, which no context
|
||||
/// holds, and the sender's texture `obj_id` over all of it at `resource_id`; each process that
|
||||
/// opens it later has its own texture over the same storage at its own index
|
||||
/// ([`RGFX_CMD_SHARED_TEXTURE_IMPORT`]). So the storage outlives the context that made it while
|
||||
/// another process's texture or a name holds it, and no context's addresses or indices are held
|
||||
/// past its close. Its storage mode is Private: a create of any other is refused. Not answered;
|
||||
/// a create the host refuses stands for a refused object, as a `TEXTURE_CREATE`'s does.
|
||||
/// `OBJECT_DESTROY` drops the sender's texture; the storage goes with its last texture and its
|
||||
/// last name.
|
||||
pub const RGFX_CMD_SHARED_TEXTURE_CREATE: u32 = 0x23e;
|
||||
/// Command `SHARED_TEXTURE_NAME` ([`RgfxSharedTextureName`]), which the accelerator kext posts for
|
||||
/// a process's handle of its shared texture `obj_id` (`newSharedTextureHandle`), where the host
|
||||
/// offers [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: the texture's storage is named `name`
|
||||
/// device-wide, so another process may open it ([`RGFX_CMD_SHARED_TEXTURE_IMPORT`]), until the kext
|
||||
/// lets go of the name ([`RGFX_CMD_SHARED_TEXTURE_UNNAME`]). A name holds the storage as a texture
|
||||
/// over it does. Answered by [`RGFX_EVT_COMPLETE`]: [`RGFX_STATUS_OK`], or
|
||||
/// [`RGFX_STATUS_NOT_FOUND`] where the sender holds no shared texture of that id (one whose
|
||||
/// create the host refused among them), and [`RGFX_STATUS_INVALID_ARGUMENT`] for a name of 0. The
|
||||
/// kext builds the message: `name` is the kext's, never the process's.
|
||||
pub const RGFX_CMD_SHARED_TEXTURE_NAME: u32 = 0x23f;
|
||||
/// Command `SHARED_TEXTURE_IMPORT` ([`RgfxSharedTextureImport`]), which the accelerator kext posts
|
||||
/// for a process that opens a handle another process's `SHARED_TEXTURE_NAME` named
|
||||
/// (`newSharedTextureWithHandle:`), where the host offers
|
||||
/// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: the process's new texture `obj_id` lies over all of
|
||||
/// the storage `name` names, in the shape it was made in, at the guest-picked `resource_id`.
|
||||
/// Answered by [`RGFX_EVT_SHARED_TEXTURE`] with the shape, which the process's texture answers,
|
||||
/// or [`RGFX_STATUS_NOT_FOUND`] where the name was let go of or never given, and
|
||||
/// [`RGFX_STATUS_INVALID_ARGUMENT`] for another context's id or a resource index the sender does
|
||||
/// not hold; nothing is made then. `OBJECT_DESTROY` drops it, as any texture.
|
||||
pub const RGFX_CMD_SHARED_TEXTURE_IMPORT: u32 = 0x240;
|
||||
/// Command `SHARED_TEXTURE_UNNAME` ([`RgfxSharedTextureUnname`]), which the accelerator kext posts
|
||||
/// once nothing but the kext holds the handle a `SHARED_TEXTURE_NAME` named, where the host offers
|
||||
/// [`RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES`]: no process can open the name from then on, and the
|
||||
/// storage goes once no texture lies over it. Context 0's, which no process is. Not answered.
|
||||
pub const RGFX_CMD_SHARED_TEXTURE_UNNAME: u32 = 0x241;
|
||||
|
||||
/// `CONTEXT_CLOSE` ([`RgfxContextClose`]), on ring 0 from the accelerator kext: the process that
|
||||
/// held context `context` closed the device or died. The host ends the context's command queues
|
||||
@@ -1798,16 +1631,6 @@ pub const RGFX_EVT_POOL_BLOCK: u32 = 0x410;
|
||||
/// [`RGFX_CMD_PRIVATE_TAKE`]'s `seqno`: its answer. `status` [`RGFX_STATUS_OK`] with the block's
|
||||
/// `gpu_address` and `length`; otherwise each 0.
|
||||
pub const RGFX_EVT_PRIVATE_BLOCK: u32 = 0x411;
|
||||
/// Event `SHARED_TEXTURE` ([`RgfxSharedTexture`], on the control completion ring), with a
|
||||
/// [`RGFX_CMD_SHARED_TEXTURE_IMPORT`]'s `seqno`: its answer. `status` [`RGFX_STATUS_OK`] with the
|
||||
/// shape the storage was made in; otherwise the shape is zeros.
|
||||
pub const RGFX_EVT_SHARED_TEXTURE: u32 = 0x412;
|
||||
/// Event `SURFACE_HOLD_LOWERED` ([`RgfxSurfaceHoldLowered`], on the control completion ring,
|
||||
/// `seqno` 0), where the guest took [`RGFX_FEATURE_EXT_SURFACE_HOLD`]: the host lowered the hold
|
||||
/// word of the cached surface's block at `block_offset` after a read-write CPU lock set
|
||||
/// [`RGFX_SURFACE_HOLD_WAITED`] beside it, so the lock looks at the word again. Posted with no
|
||||
/// wait: one the ring has no room for is dropped, and the lock looks again within 1 ms.
|
||||
pub const RGFX_EVT_SURFACE_HOLD_LOWERED: u32 = 0x413;
|
||||
|
||||
/// A command buffer's status in [`RgfxCbComplete`]: finished with no error.
|
||||
pub const RGFX_CB_OK: u32 = 0;
|
||||
@@ -2269,19 +2092,6 @@ pub struct RgfxDisplayChanged {
|
||||
pub reserved_14: u32,
|
||||
}
|
||||
|
||||
/// `SURFACE_HOLD_LOWERED`: the host lowered a cached surface's hold word that a lock waited on
|
||||
/// ([`RGFX_EVT_SURFACE_HOLD_LOWERED`]).
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
|
||||
)]
|
||||
pub struct RgfxSurfaceHoldLowered {
|
||||
/// [`RGFX_EVT_SURFACE_HOLD_LOWERED`], `seqno` 0.
|
||||
pub header: RgfxMsgHeader,
|
||||
/// The region offset of the surface's block.
|
||||
pub block_offset: u64,
|
||||
}
|
||||
|
||||
/// `VBLANK`: the display's host screen refreshed.
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
@@ -2372,47 +2182,6 @@ pub struct RgfxScrollDevices {
|
||||
pub reserved_14: u32,
|
||||
}
|
||||
|
||||
/// `HIDDEN_PLACES`: whether the guest reports where its hidden cursor goes (`reports` 1, else 0),
|
||||
/// which its driver sends once its mouse ([`RGFX_FEATURE_POINTER_MOTION`]) is up after each start.
|
||||
/// A guest that reports them is sent [`RGFX_EVT_POINTER_LOOK`] when the host's pointer moves its
|
||||
/// tablet while it hides its cursor, and answers with a `MOVE_CURSOR` of the cursor still hidden
|
||||
/// (`visible` 0) at each new place it reads for a while after; the device then counts a hide as a
|
||||
/// game's only once its hidden cursor has followed the tablet (docs/graphics-kext/design.md, "A
|
||||
/// pointer for games", "The hidden cursor's place"). A guest that sends none, or 0, is never sent
|
||||
/// `POINTER_LOOK`, and each hide of its counts as a game's as before, until the next reset. The
|
||||
/// x86-64 kext sends it; the arm64e kext, whose cursor is a layer of its swaps, sends none.
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
|
||||
)]
|
||||
pub struct RgfxHiddenPlaces {
|
||||
/// [`RGFX_CMD_HIDDEN_PLACES`].
|
||||
pub header: RgfxMsgHeader,
|
||||
/// 1 where the guest reports where its hidden cursor goes, else 0.
|
||||
pub reports: u32,
|
||||
/// 0.
|
||||
pub reserved_14: u32,
|
||||
}
|
||||
|
||||
/// `POINTER_LOOK`: the host's pointer, over display `display`'s window, moved the guest's tablet
|
||||
/// while the guest hides its cursor on every display: the guest looks where its hidden cursor
|
||||
/// goes for a while, and reports each new place in a `MOVE_CURSOR` of the cursor still hidden
|
||||
/// (`visible` 0). Sent only to a guest whose [`RGFX_CMD_HIDDEN_PLACES`] said it reports them,
|
||||
/// while the hide has not shown its hidden cursor following the tablet, one at most every 50 ms;
|
||||
/// one that finds the ring held or full is not sent, and the next move sends it.
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
|
||||
)]
|
||||
pub struct RgfxPointerLook {
|
||||
/// [`RGFX_EVT_POINTER_LOOK`], `seqno` 0.
|
||||
pub header: RgfxMsgHeader,
|
||||
/// The display whose window the host's pointer is over.
|
||||
pub display: u32,
|
||||
/// 0.
|
||||
pub reserved_14: u32,
|
||||
}
|
||||
|
||||
/// [`RgfxScrollDevices`]'s `devices`: the guest's mouse takes wheel notches, up and sideways
|
||||
/// ([`RgfxScroll`]'s `notches_up` and `notches_right`).
|
||||
pub const RGFX_SCROLL_DEVICE_WHEEL: u32 = 1 << 0;
|
||||
@@ -2510,9 +2279,6 @@ const _: () = {
|
||||
assert!(offset_of!(RgfxPointerMotion, wheel) == 24);
|
||||
assert!(offset_of!(RgfxPointerMotion, buttons) == 28);
|
||||
assert!(size_of::<RgfxScrollDevices>() == 24);
|
||||
assert!(size_of::<RgfxHiddenPlaces>() == 24);
|
||||
assert!(size_of::<RgfxPointerLook>() == 24);
|
||||
assert!(offset_of!(RgfxPointerLook, display) == 16);
|
||||
assert!(size_of::<RgfxScroll>() == 32);
|
||||
assert!(offset_of!(RgfxScroll, fine_up) == 24);
|
||||
assert!(size_of::<RgfxDisplayBounds>() == 40);
|
||||
@@ -2705,87 +2471,6 @@ pub struct RgfxSharedEventValue {
|
||||
pub value: u64,
|
||||
}
|
||||
|
||||
/// `SHARED_TEXTURE_CREATE`: the sender's texture `obj_id`, of shape `desc`, over storage the host
|
||||
/// makes for it, which other processes may open.
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
|
||||
)]
|
||||
pub struct RgfxSharedTextureCreate {
|
||||
/// [`RGFX_CMD_SHARED_TEXTURE_CREATE`].
|
||||
pub header: RgfxMsgHeader,
|
||||
/// The new texture's guest-picked id.
|
||||
pub obj_id: u64,
|
||||
/// The texture's guest-picked resource id.
|
||||
pub resource_id: u64,
|
||||
/// The texture's shape: Private storage.
|
||||
pub desc: RgfxTextureDescriptor,
|
||||
}
|
||||
|
||||
/// `SHARED_TEXTURE_NAME`: the storage of the sender's shared texture `obj_id` named `name`
|
||||
/// device-wide. The kext builds the message: `name` is the kext's, never the process's.
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
|
||||
)]
|
||||
pub struct RgfxSharedTextureName {
|
||||
/// [`RGFX_CMD_SHARED_TEXTURE_NAME`].
|
||||
pub header: RgfxMsgHeader,
|
||||
/// The sender's shared texture, or a texture it opened from another's name.
|
||||
pub obj_id: u64,
|
||||
/// Its name, unique to the device from the kext's start: never 0.
|
||||
pub name: u64,
|
||||
}
|
||||
|
||||
/// `SHARED_TEXTURE_IMPORT`: the sender's new texture `obj_id` over the storage named `name`, at
|
||||
/// `resource_id`. The kext builds the message from the handle the process holds.
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
|
||||
)]
|
||||
pub struct RgfxSharedTextureImport {
|
||||
/// [`RGFX_CMD_SHARED_TEXTURE_IMPORT`].
|
||||
pub header: RgfxMsgHeader,
|
||||
/// The sender's new texture's guest-picked id.
|
||||
pub obj_id: u64,
|
||||
/// The name the storage was given ([`RgfxSharedTextureName::name`]).
|
||||
pub name: u64,
|
||||
/// The new texture's guest-picked resource id.
|
||||
pub resource_id: u64,
|
||||
}
|
||||
|
||||
/// `SHARED_TEXTURE_UNNAME`: the name `name` is no longer the kext's to give out.
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
|
||||
)]
|
||||
pub struct RgfxSharedTextureUnname {
|
||||
/// [`RGFX_CMD_SHARED_TEXTURE_UNNAME`].
|
||||
pub header: RgfxMsgHeader,
|
||||
/// 0: the message is context 0's, which no process is, so it waits for no process's
|
||||
/// messages.
|
||||
pub reserved_10: u64,
|
||||
/// The name ([`RgfxSharedTextureName::name`]).
|
||||
pub name: u64,
|
||||
}
|
||||
|
||||
/// `SHARED_TEXTURE`: a `SHARED_TEXTURE_IMPORT`'s answer, with its `seqno`: the shape the storage
|
||||
/// was made in, which the new texture answers.
|
||||
#[repr(C)]
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, PartialEq, Eq, FromBytes, IntoBytes, Immutable, KnownLayout,
|
||||
)]
|
||||
pub struct RgfxSharedTexture {
|
||||
/// [`RGFX_EVT_SHARED_TEXTURE`], with the import's `seqno`.
|
||||
pub header: RgfxMsgHeader,
|
||||
/// An `RGFX_STATUS_*`: [`RGFX_STATUS_OK`] where the texture is made.
|
||||
pub status: u32,
|
||||
/// Pads to a multiple of 8; 0.
|
||||
pub reserved_14: u32,
|
||||
/// The storage's shape; zeros where the texture was not made.
|
||||
pub desc: RgfxTextureDescriptor,
|
||||
}
|
||||
|
||||
/// `QUEUE_CREATE`: a command queue and its submission+completion ring pair, each
|
||||
/// a [`RgfxRingHeader`] followed by a byte ring of the given data size (a power
|
||||
/// of two) at the given region offset. The completion ring raises `vector`.
|
||||
@@ -6137,11 +5822,6 @@ const _: () = {
|
||||
assert!(size_of::<RgfxObjectCreate>() == 24);
|
||||
assert!(size_of::<RgfxSharedEventCreate>() == 32);
|
||||
assert!(size_of::<RgfxSharedEventSetValue>() == 32);
|
||||
assert!(size_of::<RgfxSharedTextureCreate>() == 80);
|
||||
assert!(size_of::<RgfxSharedTextureName>() == 32);
|
||||
assert!(size_of::<RgfxSharedTextureImport>() == 40);
|
||||
assert!(size_of::<RgfxSharedTextureUnname>() == 32);
|
||||
assert!(size_of::<RgfxSharedTexture>() == 72);
|
||||
assert!(size_of::<RgfxQueueCreate>() == 56);
|
||||
assert!(RGFX_QUEUE_CREATE_FLAGS_OFFSET as usize == size_of::<RgfxQueueCreate>());
|
||||
assert!(size_of::<RgfxQueueCreateFlags>() == 8);
|
||||
|
||||
@@ -55,9 +55,6 @@ CHECK(RGFX_EVT_POINTER_MOTION == 0x105);
|
||||
CHECK(RGFX_FEATURE_POINTER_MOTION == (1ULL << 51));
|
||||
CHECK(RGFX_CMD_SCROLL_DEVICES == 11 && sizeof(RgfxScrollDevices) == 24);
|
||||
CHECK(RGFX_EVT_SCROLL == 0x106 && sizeof(RgfxScroll) == 32);
|
||||
CHECK(RGFX_CMD_HIDDEN_PLACES == 12 && sizeof(RgfxHiddenPlaces) == 24);
|
||||
CHECK(RGFX_EVT_POINTER_LOOK == 0x107 && sizeof(RgfxPointerLook) == 24);
|
||||
CHECK(offsetof(RgfxPointerLook, display) == 16);
|
||||
CHECK(offsetof(RgfxScroll, fine_up) == 24);
|
||||
CHECK(RGFX_FEATURE_VT_MESSAGES == (1ULL << 52));
|
||||
CHECK(RGFX_CMD_VT_MESSAGE == 0x2fa);
|
||||
@@ -121,20 +118,6 @@ CHECK(RGFX_CMD_PAGES_BUFFER_ADDRESS == 0x23d && sizeof(RgfxPagesBufferAddress) =
|
||||
CHECK(offsetof(RgfxPagesBufferAddress, obj_id) == 16);
|
||||
CHECK(RGFX_FEATURE_SURFACE_CACHE_EVERY == (1ULL << 62));
|
||||
CHECK(RGFX_FEATURE_MANAGED_AT_COPY == (1ULL << 63));
|
||||
CHECK(RGFX_REG_FEATURES_EXT == 0x058 && RGFX_FEATURE_EXT_SHARED_TEXTURE_NAMES == 1);
|
||||
CHECK(RGFX_FEATURE_EXT_SURFACE_HOLD == (1 << 2) && RGFX_SURFACE_HOLD_ROOM == 0x1000);
|
||||
CHECK(RGFX_CMD_SHARED_TEXTURE_CREATE == 0x23e && sizeof(RgfxSharedTextureCreate) == 80);
|
||||
CHECK(offsetof(RgfxSharedTextureCreate, resource_id) == 24);
|
||||
CHECK(offsetof(RgfxSharedTextureCreate, desc) == 32);
|
||||
CHECK(RGFX_CMD_SHARED_TEXTURE_NAME == 0x23f && sizeof(RgfxSharedTextureName) == 32);
|
||||
CHECK(offsetof(RgfxSharedTextureName, obj_id) == 16 && offsetof(RgfxSharedTextureName, name) == 24);
|
||||
CHECK(RGFX_CMD_SHARED_TEXTURE_IMPORT == 0x240 && sizeof(RgfxSharedTextureImport) == 40);
|
||||
CHECK(offsetof(RgfxSharedTextureImport, name) == 24);
|
||||
CHECK(offsetof(RgfxSharedTextureImport, resource_id) == 32);
|
||||
CHECK(RGFX_CMD_SHARED_TEXTURE_UNNAME == 0x241 && sizeof(RgfxSharedTextureUnname) == 32);
|
||||
CHECK(offsetof(RgfxSharedTextureUnname, name) == 24);
|
||||
CHECK(RGFX_EVT_SHARED_TEXTURE == 0x412 && sizeof(RgfxSharedTexture) == 72);
|
||||
CHECK(offsetof(RgfxSharedTexture, status) == 16 && offsetof(RgfxSharedTexture, desc) == 24);
|
||||
CHECK(offsetof(RgfxCursorColor, on) == 20 && offsetof(RgfxCursorColor, source_curves) == 24);
|
||||
CHECK(offsetof(RgfxCursorColor, to_xyz) == 120 && offsetof(RgfxCursorColor, from_xyz) == 156);
|
||||
CHECK(offsetof(RgfxCursorColor, blend_curves) == 192);
|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
//! Each wire record's size, as the committed header lays it out, against the table pinned to the
|
||||
//! wire's version, `include/reims_graphics_wire_sizes.h` (docs/graphics-kext/design.md, "The
|
||||
//! wire's version"): a record whose size changed without `RGFX_VERSION` moving is one a guest of
|
||||
//! that version misreads. The header is cbindgen's of `wire`'s and `ops`' records, which `cargo
|
||||
//! xtask header --check` holds it to, so its sizes are the records' own. The guest checks the same
|
||||
//! table as it compiles the header (`guest/kext/tests/wire_sizes_test.cpp`).
|
||||
|
||||
// A failure is the assertion (architecture 17.4).
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use reims_vgpu_graphics::wire::RGFX_VERSION;
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
/// The crate's `include` directory, which holds the header and the table.
|
||||
fn include_dir() -> PathBuf {
|
||||
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("include")
|
||||
}
|
||||
|
||||
/// The table's text.
|
||||
fn table() -> String {
|
||||
std::fs::read_to_string(include_dir().join("reims_graphics_wire_sizes.h")).unwrap()
|
||||
}
|
||||
|
||||
/// The version the table pins its sizes to: its `RGFX_WIRE_SIZES_VERSION`.
|
||||
fn table_version(table: &str) -> u32 {
|
||||
table
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("#define RGFX_WIRE_SIZES_VERSION "))
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The table's rows, each a record's name and its size in bytes, in the table's order.
|
||||
fn rows(table: &str) -> Vec<(String, u64)> {
|
||||
table
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("RGFX_WIRE_SIZE("))
|
||||
.map(|l| {
|
||||
let (name, size) = l.strip_suffix(')').unwrap().split_once(", ").unwrap();
|
||||
(name.to_owned(), size.parse().unwrap())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The table is pinned to the version the host speaks: one that moved without its table, or a
|
||||
/// table moved without the version, fails here
|
||||
#[test]
|
||||
fn the_size_table_is_pinned_to_the_wire_s_version() {
|
||||
assert_eq!(
|
||||
table_version(&table()),
|
||||
RGFX_VERSION,
|
||||
"include/reims_graphics_wire_sizes.h pins its sizes to another version than \
|
||||
RGFX_VERSION: pin the records' sizes at the version the wire speaks"
|
||||
);
|
||||
}
|
||||
|
||||
/// The table's register rows, each a register's name and its offset in BAR 0, in the table's
|
||||
/// order.
|
||||
fn registers(table: &str) -> Vec<(String, u32)> {
|
||||
table
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("RGFX_WIRE_REGISTER("))
|
||||
.map(|l| {
|
||||
let (name, at) = l.strip_suffix(')').unwrap().split_once(", ").unwrap();
|
||||
let at = u32::from_str_radix(at.strip_prefix("0x").unwrap(), 16).unwrap();
|
||||
(name.to_owned(), at)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The table has one row for each register of BAR 0 the header defines and names none other, no
|
||||
/// two at one offset, so a new register takes its offset at the version it lands in, and one
|
||||
/// that moved fails `each_wire_record_keeps_its_size_at_the_wire_s_version`
|
||||
#[test]
|
||||
fn the_layout_table_names_each_register_of_the_header_once() {
|
||||
let header = std::fs::read_to_string(include_dir().join("reims_graphics_wire.h")).unwrap();
|
||||
let defined: BTreeSet<&str> = header
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("#define RGFX_REG_"))
|
||||
.filter_map(|l| l.split_whitespace().next())
|
||||
.collect();
|
||||
assert!(
|
||||
defined.len() >= 20,
|
||||
"only {} registers found",
|
||||
defined.len()
|
||||
);
|
||||
let table = table();
|
||||
let rows = registers(&table);
|
||||
let named: BTreeSet<&str> = rows
|
||||
.iter()
|
||||
.map(|(n, _)| n.strip_prefix("RGFX_REG_").unwrap())
|
||||
.collect();
|
||||
let offsets: BTreeSet<u32> = rows.iter().map(|(_, at)| *at).collect();
|
||||
assert_eq!(named.len(), rows.len(), "a register has two rows");
|
||||
assert_eq!(offsets.len(), rows.len(), "two registers share an offset");
|
||||
let missing: Vec<_> = defined.difference(&named).collect();
|
||||
let unknown: Vec<_> = named.difference(&defined).collect();
|
||||
assert!(
|
||||
missing.is_empty() && unknown.is_empty(),
|
||||
"registers without a row: {missing:?}; rows of no register: {unknown:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The table has one row for each record of the header and names none other, so a new record
|
||||
/// takes its size at the version it lands in
|
||||
#[test]
|
||||
fn the_size_table_names_each_record_of_the_header_once() {
|
||||
let header = std::fs::read_to_string(include_dir().join("reims_graphics_wire.h")).unwrap();
|
||||
let records: BTreeSet<&str> = header
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("} ")?.strip_suffix(';'))
|
||||
.filter(|n| n.starts_with("Rgfx"))
|
||||
.collect();
|
||||
assert!(records.len() > 300, "only {} records found", records.len());
|
||||
let table = table();
|
||||
let rows = rows(&table);
|
||||
let named: BTreeSet<&str> = rows.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert_eq!(named.len(), rows.len(), "a record has two rows");
|
||||
let missing: Vec<_> = records.difference(&named).collect();
|
||||
let unknown: Vec<_> = named.difference(&records).collect();
|
||||
assert!(
|
||||
missing.is_empty() && unknown.is_empty(),
|
||||
"records without a row: {missing:?}; rows of no record: {unknown:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Each record of the header has the size the table pins at the wire's version, and each register
|
||||
/// its offset, in C11 as the option ROM compiles it and in C++17 as the kext does: a size or an
|
||||
/// offset that moved fails here, naming each, and moves `RGFX_VERSION` on
|
||||
#[test]
|
||||
fn each_wire_record_keeps_its_size_at_the_wire_s_version() {
|
||||
for (language, std) in [("c", "-std=c11"), ("c++", "-std=c++17")] {
|
||||
let checks = "#include \"reims_graphics_wire.h\"\n\
|
||||
#ifdef __cplusplus\n#define CHECK(e, m) static_assert(e, m)\n\
|
||||
#else\n#define CHECK(e, m) _Static_assert(e, m)\n#endif\n\
|
||||
#define RGFX_WIRE_SIZE(T, n) CHECK(sizeof(T) == n, #T \" changed size \
|
||||
without RGFX_VERSION moving\");\n\
|
||||
#define RGFX_WIRE_REGISTER(R, at) CHECK(R == at, #R \" moved without \
|
||||
RGFX_VERSION moving\");\n\
|
||||
#include \"reims_graphics_wire_sizes.h\"\n\
|
||||
CHECK(RGFX_WIRE_SIZES_VERSION == RGFX_VERSION, \"the table's version\");\n\
|
||||
int main(void) { return 0; }\n";
|
||||
let tmp = std::env::temp_dir().join(format!(
|
||||
"rgfx-wire-sizes-{}-{language}.c",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::write(&tmp, checks).unwrap();
|
||||
let out = Command::new("cc")
|
||||
.args(["-x", language, std, "-Wall", "-Wextra", "-Werror"])
|
||||
.arg("-fsyntax-only")
|
||||
.arg("-I")
|
||||
.arg(include_dir())
|
||||
.arg(&tmp)
|
||||
.output()
|
||||
.unwrap();
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let moved: Vec<&str> = stderr
|
||||
.lines()
|
||||
.filter(|l| {
|
||||
l.contains("changed size without RGFX_VERSION moving")
|
||||
|| l.contains("moved without RGFX_VERSION moving")
|
||||
|| l.contains("evaluates to")
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{language}: records whose size, or registers whose offset, differs from \
|
||||
include/reims_graphics_wire_sizes.h at version {RGFX_VERSION}: move RGFX_VERSION \
|
||||
on by one and pin the new sizes and offsets at it (docs/graphics-kext/design.md, \
|
||||
\"The wire's version\"):\n{}\n{stderr}",
|
||||
moved.join("\n")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,6 @@ license.workspace = true
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# The test-only delays at named points of the arms and the sessions (`video_delay`), and the
|
||||
# paravirtual protocol's key names (`paravirt::names`), for the host-only harness of reims-vgpu's
|
||||
# tests, whose `testkit` feature turns this on. Without it the delays are empty inline functions.
|
||||
testkit = []
|
||||
|
||||
[dependencies]
|
||||
thiserror = "2"
|
||||
log = { version = "0.4", features = ["kv"] }
|
||||
|
||||
@@ -5,10 +5,7 @@
|
||||
//! - [`mp4`] reads a track's configuration record and samples out of an
|
||||
//! MP4, and [`mp4_write`] writes one of what an encoder gave.
|
||||
//! - [`md5`] hashes frames, as ffmpeg's `framemd5` does.
|
||||
//! - [`marks`] reads what the conformance suite's scripts say of their streams beside them, the
|
||||
//! streams the decoder refuses, and holds a test's decode of each to it.
|
||||
|
||||
pub mod marks;
|
||||
pub mod md5;
|
||||
pub mod mp4;
|
||||
pub mod mp4_write;
|
||||
@@ -1,124 +0,0 @@
|
||||
//! What the conformance suite's scripts write beside their streams, for the tests that decode
|
||||
//! those streams elsewhere (`tools/lib.sh`'s `refusals`, and `tools/hevc-check.sh`):
|
||||
//! `refused.txt`, the streams the decoder refuses on every host, a line each, `NAME|BEFORE|SAYS`
|
||||
//! (the Annex B stream's file name, the pictures it decodes before its refusal, and what the
|
||||
//! refusal says), and `range-extensions.txt`, the range extensions' streams, a file name a line
|
||||
//! ([`Marks`]).
|
||||
//!
|
||||
//! A test holds each stream's decode to them ([`Marks::judge`]): a stream they name as refused
|
||||
//! is refused as they say, after the pictures they say; a refusal they do not name fails the
|
||||
//! test, as does a named stream that decodes past its refusal. So a stream that decoded and
|
||||
//! starts being refused turns the test red, and a test skips no refusal for being one.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
/// A refusal `refused.txt` names.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Refusal {
|
||||
/// The pictures the stream decodes before it.
|
||||
pub before: usize,
|
||||
/// What it says: text the decoder's error holds.
|
||||
pub says: String,
|
||||
}
|
||||
|
||||
/// The lists of the directories read, by stream file name.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Marks {
|
||||
/// `refused.txt`'s streams.
|
||||
pub refused: HashMap<String, Refusal>,
|
||||
/// `range-extensions.txt`'s streams.
|
||||
pub range_extensions: HashSet<String>,
|
||||
}
|
||||
|
||||
/// How a stream's decode ended.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Ended<'a> {
|
||||
/// At the stream's end, every access unit decoded.
|
||||
Whole,
|
||||
/// Where the caller stopped it, before its end.
|
||||
Stopped,
|
||||
/// At a refusal, which says this.
|
||||
Refused(&'a str),
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
/// The lists in each of `dirs`; a directory without them names none. `Err` where one does
|
||||
/// not read, or holds a line that does not parse.
|
||||
pub fn read<P: AsRef<Path>>(dirs: impl IntoIterator<Item = P>) -> Result<Self, String> {
|
||||
let mut marks = Self::default();
|
||||
for dir in dirs {
|
||||
let read = |name: &str| {
|
||||
let path = dir.as_ref().join(name);
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => Ok(text),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
|
||||
Err(error) => Err(format!("{}: {error}", path.display())),
|
||||
}
|
||||
};
|
||||
for line in read("refused.txt")?.lines().filter(|line| !line.is_empty()) {
|
||||
let mut fields = line.splitn(3, '|');
|
||||
let (Some(stream), Some(before), Some(says)) =
|
||||
(fields.next(), fields.next(), fields.next())
|
||||
else {
|
||||
return Err(format!("refused.txt: a line of three fields, not {line:?}"));
|
||||
};
|
||||
let before = (before.parse())
|
||||
.map_err(|_| format!("refused.txt: a count of pictures, not {before:?}"))?;
|
||||
let says = says.to_owned();
|
||||
marks
|
||||
.refused
|
||||
.insert(stream.to_owned(), Refusal { before, says });
|
||||
}
|
||||
let names = read("range-extensions.txt")?;
|
||||
let names = names.lines().filter(|line| !line.is_empty());
|
||||
marks.range_extensions.extend(names.map(str::to_owned));
|
||||
}
|
||||
Ok(marks)
|
||||
}
|
||||
|
||||
/// Whether `range-extensions.txt` names the stream `name`.
|
||||
pub fn is_range_extensions(&self, name: &str) -> bool {
|
||||
self.range_extensions.contains(name)
|
||||
}
|
||||
|
||||
/// The decode of the stream `name`, which gave `decoded` pictures and ended as `ended` says,
|
||||
/// held to `refused.txt` (module doc): `Ok(Some(line))`, naming the stream and its refusal,
|
||||
/// where it was refused as the list says; `Ok(None)` where the list names no refusal it
|
||||
/// reached; `Err` saying how it differs otherwise.
|
||||
pub fn judge(
|
||||
&self,
|
||||
name: &str,
|
||||
decoded: usize,
|
||||
ended: Ended<'_>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let listed = self.refused.get(name);
|
||||
let said = |r: &Refusal| format!("after {} pictures: {}", r.before, r.says);
|
||||
match (ended, listed) {
|
||||
(Ended::Refused(error), Some(r)) if decoded == r.before && error.contains(&r.says) => {
|
||||
Ok(Some(format!("{name}: after {decoded} pictures: {error}")))
|
||||
}
|
||||
(Ended::Refused(error), Some(r)) => Err(format!(
|
||||
"{name}: refused after {decoded} pictures: {error}; the suite's list says {}",
|
||||
said(r)
|
||||
)),
|
||||
(Ended::Refused(error), None) => Err(format!(
|
||||
"{name}: refused after {decoded} pictures, which the suite's list does not say: \
|
||||
{error}"
|
||||
)),
|
||||
(Ended::Whole, Some(r)) => Err(format!(
|
||||
"{name}: decoded whole, {decoded} pictures, where the suite's list says it is \
|
||||
refused {}",
|
||||
said(r)
|
||||
)),
|
||||
(Ended::Stopped, Some(r)) if decoded > r.before => Err(format!(
|
||||
"{name}: {decoded} pictures decoded, past its refusal: the suite's list says {}",
|
||||
said(r)
|
||||
)),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,155 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A directory of the test's own, empty: one a call, as the tests may run in one process.
|
||||
fn scratch() -> PathBuf {
|
||||
static MADE: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = MADE.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("rvg-marks-{}-{n}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// The lists h264-check.sh and hevc-check.sh wrote (potluck job m3-max-85184), two directories'
|
||||
/// worth, read from a directory of the test's own; and one directory with no lists.
|
||||
fn suites() -> Marks {
|
||||
let root = scratch();
|
||||
let (h264, hevc, none) = (root.join("h264"), root.join("hevc"), root.join("none"));
|
||||
for dir in [&h264, &hevc, &none] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(
|
||||
h264.join("refused.txt"),
|
||||
"high-1080p-interlaced.264|0|interlaced: \nhigh-1080p-fakeint.264|0|interlaced: \n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
hevc.join("refused.txt"),
|
||||
"kvz-720p-tiles-col64.265|0|ColumnWidthInLumaSamples is out of range\r\n\
|
||||
kvz-720p-ref15.265|9|VA-API takes 8\r\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
hevc.join("range-extensions.txt"),
|
||||
"main444-360p.265\nmain12-360p.265\n",
|
||||
)
|
||||
.unwrap();
|
||||
let marks = Marks::read([&h264, &hevc, &none]).unwrap();
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
marks
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lists_read_by_stream_name() {
|
||||
let marks = suites();
|
||||
assert_eq!(marks.refused.len(), 4);
|
||||
let ref15 = Refusal {
|
||||
before: 9,
|
||||
says: "VA-API takes 8".to_owned(),
|
||||
};
|
||||
assert_eq!(marks.refused.get("kvz-720p-ref15.265"), Some(&ref15));
|
||||
assert_eq!(
|
||||
marks
|
||||
.refused
|
||||
.get("high-1080p-fakeint.264")
|
||||
.map(|r| r.says.as_str()),
|
||||
Some("interlaced: ")
|
||||
);
|
||||
assert!(marks.is_range_extensions("main12-360p.265"));
|
||||
assert!(!marks.is_range_extensions("main-720p.265"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_does_not_parse_is_an_error() {
|
||||
let dir = scratch();
|
||||
for bad in ["a.264|0\n", "a.264|none|interlaced\n"] {
|
||||
std::fs::write(dir.join("refused.txt"), bad).unwrap();
|
||||
assert!(Marks::read([&dir]).is_err(), "{bad:?}");
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listed_stream_refused_as_its_line_says_is_named() {
|
||||
let marks = suites();
|
||||
let interlaced = "interlaced: the SPS's frame_mbs_only_flag is 0";
|
||||
assert_eq!(
|
||||
marks.judge("high-1080p-interlaced.264", 0, Ended::Refused(interlaced)),
|
||||
Ok(Some(format!(
|
||||
"high-1080p-interlaced.264: after 0 pictures: {interlaced}"
|
||||
)))
|
||||
);
|
||||
let ref15 = "the driver cannot: 9 pictures in the current reference sets: VA-API takes 8";
|
||||
assert!(matches!(
|
||||
marks.judge("kvz-720p-ref15.265", 9, Ended::Refused(ref15)),
|
||||
Ok(Some(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listed_stream_refused_otherwise_fails() {
|
||||
let marks = suites();
|
||||
let ref15 = "the driver cannot: 9 pictures in the current reference sets: VA-API takes 8";
|
||||
// Earlier than its line says, or for another reason.
|
||||
assert!(
|
||||
marks
|
||||
.judge("kvz-720p-ref15.265", 3, Ended::Refused(ref15))
|
||||
.is_err()
|
||||
);
|
||||
let other = "the driver cannot: HEVCMain: no YUV420 render targets";
|
||||
assert!(
|
||||
marks
|
||||
.judge("kvz-720p-ref15.265", 9, Ended::Refused(other))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// A stream that decoded, refused now: the planner's rule (12-03), that no refusal is skipped for
|
||||
/// being one.
|
||||
#[test]
|
||||
fn a_refusal_the_lists_do_not_name_fails() {
|
||||
let marks = suites();
|
||||
let refused = "the driver cannot: HEVCMain: the driver has no decoder";
|
||||
let judged = marks.judge("main-720p.265", 0, Ended::Refused(refused));
|
||||
assert!(judged.unwrap_err().contains("does not say"));
|
||||
let empty = Marks::default();
|
||||
let interlaced = "interlaced: the SPS's frame_mbs_only_flag is 0";
|
||||
assert!(
|
||||
empty
|
||||
.judge("high-1080p-interlaced.264", 0, Ended::Refused(interlaced))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listed_stream_that_decodes_past_its_refusal_fails() {
|
||||
let marks = suites();
|
||||
assert!(
|
||||
marks
|
||||
.judge("high-1080p-fakeint.264", 30, Ended::Whole)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
marks
|
||||
.judge("kvz-720p-ref15.265", 10, Ended::Stopped)
|
||||
.is_err()
|
||||
);
|
||||
// Stopped by its caller before it.
|
||||
assert_eq!(
|
||||
marks.judge("kvz-720p-ref15.265", 4, Ended::Stopped),
|
||||
Ok(None)
|
||||
);
|
||||
assert_eq!(
|
||||
marks.judge("kvz-720p-ref15.265", 9, Ended::Stopped),
|
||||
Ok(None)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unlisted_stream_that_decodes_is_nothing_to_name() {
|
||||
let marks = suites();
|
||||
assert_eq!(marks.judge("main-720p.265", 120, Ended::Whole), Ok(None));
|
||||
assert_eq!(marks.judge("main-720p.265", 4, Ended::Stopped), Ok(None));
|
||||
}
|
||||
@@ -52,10 +52,6 @@ pub enum Profile {
|
||||
HevcMain,
|
||||
/// HEVC Main 10, `general_profile_idc` 2: 10-bit 4:2:0.
|
||||
HevcMain10,
|
||||
/// HEVC Main 4:2:2 10, `general_profile_idc` 4 (the format range
|
||||
/// extensions) with Main 4:2:2 10's constraint flags (A.3.5, Table
|
||||
/// A.2): 10-bit 4:2:2.
|
||||
HevcMain42210,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
@@ -63,7 +59,7 @@ impl Profile {
|
||||
pub const fn codec(self) -> Codec {
|
||||
match self {
|
||||
Self::H264ConstrainedBaseline | Self::H264Main | Self::H264High => Codec::H264,
|
||||
Self::HevcMain | Self::HevcMain10 | Self::HevcMain42210 => Codec::Hevc,
|
||||
Self::HevcMain | Self::HevcMain10 => Codec::Hevc,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,31 +72,21 @@ impl Profile {
|
||||
Self::H264High => 100,
|
||||
Self::HevcMain => 1,
|
||||
Self::HevcMain10 => 2,
|
||||
Self::HevcMain42210 => 4,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bits a sample.
|
||||
pub const fn bit_depth(self) -> u8 {
|
||||
match self {
|
||||
Self::HevcMain10 | Self::HevcMain42210 => 10,
|
||||
Self::HevcMain10 => 10,
|
||||
_ => 8,
|
||||
}
|
||||
}
|
||||
|
||||
/// `chroma_format_idc`: 1 for 4:2:0, 2 for 4:2:2.
|
||||
pub const fn chroma_format_idc(self) -> u8 {
|
||||
match self {
|
||||
Self::HevcMain42210 => 2,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The input format the profile takes.
|
||||
pub const fn input_format(self) -> InputFormat {
|
||||
match self {
|
||||
Self::HevcMain10 => InputFormat::P010,
|
||||
Self::HevcMain42210 => InputFormat::P210,
|
||||
_ => InputFormat::Nv12,
|
||||
}
|
||||
}
|
||||
@@ -111,18 +97,15 @@ impl Profile {
|
||||
}
|
||||
}
|
||||
|
||||
/// How the frames handed to an encoder are laid out: a luma plane and an
|
||||
/// interleaved Cb/Cr plane, half as tall in 4:2:0 and as tall in 4:2:2.
|
||||
/// How the frames handed to an encoder are laid out: 4:2:0, a luma plane
|
||||
/// and an interleaved Cb/Cr plane half as tall.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum InputFormat {
|
||||
/// 4:2:0, 8-bit samples, one byte each (CoreVideo's `420v` and `420f`).
|
||||
/// 8-bit samples, one byte each (CoreVideo's `420v` and `420f`).
|
||||
Nv12,
|
||||
/// 4:2:0, 10-bit samples in the high bits of little-endian 16-bit
|
||||
/// words (CoreVideo's `x420` and `xf20`).
|
||||
/// 10-bit samples in the high bits of little-endian 16-bit words
|
||||
/// (CoreVideo's `x420` and `xf20`).
|
||||
P010,
|
||||
/// 4:2:2, 10-bit samples in the high bits of little-endian 16-bit
|
||||
/// words (CoreVideo's `x422` and `xf22`).
|
||||
P210,
|
||||
}
|
||||
|
||||
impl InputFormat {
|
||||
@@ -130,16 +113,7 @@ impl InputFormat {
|
||||
pub const fn bytes_per_sample(self) -> usize {
|
||||
match self {
|
||||
Self::Nv12 => 1,
|
||||
Self::P010 | Self::P210 => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// The chroma plane's rows of a picture of `rows` luma rows: half of
|
||||
/// them, rounded down, in 4:2:0, and all of them in 4:2:2.
|
||||
pub const fn chroma_rows(self, rows: u32) -> u32 {
|
||||
match self {
|
||||
Self::Nv12 | Self::P010 => rows / 2,
|
||||
Self::P210 => rows,
|
||||
Self::P010 => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,12 +68,6 @@ pub struct DriverLimits {
|
||||
pub max_width: u32,
|
||||
/// The tallest surface it encodes.
|
||||
pub max_height: u32,
|
||||
/// What the coded width is a multiple of beside the codec's own
|
||||
/// block, a power of two: 1 where the driver states nothing.
|
||||
pub width_alignment: u32,
|
||||
/// What the coded height is a multiple of beside the codec's own
|
||||
/// block, a power of two: 1 where the driver states nothing.
|
||||
pub height_alignment: u32,
|
||||
/// HEVC's tools, resolved from what the driver allows and requires.
|
||||
pub hevc_tools: Option<hevc::Tools>,
|
||||
}
|
||||
@@ -363,12 +357,7 @@ fn check_settings(settings: &EncoderSettings) -> Result<(), Unsupported> {
|
||||
check(s.width > 0 && s.height > 0, || "an empty picture".into())?;
|
||||
check(
|
||||
s.width.is_multiple_of(2) && s.height.is_multiple_of(2),
|
||||
|| {
|
||||
format!(
|
||||
"{}x{}: the encoder takes even sizes alone",
|
||||
s.width, s.height
|
||||
)
|
||||
},
|
||||
|| format!("{}x{}: 4:2:0 needs an even size", s.width, s.height),
|
||||
)?;
|
||||
check(
|
||||
s.frame_rate.numerator > 0 && s.frame_rate.denominator > 0,
|
||||
@@ -528,14 +517,13 @@ impl<A: Accelerator> Encoder<A> {
|
||||
let intra_period = s.key_frame_interval.unwrap_or(0);
|
||||
// The coded size: the settings' raised to the driver's least and
|
||||
// rounded up to `to`, and what the SPS crops off it.
|
||||
// The codec's block, or the driver's alignment where it is wider.
|
||||
let coded = |to: u32| {
|
||||
let size = |value: u32, least: u32, alignment: u32| {
|
||||
let coded = align(value.max(least), to.max(alignment))?;
|
||||
let size = |value: u32, least: u32| {
|
||||
let coded = align(value.max(least), to)?;
|
||||
Some((coded, coded.checked_sub(value)?))
|
||||
};
|
||||
size(s.width, limits.min_width, limits.width_alignment)
|
||||
.zip(size(s.height, limits.min_height, limits.height_alignment))
|
||||
size(s.width, limits.min_width)
|
||||
.zip(size(s.height, limits.min_height))
|
||||
.ok_or_else(|| Unsupported::overflow("the coded size"))
|
||||
};
|
||||
let (headers, coded_size) = match s.profile.codec() {
|
||||
@@ -592,7 +580,6 @@ impl<A: Accelerator> Encoder<A> {
|
||||
.ok_or_else(|| Unsupported::overflow("the least coding block"))?;
|
||||
let ((coded_width, crop_right), (coded_height, crop_bottom)) = coded(min_cb)?;
|
||||
let needs = hevc::LevelNeeds {
|
||||
profile: s.profile,
|
||||
width: coded_width,
|
||||
height: coded_height,
|
||||
frames_per_second: fps,
|
||||
@@ -1454,8 +1441,6 @@ pub mod tests {
|
||||
min_height: 128,
|
||||
max_width: 4096,
|
||||
max_height: 4096,
|
||||
width_alignment: 1,
|
||||
height_alignment: 1,
|
||||
hevc_tools: Some(hevc::Tools {
|
||||
log2_min_cb_size: 3,
|
||||
log2_ctb_size: 6,
|
||||
@@ -1714,66 +1699,6 @@ pub mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A coded size, and the rectangle an SPS shows: x, y, width and height.
|
||||
type Shown = ((u32, u32), (u32, u32, u32, u32));
|
||||
|
||||
/// The coded size of an encoder of `profile` at `width` x `height`, under a driver that
|
||||
/// states the alignment `(width, height)`, and the rectangle its SPS shows, as a decoder's
|
||||
/// parser reads it.
|
||||
fn shown(
|
||||
profile: Profile,
|
||||
(width, height): (u32, u32),
|
||||
alignment: (u32, u32),
|
||||
) -> Result<Shown, Unsupported> {
|
||||
let limits = DriverLimits {
|
||||
width_alignment: alignment.0,
|
||||
height_alignment: alignment.1,
|
||||
..limits()
|
||||
};
|
||||
let encoder = Encoder::new(
|
||||
Fake::default(),
|
||||
EncoderSettings::new(profile, width, height),
|
||||
&limits,
|
||||
)?;
|
||||
let rect = match &encoder.headers {
|
||||
Headers::Hevc { sps, .. } => crate::codec::hevc::sps::Sps::parse(&sps.sps_nal()?)
|
||||
.expect("our SPS parses")
|
||||
.crop_rect(),
|
||||
Headers::H264 { sps, .. } => crate::codec::h264::sps::Sps::parse(&sps.to_nal()?)
|
||||
.expect("our SPS parses")
|
||||
.crop_rect(),
|
||||
};
|
||||
Ok((encoder.coded_size(), rect))
|
||||
}
|
||||
|
||||
/// The coded size is a multiple of the codec's block and of the alignment the driver
|
||||
/// states, and the SPS's window (HEVC) or crop (H.264) takes the rest off: a decoder shows
|
||||
/// the asked rectangle. With none stated, the codec's block alone, as before.
|
||||
#[test]
|
||||
fn the_coded_size_follows_the_drivers_alignment_and_the_sps_shows_the_asked_size()
|
||||
-> Result<(), Unsupported> {
|
||||
// radeonsi's answers for HEVC (64x16) and H.264 (16x16) on an RX 550 and a Radeon 780M
|
||||
// (m3-max-85418, m3-max-85437); iHD states none (m3-max-85417).
|
||||
let cases = [
|
||||
(Profile::HevcMain, (1920, 1080), (64, 16), (1920, 1088)),
|
||||
(Profile::HevcMain10, (1920, 1080), (64, 16), (1920, 1088)),
|
||||
(Profile::HevcMain, (1366, 768), (64, 16), (1408, 768)),
|
||||
(Profile::HevcMain, (1366, 766), (64, 16), (1408, 768)),
|
||||
(Profile::HevcMain, (1920, 1080), (1, 1), (1920, 1080)),
|
||||
(Profile::HevcMain, (1366, 766), (1, 1), (1368, 768)),
|
||||
(Profile::H264High, (1920, 1080), (16, 16), (1920, 1088)),
|
||||
(Profile::H264High, (1366, 766), (16, 16), (1376, 768)),
|
||||
(Profile::H264High, (1366, 766), (1, 1), (1376, 768)),
|
||||
];
|
||||
for (profile, size, alignment, coded) in cases {
|
||||
let at = format!("{profile:?} at {size:?}, the driver's alignment {alignment:?}");
|
||||
let (got, rect) = shown(profile, size, alignment)?;
|
||||
assert_eq!(got, coded, "{at}: the coded size");
|
||||
assert_eq!(rect, (0, 0, size.0, size.1), "{at}: what the SPS shows");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hevc_predicts_from_the_last_picture_in_order() -> Result<(), Unsupported> {
|
||||
let mut settings = EncoderSettings::new(Profile::HevcMain10, 100, 50);
|
||||
|
||||
@@ -114,14 +114,11 @@ fn header(unit_type: u8) -> [u8; 2] {
|
||||
|
||||
impl Sps {
|
||||
/// `general_profile_compatibility_flag[j]` as hvcC's 32 bits, flag 0
|
||||
/// first: Main streams are Main 10 streams too (A.3.2, A.3.3), and a
|
||||
/// Main 4:2:2 10 stream is of the format range extensions, profile 4
|
||||
/// (A.3.5).
|
||||
/// first: Main streams are Main 10 streams too (A.3.2, A.3.3).
|
||||
pub(crate) fn compatibility_flags(&self) -> u32 {
|
||||
let flag = |j: u32| 0x8000_0000u32 >> j;
|
||||
match self.profile {
|
||||
Profile::HevcMain => flag(1) | flag(2),
|
||||
Profile::HevcMain42210 => flag(4),
|
||||
_ => flag(2),
|
||||
}
|
||||
}
|
||||
@@ -135,21 +132,9 @@ impl Sps {
|
||||
w.flag(false); // general_interlaced_source_flag
|
||||
w.flag(false); // general_non_packed_constraint_flag
|
||||
w.flag(true); // general_frame_only_constraint_flag
|
||||
if self.profile.profile_idc() == 4 {
|
||||
// Main 4:2:2 10's constraint flags (Table A.2):
|
||||
// general_max_12bit, _10bit, _8bit, _422chroma, _420chroma,
|
||||
// _monochrome, general_intra, general_one_picture_only and
|
||||
// general_lower_bit_rate_constraint_flag.
|
||||
for flag in [true, true, false, true, false, false, false, false, true] {
|
||||
w.flag(flag);
|
||||
}
|
||||
// general_reserved_zero_34bits, then general_inbld_flag.
|
||||
w.bits(35, 0);
|
||||
} else {
|
||||
// general_reserved_zero_43bits (or Main 10's reserved and
|
||||
// one_picture_only bits, all 0), then general_inbld_flag.
|
||||
w.bits(44, 0);
|
||||
}
|
||||
// general_reserved_zero_43bits (or Main 10's reserved and
|
||||
// one_picture_only bits, all 0), then general_inbld_flag.
|
||||
w.bits(44, 0);
|
||||
w.u(8, u32::from(self.level_idc));
|
||||
}
|
||||
|
||||
@@ -199,21 +184,17 @@ impl Sps {
|
||||
w.flag(true); // sps_temporal_id_nesting_flag
|
||||
self.write_profile_tier_level(&mut w);
|
||||
w.ue(0); // sps_seq_parameter_set_id
|
||||
w.ue(u32::from(self.profile.chroma_format_idc()));
|
||||
w.ue(1); // chroma_format_idc: 4:2:0
|
||||
w.ue(self.width);
|
||||
w.ue(self.height);
|
||||
let cropped = self.crop_right > 0 || self.crop_bottom > 0;
|
||||
w.flag(cropped); // conformance_window_flag
|
||||
if cropped {
|
||||
// In chroma samples: SubWidthC is 2, and SubHeightC 2 in 4:2:0
|
||||
// and 1 in 4:2:2 (Table 6-1).
|
||||
// In chroma samples: SubWidthC and SubHeightC are 2 (6-1).
|
||||
w.ue(0);
|
||||
w.ue(self.crop_right / 2);
|
||||
w.ue(0);
|
||||
w.ue(match self.profile.chroma_format_idc() {
|
||||
2 => self.crop_bottom,
|
||||
_ => self.crop_bottom / 2,
|
||||
});
|
||||
w.ue(self.crop_bottom / 2);
|
||||
}
|
||||
let depth = u32::from(self.profile.bit_depth())
|
||||
.checked_sub(8)
|
||||
@@ -573,8 +554,7 @@ struct Level {
|
||||
max_luma_ps: u64,
|
||||
/// MaxLumaSr: luma samples a second.
|
||||
max_luma_sr: u64,
|
||||
/// MaxBR, in units of CpbVclFactor bit/s (Table A.9; Main's and Main
|
||||
/// 10's CpbVclFactor is 1000).
|
||||
/// MaxBR, in units of 1000 bit/s (CpbVclFactor, Table A.11).
|
||||
max_br: u64,
|
||||
}
|
||||
|
||||
@@ -603,20 +583,9 @@ const fn level(level_idc: u8, max_luma_ps: u64, max_luma_sr: u64, max_br: u64) -
|
||||
}
|
||||
}
|
||||
|
||||
/// `CpbVclFactor` (Table A.8): what the levels' MaxBR is in units of, in
|
||||
/// bit/s: 1000 for Main and Main 10, 1667 for Main 4:2:2 10.
|
||||
const fn cpb_vcl_factor(profile: Profile) -> u64 {
|
||||
match profile {
|
||||
Profile::HevcMain42210 => 1667,
|
||||
_ => 1000,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a stream needs of its level.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct LevelNeeds {
|
||||
/// The profile, whose CpbVclFactor scales the levels' bitrates.
|
||||
pub profile: Profile,
|
||||
/// The width in luma samples.
|
||||
pub width: u32,
|
||||
/// The height in luma samples.
|
||||
@@ -664,13 +633,11 @@ impl LevelNeeds {
|
||||
&& side(h)
|
||||
&& (size as f64) * self.frames_per_second <= level.max_luma_sr as f64
|
||||
&& u64::from(self.dpb_pictures) <= max_dpb
|
||||
// At most MaxBR units of the profile's CpbVclFactor.
|
||||
// At most MaxBR thousand, so in thousands, rounded up, at most
|
||||
// MaxBR.
|
||||
&& self
|
||||
.bits_per_second
|
||||
.is_none_or(|bps| {
|
||||
(level.max_br.checked_mul(cpb_vcl_factor(self.profile)))
|
||||
.is_some_and(|max| u64::from(bps) <= max)
|
||||
})
|
||||
.is_none_or(|bps| u64::from(bps).div_ceil(1000) <= level.max_br)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -789,46 +756,6 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A Main 4:2:2 10 SPS says profile 4 with Main 4:2:2 10's constraint flags (Table A.2), 4:2:2
|
||||
/// at 10 bits, and its conformance window in rows of luma (SubHeightC 1), as a decoder's
|
||||
/// parser reads it.
|
||||
#[test]
|
||||
fn a_main_422_10_sps_says_its_profile_and_chroma_format()
|
||||
-> Result<(), crate::codec::hevc::Error> {
|
||||
let sps = Sps {
|
||||
profile: Profile::HevcMain42210,
|
||||
level_idc: 120,
|
||||
height: 1088,
|
||||
crop_right: 8,
|
||||
crop_bottom: 8,
|
||||
..sps()
|
||||
};
|
||||
let unit = sps.sps_nal().unwrap();
|
||||
let mut r = BitReader::new(&unit);
|
||||
r.skip(16 + 8)?;
|
||||
assert_eq!(r.bits(8)?, 4); // space, tier, profile 4
|
||||
assert_eq!(r.bits(32)?, 0x0800_0000); // compatible with profile 4 alone
|
||||
assert_eq!(r.bits(4)?, 0b1001);
|
||||
// max_12bit, max_10bit, max_8bit, max_422chroma, max_420chroma, max_monochrome, intra,
|
||||
// one_picture_only, lower_bit_rate; 34 reserved bits and general_inbld_flag.
|
||||
assert_eq!(r.bits(9)?, 0b1_1010_0001);
|
||||
assert_eq!(r.bits(32)?, 0);
|
||||
assert_eq!(r.bits(3)?, 0);
|
||||
assert_eq!(r.bits(8)?, 120);
|
||||
let parsed = crate::codec::hevc::sps::Sps::parse(&unit)?;
|
||||
let ptl = &parsed.profile_tier_level;
|
||||
assert_eq!(ptl.general_profile_idc, 4);
|
||||
assert!(ptl.compatible_with(4) && !ptl.compatible_with(2));
|
||||
assert_eq!(parsed.chroma_format_idc, 2);
|
||||
assert_eq!(
|
||||
(parsed.bit_depth_luma_minus8, parsed.bit_depth_chroma_minus8),
|
||||
(2, 2)
|
||||
);
|
||||
assert_eq!(parsed.conformance_window, [0, 4, 0, 8]);
|
||||
assert_eq!(parsed.crop_rect(), (0, 0, 1912, 1080));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slice_headers_carry_their_reference_sets() -> Result<(), crate::codec::hevc::Error> {
|
||||
let sps = sps();
|
||||
@@ -907,7 +834,6 @@ mod tests {
|
||||
#[test]
|
||||
fn levels_come_from_tables_a_8_and_a_9() -> Result<(), Unsupported> {
|
||||
let needs = |width, height, fps, bps| LevelNeeds {
|
||||
profile: Profile::HevcMain,
|
||||
width,
|
||||
height,
|
||||
frames_per_second: fps,
|
||||
@@ -930,14 +856,6 @@ mod tests {
|
||||
assert_eq!(choose_level(&needs(3840, 2160, 60.0, None))?, 153);
|
||||
assert_eq!(choose_level(&needs(136, 128, 30.0, None))?, 30);
|
||||
assert!(choose_level(&needs(8192, 8192, 60.0, None)).is_err());
|
||||
// Main 4:2:2 10's bitrates are 1667 bit/s a unit of MaxBR: level 4's 20 Mbit/s.
|
||||
let main_422_10 = |bps| LevelNeeds {
|
||||
profile: Profile::HevcMain42210,
|
||||
..needs(1920, 1080, 30.0, Some(bps))
|
||||
};
|
||||
assert_eq!(choose_level(&main_422_10(15_000_000))?, 120);
|
||||
assert_eq!(choose_level(&main_422_10(20_004_000))?, 120);
|
||||
assert_eq!(choose_level(&main_422_10(20_004_001))?, 123);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -30,34 +30,6 @@ pub(crate) const PROFILE_0_MD5: &str = include_str!("tests/vp9p0.md5");
|
||||
/// high bits of a 16-bit little-endian word.
|
||||
pub(crate) const PROFILE_2_MD5: &str = include_str!("tests/vp9p2.md5");
|
||||
|
||||
/// A profile 0 stream whose inter frames change size: 30 frames of ffmpeg's
|
||||
/// `testsrc2` at each size, coded by libvpx-vp9 in one pass with no altref
|
||||
/// frames, its size changed between frames with `vpx_codec_enc_config_set`,
|
||||
/// as libvpx's own resize test changes it, in IVF. Its key frame is its first;
|
||||
/// each frame after a change predicts from frames of the size before, scaled
|
||||
/// (8.5.2.3): [`RESIZE_SIZES`].
|
||||
pub(crate) const RESIZE_IVF: &[u8] = include_bytes!("tests/vp9resize.ivf");
|
||||
/// The MD5 of each frame of [`RESIZE_IVF`] as libvpx's `vpxdec` decodes it, at
|
||||
/// its own size, over NV12 planes as [`PROFILE_0_MD5`] is. ffmpeg's own VP9
|
||||
/// decoder gives the same frames.
|
||||
pub(crate) const RESIZE_MD5: &str = include_str!("tests/vp9resize.md5");
|
||||
/// [`RESIZE_IVF`]'s sizes: each from the frame it names to the next's.
|
||||
pub(crate) const RESIZE_SIZES: [(usize, (u32, u32)); 5] = [
|
||||
(0, (352, 288)),
|
||||
(8, (176, 144)),
|
||||
(14, (264, 216)),
|
||||
(20, (352, 288)),
|
||||
(26, (320, 240)),
|
||||
];
|
||||
|
||||
/// The size of [`RESIZE_IVF`]'s frame `frame`.
|
||||
pub(crate) fn resize_size(frame: usize) -> (u32, u32) {
|
||||
let (_, size) = (RESIZE_SIZES.iter().rev())
|
||||
.find(|(first, _)| *first <= frame)
|
||||
.expect("the first frame's size");
|
||||
*size
|
||||
}
|
||||
|
||||
/// A libvpx stream of one of VP9's formats past profile 0 and profile 2 at 10
|
||||
/// bits: 352x288, 20 frames of ffmpeg's `testsrc2` coded by libvpx-vp9 (two
|
||||
/// passes, altref frames on, so hidden frames in superframes), in IVF, with
|
||||
@@ -1202,37 +1174,6 @@ fn libvpx_streams_of_every_format_decode_every_frame_in_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each frame of the stream whose inter frames change size comes out at its
|
||||
/// own size, the accelerator configured again at each change, and the first
|
||||
/// frame after each change, an inter frame, given its last frame, the frame
|
||||
/// before it, at the size before.
|
||||
#[test]
|
||||
fn a_libvpx_stream_whose_inter_frames_change_size_decodes_every_frame_at_its_own_size() {
|
||||
let mut decoder = Decoder::new(Recording::default());
|
||||
for (id, sample) in (0u64..).zip(ivf_frames(RESIZE_IVF)) {
|
||||
let out = decoder.decode(sample, id).unwrap();
|
||||
assert_eq!(out.len(), 1, "sample {id} shows one frame");
|
||||
let frame = usize::try_from(id).unwrap();
|
||||
assert_eq!(out[0].size, resize_size(frame), "sample {id}");
|
||||
assert_eq!(out[0].key_frame, id == 0, "sample {id}");
|
||||
}
|
||||
assert_eq!(RESIZE_MD5.lines().count(), 30, "a reference MD5 a frame");
|
||||
let configured: Vec<_> = (decoder.accelerator().configured.iter())
|
||||
.map(|format| (format.width, format.height))
|
||||
.collect();
|
||||
let sizes: Vec<_> = RESIZE_SIZES.iter().map(|(_, size)| *size).collect();
|
||||
assert_eq!(configured, sizes);
|
||||
let frames = &decoder.accelerator().frames;
|
||||
for &(first, size) in &RESIZE_SIZES[1..] {
|
||||
let (_, header, slots, _) = &frames[first];
|
||||
assert!(!header.is_intra(), "frame {first}");
|
||||
assert_eq!((header.width, header.height), size, "frame {first}");
|
||||
let last = usize::from(header.ref_frame_idx[0]);
|
||||
let (_, width, height) = slots[last].expect("its last frame");
|
||||
assert_eq!((width, height), resize_size(first - 1), "frame {first}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_frames_keep_their_pictures_alive_beside_the_slots() {
|
||||
let mut decoder = Decoder::new(Recording::default());
|
||||
|
||||
Binary file not shown.
@@ -1,30 +0,0 @@
|
||||
382192e69ba47cf2aac051ada618cdc6
|
||||
658ed97d3f77b828dfa2c70b122293b7
|
||||
7f483b61d23cc900a33301a8208cd5f9
|
||||
37ac20777df1fba89044ac3aeeb26898
|
||||
b74df151274816526c3bce57f84dbee0
|
||||
751d06ff288eb369139a59b67858bd26
|
||||
d0fca88b2392acf1793e63f3961fbaa3
|
||||
aef35dd2ed84595885bab482d68f7ebf
|
||||
924a448a7a4acd7753021829a8afbfe6
|
||||
bdc3b78b00226588c18c4c583f299159
|
||||
9dacde185249742697f45d2e8ea25fb6
|
||||
eaf5a370c39295d99bd5c206f7922a39
|
||||
a6527ef009ec06be065c611a255ff25c
|
||||
bd16282b63ed77b495746bf57b97e019
|
||||
e165d13a0cfff7aa4a8e02542b97164b
|
||||
f6ba6bb67670c9385056a5b35d9fa1a2
|
||||
5d7d23dd933810e29528c0126ef698ff
|
||||
1964c25c69b459cf4589f3398dd6803a
|
||||
73f88aff8168799f2f8b46337753dc80
|
||||
bdf2df94730a01541b09a51650a39ecf
|
||||
82e0eabc5c4446b5f43c725a3aaf8029
|
||||
1821dfcb28a2be86229f042ec8094288
|
||||
dbf7a6cb64937b7bfa5b446e8f8ce347
|
||||
a5188383b92612271581b258503c89cc
|
||||
137e188302533648dcd921ba43ff9e9e
|
||||
ebcd4d300532cdd4e673873dbb456ae8
|
||||
651e3e03bc1d32edb67638b23a2e6054
|
||||
f8adc30af51fb3214520cd75f204f092
|
||||
38d3aeda3edba90a9fcec3a30fc385d3
|
||||
36e36ae3730922b2fad39c89a4a7c3f3
|
||||
Loaded 100 of 620 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user