🆕 Replace the tree with libreims_vgpu and its C API
This repository now holds libreims_vgpu, a Rust library that is the host side of the paravirtualized GPU macOS guests drive, in place of Apple's ParavirtualizedGraphics.framework: the library and its C API (reims_vgpu.h), the PCI device's option ROM, QEMU's apple-gfx on that API (vendor/qemu), the behaviour-lock suite that drives the C API as QEMU does, and reims-ctl, the VM manager users run. README.md says what it is and how it is laid out, and AGENTS.md how to change it. Every file of the earlier tree is replaced. vendor/qemu moves to the steelbrain/reims-vgpu branch of the same public repository.
This commit is contained in:
1 parent
69a57dd69a
commit
98fe2a3bd5
7821 files changed
+1862024
-488319
No files matched your search
@@ -0,0 +1,2 @@
|
||||
[alias]
|
||||
xtask = "run --package xtask --"
|
||||
@@ -1,8 +0,0 @@
|
||||
[profile.default]
|
||||
slow-timeout = { period = "30s", terminate-after = 3 }
|
||||
retries = 0
|
||||
failure-output = "immediate-final"
|
||||
|
||||
[profile.full]
|
||||
slow-timeout = { period = "60s", terminate-after = 3 }
|
||||
fail-fast = false
|
||||
+13
-66
@@ -1,70 +1,17 @@
|
||||
# Build output: QEMU's builds, the coverage build and the VM clones.
|
||||
/build/
|
||||
|
||||
build/
|
||||
# build output
|
||||
.cache/
|
||||
# caches / scratch
|
||||
dist/
|
||||
*.dmg
|
||||
.DS_Store
|
||||
# editor / OS cruft
|
||||
*.fd
|
||||
/target/
|
||||
/host/target/
|
||||
.idea/
|
||||
# (Negations must re-include the parent dir before re-including files within it.)
|
||||
*.o
|
||||
OVMF_VARS*.fd
|
||||
*.part
|
||||
*.png
|
||||
!/assets/
|
||||
!/assets/readme/
|
||||
!/assets/readme/reims-vgpu-macos-arm64-desktop.png
|
||||
!/assets/readme/reims-vgpu-macos-x86-desktop.png
|
||||
*.ppm
|
||||
# The option ROM's build, when make runs in firmware/ (cargo xtask dist builds
|
||||
# it under the target directory).
|
||||
/firmware/build/
|
||||
|
||||
# Python's bytecode caches.
|
||||
__pycache__/
|
||||
*.qcow2
|
||||
*.spv
|
||||
*.spv.h
|
||||
*.swp
|
||||
/vm/*
|
||||
!/vm/boot-arm64.sh
|
||||
!/vm/boot-x86.sh
|
||||
!/vm/guest-authorize.sh
|
||||
!/vm/rail-debug-posture.sh
|
||||
!/vm/rail-sweep.sh
|
||||
!/vm/drive-desktop.sh
|
||||
vm/debug/
|
||||
vm/logs/
|
||||
# OVMF firmware blobs (CODE/VARS .fd) — large binary runtime, never commit
|
||||
/vm/ovmf/
|
||||
!/vm/README.md
|
||||
!/vm/.version
|
||||
.vscode/
|
||||
Vulkan-Headers/
|
||||
.claude/worktrees/
|
||||
.claude/settings.local.json
|
||||
/.agents/
|
||||
|
||||
# Private research notes and handoff material.
|
||||
/kb/
|
||||
/journal/
|
||||
/m2v-handoff/
|
||||
# Packaged metal2vulkan defects: a README plus the Apple AIR that reproduces each.
|
||||
# Apple bytes, so local only — hand a directory over by copying it. See AGENTS.md.
|
||||
/bugs/
|
||||
# Editor / OS
|
||||
.DS_Store
|
||||
|
||||
# vendor/qemu is a git submodule (steelbrain/qemu-reims-vgpu, branch host-reims-vgpu-vmapple).
|
||||
# Its own build/ output is ignored by QEMU's own .gitignore.
|
||||
|
||||
# In-workspace vmapple guest bundle (provisioned by scripts/vmapple-provision;
|
||||
# disk/aux images + instance-specific vm.json + per-boot run scratch). Large/private.
|
||||
/vm/guest/
|
||||
/vm/ipsw/
|
||||
|
||||
# Guest crash reports (.ips) — Apple diagnostic artifacts, keep local, never commit
|
||||
.agents/crashes/
|
||||
|
||||
# LLVM coverage artifacts (scripts/runtime-dead writes under /tmp; these are
|
||||
# what a stray instrumented `cargo test` drops in the tree).
|
||||
*.profraw
|
||||
*.profdata
|
||||
# The Cargo workspace's build trees (target, and any target-* beside it), and
|
||||
# reims-ctl's, which is a workspace of its own.
|
||||
/target*/
|
||||
/crates/reims-ctl/target/
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
[submodule "vendor/qemu"]
|
||||
path = vendor/qemu
|
||||
url = https://github.com/steelbrain/qemu-reims-vgpu.git
|
||||
branch = host-reims-vgpu-vmapple
|
||||
url = https://github.com/steelbrain/qemu-reims-vgpu
|
||||
branch = steelbrain/reims-vgpu
|
||||
@@ -1,142 +1,346 @@
|
||||
# AGENTS.md
|
||||
# Working on this repository
|
||||
|
||||
This project emulates Apple's paravirtualized GPU. The unmodified macOS guest supplies the driver;
|
||||
QEMU and the Rust backend decode its command stream and execute it through Metal or Vulkan.
|
||||
This repository builds `libreims_vgpu`, a Rust library that is the host
|
||||
side of the paravirtualized GPU macOS guests drive (PCI `106b:eeee`, and
|
||||
vmapple's MMIO device), in place of Apple's
|
||||
`ParavirtualizedGraphics.framework`:
|
||||
- the library and its C API, `reims_vgpu.h`, which `cargo xtask dist`
|
||||
writes into `target/dist` with a pkg-config package and the option ROM;
|
||||
- the option ROM (`firmware/`), the PCI device's UEFI driver in C, which an
|
||||
x86-64 guest's firmware runs;
|
||||
- QEMU's `apple-gfx` (`vendor/qemu`), in C on that API, which finds the
|
||||
library through pkg-config and links it statically;
|
||||
- the behaviour-lock suite (`tests/suite`), whose runner drives the C API
|
||||
as QEMU does.
|
||||
|
||||
Nested `AGENTS.md` files apply within their directories.
|
||||
The library draws frames with its own shaders. On macOS it runs on Metal.
|
||||
On Linux it runs on the Vulkan platform (`crates/reims-vgpu-vulkan`), over
|
||||
metal2vulkan's Metal-shaped runtime, which a Mac can also build on MoltenVK.
|
||||
Under process isolation it runs each guest task other than task 0 on threads
|
||||
of its own, in the host's process.
|
||||
|
||||
## Build the contract into the structure
|
||||
[README.md](README.md) says what the project is and how it is laid out. This
|
||||
file covers what holds the code, how to check a change, and the rules for
|
||||
changing it. [docs/architecture.md](docs/architecture.md) describes the
|
||||
code, and [docs/conventions.md](docs/conventions.md) the conventions it
|
||||
follows.
|
||||
|
||||
- Implement behavior from decoded fields, layouts, calling conventions, or host capabilities. If a
|
||||
decision-affecting contract term is unknown, recover it or return a typed refusal; do not guess.
|
||||
- Put each invariant in the type, resolver, transaction, or state machine that owns it. Change the
|
||||
owner when it cannot express the invariant instead of adding call-site flags, duplicate lookups,
|
||||
fixup passes, or special cases around it.
|
||||
- Parse guest ordinals once into total Rust types and carry those types. Keep page geometry explicit
|
||||
through `page_shift` or `page_size`, and derive constants from the contract.
|
||||
- Prefer making invalid states unrepresentable, deriving duplicated values from one source, and
|
||||
testing behavior at the owner's boundary.
|
||||
- Gate optional paths on structural capabilities, not device names. Environment overrides may
|
||||
narrow capability but never widen it.
|
||||
**The codebase is its own reference.** Its unit tests, its pins and the
|
||||
suite's expected files record what it does. Every merge ends green: the
|
||||
merged tree passes what the tree before it passed. A change meant to
|
||||
alter behaviour records the affected files again from its own build, and the
|
||||
diff is reviewed with the change.
|
||||
|
||||
Conformance records compatibility; it does not define an unknown API contract. Static inspection
|
||||
of locally available binaries is acceptable for recovering missing contracts, but third-party
|
||||
bytes, disassembly, extracted assets, and binary provenance must remain local and uncommitted.
|
||||
Persist only the resulting field, layout, lifetime, ordering, or calling-convention contract.
|
||||
## Start here
|
||||
|
||||
## Ownership boundaries
|
||||
```sh
|
||||
make # the library in target/dist (cargo xtask dist): libreims_vgpu.a and
|
||||
# .dylib, reims_vgpu.h, reims-vgpu.pc and the option ROM
|
||||
make smoke # link it as QEMU does and run an isolated guest task
|
||||
make test # the suite on the checkout's library, against its expected files
|
||||
cargo xtask check # lints, rustfmt, clippy and every test: run it once before a branch merges
|
||||
```
|
||||
|
||||
- `vendor/qemu`: thin QEMU device shim for QOM, MMIO/BAR, IRQ/MSI, display integration, and
|
||||
`HostOps` plumbing.
|
||||
- `crates/reims-vgpu`: device model, decode, mapping, scheduling, command execution, presentation,
|
||||
and backend policy.
|
||||
- `crates/reims-vgpu-wire`: derived wire views; its nested instructions also apply.
|
||||
- `crates/reims-vgpu-protocol`: `no_std`. The first layer allowed to assign meaning to a wire tag —
|
||||
backend-neutral layouts, formats, geometry, page arithmetic, closed ordinal rules, and the
|
||||
contract refusals they name.
|
||||
- `crates/reims-vgpu-core`: the backend-independent semantic model. Transactions, dependency and
|
||||
publication domains, session generations and device epochs, the fixed executor, and the serial
|
||||
reference interpreter every parallel schedule is checked against. It can name no Vulkan handle,
|
||||
Metal object, QEMU structure or guest-RAM pointer, and its dependency list is that claim.
|
||||
- `crates/reims-vgpu-memory`: the guest-RAM bound — imports, checked slices, page footprints.
|
||||
- `crates/reims-vgpu-config`: the single parse and declaration point for operator switches. An
|
||||
override may only narrow what the device does; it may never widen it.
|
||||
- `crates/reims-vgpu-observe`: typed observations and refusals. It describes decisions but does not
|
||||
select behavior.
|
||||
- `crates/reims-vgpu-vulkan`: the Vulkan rail — the only layer that turns host
|
||||
capabilities into placement and transfer policy. It sees `ash`, the semantic
|
||||
model, the refusal vocabulary and the operator switches, and nothing of QEMU,
|
||||
the device model, guest-RAM ownership or decode.
|
||||
- `crates/reims-vgpu-testkit`: shared behavioral fixtures and test instruments —
|
||||
where the oracle's capture is, whether it is there, how the suites that read it
|
||||
read it, and the allocation counter the structural-zero suites measure with.
|
||||
- `conformance`: native-oracle and guest-visible compatibility cases.
|
||||
- `vm`: rail-selected, snapshot-reverting boot harnesses.
|
||||
The Makefile's header lists every target (`bless`, `coverage`, `qemu`, `vm`,
|
||||
`clean`). README.md lists the requirements.
|
||||
|
||||
Product logic belongs in Rust. C and Objective-C connect QEMU to Rust and must not reconstruct
|
||||
policy from multiple Rust queries. Shared C/Rust constants need a `qemu::abi::header_define` test.
|
||||
No panic may cross an FFI boundary.
|
||||
## Where things are
|
||||
|
||||
Guest RAM bounds and provenance belong to `crates/reims-vgpu-memory`; extend `GuestRamImport` or
|
||||
`GuestSlice` instead of exposing raw pointers and offsets. Resource state that represents guest
|
||||
work follows the contract-owned guest lifetime. Do not silently evict it with arbitrary cache
|
||||
bounds; refuse excess work explicitly when the contract provides no lawful loss.
|
||||
| what | where |
|
||||
|---|---|
|
||||
| the Cargo workspace and its six crates | `Cargo.toml`, `crates/` |
|
||||
| `reims-ctl`, the VM manager users run, and its installer | `crates/reims-ctl` (a workspace of its own, linking nothing of the library), `scripts/install-ctl.sh` |
|
||||
| the C API | `crates/reims-vgpu-c/include/reims_vgpu.h`, specified in [docs/api.md](docs/api.md) |
|
||||
| isolated tasks | `crates/reims-vgpu-core/src/tasks/isolation`, `crates/reims-vgpu-core/src/gpu_task` |
|
||||
| the display's and XR10's shaders | `crates/reims-vgpu-metal/src/gpu/shaders.metal` |
|
||||
| the Vulkan platform | `crates/reims-vgpu-vulkan`, over metal2vulkan's runtime, at the commit of its public repository `Cargo.toml` names; what its defaults trade against Metal's answers is [docs/accuracy-ledger.md](docs/accuracy-ledger.md) |
|
||||
| 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/walk_window_macos.sh`; the wiring is `crates/reims-vgpu/src/window.rs` |
|
||||
| the dist tree QEMU and the suite link | `xtask/src/dist.rs` (`cargo xtask dist`) |
|
||||
| the option ROM `apple-gfx-pci` loads | `firmware/`, described in [docs/architecture.md](docs/architecture.md) section 11.4 |
|
||||
| `cargo xtask` | `xtask/` |
|
||||
| the behaviour-lock suite | `tests/suite` ([README](tests/suite/README.md)); its runner is `tests/suite/runner/pgrun.m`, and its specification and the guest ABI are [docs/testing.md](docs/testing.md) |
|
||||
| the pins | `crates/reims-vgpu-c/tests/pins` (the C API) |
|
||||
| QEMU and VM boots | `vendor/qemu`, `scripts/run_vmapple.sh`, `scripts/vm_drive.py`, [docs/qemu.md](docs/qemu.md) |
|
||||
| the architecture | [docs/architecture.md](docs/architecture.md) |
|
||||
| traps the suite and reviews caught | [docs/lessons.md](docs/lessons.md) |
|
||||
| measured platform facts | the docs of the modules that rely on them |
|
||||
|
||||
For asynchronous work, the owning transaction must retain inputs through host completion, make
|
||||
results visible before the completion word or interrupt, and prevent callbacks or memory access
|
||||
after the guest may release or reuse resources. Submission is not completion.
|
||||
## The contract
|
||||
|
||||
Unknown, dropped, rejected, degraded, or unsupported guest work must produce a typed reason on the
|
||||
always-on failure channel. Expected not-ready control flow stays quiet. Read environment variables
|
||||
only through the configuration owner.
|
||||
The guest drivers were written against Apple's framework, and the host
|
||||
drives this library through its C API, as QEMU's `apple-gfx` does. What the
|
||||
guest and the host observe is the contract, in its order:
|
||||
- C API results: every status, returned value and refusal;
|
||||
- host callbacks, with their arguments and their order, on the threads the
|
||||
header names for each ([docs/api.md](docs/api.md) section 5): a library
|
||||
thread, or the host's own inside a call that may call back. A process's
|
||||
display callbacks run one at a time, in the order the library queued them;
|
||||
- the order of operations on guest memory and on retained objects: task
|
||||
creates and destroys, maps, unmaps and reads, releases and IOSurface use
|
||||
counts;
|
||||
- guest memory and MMIO reads;
|
||||
- interrupts, and their order relative to guest-visible writes;
|
||||
- display frames, pixels, modes and the cursor;
|
||||
- GPU results;
|
||||
- every value that reaches the guest: IDs, GPU addresses, numbering and
|
||||
stamps;
|
||||
- where a run dies or hangs: invalid guest input ends the process at the
|
||||
same op, or, in an isolated task's own code, ends that task there; a hang
|
||||
stays a hang there.
|
||||
|
||||
## Supported pathways
|
||||
An effect that shows at the API only under a race, a mid-operation release
|
||||
or exhaustion is still part of it.
|
||||
|
||||
| Pathway | Host | Guest | Attach | Page shift | Backend |
|
||||
|---|---|---|---|---|---|
|
||||
| x86 macOS | Linux x86_64 KVM | x86_64 macOS | PCI | 12 | Vulkan |
|
||||
| arm64 macOS | Apple Silicon HVF | arm64 macOS | sysbus | 14 | Metal |
|
||||
| arm64 macOS | Apple Silicon HVF | arm64 macOS | sysbus | 14 | Vulkan/MoltenVK |
|
||||
| arm64 macOS | Apple Silicon HVF | arm64 macOS | sysbus | 14 | both, chosen at run time |
|
||||
**What is free**: which library thread runs what where the header names no
|
||||
thread, internal locking, how isolated tasks are hosted and reach the
|
||||
device, the retention machinery (autorelease pools, retains) where the order
|
||||
of releases the host sees is unchanged, Metal's internal call order where no
|
||||
result or guest-visible value changes, and diagnostics (log lines and their
|
||||
targets, thread and queue names, Metal labels, crash messages, signals).
|
||||
|
||||
The last row is one binary carrying both rails, built with
|
||||
`scripts/qemu-build/qemu-build.sh --backend both` and selected per run with `REIMS_VGPU_RAIL`.
|
||||
It exists so the same guest stream can be executed through native Metal and through MoltenVK
|
||||
without a rebuild, which is the only way to attribute a wrong frame to metal2vulkan rather than to
|
||||
this device. It is a measurement configuration, not a shipping one; the three rows above it are
|
||||
what ships.
|
||||
**The interface stays whole:** the C API is the hosts' interface. QEMU's
|
||||
`apple-gfx` and the suite's runner call it, and its changes are additive
|
||||
(docs/api.md section 1): no function, field, constant or status value is
|
||||
renamed, renumbered or removed. `cargo xtask header --check` keeps the
|
||||
committed header equal to cbindgen's output.
|
||||
|
||||
**A `cfg` may answer only "what did this build compile". It may never answer "which rail is
|
||||
running".** Those are different questions on the fourth row and the compiler cannot tell them
|
||||
apart: a `not(feature = "backend-vulkan")` block meaning "the Metal arm" disappears silently when
|
||||
both features are on, and a `feature = "backend-vulkan"` block meaning "the running rail" executes
|
||||
against Metal. Every decision the running rail makes goes through `backend::Backend`, whose
|
||||
implementation `backend::select` picks once per process. Tests obey the same rule: name the rail
|
||||
(`MetalBackend`, `VulkanBackend`) when the test is about one, and ask `selected().rail()` when the
|
||||
expected answer legitimately differs.
|
||||
## Checking a change
|
||||
|
||||
Do not generalize observations between architectures, backends, memory topologies, host GPU
|
||||
classes, or guest rails. Vulkan 1.2 is the baseline; newer functionality requires a
|
||||
capability-gated fallback. Host-pointer import is optional, and guest-visible semantics must be the
|
||||
same on imported and copying paths.
|
||||
Run the checks a change can reach, and no others. Measured on the M3 Max,
|
||||
`cargo xtask check` takes about 3 min, 180 s after a core edit, of which
|
||||
the workspace's tests are 138 s of GPU time and core's x86-64 tests under
|
||||
Rosetta 8 s; `make test`, the full suite, takes 5 min of GPU time. Some of
|
||||
the Vulkan crate's GPU tests (the YCbCr sampling sweeps among them) fail
|
||||
under the check's own load and pass run again alone.
|
||||
|
||||
## Working and verification
|
||||
| the change touches | check it with |
|
||||
|---|---|
|
||||
| the library (`crates/`), the C API or its header | `cargo xtask check`, and `make test` where the change reaches what the suite drives (core, the Metal platform, the C API) |
|
||||
| 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, or the metal crate's `shaders.metal` | `cargo xtask metallibs` on a Mac, committing the metallibs it writes with the change; then the library's checks |
|
||||
| the suite's runner, `normalize.py` or scenarios | `make test` on the cases it affects, and the records it re-records (below) |
|
||||
| `xtask/` | `cargo test -p xtask`, rustfmt and clippy on it |
|
||||
| `crates/reims-ctl` | `cargo test`, `cargo fmt --check` and `cargo clippy --all-targets` in it (`cargo xtask check` does not reach it); a change to the QEMU command it builds, or to `scripts/install-ctl.sh`, also needs an install and a VM boot on each host it touches |
|
||||
| `firmware/` | build it (`make -C firmware`); a change not meant to alter what the guest's firmware sees keeps the ROM's bytes |
|
||||
| `vendor/qemu` | build it (`make qemu`) and realize the devices paused (`-S`); a change to `hw/display/apple-gfx*.c`, or to what QEMU calls, also needs a VM boot ([docs/lessons.md](docs/lessons.md), [docs/qemu.md](docs/qemu.md)) |
|
||||
| docs and comments | nothing |
|
||||
|
||||
Use a workflow proportionate to the change:
|
||||
Neither `cargo xtask check` nor the suite builds or runs QEMU or the option
|
||||
ROM, and the suite sees only the library's C API. When a rule here seems to
|
||||
ask for a check the change cannot affect, say why it is skipped.
|
||||
|
||||
1. Reproduce or otherwise identify the behavior being changed.
|
||||
2. Establish the relevant contract and its owner. Use focused instrumentation when necessary.
|
||||
3. Add an owner-level regression test when the invariant is testable there.
|
||||
4. Implement the invariant in its owner.
|
||||
5. Format and run the focused and affected tests. Run GPU-touching Rust tests serially.
|
||||
6. For guest-visible translation or rendering changes, run the relevant conformance case and live
|
||||
pathway. Use the broader conformance suite when the change can affect unrelated cases.
|
||||
Three tiers:
|
||||
|
||||
Mechanical changes do not require VM or conformance work unless they can change behavior. A defect
|
||||
seen only in an unmodified guest requires a live guest check. Intermittent failures require repeated
|
||||
runs before claiming a fix. State what was actually verified without treating one pathway as proof
|
||||
of another.
|
||||
1. **The loop**, while editing: build, then run only the affected tests
|
||||
(`cargo nextest run -p <crate> -E 'test(/<pattern>/)'`) and the affected
|
||||
suite cases (`make test TEST=<patterns>`). The loop never runs clippy,
|
||||
rustfmt or rustdoc.
|
||||
2. **The task**, once: one commit per task, staging only the task's own
|
||||
paths (`git add <new files>`, then `git commit -m ... -- <paths>`), never
|
||||
`git add -A` or `git commit -a`. A commit runs no full check.
|
||||
3. **The merge**, once per branch, by whoever merges it: the checks the
|
||||
branch's changes reach (the table), once, on its tree before it merges
|
||||
into the integration branch. A failure gets a fix commit on the branch
|
||||
before it merges. A GPU test that fails under the check's load runs once
|
||||
more alone; passing alone, it is not a failure. Nothing runs beyond that
|
||||
for its own sake: no second suite, sweep, review or confirming run.
|
||||
|
||||
For VM work, select and report the rail explicitly. Ensure an older VM cannot answer probes, clear
|
||||
`/tmp/reims-vgpu-fail.log` before a new evidence run, and preserve the useful crash or serial output
|
||||
before rebooting. Use host-driven input and host-owned frame capture for visual interactions.
|
||||
- **The load-sensitive cases** (tests/suite/README.md) can fail under
|
||||
concurrent GPU load. Run one again alone before calling it a failure.
|
||||
- **Wall-clock first, nothing skipped.** Checks run in the background,
|
||||
cheapest to fail first (the affected tests, then `cargo xtask check`, then
|
||||
the suite), and stop at the first failure. While a slow run or a boot is
|
||||
in flight, work the runs have already shown goes on. Work may be reordered
|
||||
freely; a check the change reaches is never skipped, a result never faked
|
||||
and a comparison never loosened.
|
||||
- **A boot is the only check of what guests choose.** The suite and the unit
|
||||
tests run the library's own shaders and scenarios, and guest shaders are
|
||||
never committed, so neither sees which code a guest's frameworks pick from
|
||||
the device's answers, nor a death every boot reaches
|
||||
([docs/lessons.md](docs/lessons.md)). For the table's row: first look up
|
||||
each code the change would end the process on in the last good boot's
|
||||
logged degradation counts, which needs no GPU; then boot each guest cold
|
||||
and fail on any `reims-vgpu: fatal` line. An answer stays as it was until
|
||||
the guests boot with the new one, and each exact fix of a death lands
|
||||
with a test of its pattern in a shader of our own.
|
||||
- **A change meant to alter what the guest or host observes** is its own
|
||||
commit.
|
||||
- It records the affected expected files again from its own build
|
||||
(`make bless TEST=<patterns> ARGS=--update`), and re-records the pin
|
||||
files it changes (`RVG_PINS_RECORD=1 cargo test -p reims-vgpu-c --test
|
||||
pins`).
|
||||
- The commit message says what changed for the guest or the host. The
|
||||
diff of the expected files is the review.
|
||||
|
||||
Follow `conformance/README.md` when changing or running conformance. Native results establish the
|
||||
expected Metal behavior; existing classified guest failures are compatibility debt, not permission
|
||||
to add or hide regressions.
|
||||
The suite's inputs:
|
||||
- A scenario's ops and the runner (`runner/pgrun.m`, `pgtest/normalize.py`)
|
||||
are hashed into every expected file's input.
|
||||
- A scenario's docstring is not, so editing it needs nothing more.
|
||||
- Changing a scenario's ops records its files again (`make bless`).
|
||||
- Changing the runner or `normalize.py` records every file again: do it in
|
||||
its own commit, and check that the observations did not change.
|
||||
- Never edit an expected file by hand, and never loosen a comparison to make
|
||||
a change pass.
|
||||
|
||||
Run formatting, tests, clippy, feature checks, documentation checks, and live validation only for
|
||||
the workspaces, features, APIs, and pathways the change can affect. Do not weaken warnings or tests
|
||||
to make a gate pass. Treat every commit as a release candidate: clear regressions exposed by the
|
||||
change before committing rather than recording knowingly broken intermediate states.
|
||||
## Working in parallel
|
||||
|
||||
## Repository safety
|
||||
- **Each agent works in a worktree of its own** (`git worktree add`), from
|
||||
its first edit, docs included, on a branch of its own. The main checkout
|
||||
is the owner's: agents do not edit it. Finished work is merged on an
|
||||
integration worktree, and the owner's branch is fast-forwarded to it once
|
||||
the merge's checks pass.
|
||||
- **Each worktree has its own `CARGO_TARGET_DIR`** under `~/.cache`: cargo
|
||||
can run another tree's `xtask` from a shared one
|
||||
([docs/lessons.md](docs/lessons.md)). Caches never go under `/tmp`.
|
||||
- **Two full checks at once can exceed RAM** (one test maps 32 GiB), and
|
||||
full suites compete for the GPU: run one at a time on the host.
|
||||
- **Set work aside with a WIP commit or a patch**, never `git stash`, whose
|
||||
list every worktree shares.
|
||||
- **Never initialise `vendor/qemu` inside a worktree** that shares the main
|
||||
checkout's module repository: it rewrites the module's `core.worktree`
|
||||
([docs/lessons.md](docs/lessons.md)). A worktree that builds QEMU clones
|
||||
the submodule for itself.
|
||||
- **Keep agents few**: as many as the critical path needs, each stopped when
|
||||
its work is done.
|
||||
- **Whoever merges resolves the merge.** Merging finished work and
|
||||
fast-forwarding the owner's branch are not questions for the owner.
|
||||
Uncommitted work is never called merged, or clean to merge, before a
|
||||
hunk-level comparison shows it.
|
||||
- **Clean up after merged work**: remove its worktree (saving any dirty
|
||||
diff first) and its target directory. When a VM round ends, remove its
|
||||
disk clones and keep its logs. Never remove a worktree or cache someone
|
||||
else made.
|
||||
- **The metal2vulkan pin in `Cargo.toml` moves in batches**: to a newer
|
||||
runtime commit once a set of changes has landed, or one the work waits
|
||||
on, with one merge's checks for the move and what rides with it, never a
|
||||
check per runtime commit.
|
||||
- **Decide what the rules decide.** A routine trade-off (a residual, an
|
||||
interim difference, where a death goes, the order of work) is decided from
|
||||
these rules and the docs, and reported with its reason. The owner decides
|
||||
large spends of time or money, the project's direction and rules, and
|
||||
anything irreversible or outward-facing. A question for the owner never
|
||||
blocks the rest of the work.
|
||||
|
||||
Existing dirty changes belong to the user. Preserve them and avoid unrelated edits. Do not use
|
||||
checkout, switch, stash, reset, or restore to manufacture a baseline in the shared checkout; use an
|
||||
isolated copy when a control build is needed. Create a new commit by default; amend an existing
|
||||
commit only when the user specifically requests or authorizes it.
|
||||
## Rules for changing code
|
||||
|
||||
Do not commit guest images, firmware, captured shaders, AIR, SPIR-V, disassembly, extracted assets,
|
||||
or other third-party binary material. Keep investigation artifacts in ignored locations. Commit
|
||||
only task-related source and state validation results narrowly.
|
||||
- **Behaviour changes are deliberate.** Some behaviours look odd and are
|
||||
kept because guests or hosts may rely on Apple's framework behaving that
|
||||
way ([docs/testing.md](docs/testing.md) section 7 lists them). Changing
|
||||
one is a behaviour change: make it on purpose, in its own commit, with its
|
||||
expected files recorded again and the reason stated.
|
||||
- **The window's features are a register.** What a display's window does
|
||||
for the person at the host is listed in
|
||||
`crates/reims-vgpu-window/features.md`, each entry with its guard: a named
|
||||
test, which `features_md_guards_exist` keeps, or a manual check on a VM
|
||||
boot. Dropping or changing an entry is a deliberate change, made in its
|
||||
own commit that updates the file and says why.
|
||||
- **Unread is not dead.** The binary versions and the features each gives
|
||||
(`guest/abi/features.rs`), the device's feature level, `Preferences` and
|
||||
`DisplayMode::with_preferences`, the device-info family bits (the −1009
|
||||
bit among them), and suspend and resume in the C and the Rust API stay,
|
||||
though nothing reads or calls some of them: hosts are to configure the
|
||||
features, and hosts other than QEMU call suspend and resume. They may be
|
||||
reshaped, never removed.
|
||||
- **The Vulkan platform's rules** (guest memory in place, where stalls are
|
||||
fixed, what is the runtime's, dependencies as released) are in
|
||||
[docs/conventions.md](docs/conventions.md).
|
||||
- **Never guess a name.** A field of a guest record or of a copy of a Metal
|
||||
struct whose meaning nothing states is `field_xx`, `xx` its byte offset in
|
||||
lowercase hex. A wrong name is worse than an unknown one: it attaches the
|
||||
wrong meaning to the right bytes, and nothing flags it.
|
||||
- **Say what the code does.** Comments and docs describe the code and what
|
||||
the guest or host observes. They do not cite the earlier ports, which
|
||||
stay at their tags (README.md, History).
|
||||
- **arm64 on the Mac.** Every Rust binary built for macOS is arm64
|
||||
(`aarch64-apple-darwin`). rustc's arm64e target has no pointer
|
||||
authentication, and its binaries crash before `main`
|
||||
(`rust-toolchain.toml`). On Linux the library ships as
|
||||
`x86_64-unknown-linux-gnu`, built there.
|
||||
`cargo xtask check` on a Mac also clippy-checks that target, and, where
|
||||
Rosetta is installed, runs core's tests as `x86_64-apple-darwin`, for
|
||||
the x86-64 guest's 4 KiB pages and instructions; it skips them, saying
|
||||
so, where Rosetta is not. No x86-64 macOS binary ships.
|
||||
- **Run `cargo xtask check` once before a branch that changes the library
|
||||
merges**, not before each commit (Checking a change).
|
||||
- **Stage explicit paths, and never commit build output.** Before each
|
||||
commit, `git diff --cached --name-only | grep -E
|
||||
'(^|/)target[^/]*/|\.(bin|o|obj|rlib|rmeta|dylib|a|efi|rom)$'` must print
|
||||
nothing.
|
||||
- **The one exception is metallibs** compiled from this repository's own
|
||||
`.metal` sources, which only Apple's compiler makes: the Vulkan
|
||||
platform's, in `crates/reims-vgpu-vulkan/metallibs`, which a build off a
|
||||
Mac copies, and the suite's inputs, in `tests/suite/fixtures/shaders`.
|
||||
Each is committed with the source it is compiled from. The Vulkan
|
||||
platform's are rewritten by `cargo xtask metallibs` on a Mac, and a
|
||||
stale one fails the Mac's `cargo xtask check` and the Linux build.
|
||||
- **Never commit Apple binaries.** The build needs none: the option ROM is
|
||||
built from `firmware/`. The committed metallibs hold only our shaders and
|
||||
constant samplers, with no Apple code linked in. Nothing taken from a
|
||||
guest or from Apple's binaries is committed or pushed either: a guest's
|
||||
shader caches and metallibs, what is translated or dumped from them, logs
|
||||
that carry its serialized descriptors, excerpts of Apple's code. A report
|
||||
to an upstream project carries inputs written from scratch.
|
||||
|
||||
## Fixing bugs
|
||||
|
||||
- **Fix what runs show.** Boot guests and use their apps, and fix the
|
||||
deaths, glitches, stalls and slow frames they show, biggest first, end to
|
||||
end. A gap no run reaches waits, unless it is cheap.
|
||||
- **Fix a case by its class.** A boot shows only its first death, and users
|
||||
would meet the rest: when a run finds one unhandled case, find every case
|
||||
of its kind (every pixel format, every death site, every refusal of the
|
||||
runtime) and fix them together.
|
||||
- **Reproduce under the conditions the bug was seen in**, not under a
|
||||
theory's trigger. Size a proof window from the measured failure rate, and
|
||||
ship a cheap, low-risk fix as soon as the evidence points to it, with its
|
||||
confirmation run behind it.
|
||||
- **Check a claim before relaying it.** A claim about Metal is tagged
|
||||
measured or read from code ([docs/testing.md](docs/testing.md), "Tags").
|
||||
A claim that the hardware cannot do something is checked against the
|
||||
driver (its format features and extensions) first.
|
||||
|
||||
## GPU and VM discipline
|
||||
|
||||
The suite's cases fault the GPU and crash processes on purpose, and the GPU
|
||||
watchdog corrupts concurrent work.
|
||||
|
||||
- **A VM boot never overlaps GPU work.** The suite never boots a VM. Before
|
||||
a boot, whoever may run GPU work holds it ([docs/qemu.md](docs/qemu.md),
|
||||
"Booting a guest to check a change", which also says how a boot checks
|
||||
its screen and which crashes are out of scope).
|
||||
- **A boot writes only a copy** of a guest's disk (a clone, or a
|
||||
`snapshot=on` overlay), and a step that changes the guest's state runs
|
||||
only there. A damaged disk is copied again from its source.
|
||||
- **Measure what users get.** Boots and timings run on hosts set up as
|
||||
users' are: no option that dodges a host policy users have (a renamed
|
||||
process, a raised priority, a stopped daemon). Undo only what the harness
|
||||
itself adds. Contention under such a policy is the code's to fix.
|
||||
- **Run the load-sensitive cases again alone** before counting a failure.
|
||||
- **Stop only the processes you started**, by their pids.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Branches are prefixed `steelbrain/`.
|
||||
- Commit messages use an emoji prefix (`:new:`, `:bug:`, `:art:`,
|
||||
`:racehorse:`, `:fire:`, `:memo:`, `:white_check_mark:`), imperative mood,
|
||||
a subject of at most 72 characters, and a body wrapped at 80 that explains
|
||||
why. Docs-only commits carry `[ci skip]`.
|
||||
- Never `git push` unless asked.
|
||||
- Merged commits are not rewritten: a fix to merged work, a review's
|
||||
included, is a new commit on top. Amend only a commit the owner names; a
|
||||
flaw only in a merged commit's message stays.
|
||||
- Scratch goes under `/tmp`, and is removed when the work is done. Caches
|
||||
(a target directory, a build kept for reuse) go under `~/.cache/<name>`,
|
||||
and so does what must outlive a reboot, which empties `/tmp`: a worktree,
|
||||
the state a long run resumes from.
|
||||
- The code's conventions are [docs/conventions.md](docs/conventions.md).
|
||||
|
||||
## Recording what was learned
|
||||
|
||||
- A trap about what decides behaviour, found by a review or by the suite,
|
||||
goes in [docs/lessons.md](docs/lessons.md): what went wrong, why, and how
|
||||
to spot the next one.
|
||||
- A measured platform fact goes in the `//!` doc of the module that relies on
|
||||
it.
|
||||
- QEMU and VM measurements go in [docs/qemu.md](docs/qemu.md).
|
||||
@@ -1,9 +0,0 @@
|
||||
@AGENTS.md
|
||||
|
||||
## For Claude
|
||||
|
||||
- **CRITICAL — never persist anything outside this workspace.** Do not write to your global
|
||||
memory store (`~/.claude/...`) or any location outside this repo. Memory kept there does not
|
||||
travel with the project and **will be lost** to the next session, agent, or machine. Durable
|
||||
operating rules belong in `AGENTS.md`; other durable project information belongs in the relevant
|
||||
tracked doc or source comment.
|
||||
Generated
+322
-1567
File diff suppressed because it is too large.
Load diff
+103
-32
@@ -1,37 +1,108 @@
|
||||
# Cargo workspace for the project's host-side product crate.
|
||||
#
|
||||
# Product path: crates/reims-vgpu (protocol + C ABI + Metal|Vulkan backend).
|
||||
# UEFI option ROM: crates/reims-vgpu-efi (own Cargo workspace — x86_64-unknown-uefi;
|
||||
# not a member here so host builds never pull the no_std PE graph).
|
||||
# ReimsVGPU: the framework and its tooling (architecture.md).
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
resolver = "3"
|
||||
members = [
|
||||
"crates/reims-vgpu",
|
||||
"crates/reims-vgpu-core",
|
||||
"crates/reims-vgpu-config",
|
||||
"crates/reims-vgpu-memory",
|
||||
"crates/reims-vgpu-observe",
|
||||
"crates/reims-vgpu-paging",
|
||||
"crates/reims-vgpu-protocol",
|
||||
"crates/reims-vgpu-testkit",
|
||||
"crates/reims-vgpu-vulkan",
|
||||
"crates/reims-vgpu-wire",
|
||||
]
|
||||
exclude = [
|
||||
"crates/reims-vgpu-efi",
|
||||
"crates/reims-vgpu-core",
|
||||
"crates/reims-vgpu-metal",
|
||||
"crates/reims-vgpu-window",
|
||||
"crates/reims-vgpu",
|
||||
"crates/reims-vgpu-c",
|
||||
"crates/reims-vgpu-vulkan",
|
||||
"xtask",
|
||||
]
|
||||
|
||||
# The shipping artifact is this workspace's staticlib linked into QEMU, and the
|
||||
# device's own largest cost is host CPU in that staticlib — `chain_phase` divides
|
||||
# the whole per-draw chain and its columns are Rust work, not GPU work. So these
|
||||
# are the settings the product runs under, not a developer convenience.
|
||||
#
|
||||
# `panic` stays at the default `unwind` and must not become `abort`: every
|
||||
# `reims_vgpu_qemu_*` entry point wraps its body in `catch_unwind`
|
||||
# (`device::mod`), because a Rust panic unwinding into QEMU's C frames is
|
||||
# undefined behavior. Aborting would turn every caught panic into a dead VM.
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.98.1"
|
||||
publish = false
|
||||
license = "GPL-2.0-or-later OR LGPL-3.0-or-later"
|
||||
|
||||
[workspace.dependencies]
|
||||
reims-vgpu-core = { path = "crates/reims-vgpu-core" }
|
||||
reims-vgpu-metal = { path = "crates/reims-vgpu-metal" }
|
||||
# Without their default features: each member that wants SDL3's macOS window asks for it
|
||||
# (`macos-sdl`), so `reims-vgpu-c`'s default decides whether the library has it.
|
||||
reims-vgpu-window = { path = "crates/reims-vgpu-window", default-features = false }
|
||||
reims-vgpu = { path = "crates/reims-vgpu", default-features = false }
|
||||
reims-vgpu-vulkan = { path = "crates/reims-vgpu-vulkan" }
|
||||
# The Vulkan platform's proof of concept (architecture D1): a Metal-shaped API on Vulkan, from
|
||||
# metal2vulkan's public repository at the commit both name.
|
||||
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "13b279df1bf87893d389f955a90c55b6ff3d0f9b" }
|
||||
# Its translator, for the Metal enums and descriptor values the runtime's calls take.
|
||||
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "13b279df1bf87893d389f955a90c55b6ff3d0f9b" }
|
||||
# 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
|
||||
# version: `loaded` opens the Vulkan loader at run time, as the runtime does.
|
||||
ash = { version = "0.38", default-features = false, features = ["std", "loaded"] }
|
||||
# A display's window on Linux, and on macOS with REIMS_VGPU_WINDOW_IMPL=sdl
|
||||
# (reims-vgpu-window/src/sdl): SDL3, built from its pinned source release (sdl3-src 3.4.18) and
|
||||
# linked statically, with its video subsystem alone; its Vulkan types are ash's.
|
||||
sdl3-sys = { version = "=0.7.2", default-features = false, features = [
|
||||
"build-from-source-static",
|
||||
"no-default-subsystems",
|
||||
"sdl-video",
|
||||
"use-ash-v0-38",
|
||||
] }
|
||||
# core (architecture 2.2)
|
||||
parking_lot = "0.12.5"
|
||||
zerocopy = { version = "0.8.27", features = ["derive"] }
|
||||
bitflags = "2.9"
|
||||
# every crate's lines, and the default stderr logger (core::logging)
|
||||
log = "0.4.34"
|
||||
# metal and the public crate. objc2 `exception` is always on; `catch-all` is never enabled
|
||||
# (architecture 2.3). objc2's checks (a message to nil, a missing method, the encodings) are
|
||||
# debug assertions: on in dev, off in `checked` (the objc2 profile override below).
|
||||
objc2 = { version = "0.6.4", features = ["exception"] }
|
||||
objc2-foundation = "0.3.2"
|
||||
objc2-metal = "0.3.2"
|
||||
objc2-io-surface = "0.3.2"
|
||||
block2 = "0.6.2"
|
||||
dispatch2 = "0.3.1"
|
||||
# the window crate (AppKit, Core Animation, CoreGraphics). Default features off: their defaults
|
||||
# pull in every framework the crates cover (objc2-open-gl among them).
|
||||
objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std"] }
|
||||
objc2-quartz-core = { version = "0.3.2", default-features = false, features = ["std"] }
|
||||
objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std"] }
|
||||
mach2 = "0.7"
|
||||
libc = "0.2.180"
|
||||
# dev and tooling
|
||||
proptest = "1.7"
|
||||
loom = "0.7"
|
||||
|
||||
# Architecture 17.4. reims-vgpu-core adds its stricter set in lib.rs.
|
||||
[workspace.lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
missing_docs = "warn"
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(loom)"] }
|
||||
|
||||
[workspace.lints.clippy]
|
||||
unwrap_used = "deny"
|
||||
expect_used = "deny"
|
||||
panic = "deny"
|
||||
todo = "deny"
|
||||
|
||||
# Architecture 2.3.
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
incremental = true
|
||||
panic = "unwind" # D9: objc2 exception::catch unwinds through its closure frame
|
||||
overflow-checks = false # wrapping is explicit (D19); release is the product
|
||||
debug = "line-tables-only"
|
||||
lto = "thin"
|
||||
|
||||
[profile.dev]
|
||||
panic = "unwind"
|
||||
overflow-checks = true # an unannotated arithmetic slip dies in tests
|
||||
|
||||
[profile.checked] # the suite's second pass (13.6)
|
||||
inherits = "release"
|
||||
overflow-checks = true
|
||||
debug-assertions = true
|
||||
|
||||
# objc2's debug_assertions checks panic on a message to nil, on a missing
|
||||
# method and on an encoding the runtime disagrees with. Dev builds keep them,
|
||||
# so the tests that send to real Metal check every send they make; the
|
||||
# suite's `checked` pass leaves them off, and release has none at all (D36).
|
||||
[profile.checked.package.objc2]
|
||||
debug-assertions = false
|
||||
@@ -1,165 +1,21 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
reims-vgpu is free software: you can redistribute it and/or modify it under
|
||||
the terms of either of these licenses, at your option:
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
- the GNU General Public License, version 2, or (at your option) any later
|
||||
version: LICENSES/GPL-2.0-or-later.txt;
|
||||
- the GNU Lesser General Public License, version 3, or (at your option) any
|
||||
later version: LICENSES/LGPL-3.0-or-later.txt. The LGPL's version 3 is a
|
||||
set of permissions added to the GNU General Public License, version 3,
|
||||
whose text is LICENSES/GPL-3.0-or-later.txt.
|
||||
|
||||
As an SPDX license expression: GPL-2.0-or-later OR LGPL-3.0-or-later.
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
It is distributed in the hope that it will be useful, but WITHOUT ANY
|
||||
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
|
||||
A PARTICULAR PURPOSE. See the licenses for more details.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
This covers everything in the repository but QEMU, the submodule at
|
||||
vendor/qemu, which keeps QEMU's own licenses (its LICENSE and COPYING
|
||||
files). The crates the build takes, from crates.io and from the metal2vulkan
|
||||
repository, are not part of the repository, and each keeps its
|
||||
own license.
|
||||
@@ -0,0 +1,338 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
<https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Moe Ghoul>, 1 April 1989
|
||||
Moe Ghoul, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,165 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
@@ -0,0 +1,122 @@
|
||||
# The Rust library and its tooling. The Cargo workspace is at the
|
||||
# repository root; the behaviour-lock suite (tests/suite) records what it
|
||||
# does in expected files, recorded from the checkout's own build.
|
||||
#
|
||||
# make the library as a plain library (cargo xtask dist) in
|
||||
# target/dist: libreims_vgpu.a and .dylib, reims_vgpu.h,
|
||||
# reims-vgpu.pc and the option ROM
|
||||
# make smoke a guest workload linked with the library as QEMU links it,
|
||||
# with an isolated guest task, against its expected values
|
||||
# (cargo xtask smoke)
|
||||
# make test the behaviour-lock suite (tests/suite) on the library in
|
||||
# target/dist, compared with its expected files;
|
||||
# TEST=<patterns> selects scenarios or modules, e.g.
|
||||
# TEST='fifo_*,display'
|
||||
# make bless record expected files from the library this checkout builds:
|
||||
# those missing (a new scenario, or a new host key after an OS
|
||||
# update) or recorded from other input (a changed scenario);
|
||||
# ARGS=--update records the selected cases again for a
|
||||
# deliberate change of behaviour, whose expected-file diff is
|
||||
# reviewed in the same commit
|
||||
# make coverage the suite on the library built instrumented into
|
||||
# build/cov/dist, with a line report per crate file
|
||||
# (pgtest/coverage.py); ARGS=--per-case maps each line to the
|
||||
# cases that reach it
|
||||
# make qemu the library as a plain library (cargo xtask dist), then
|
||||
# vendor/qemu's qemu-system-aarch64 with apple-gfx on its C API,
|
||||
# linked statically through pkg-config, in build/qemu
|
||||
# (docs/qemu.md)
|
||||
# make vm VM=<macosvm VM directory> [CLONE=<dir>]
|
||||
# boot that macOS guest on make qemu's QEMU from APFS clones of
|
||||
# its disks in CLONE (default build/vm, which must be on the
|
||||
# VM's volume) (scripts/run_vmapple.sh)
|
||||
# make clean remove build/, QEMU's build included
|
||||
#
|
||||
# ARGS adds options to pgtest in test, bless and coverage, e.g.
|
||||
# ARGS='-j 8 --setup isolate'. QEMU_CONFIGURE adds options to QEMU's configure
|
||||
# and runs it again. CARGO_TARGET_DIR moves the build, and with it
|
||||
# RUST_TARGET, out of target.
|
||||
|
||||
BUILD := build
|
||||
# $(BUILD) made absolute without abspath, which splits a path with spaces.
|
||||
BUILD_DIR := $(if $(filter /%,$(BUILD)),$(BUILD),$(CURDIR)/$(BUILD))
|
||||
QEMU_CONFIGURE ?=
|
||||
QEMU_BUILD := $(BUILD_DIR)/qemu
|
||||
QEMU_SRC := $(CURDIR)/vendor/qemu
|
||||
# Cargo's target directory, made absolute the same way: the dist tree is
|
||||
# under it, which the suite's runner and QEMU's config.status record, and
|
||||
# cargo resolves a relative one against the directory it runs in.
|
||||
RUST_TARGET_REL := $(or $(CARGO_TARGET_DIR),target)
|
||||
RUST_TARGET := $(if $(filter /%,$(RUST_TARGET_REL)),$(RUST_TARGET_REL),$(CURDIR)/$(RUST_TARGET_REL))
|
||||
RUST_DIST := $(RUST_TARGET)/dist
|
||||
|
||||
.PHONY: all smoke test bless coverage qemu vm clean
|
||||
|
||||
all:
|
||||
CARGO_TARGET_DIR="$(RUST_TARGET)" cargo xtask dist
|
||||
|
||||
smoke: all
|
||||
CARGO_TARGET_DIR="$(RUST_TARGET)" cargo xtask smoke
|
||||
|
||||
TEST ?=
|
||||
ARGS ?=
|
||||
PGTEST = cd tests/suite && python3 -m pgtest
|
||||
|
||||
test: all
|
||||
$(PGTEST) run -k "$(TEST)" --dist "$(RUST_DIST)" $(ARGS)
|
||||
|
||||
# bless records from the library make builds, the one make test runs.
|
||||
bless: all
|
||||
$(PGTEST) bless -k "$(TEST)" --dist "$(RUST_DIST)" $(ARGS)
|
||||
|
||||
# pgtest cov builds its own instrumented dist tree, in build/cov/dist.
|
||||
coverage:
|
||||
$(PGTEST) cov -k "$(TEST)" $(ARGS)
|
||||
|
||||
vendor/qemu/configure:
|
||||
@echo "vendor/qemu is empty: git submodule update --init vendor/qemu" >&2
|
||||
@exit 1
|
||||
|
||||
# QEMU finds reims-vgpu.pc in the dist tree and links libreims_vgpu.a, so the
|
||||
# binary records no path to the library; apple-gfx calls its C API
|
||||
# (reims_vgpu.h). QEMU's build installs the package's option ROM into its
|
||||
# data directory, which the build tree's qemu-bundle mirrors, as
|
||||
# apple-gfx-pci's default romfile. Configure runs once, out of tree, and again
|
||||
# whenever QEMU_CONFIGURE is set or config.status was made from another
|
||||
# source or with another PKG_CONFIG_PATH, or names --apple-gfx-backend or
|
||||
# --pvg-framework, which vendor/qemu's configure does not take. It also runs
|
||||
# again when reims-vgpu.pc differs from the one it last read: meson keeps the
|
||||
# package's flags from configure, so a framework the library came to need
|
||||
# (its Libs.private) would otherwise be missing from QEMU's link.
|
||||
QEMU_PKG_CONFIG := $(RUST_DIST)/lib/pkgconfig
|
||||
QEMU_PC_READ := $(QEMU_BUILD)/reims-vgpu.pc.configured
|
||||
|
||||
qemu: all vendor/qemu/configure
|
||||
@mkdir -p "$(QEMU_BUILD)"
|
||||
@if [ ! -f "$(QEMU_BUILD)/build.ninja" ] || [ -n "$(QEMU_CONFIGURE)" ] \
|
||||
|| ! grep -qF -- "exec '$(QEMU_SRC)/configure'" "$(QEMU_BUILD)/config.status" 2>/dev/null \
|
||||
|| ! grep -qxF -- "PKG_CONFIG_PATH='$(QEMU_PKG_CONFIG)'" "$(QEMU_BUILD)/config.status" \
|
||||
|| grep -qE -- "'--(apple-gfx-backend|pvg-framework)=" "$(QEMU_BUILD)/config.status" \
|
||||
|| ! cmp -s "$(QEMU_PKG_CONFIG)/reims-vgpu.pc" "$(QEMU_PC_READ)"; then \
|
||||
cd "$(QEMU_BUILD)" && PKG_CONFIG_PATH="$(QEMU_PKG_CONFIG)" "$(QEMU_SRC)/configure" \
|
||||
--target-list=aarch64-softmmu --enable-hvf --enable-pvg \
|
||||
--disable-docs $(QEMU_CONFIGURE) \
|
||||
&& cp "$(QEMU_PKG_CONFIG)/reims-vgpu.pc" "$(QEMU_PC_READ)"; \
|
||||
fi
|
||||
$(MAKE) -C "$(QEMU_BUILD)" qemu-system-aarch64
|
||||
@find -L "$(QEMU_BUILD)/qemu-bundle" -name ReimsVgpu.rom -type f | grep -q . \
|
||||
|| { echo "make qemu: QEMU's build installed no ReimsVgpu.rom" >&2; exit 1; }
|
||||
|
||||
VM ?=
|
||||
CLONE ?= $(BUILD_DIR)/vm
|
||||
|
||||
vm:
|
||||
@if [ -z "$(VM)" ]; then \
|
||||
echo "usage: make vm VM=<macosvm VM directory> [CLONE=<dir>]" >&2; \
|
||||
exit 1; \
|
||||
fi
|
||||
@$(MAKE) --no-print-directory qemu
|
||||
QEMU="$(QEMU_BUILD)/qemu-system-aarch64" scripts/run_vmapple.sh "$(VM)" "$(CLONE)"
|
||||
|
||||
clean:
|
||||
rm -rf "$(BUILD_DIR)"
|
||||
@@ -1,241 +1,392 @@
|
||||
# reims-vgpu
|
||||
|
||||
[](LICENSE) [](https://discord.gg/D2AM9mrDgs)
|
||||
A Rust library, `libreims_vgpu`, that is the host side of the
|
||||
paravirtualized GPU macOS guests drive, in place of Apple's
|
||||
`ParavirtualizedGraphics.framework`: the device `vmapple` and `apple-gfx-pci`
|
||||
guests draw through, its displays, its IOSurface host device and its
|
||||
isolated GPU tasks. Its C API (`crates/reims-vgpu-c/include/reims_vgpu.h`,
|
||||
specified in [docs/api.md](docs/api.md)) is its interface, and
|
||||
`cargo xtask dist` writes the library, the header, a pkg-config package and
|
||||
the device's EFI option ROM into `target/dist`. QEMU's `apple-gfx` devices
|
||||
(`vendor/qemu`), in C on that API, find it through pkg-config and link it
|
||||
statically, and the behaviour-lock suite's runner drives the same API as
|
||||
QEMU does.
|
||||
|
||||
> **Alpha.** This project is early and under active development. The QEMU device ABI, boot scripts,
|
||||
> crate layout, backend behavior, and supported host/guest pathways may change without a stable
|
||||
> compatibility guarantee. Treat it as research-quality: useful for experimentation and bring-up,
|
||||
> not a frozen virtualization product.
|
||||
On macOS the library runs on Metal. On Linux it runs on the Vulkan platform
|
||||
(`crates/reims-vgpu-vulkan`), over metal2vulkan's Metal-shaped runtime,
|
||||
which a Mac can build too, on MoltenVK. The library draws frames with its
|
||||
own shaders, and under process isolation it runs each guest task other than
|
||||
task 0 on threads of its own, in the host's process. A display created with
|
||||
a window config gets a window of the library's own
|
||||
(`crates/reims-vgpu-window`), into which the guest's frames are drawn on the
|
||||
GPU, and whose pointer and keys go to the host: QEMU under `-display none`
|
||||
opens one for each guest display.
|
||||
|
||||
reims-vgpu is an experimental virtual GPU for macOS guests. It aims to let macOS running inside a
|
||||
VM use accelerated graphics instead of a basic framebuffer, while keeping the guest operating system
|
||||
unchanged.
|
||||
The guest drivers were written against Apple's framework, so what the guest
|
||||
and the host observe is the contract: API results and refusals, host
|
||||
callbacks and their order, guest memory, MMIO reads, interrupts, frames,
|
||||
GPU results, and where a run faults, dies or hangs. The codebase's own tests
|
||||
pin it: the behaviour-lock suite's expected files record what the code does,
|
||||
and every change is checked against them. [AGENTS.md](AGENTS.md) has the
|
||||
rules for changing it.
|
||||
|
||||
macOS already includes a paravirtual GPU driver named `AppleParavirtGPU.kext`.
|
||||
reims-vgpu provides the QEMU device that driver attaches to, then decodes the guest's GPU command
|
||||
stream on the host and executes it through Metal (TODO) or Vulkan, with Vulkan translation handled
|
||||
by [`metal2vulkan`](https://github.com/steelbrain/metal2vulkan). There is no custom macOS kext and
|
||||
no guest driver to install.
|
||||
## Running VMs: reims-ctl
|
||||
|
||||
Contributions are welcome. I am especially interested in collaborating with developers who want to
|
||||
work on correctness, visual glitches, synchronization bugs, command-stream decoding, Metal/Vulkan
|
||||
translation, and making more host/guest combinations reliable.
|
||||
`reims-ctl` (`crates/reims-ctl`) creates, boots and manages macOS VMs on QEMU
|
||||
with this library: arm64 guests on an Apple silicon Mac (QEMU's `vmapple`
|
||||
machine), x86-64 guests on x86-64 Linux (`q35` through OpenCore, on KVM).
|
||||
Clone the repository (without `--recursive`: QEMU's own submodules are not
|
||||
needed) and run:
|
||||
|
||||

|
||||
|
||||
*arm64 macOS 13 Ventura guest on an Apple Silicon host.*
|
||||
|
||||

|
||||
|
||||
*x86_64 macOS 13 Ventura guest on a Linux host.*
|
||||
|
||||
## Three pathways
|
||||
|
||||
`crates/reims-vgpu` targets the following host/guest/backend combinations. Agents pick the pathway
|
||||
their unit of work is on.
|
||||
|
||||
| Pathway | Host | Guest | Device attach | Backend | Boot |
|
||||
|---|---|---|---|---|---|
|
||||
| **x86 macOS / Linux Vulkan** | Linux x86_64 (KVM) | x86_64 macOS Metal guest | PCI `reims-vgpu-pci` | host **Vulkan** via `metal2vulkan` | `vm/boot-x86.sh` |
|
||||
| **arm64 macOS / macOS Metal** | Apple Silicon macOS (HVF) | arm64 macOS Metal guest (`vmapple`) | sysbus MMIO `reims-vgpu-mmio` | host **Metal** | `vm/boot-arm64.sh` |
|
||||
| **arm64 macOS / macOS Vulkan** | Apple Silicon macOS (HVF) | arm64 macOS Metal guest (`vmapple`) | sysbus MMIO `reims-vgpu-mmio` | host **Vulkan** via `metal2vulkan` through MoltenVK | `vm/boot-arm64.sh` |
|
||||
|
||||
- QEMU device shims: `vendor/qemu` tracks
|
||||
[`steelbrain/qemu-reims-vgpu@host-reims-vgpu-vmapple`](https://github.com/steelbrain/qemu-reims-vgpu/tree/host-reims-vgpu-vmapple)
|
||||
(thin C — QOM/MMIO/IRQ/console/HostOps only)
|
||||
- Product logic: `crates/reims-vgpu` (decode + device model + Metal/Vulkan backends)
|
||||
- Wire layouts: `crates/reims-vgpu-wire` (derived serializer views/parsers; decode uses these as the layout authority for covered records)
|
||||
- Vulkan translator dependency: public `steelbrain/metal2vulkan` Git crate. On macOS, the Vulkan
|
||||
host backend runs through MoltenVK.
|
||||
- VM lifecycle: `vm/` (snapshot-revert; arm and x86 guest boot scripts)
|
||||
|
||||
## Getting started
|
||||
|
||||
This tree ships **boot scripts and the device**, not a ready-made macOS disk image. Guest disks,
|
||||
firmware vars, and OpenCore blobs are private/gitignored under `vm/`. Pick a pathway, provision a
|
||||
guest once, freeze a golden snapshot, then use the snapshot-revert boots for day-to-day work.
|
||||
macOS 13 Ventura is the recommended guest release for bring-up.
|
||||
|
||||
### x86_64 guest on Linux (KVM)
|
||||
|
||||
1. **Host prep.** You need KVM (`/dev/kvm`), a working NVIDIA (or other) Vulkan stack for the product
|
||||
backend, and build deps for the in-tree QEMU (`scripts/qemu-build/qemu-build.sh --target x86_64
|
||||
--backend vulkan`).
|
||||
|
||||
2. **Generate OpenCore, OVMF, and a guest disk with [OSX-KVM](https://github.com/kholia/OSX-KVM).**
|
||||
**macOS 13 is recommended**.Follow that project’s docs to fetch recovery media, build OpenCore,
|
||||
and install macOS under QEMU+KVM. The point of this step is only to produce a
|
||||
**working, post-Setup-Assistant guest** plus the usual OpenCore/OVMF pieces — not to stay on
|
||||
OSX-KVM’s long-term launcher.
|
||||
|
||||
3. **Drop the artifacts where this repo expects them** (paths are the defaults in `vm/boot-x86.sh`;
|
||||
override with env if you prefer):
|
||||
|
||||
| Artifact | Default location |
|
||||
|---|---|
|
||||
| Guest system disk | `vm/disks/macos.img` |
|
||||
| OpenCore boot disk | `vm/disks/OpenCore.qcow2` |
|
||||
| OVMF code | `vm/ovmf/OVMF_CODE_4M.fd` |
|
||||
| OVMF vars template | `vm/ovmf/OVMF_VARS-1920x1080.fd` |
|
||||
|
||||
Finish install in the guest: enable Remote Login, install your SSH key, turn off sleep/screensaver
|
||||
as you like. Host SSH is typically `localhost:2222` → guest `:22` (see `vm/boot-x86.sh`).
|
||||
|
||||
4. **Capture the first immutable snapshot.** Guests are organised into **rails** — one rail per guest
|
||||
OS line (`macos-11` … `macos-26`), each with a snapshot history of its own under
|
||||
`vm/disks/rails/<rail>/snapshots/`. Create the rail's directory, then from a clean guest state
|
||||
(logged in, network/SSH known-good) shut down cleanly while booting in capture mode:
|
||||
|
||||
```bash
|
||||
mkdir -p vm/disks/rails/macos-15
|
||||
vm/boot-x86.sh --rail macos-15 --capture --device vmware-svga
|
||||
# clean shutdown from inside the guest → new label under
|
||||
# vm/disks/rails/macos-15/snapshots/, and that rail's snapshots/current points at it
|
||||
```
|
||||
|
||||
Every later boot clones the selected rail's `snapshots/current` (COW when possible) and **throws
|
||||
the clone away** on exit, so wedges and hard kills never poison the golden image.
|
||||
|
||||
Importing a guest built elsewhere is the same shape without the boot — drop
|
||||
`{macos.img,OpenCore.qcow2,OVMF_VARS.fd}` (plus `OVMF_CODE.fd` if that guest was installed under
|
||||
a different OVMF build) into `vm/disks/rails/<rail>/snapshots/base/`, `chmod 444` them, and
|
||||
`ln -sfn base vm/disks/rails/<rail>/snapshots/current`. Use `cp --reflink=auto` on btrfs and the
|
||||
import costs no disk.
|
||||
|
||||
5. **Day-to-day boots.**
|
||||
|
||||
```bash
|
||||
vm/boot-x86.sh --list-rails # what guest lines exist (* = default)
|
||||
vm/boot-x86.sh --rail macos-15 --list-snapshots
|
||||
|
||||
# Console only (mainstream OSX-KVM-style VGA) while you debug the host stack
|
||||
vm/boot-x86.sh --testing --device vmware-svga
|
||||
|
||||
# Product Reims VGPU device (needs in-tree QEMU + reims-vgpu Vulkan)
|
||||
REIMS_VGPU_BACKEND=vulkan scripts/qemu-build/qemu-build.sh --target x86_64
|
||||
vm/boot-x86.sh --testing --device reims-vgpu-pci --rail macos-15
|
||||
|
||||
# Host-window screenshot (Linux/Plasma or macOS host)
|
||||
scripts/screenshot/screenshot.sh -o /tmp/screen.png
|
||||
```
|
||||
|
||||
Without `--rail` a boot follows `vm/disks/rails/current`; change it with
|
||||
`ln -sfn <rail> vm/disks/rails/current`. Neither `--rail` nor `--snapshot` repoints anything.
|
||||
|
||||
### arm64 guest on Apple Silicon (HVF / vmapple)
|
||||
|
||||
Arm bring-up is **in-tree**: Virtualization.framework via Homebrew **`macosvm`**, then QEMU’s
|
||||
`vmapple` machine under HVF. There is no OSX-KVM step.
|
||||
|
||||
1. Install **`macosvm`**, and build the vendored QEMU:
|
||||
|
||||
```bash
|
||||
scripts/qemu-build/qemu-build.sh --target aarch64 --backend metal
|
||||
```
|
||||
|
||||
2. Provision a guest from a UniversalMac IPSW with the project helpers in
|
||||
`scripts/vmapple-provision/`. The live bundle lives under `vm/guest/` (disk, aux, `vm.json` /
|
||||
ECID).
|
||||
|
||||
3. Configure the guest once: enable Remote Login, run `scripts/vmapple-guest-config/` for no-sleep
|
||||
settings, and optionally enable auto-login by hand in System Settings. Capture a golden under
|
||||
`vm/guest/rails/<rail>/snapshots/` with the snapshot helpers (`scripts/vmapple-snapshot/`, or
|
||||
`vm/boot-arm64.sh --rail <rail> --capture` once the disk is ready).
|
||||
|
||||
4. Boot:
|
||||
|
||||
```bash
|
||||
vm/boot-arm64.sh --testing --device reims-vgpu-mmio # product
|
||||
vm/boot-arm64.sh --testing --device apple-gfx-mmio # Apple ParavirtualizedGraphics A/B
|
||||
scripts/screenshot/screenshot.sh /tmp/screen.png
|
||||
```
|
||||
|
||||
Optional **performance ceiling** reference: the same guest under native VZ via `macosvm --gui`.
|
||||
|
||||
### After the first snapshot
|
||||
|
||||
- Prefer **`--testing`** for agent/measurement boots (time-bounded, always reverts).
|
||||
- Use **`--interactive`** when you need an open-ended GUI session (still reverts unless you are in
|
||||
`--capture` mode).
|
||||
- Say which rail a result came from. A number from `macos-11` and a number from `macos-26` are two
|
||||
measurements, not one — that separation is the whole reason snapshots are per-rail.
|
||||
- Never commit disks, IPSWs, or OpenCore/OVMF runtime under `vm/`.
|
||||
- Device/backend work lives in `crates/reims-vgpu` + the thin shims in `vendor/qemu`; rebuild QEMU after
|
||||
product changes before claiming a live boot result.
|
||||
|
||||
### The host window takes your keyboard shortcuts
|
||||
|
||||
On the `reims-vgpu-pci` / `reims-vgpu-mmio` device the guest is displayed in a window this project
|
||||
owns, and while that window has keyboard focus it asks the host desktop to **stop acting on its own
|
||||
shortcuts** so they reach the guest instead. Without that the desktop consumes them first: a stock
|
||||
Plasma session claims 63 `Meta`/`Alt`/`Ctrl` combinations, and because a macOS guest reads host
|
||||
`Meta` as `Cmd`, that covers most of what the guest expects — `Cmd+A`, `Cmd+V`, `Cmd+Q`, `Cmd+W`,
|
||||
`Cmd+1`…`Cmd+9`, and `Alt+Tab`.
|
||||
|
||||
**Press `Ctrl+Alt+Esc` to release the grab.** While it is held your own `Alt+Tab` goes to the guest,
|
||||
so this is how you get back to the host desktop. The chord is consumed rather than forwarded, and the
|
||||
grab re-arms by itself the next time you focus the window — it is an escape hatch, not a mode you
|
||||
have to remember you are in. The guest's own `Cmd+Option+Esc` (Force Quit) carries no `Ctrl` and is
|
||||
forwarded to the guest untouched.
|
||||
|
||||
The window says so on stderr the first time it captures, and records it in the always-on log:
|
||||
|
||||
```text
|
||||
window_capture_engaged mechanism=wayland_shortcuts_inhibit release=Ctrl+Alt+Esc
|
||||
```sh
|
||||
scripts/install-ctl.sh
|
||||
```
|
||||
|
||||
How much can be captured depends on the host, and the log names which mechanism a boot got:
|
||||
It installs what the build needs (Homebrew on macOS; apt on Ubuntu and
|
||||
Debian, pacman on Arch and CachyOS; Rust through rustup.rs), fetches
|
||||
`vendor/qemu`, builds the library and QEMU on it, installs QEMU into
|
||||
`~/.local/share/reims-ctl/qemu`, and `reims-ctl` into `~/.cargo/bin`.
|
||||
`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.
|
||||
Then `reims-ctl` opens its interactive interface: create a VM (a new disk
|
||||
or an existing one, an OpenCore image and an installer on Linux; an IPSW
|
||||
or a macosvm or tart VM on a Mac), start it (a window for each display),
|
||||
stop it (the guest shuts down, or is powered off after a timeout), edit its
|
||||
CPUs, memory, displays, resolution, HiDPI, 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.
|
||||
`reims-ctl help` lists the same as commands (`list`, `create`, `start`,
|
||||
`stop`, `set`, `command`, `report`, `update`, `doctor`, ...); every option
|
||||
takes `--name value` or `--name=value`. `reims-ctl update` pulls the
|
||||
checkout and installs again; a running VM keeps the QEMU it started with.
|
||||
|
||||
| Host | Mechanism | Coverage |
|
||||
## Requirements
|
||||
|
||||
- An Apple silicon Mac. Every Rust binary is arm64
|
||||
(`aarch64-apple-darwin`): rustc's arm64e target has no pointer
|
||||
authentication, and its binaries crash before `main`
|
||||
(`rust-toolchain.toml`).
|
||||
- The toolchain `rust-toolchain.toml` pins: stable 1.98.1 with rustfmt and
|
||||
clippy. rustup installs it on first use.
|
||||
- `cargo-nextest`, which runs the tests in `cargo xtask check`
|
||||
(`cargo install --locked cargo-nextest`).
|
||||
- cbindgen 0.29.4, for `cargo xtask header`
|
||||
(`cargo install --locked cbindgen --version 0.29.4`).
|
||||
- `cargo-llvm-cov` and rustup's `llvm-tools` component, for `make coverage`
|
||||
only.
|
||||
- Xcode's clang, for objc2's exception helper (which the `cc` crate builds),
|
||||
the C API's pins, the smoke program and the suite's runner. The library
|
||||
compiles its shaders from source at run time, so `make` needs no Metal
|
||||
toolchain; the Vulkan platform's crate, which `cargo build --workspace`
|
||||
and `cargo xtask check` build, does (`xcodebuild -downloadComponent
|
||||
MetalToolchain`).
|
||||
- Homebrew's `lld` (`brew install lld`), whose `lld-link` and `ld.lld` link
|
||||
the EFI option ROM (`firmware/`) that `cargo xtask dist` builds with
|
||||
Xcode's clang.
|
||||
- For the QEMU targets: the `vendor/qemu` submodule
|
||||
(`git submodule update --init vendor/qemu`) and QEMU's build dependencies
|
||||
(Homebrew's `meson`, `ninja`, `pkg-config`, `glib`, `pixman` and so on).
|
||||
|
||||
The suite's host-dependent expected files are recorded on an Apple M3 Max
|
||||
with a 40-core GPU, macOS build 25G229.
|
||||
|
||||
On x86-64 Linux the library builds on the Vulkan platform alone, with no Mac
|
||||
and no Xcode. It needs the toolchain above (cargo fetches metal2vulkan at the
|
||||
commit the workspace's `Cargo.toml` names), CMake and a C compiler for SDL3, which the build compiles from its pinned
|
||||
source, and, for `cargo xtask dist`, clang, lld and binutils.
|
||||
|
||||
## Building
|
||||
|
||||
```sh
|
||||
make # the library as a plain library (cargo xtask dist): target/dist
|
||||
make smoke # link it as QEMU does and run an isolated guest task
|
||||
make test # the behaviour-lock suite on the library
|
||||
make bless # record expected files for new or changed scenarios
|
||||
make coverage # the suite on an instrumented build; a line report per file
|
||||
make qemu # QEMU with apple-gfx on the library (cargo xtask dist), in build/qemu
|
||||
make vm VM=path/to/macosvm-vm # boot a macOS guest on it (docs/qemu.md)
|
||||
make clean # remove build/
|
||||
```
|
||||
|
||||
The Makefile's header describes every target and its variables. `make` runs
|
||||
`cargo`, which you can drive directly (below).
|
||||
|
||||
On Linux, `cargo xtask dist` builds the library on the Vulkan platform into
|
||||
`target/dist-vulkan`. The Vulkan platform's shaders are metallibs, which
|
||||
only Apple's compiler makes. A Mac compiles its own as it builds; any other
|
||||
host copies those a Mac compiled, committed in
|
||||
`crates/reims-vgpu-vulkan/metallibs`, once their `metallibs.toml` names each
|
||||
with the sha256 of the commands and sources this tree compiles it from
|
||||
(`crates/reims-vgpu-vulkan/build.rs`). `RVG_METALLIB_DIR=<dir>` takes them
|
||||
from `<dir>` instead.
|
||||
|
||||
```sh
|
||||
cargo xtask metallibs # on a Mac: compile them into crates/reims-vgpu-vulkan/metallibs
|
||||
cargo xtask metallibs <dir> # the same into <dir>, for RVG_METALLIB_DIR
|
||||
```
|
||||
|
||||
A change to a `.metal` source of the Vulkan crate, or to the metal crate's
|
||||
`shaders.metal`, commits the metallibs `cargo xtask metallibs` writes with
|
||||
it: until then a test of `cargo xtask check` fails on the Mac
|
||||
(`the_committed_metallibs_are_this_trees`), and the build fails on Linux.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
Cargo.toml the Cargo workspace, with Cargo.lock,
|
||||
rust-toolchain.toml, clippy.toml and
|
||||
.cargo/config.toml
|
||||
crates/ its six crates (below), and reims-ctl, a
|
||||
workspace of its own that links none of them
|
||||
xtask/ cargo xtask (below)
|
||||
firmware/ the option ROM: the PCI device's UEFI driver,
|
||||
in C
|
||||
tests/
|
||||
suite/ the behaviour-lock suite (its README)
|
||||
scripts/
|
||||
install-ctl.sh builds and installs reims-ctl and its QEMU
|
||||
run_vmapple.sh boots a macOS VM on make qemu's QEMU
|
||||
vm_drive.py, vm_ocr.swift drive a VM through a fixed tour
|
||||
walk_window_macos.sh the manual walk of a display's window on macOS
|
||||
docs/
|
||||
api.md the C API and the Rust API it wraps, with the
|
||||
settings and environment variables
|
||||
architecture.md how the code is built
|
||||
conventions.md the conventions the code follows
|
||||
testing.md the suite's specification, and the guest ABI
|
||||
qemu.md QEMU on the library: its build, VM boots and
|
||||
what they measured
|
||||
lessons.md traps the suite and reviews found
|
||||
accuracy-ledger.md what the Vulkan platform's defaults trade
|
||||
against Metal's answers, and the switches
|
||||
vendor/qemu/ QEMU with apple-gfx on reims-vgpu (submodule)
|
||||
LICENSE the license, and LICENSES/ its texts (License)
|
||||
```
|
||||
|
||||
## QEMU and a VM
|
||||
|
||||
`make qemu` runs `cargo xtask dist` and configures `vendor/qemu` with
|
||||
`PKG_CONFIG_PATH=<target>/dist/lib/pkgconfig`, so meson finds
|
||||
`reims-vgpu.pc`, `apple-gfx` calls the C API, and QEMU links
|
||||
`libreims_vgpu.a` into its binary. QEMU's build installs the package's
|
||||
option ROM into its data directory as `apple-gfx-pci`'s default `romfile`.
|
||||
The ROM is the device's UEFI driver, built from `firmware/`, which only an
|
||||
x86-64 guest's firmware runs ([docs/architecture.md](docs/architecture.md)
|
||||
section 11.4).
|
||||
|
||||
`make vm VM=<dir>` boots a macOS guest installed with
|
||||
Virtualization.framework on that QEMU, from APFS clones of its disks.
|
||||
`scripts/vm_drive.py` drives a booted guest through a fixed tour, and
|
||||
`vm_drive.py pair` boots a change's QEMU beside another build's and compares
|
||||
the two. Under `-display none`, QEMU's `apple-gfx` has the library open a
|
||||
window for each guest display, unless `REIMS_VGPU_WINDOW=0`, which
|
||||
`run_vmapple.sh` sets unless it is run with `WINDOW=1`.
|
||||
[docs/qemu.md](docs/qemu.md) covers how QEMU uses the library, the VM
|
||||
procedure, and what the boots measured. An x86-64 macOS guest needs one
|
||||
setting inside it, `sudo defaults write /Library/Preferences/.GlobalPreferences
|
||||
METAL_ERROR_MODE -int 5`, or its icon service crash-loops; docs/qemu.md,
|
||||
"x86-64 macOS guests: Metal's error mode", says why.
|
||||
|
||||
## Testing
|
||||
|
||||
- **`cargo xtask check`** runs the lints, rustfmt, clippy and every unit
|
||||
test. Run it once before a branch that changes code merges.
|
||||
- **`make smoke`** (`cargo xtask smoke`) links a guest program with the
|
||||
library the way QEMU links it and runs an isolated guest task.
|
||||
- **The behaviour-lock suite** (`tests/suite`, `make test`) plays the
|
||||
hypervisor and the guest, and compares what the guest and the host observe
|
||||
with its expected files. [docs/testing.md](docs/testing.md) specifies the
|
||||
suite and the guest ABI it is written against, and
|
||||
[tests/suite/README.md](tests/suite/README.md) is its user's guide.
|
||||
- **The pins**: `crates/reims-vgpu-c/tests/pins`, a C host against the C
|
||||
API, which `cargo xtask check` runs with the other tests.
|
||||
|
||||
Expected files and pin files are recorded from the checkout's own build. A
|
||||
change that means to alter behaviour records them again in the same commit
|
||||
(`make bless TEST=<patterns> ARGS=--update`,
|
||||
`RVG_PINS_RECORD=1 cargo test -p reims-vgpu-c --test pins`), so the diff
|
||||
shows exactly what changed for the guest and the host.
|
||||
|
||||
## The Rust library
|
||||
|
||||
[docs/architecture.md](docs/architecture.md) describes the crates, threads
|
||||
and locks, the raise and death model, the platform boundary, isolated
|
||||
tasks, the APIs, the option ROM and QEMU. Each module's `//!` doc holds its
|
||||
area's ordering contracts and the measured platform facts it relies on.
|
||||
|
||||
### Crates
|
||||
|
||||
| crate | path | role |
|
||||
|---|---|---|
|
||||
| Wayland | `zwp_keyboard_shortcuts_inhibit_v1` | full, when the compositor implements it |
|
||||
| X11 | `XGrabKeyboard` | full, unless another client holds the keyboard |
|
||||
| macOS | `NSApplicationPresentationDisableProcessSwitching` | partial — `Cmd+Tab` and `Cmd+H` only; the window server keeps its reserved chords |
|
||||
| `reims-vgpu-core` | `crates/reims-vgpu-core` | all behaviour, generic over `P: Platform`; links no Apple framework |
|
||||
| `reims-vgpu-metal` | `crates/reims-vgpu-metal` | the `Platform` over Metal, IOSurface, Mach VM and threads, and the library's shaders (`src/gpu/shaders.metal`) |
|
||||
| `reims-vgpu-vulkan` | `crates/reims-vgpu-vulkan` | the `Platform` over metal2vulkan's runtime: the library on Linux, and on macOS behind the `vulkan` features, on MoltenVK |
|
||||
| `reims-vgpu-window` | `crates/reims-vgpu-window` | a display's own window: AppKit's or SDL3's on macOS, SDL3's on Linux, its input and the host's screens; knows nothing of devices or displays. `features.md` lists what the window does, each entry deliberate |
|
||||
| `reims-vgpu` | `crates/reims-vgpu` | the public Rust API; the process's platform; a display's window over the window crate |
|
||||
| `reims-vgpu-c` | `crates/reims-vgpu-c` | the C API (`rvg_*`, `include/reims_vgpu.h`), which QEMU links; `cdylib`, `staticlib` and `rlib` |
|
||||
| `xtask` | `xtask` | `cargo xtask`, below |
|
||||
|
||||
A host that cannot capture at all still runs; it emits a `window_capture_*` reason on
|
||||
`/tmp/reims-vgpu-fail.log` rather than silently dropping the keys.
|
||||
### Build and test
|
||||
|
||||
### Environment overrides
|
||||
Run from the repository root. `cargo xtask` is an alias for
|
||||
`cargo run --package xtask --` (`.cargo/config.toml`), and with no command it
|
||||
lists the commands.
|
||||
|
||||
Set on the boot command; every one is optional and every default is "let the device decide". The
|
||||
full list, with the parse, is `crates/reims-vgpu/src/env.rs`. Each accepts `1`/`on`/`true`/`yes` and
|
||||
`0`/`off`/`false`/`no`, case-insensitively.
|
||||
|
||||
| Variable | Effect |
|
||||
|---|---|
|
||||
| `REIMS_VGPU_DMABUF=off` | Stop reaching guest pages through a dma-buf, even where the host can. Every guest-memory rail takes the copying path instead — which is what runs on any host without `VK_EXT_external_memory_dma_buf`, so this is how that half is exercised on a machine that has it. |
|
||||
| `REIMS_VGPU_DRAW_LOG=on` | Verbose per-draw detail on top of the always-on failure log. |
|
||||
|
||||
An override can only **narrow** what the device does. There is no way to switch a rail *on* that the
|
||||
host reported it cannot run: capability is measured from the device at startup, and asking a driver
|
||||
for an extension it does not advertise fails device creation rather than degrading. `REIMS_VGPU_DMABUF`
|
||||
has no on direction for that reason — on a host without the extension it is already off, and the
|
||||
`vk_caps` line in `/tmp/reims-vgpu-fail.log` names which check said so.
|
||||
|
||||
## Repo layout
|
||||
|
||||
```text
|
||||
AGENTS.md - repo operating guide for agents
|
||||
crates/ - Rust crates (`reims-vgpu`, `reims-vgpu-wire`, `reims-vgpu-efi`)
|
||||
scripts/ - host setup, VM lifecycle, screenshot, and diagnostic helpers
|
||||
vendor/ - vendored QEMU submodule and patch record
|
||||
vm/ - VM launch/configuration glue; images are private/untracked
|
||||
```sh
|
||||
cargo build --workspace
|
||||
cargo nextest run --workspace
|
||||
cargo xtask check # the lints, rustfmt, clippy and every test; run it once before a merge
|
||||
cargo xtask dist # target/dist: the library, its header, reims-vgpu.pc and
|
||||
# the option ROM, for a host that links it through pkg-config
|
||||
cargo xtask smoke # a guest linked with the library as QEMU links it (make smoke)
|
||||
```
|
||||
|
||||
`crates/reims-vgpu-wire` holds zero-copy views and parsers for the Apple
|
||||
paravirtualized GPU serializer format, derived from Apple's own encoder rather
|
||||
than inferred from captures. `crates/reims-vgpu`'s `runtime::decode` uses those
|
||||
exports for opcodes, record framing, and field layouts on wire-covered
|
||||
families (encoder blit/compute/render binds and state, and the create records
|
||||
above); decode remains the mapping layer into the device's `Command` / `Kind`
|
||||
model and decline naming. Gaps without a wire export (FIFO, event opcodes,
|
||||
unobserved compute residency, pipeline TLV) stay local to decode.
|
||||
| command | what it does |
|
||||
|---|---|
|
||||
| `testkit` | core's `testkit` module is gated, and only dev-dependencies turn its feature on (D50) |
|
||||
| `header [--check]` | `include/reims_vgpu.h` from cbindgen; `--check` fails when the committed header drifts from cbindgen's output |
|
||||
| `dist` | the library as a plain library, below |
|
||||
| `smoke` | the arm64 smoke of the library, below |
|
||||
| `check` | `testkit`, `header --check`, rustfmt, clippy and the tests ([docs/architecture.md](docs/architecture.md) 13.1); `--no-cargo` skips the cargo steps |
|
||||
|
||||
`cargo xtask check` tests with every feature but `reims-vgpu-c/vulkan`,
|
||||
which puts the C API on the Vulkan platform, and lints with every feature
|
||||
too. On a Mac it also clippy-checks the Linux target, and, where Rosetta is
|
||||
installed, runs core's tests as `x86_64-apple-darwin`.
|
||||
|
||||
#### Dist
|
||||
|
||||
```sh
|
||||
cargo xtask dist # release, into target/dist
|
||||
cargo xtask dist --profile checked --out /tmp/reims-vgpu
|
||||
cargo xtask dist --platform vulkan # the Vulkan platform, into target/dist-vulkan
|
||||
```
|
||||
|
||||
`cargo xtask dist` builds `reims-vgpu-c` and writes the library for a host
|
||||
that links it the way it links its other dependencies, through pkg-config:
|
||||
|
||||
```
|
||||
target/dist/
|
||||
include/reims_vgpu.h the committed header
|
||||
lib/libreims_vgpu.a the staticlib
|
||||
lib/libreims_vgpu.dylib the cdylib, @rpath/libreims_vgpu.dylib, signed ad hoc
|
||||
lib/pkgconfig/reims-vgpu.pc the package
|
||||
share/reims-vgpu/ReimsVgpu.rom the EFI option ROM, built from firmware/
|
||||
share/doc/reims-vgpu/ the license: LICENSE and LICENSES/, as in the repository
|
||||
```
|
||||
|
||||
`reims-vgpu.pc` takes its prefix from its own path, so the tree can move.
|
||||
Its `Libs.private` lists the system frameworks and libraries a static link
|
||||
needs, and its `optionrom` variable names the ROM, which QEMU installs as
|
||||
`apple-gfx-pci`'s default `romfile`. QEMU and the smoke link
|
||||
`libreims_vgpu.a`, so the library is part of their binaries; the suite's
|
||||
runner links `libreims_vgpu.dylib` with an `LC_RPATH` at the tree's `lib`.
|
||||
|
||||
`--platform vulkan` builds the C API on the Vulkan platform into
|
||||
`target/dist-vulkan`, laid out the same; the smoke (`--dist`) and the suite
|
||||
(`pgtest run --dist`) take either tree. On Linux `dist` builds that platform
|
||||
alone, with `libreims_vgpu.so` in place of the dylib (architecture 11.3).
|
||||
`CARGO_TARGET_DIR` moves every output, the dist tree included, out of
|
||||
`target`.
|
||||
|
||||
#### Smoke
|
||||
|
||||
```sh
|
||||
cargo xtask dist
|
||||
cargo xtask smoke # --dist DIR for another tree
|
||||
```
|
||||
|
||||
It runs arm64 only: a guest program (`xtask/src/smoke_guest.m`), linked
|
||||
statically with the dist tree's library, that brings up a device and runs an
|
||||
isolated task, whose facts must equal the library's expected values
|
||||
(`GUEST_EXPECTED` in `xtask/src/smoke.rs`). `make smoke` builds the tree and
|
||||
runs it.
|
||||
|
||||
#### The behaviour suite
|
||||
|
||||
The suite (`tests/suite`) runs against the library, by default the
|
||||
checkout's dist tree (`target/dist`):
|
||||
|
||||
```sh
|
||||
make test # the dist tree, then the suite
|
||||
cd tests/suite && python3 -m pgtest run -j 32 # the same, with pgtest's options
|
||||
make bless TEST=<patterns> # record new or changed scenarios from the checkout's build
|
||||
make bless TEST=<patterns> ARGS=--update # record them again after a deliberate change
|
||||
```
|
||||
|
||||
[docs/testing.md](docs/testing.md) 5.7 and
|
||||
[tests/suite/README.md](tests/suite/README.md) have the rest.
|
||||
|
||||
### Profiles
|
||||
|
||||
Set in `Cargo.toml` (architecture 2.3):
|
||||
|
||||
| profile | settings | why |
|
||||
|---|---|---|
|
||||
| `dev` | `panic = "unwind"`, overflow checks on | an unannotated arithmetic slip dies in tests |
|
||||
| `release` | `panic = "unwind"`, overflow checks off, `debug = "line-tables-only"`, thin LTO | the product. Wrapping is explicit where the guest's values wrap (D19), so the checks add nothing |
|
||||
| `checked` | `release` plus overflow checks and debug assertions | a second pass of the suite: a death here is an arithmetic site review missed |
|
||||
|
||||
- **`panic = "unwind"` everywhere** (D9). objc2's `exception::catch` needs
|
||||
it. It is not a way to survive a panic: `reims-vgpu`'s singleton installs a
|
||||
hook that aborts before anything unwinds, so an unintended panic dies at its
|
||||
op with no side effects.
|
||||
- **objc2's debug assertions are on in `dev`** and off in `checked`
|
||||
(`[profile.checked.package.objc2]`, D36). They panic on a message to nil,
|
||||
a missing method and an encoding the runtime disagrees with, which the
|
||||
library never sends, so the tests that send to real Metal check each send.
|
||||
Declarations are also checked with `AnyClass::verify_sel` in
|
||||
`reims-vgpu-metal/tests/spi_encodings.rs`.
|
||||
- objc2's `exception` feature is always on, and `catch-all` never.
|
||||
|
||||
### Features
|
||||
|
||||
- `reims-vgpu/vulkan` and `reims-vgpu-c/vulkan`: the Vulkan platform as the
|
||||
API's, and the C API's, platform. Off by default on macOS; on Linux the
|
||||
library builds only with them.
|
||||
- `macos-sdl` (`reims-vgpu-window`, forwarded by `reims-vgpu` and
|
||||
`reims-vgpu-c`), on by default: SDL3's window on macOS, which
|
||||
`REIMS_VGPU_WINDOW_IMPL=sdl` opens in place of AppKit's. Without it the
|
||||
macOS library has no SDL.
|
||||
- `reims-vgpu-window/sdl-no-link`: SDL left unbuilt, for the Linux target's
|
||||
clippy on a Mac.
|
||||
- `reims-vgpu-core/testkit`: `core::testkit` for other crates' tests.
|
||||
- `reims-vgpu/testkit`: the same, through the public crate, and each
|
||||
handle's core object.
|
||||
|
||||
[docs/api.md](docs/api.md) section 2 lists the device's settings and the
|
||||
environment variables the library reads.
|
||||
|
||||
## History
|
||||
|
||||
The project's earlier stages are at their tags; nothing in this tree needs
|
||||
them:
|
||||
|
||||
- `byte-exact-parity`: a matching decompilation of the framework in macOS
|
||||
26.6 (build 25G83, framework version 64.4.7), its toolchain and its
|
||||
matcher;
|
||||
- `rust-port-parity`: a Rust port of that source, beside the source and its
|
||||
CMake build;
|
||||
- `native-parity`: the rewrite of the port into this library, with the
|
||||
evidence that it kept the port's behaviour.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under the [GNU Lesser General Public License v3.0 or later](LICENSE)
|
||||
(`LGPL-3.0-or-later`).
|
||||
The repository is free software under the GNU General Public License,
|
||||
version 2 or later, or the GNU Lesser General Public License, version 3 or
|
||||
later, at the recipient's choice: `GPL-2.0-or-later OR LGPL-3.0-or-later`,
|
||||
the workspace's `license` in `Cargo.toml`. [LICENSE](LICENSE) says so, and
|
||||
`LICENSES/` holds the texts, the GPL's version 3 among them, since the LGPL's
|
||||
version 3 adds its permissions to it.
|
||||
|
||||
Metal, macOS are trademarks of Apple Inc. reims-vgpu is an independent project and is not affiliated
|
||||
with, sponsored by, or endorsed by Apple Inc.
|
||||
QEMU (`vendor/qemu`) keeps QEMU's licenses. The crates the build takes keep
|
||||
their own: metal2vulkan's, which the Vulkan platform links, and SDL3's
|
||||
sources, which the window crate builds and links statically, among them.
|
||||
|
||||
## Legal
|
||||
|
||||
Interoperability work on a framework already present on the user's own
|
||||
machine. No Apple code or binary is in the repository or in what it
|
||||
builds.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 942 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.5 MiB |
+21
@@ -0,0 +1,21 @@
|
||||
# Architecture 17.4. reims-vgpu-core denies clippy::disallowed_types and
|
||||
# clippy::disallowed_methods; other crates see them as warnings.
|
||||
|
||||
disallowed-types = [
|
||||
{ path = "std::sync::Mutex", reason = "use sync::Mutex (parking_lot) (7.1)" },
|
||||
{ path = "std::sync::RwLock", reason = "use parking_lot or sync::WriterPrefRwLock (7.1)" },
|
||||
]
|
||||
|
||||
disallowed-methods = [
|
||||
{ path = "std::process::abort", reason = "use raise::death::fatal (6.4)" },
|
||||
{ path = "std::thread::spawn", reason = "core's threads come from the platform's Threads: rt::thread::spawn_named (7.1)" },
|
||||
{ path = "std::time::Instant::now", reason = "use Clock (7.5)" },
|
||||
{ path = "std::time::SystemTime::now", reason = "use Clock (7.5)" },
|
||||
{ path = "std::panic::catch_unwind", reason = "allowed only in the testkit (capture, death, launcher), an isolated task's trap (tasks::isolation::life) (6.5) and the C API's catch on Linux (ffi::catch, 6.7)" },
|
||||
]
|
||||
|
||||
# Tests may unwrap, index and panic: a failure is the assertion (architecture 17.4).
|
||||
allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
@@ -1,356 +0,0 @@
|
||||
# conformance
|
||||
|
||||
A self-verifying Metal battery that runs the same source on a native macOS host
|
||||
and inside the guest, and names the seam when the two disagree.
|
||||
|
||||
Every result this project had about Maps' missing type layer was scored by
|
||||
opening a screenshot, and a screenshot names no seam: "labels absent" is what a
|
||||
wrong pitch, a wrong swizzle, a dropped dispatch and a lost mip level all look
|
||||
like. Each case here computes a value the CPU can predict exactly, asks the GPU
|
||||
for it, and compares — so a failure names the case, the bytes wanted and the
|
||||
bytes returned.
|
||||
|
||||
```
|
||||
CASE <name> PASS|FAIL|SKIP <detail>
|
||||
SUMMARY cases=N failures=N skipped=N
|
||||
```
|
||||
|
||||
## Reading a result
|
||||
|
||||
`verdict.py` applies the table below to a pair of runs and exits non-zero when
|
||||
something in it is unexplained. `run-guest.sh` calls it, so a sweep reads a
|
||||
verdict rather than diffing hundreds of lines by eye:
|
||||
|
||||
```sh
|
||||
conformance/verdict.py --native baselines/native-apple-m4-macos15.txt \
|
||||
--guest /tmp/conf-out/conformance.txt \
|
||||
--translation-errors expectations/macos-13/translation-errors.txt \
|
||||
--driver-errors expectations/macos-13/driver-errors.txt
|
||||
```
|
||||
|
||||
It is stricter than the eye in two directions the eye is bad at. A case that
|
||||
**stopped being reported** reads as nothing at all in a summary line -- the
|
||||
totals simply shrink -- and it says `NOT-RUN`. A classified case that now
|
||||
**passes** is a failure too: an inventory nobody prunes stops being a list of
|
||||
defects and becomes a list of cases nobody looks at.
|
||||
|
||||
The comparison between the two hosts is the whole instrument:
|
||||
|
||||
| native | guest | meaning |
|
||||
|---|---|---|
|
||||
| PASS | PASS | nothing to see |
|
||||
| PASS | FAIL | a named device defect |
|
||||
| FAIL | — | a wrong expectation in the suite, not a finding |
|
||||
| — | SKIP | the device's own reported limits make the case inexpressible |
|
||||
|
||||
`baselines/` holds the native runs, one file per oracle host. Re-record whenever
|
||||
a case is added, and never treat a guest failure as a finding until the same case
|
||||
is green natively.
|
||||
|
||||
## Failure ownership is part of the verdict
|
||||
|
||||
`expectations/<rail>/translation-errors.txt` and
|
||||
`expectations/<rail>/driver-errors.txt` are separate inventories. One case name
|
||||
goes on each line; `#` starts the required diagnosis. A name in both files is
|
||||
`DUPLICATE-CLASSIFICATION` and fails scoring.
|
||||
|
||||
**They are per rail, and a rail is a driver.** `macos-13` and `macos-15` are two
|
||||
different guest drivers running the same battery, so a case one of them fails
|
||||
says nothing about the other, and neither does a case one of them passes. An
|
||||
entry established on one rail may not be copied to another to make a sweep
|
||||
green; it has to be re-established there, against that rail's own control. A
|
||||
rail with no inventory directory is refused by the runner rather than scored
|
||||
against a neighbour's debt.
|
||||
|
||||
A translation entry names its gitignored `bugs/` handoff package, containing the
|
||||
AIR reproducer and translator evidence. A driver entry names the violated Metal
|
||||
relation and the owning device rail. An unexplained mismatch belongs in neither
|
||||
inventory until the owner is proved. Both files are checked in both directions:
|
||||
a listed case that starts passing is `FIXED-TRANSLATION` or `FIXED-DRIVER`.
|
||||
|
||||
It is not a place to put a case that fails on the oracle too. That is
|
||||
`SUITE-BUG`, the expectation is wrong, and listing it hides a bug in the battery
|
||||
rather than one in the device.
|
||||
|
||||
## The oracle says right; only the control says backwards
|
||||
|
||||
`verdict.py` asks the native oracle whether a guest result is *correct*.
|
||||
`ratchet.py` asks an identified control run whether a candidate moved
|
||||
*backwards*. They are different questions and a change has to answer both.
|
||||
|
||||
```sh
|
||||
conformance/ratchet.py \
|
||||
--control runs/control/conformance.txt --control-device runs/control/device.log \
|
||||
--candidate runs/cand/conformance.txt --candidate-device runs/cand/device.log
|
||||
```
|
||||
|
||||
The distinction is load-bearing on a rail whose debt is not yet classified. Such
|
||||
a rail reads to the oracle scorer as scores of unexplained failures, and will
|
||||
until every one has an established owner. That is honest, and it also means the
|
||||
oracle scorer is red for *every* candidate on that rail and so cannot tell one
|
||||
that broke something from one that broke nothing. The control can: it already
|
||||
contains the debt, so a candidate reproducing it exactly has preserved the
|
||||
device's behavior whether or not anyone has yet written down whose fault it is.
|
||||
|
||||
Classifying a failure and detecting a regression are therefore separate jobs,
|
||||
and only the second one gates a commit.
|
||||
|
||||
**Give it more than one control.** The cases on this rail are reproducible and
|
||||
the device log is not: two back-to-back macos-13 controls of the same build
|
||||
agreed on all 290 case results exactly and still disagreed on their typed-reason
|
||||
counts, `stamp_wait_timeout` among them. `--control` may be repeated, and a
|
||||
repeated control measures the rail's variance instead of assuming it away -- a
|
||||
candidate inside the envelope has not moved. With one control the tool says so
|
||||
in its totals rather than leaving a reader to infer it. A case the controls
|
||||
themselves disagree about is `CONTROL-UNSTABLE` and is dropped from scoring,
|
||||
because charging a candidate for the rail's own noise is the same error in the
|
||||
other direction.
|
||||
|
||||
It scores the workflow's transition table, and two things no case comparison
|
||||
can see. A name in only one of the two runs is a regression rather than a
|
||||
missing row -- coverage that moved is the failure this catches. And the device's
|
||||
own typed reasons are counted on both sides, so a candidate that keeps every
|
||||
pixel and doubles the fence timeouts is red on that alone.
|
||||
|
||||
One reading it hands back rather than decides: a case that fails in both runs
|
||||
with a *different* detail is `CHANGED-DETAIL` and does not fail the run, because
|
||||
nothing in a `CASE` line separates the typed reason from its payload. The same
|
||||
defect described differently and a different defect wearing the same name look
|
||||
identical here, and only a reader who knows the case can say which it is.
|
||||
|
||||
## A case name must mean the same thing on both hosts
|
||||
|
||||
`minimumLinearTextureAlignment` is 16 on an M-series device and 256 on Apple's
|
||||
paravirtual one, so a pitch derived from it lands on a different integer per
|
||||
host. A case named after that integer -- `linear_a8Unorm_54x16_pitch80` on one
|
||||
host, `pitch512` on the other -- has no counterpart on the other side to be
|
||||
scored against, and the whole native/guest instrument is gone for it. Sixty-two
|
||||
of 216 cases were in that state, silently: they ran everywhere, tested the same
|
||||
thing everywhere, and could not be paired.
|
||||
|
||||
So the label carries the **derivation** and the detail carries the number.
|
||||
`Pitch` is `.tight`, `.padded(rows:)` or `.exact()`, and it computes the byte
|
||||
count as well as naming it, which also took the alignment arithmetic out of the
|
||||
call sites where it was written by hand five times. A case whose *width* is
|
||||
derived gets the same treatment -- `offsetOracleCase(256, …)` and `(250, …)`
|
||||
mean "tight" and "six bytes of padding" on a device aligning to 16 and on one
|
||||
aligning to 256 alike, which `align` and `align - 6` did not.
|
||||
|
||||
When adding a parameterized case, ask what its name would be on the other host.
|
||||
|
||||
A `SKIP` is not a soft failure. `minimumLinearTextureAlignment` is 16 on an
|
||||
M-series device and 256 on Apple's paravirtual one, so a literal pitch from a
|
||||
guest census is not expressible on every host — Metal itself rejects the
|
||||
descriptor. The battery also derives padded pitches from whatever the running
|
||||
device reports, so every host runs padded-pitch cases whatever its limit.
|
||||
|
||||
## Where things live
|
||||
|
||||
```
|
||||
conformance/
|
||||
suite/
|
||||
main.swift every case invocation, and nothing else
|
||||
Harness.swift report/counters, the device and queue
|
||||
Shaders.swift the one Metal source string
|
||||
Support.swift the library, pipelines, readback, helpers
|
||||
cases/*.swift the case bodies, one file per rail or family
|
||||
baselines/ native runs, one per oracle host
|
||||
expectations/<rail>/ separate translation and driver inventories, per rail
|
||||
verdict.py scores a guest run against the native one
|
||||
ratchet.py scores a candidate guest run against a control guest run
|
||||
run-native.sh build and run on the oracle
|
||||
run-guest.sh boot a rail and run the same source in the guest
|
||||
build/ binaries; gitignored
|
||||
```
|
||||
|
||||
**Swift permits top-level statements in `main.swift` alone**, which is what makes
|
||||
the split worth having: a case body physically cannot invoke itself, so the
|
||||
invocation list is one file a reader can count against the parameter grid. The
|
||||
"a case nobody called reports nothing" trap below is closed by construction.
|
||||
`dev`, `queue` and `library` are globals initialised by a closure for the same
|
||||
reason — they were top-level `guard`s and a top-level `do`/`catch` when this was
|
||||
one file, and neither form is legal outside `main.swift`.
|
||||
|
||||
Declaration order across files does not matter in Swift, so a case file may use
|
||||
anything in `Support.swift` and vice versa. Adding a case is: a function in the
|
||||
right `cases/` file, and a call in `main.swift`.
|
||||
|
||||
## Running it
|
||||
|
||||
Native, on the oracle — this also cross-builds the x86_64 fallback:
|
||||
|
||||
```sh
|
||||
conformance/run-native.sh
|
||||
```
|
||||
|
||||
`ORACLE=<ssh-host>` names the machine; it needs Xcode's command line tools and
|
||||
nothing else.
|
||||
|
||||
In the guest — this boots a rail, runs the battery and collects the device's own
|
||||
fail log beside the results:
|
||||
|
||||
```sh
|
||||
conformance/run-guest.sh /tmp/conf-out
|
||||
```
|
||||
|
||||
`RAIL` selects the guest rail and defaults to `macos-13`. Environment passes
|
||||
through, so an ablation arm is
|
||||
`REIMS_VGPU_GUEST_IMPORT=off conformance/run-guest.sh /tmp/conf-off`.
|
||||
|
||||
For a fast, shaderless gate of the integer-clear contract, use
|
||||
`CONFORMANCE_MODE=integer-clear`. Use `CONFORMANCE_MODE=topology` for the
|
||||
point, line, line-strip, and triangle raster contract, or
|
||||
`CONFORMANCE_MODE=float-sampling` for the `RGBA32Float` compute/vertex sampling
|
||||
contract. Use `CONFORMANCE_MODE=indexed-draw` for UInt16/UInt32 index offsets,
|
||||
signed base vertex, and base instance. The default is the
|
||||
complete battery. Focused guest runs require `NATIVE` to name the matching
|
||||
focused oracle output; this prevents a partial run from being scored against
|
||||
the full baseline. Every run writes `manifest.txt`, hashes the live QEMU through
|
||||
`/proc`, hashes the linked static library and guest test binary, and preserves
|
||||
the serial and fail logs. A stamp timeout, device loss, or guest panic fails the
|
||||
runner even when all classified pixel comparisons are expected. Focused probes
|
||||
are bounded at 180 seconds by default (the full battery at 600);
|
||||
`CONFORMANCE_TIMEOUT` may narrow that bound for an investigation.
|
||||
|
||||
The runner ships `build/conformance-x86_64`, the Mach-O built beside the native
|
||||
oracle result on an Apple host. This makes the oracle and guest source/build
|
||||
identity explicit and avoids treating macOS's developer-tools installer shim
|
||||
as a working compiler. Re-run `run-native.sh` whenever a case is added.
|
||||
|
||||
## A refusal is not a mismatch, and the kernel is what says which
|
||||
|
||||
This device refuses a dispatch on the *host* side, so the guest's command buffer
|
||||
completes clean and the output buffer keeps whatever was in it. Left alone,
|
||||
every case here then compares its sentinel fill against what it wanted and
|
||||
reports a **content** failure — "the device returned the wrong bytes" for a
|
||||
device that returned none.
|
||||
|
||||
The `offset_oracle` cases showed how far that misleads. Their fill is
|
||||
`1 + (i % 251)` and zero means "a byte nothing in this buffer ever held", but
|
||||
`readBack`'s `0xEE` sentinel is 238 — inside the fill's own range. A refused
|
||||
dispatch inverted to a constant source offset of 237, every texel landed in a
|
||||
different delta bucket, and four cases reported `absent=0 shifted=4080`: a
|
||||
precise, plausible account of a defect that did not exist.
|
||||
|
||||
No sentinel value fixes this. A battery covering many formats has no byte that
|
||||
is out of range for all of them. So each readback kernel writes `ran[0] = 1u`
|
||||
into a buffer of its own, **before** its grid guard — so the witness says the
|
||||
kernel was reached rather than that some thread was in range — and `readBack`
|
||||
returns `nil` when that word stays zero. A case that gets `nil` calls `refused`,
|
||||
which prints one wording for all of them.
|
||||
|
||||
Two consequences when adding a case:
|
||||
|
||||
- **A new readback kernel must take `device uint *ran [[buffer(4)]]` and write
|
||||
it first.** A kernel without the witness reports every refusal as a content
|
||||
failure, which is the state this section exists to describe.
|
||||
- **A case that cannot run because another case did not must `skipDependent`,
|
||||
not vanish.** The case *count* is what a reader diffs two runs by, and a name
|
||||
that stops appearing reads as a deleted case. One refusal of
|
||||
`incremental_a8_first_read` silently took three other names out of the totals
|
||||
before this was added.
|
||||
|
||||
## Reading it beside the device log
|
||||
|
||||
`run-guest.sh` copies `/tmp/reims-vgpu-fail.log` to `device.log` in the
|
||||
output directory. A case that fails with a refusal in that log is an
|
||||
unimplemented rail refusing by name; a case that fails with *nothing* in the log
|
||||
is silent loss, which is the worse of the two and the one worth chasing first.
|
||||
|
||||
## A `.private` render target does not reach the target-import rail
|
||||
|
||||
Every render target in sections A-H is `rd.storageMode = .private`, which means
|
||||
the device allocates it and the guest never names the pages behind it. That is
|
||||
half the render targets a compositing app uses. The other half are `.shared`:
|
||||
layers the CPU also rasterizes into, or that another process composites, whose
|
||||
bytes are guest memory the device may bind a Vulkan image *directly over*
|
||||
instead of copying.
|
||||
|
||||
Those are two rails, and for a long time this battery had exactly one case on
|
||||
the second of them — `cpu_write_after_render`, section F5. A whole rail behind
|
||||
one case is not coverage. It is a single sample that happens to pass, and it is
|
||||
what let a live defect sit underneath 173 green cases: a driven Maps boot lost
|
||||
its entire type layer on the arm where guest-backed targets are imported, and
|
||||
nothing in this file could see it, because nothing in this file created a
|
||||
guest-backed target except that one case.
|
||||
|
||||
Section I is that coverage. When adding a render-target case, ask which rail it
|
||||
is on and say so in the case name — `srt_` is the guest-backed prefix. A new
|
||||
case that reaches for `.private` because that is what the case above it used has
|
||||
tested the rail that already had coverage.
|
||||
|
||||
The widths there (60, 256, 1000) are not decoration. 60 and 1000 texels are 240
|
||||
and 4000 bytes, neither a multiple of the 256-byte linear alignment this device
|
||||
reports, so a rail that confuses the guest's stride with a padded one has
|
||||
somewhere to show it. A case list of only round widths cannot see a shear.
|
||||
|
||||
## A case that is never called reports nothing, and the totals do not notice
|
||||
|
||||
`cpu_write_after_render_256x64` was absent from every run of this battery, on
|
||||
both arms, because the invocation list called three of its four arms. Nothing
|
||||
flagged it: `ran` counts cases that reported, so a case that was never invoked
|
||||
is indistinguishable from one that does not exist.
|
||||
|
||||
That is the same failure mode as the `refused(); return` bug that `skipDependent`
|
||||
exists to fix, one level up — there the case vanished from the totals mid-run,
|
||||
here it never entered them. When adding a parameterized case, count the
|
||||
invocations against the parameter grid before trusting a green summary.
|
||||
|
||||
|
||||
## A case may claim the device rail it was written to move
|
||||
|
||||
`claims(label, "sl_gpu_landed")` in a case body prints a `ROUTE`
|
||||
line, and `verdict.py` reads those against the device's own fail log. A case
|
||||
that passes without its claimed counter ever moving is `NOT-COVERED`, which is
|
||||
the worst reading this battery produces: it is indistinguishable from coverage,
|
||||
and it is what three attempts at the case below did on the *broken* build.
|
||||
|
||||
Two limits, both deliberate:
|
||||
|
||||
- **The check is per run, not per case.** Nothing carries a case name across
|
||||
into the device, so the question it answers is "did anything in this run reach
|
||||
that rail". That is the question that was being got wrong.
|
||||
- **A claim nobody watched is worse than no claim.** Claiming a counter because
|
||||
the name sounds right makes the table read as coverage while measuring
|
||||
spelling. Watch the counter move, then claim it. An unclaimed case is
|
||||
unclaimed, not covered.
|
||||
|
||||
A narrowing `REIMS_VGPU_*` switch can legitimately close a claimed rail, so
|
||||
`run-guest.sh` passes `--claims-advisory` when any is set.
|
||||
|
||||
## A race is only a test if the broken arm loses it
|
||||
|
||||
`srt_blit_pipelined_*` is the regression gate for a host read of guest pages
|
||||
that was not ordered against this device's own submitted GPU writes. Getting it
|
||||
to reproduce took six guest boots and three wrong shapes, and each wrong shape
|
||||
failed in a way that read as a pass.
|
||||
|
||||
Three things it turns out to need, none of which is negotiable:
|
||||
|
||||
- **The copy has to be one the guest driver actually emits as a whole-surface
|
||||
texture-to-texture copy.** A `.bgra8Unorm` pair at 512x512 is not: the driver
|
||||
stages it through a buffer, and the case then exercises a different device rail
|
||||
and passes. The shape that works was *measured* off a driven compositor with a
|
||||
temporary device probe rather than chosen — a linear source, an IOSurface
|
||||
destination, `BGRA8Unorm_sRGB`, one level and one slice, at window and screen
|
||||
size.
|
||||
- **The render and the copy have to be in separate command buffers.** In one
|
||||
command buffer the driver resolves the read-after-write hazard itself and
|
||||
stages the copy, which again lands on another rail.
|
||||
- **One frame in flight is not enough.** The single-shot `srt_blit_after_render_*`
|
||||
cases reach the rail — confirmed by probe — and still pass on the broken arm,
|
||||
because one render finishes before a host reader can decode a copy and memcpy
|
||||
three megabytes. Only the pipelined form fails: eight frames, each rendering
|
||||
and copying without waiting, so a copy is serviced while earlier renders are
|
||||
still executing. That is what a compositor does and it is why the defect was
|
||||
a compositor defect.
|
||||
|
||||
The single-shot cases are kept even though they gate nothing. They record the
|
||||
shape that reaches the rail without losing the race, which is the thing that
|
||||
made three earlier attempts look like they had disproved a real bug.
|
||||
|
||||
**Distinct colours per frame are load-bearing.** Each frame renders its own
|
||||
colour into its own source and copies to its own destination, so a stale read is
|
||||
identifiable as *which* earlier state was read rather than merely "wrong". The
|
||||
report separates the two: a previous frame's colour names a stale copy, and zero
|
||||
names a copy that ran before anything was written at all.
|
||||
@@ -1,300 +0,0 @@
|
||||
CASE clear_only_rg16uint_private_store PASS 1088 RG16Uint texels retained [1,258]
|
||||
CASE clear_only_rg16uint_shared_store PASS 1020 RG16Uint texels retained [1,258]
|
||||
CASE shader_compile PASS runtime library built
|
||||
CASE topology_point_three_islands PASS lit=27 point_centres=3/3
|
||||
CASE topology_line_horizontal PASS lit=52 rows=[31]
|
||||
CASE topology_line_strip_two_arms PASS lit=88 left=44 right=44
|
||||
CASE topology_triangle_filled PASS lit=1210 centre=0xff00ff00 corner=0xff000000
|
||||
CASE sample_rgba32float_compute_1x1 PASS 1 float4 texels exact
|
||||
CASE sample_rgba32float_compute_4x1 PASS 4 float4 texels exact
|
||||
CASE sample_rgba32float_vertex_positions_4x1 PASS lit=1094 centre=0xff00ff00 lower_left=0xff00ff00 corner=0xff000000
|
||||
CASE draw_nonindexed_shared_shader_control PASS lit=1094
|
||||
CASE draw_indexed_uint16_offset_4 PASS exactly matches non-indexed control
|
||||
CASE draw_indexed_uint32_offset_4 PASS exactly matches non-indexed control
|
||||
CASE draw_indexed_uint16_base_vertex_minus1 PASS exactly matches non-indexed control
|
||||
CASE draw_indexed_uint32_offset_4_base_vertex_minus1 PASS exactly matches non-indexed control
|
||||
CASE draw_nonindexed_two_instances_base_instance_5 PASS lit=416 left=0xff00ff00 right=0xff00ff00 centre=0xff000000
|
||||
CASE draw_indexed_two_instances_base_instance_5 PASS lit=416 left=0xff00ff00 right=0xff00ff00 centre=0xff000000 matches_nonindexed=true
|
||||
CASE depth_attachment_isolated_across_tasks PASS each task loaded its own stored depth
|
||||
CASE linear_r8Unorm_64x16_pitch_tight PASS 1024 texels exact
|
||||
CASE linear_r8Unorm_64x16_pitch_tight_sampled PASS 1024 texels exact
|
||||
CASE linear_a8Unorm_64x16_pitch_tight PASS 1024 texels exact
|
||||
CASE linear_a8Unorm_64x16_pitch_tight_sampled PASS 1024 texels exact
|
||||
CASE linear_rg8Unorm_64x16_pitch_tight PASS 1024 texels exact
|
||||
CASE linear_rg8Unorm_64x16_pitch_tight_sampled PASS 1024 texels exact
|
||||
CASE linear_rgba8Unorm_64x16_pitch_tight PASS 1024 texels exact
|
||||
CASE linear_rgba8Unorm_64x16_pitch_tight_sampled PASS 1024 texels exact
|
||||
CASE linear_bgra8Unorm_64x16_pitch_tight PASS 1024 texels exact
|
||||
CASE linear_bgra8Unorm_64x16_pitch_tight_sampled PASS 1024 texels exact
|
||||
CASE linear_a8Unorm_54x16_pitch_64 PASS 864 texels exact
|
||||
CASE linear_a8Unorm_54x16_pitch_64_sampled PASS 864 texels exact
|
||||
CASE linear_a8Unorm_218x16_pitch_256 PASS 3488 texels exact
|
||||
CASE linear_a8Unorm_85x85_pitch_128 PASS 7225 texels exact
|
||||
CASE linear_r8Unorm_128x16_pitch_128 PASS 2048 texels exact
|
||||
CASE linear_bgra8Unorm_60x8_pitch_256 PASS 480 texels exact
|
||||
CASE linear_r8Unorm_54x16_pitch_tight_plus1 PASS 864 texels exact
|
||||
CASE linear_r8Unorm_54x16_pitch_tight_plus2 PASS 864 texels exact
|
||||
CASE linear_a8Unorm_54x16_pitch_tight_plus1 PASS 864 texels exact
|
||||
CASE linear_a8Unorm_54x16_pitch_tight_plus2 PASS 864 texels exact
|
||||
CASE linear_rg8Unorm_54x16_pitch_tight_plus1 PASS 864 texels exact
|
||||
CASE linear_rg8Unorm_54x16_pitch_tight_plus2 PASS 864 texels exact
|
||||
CASE linear_rgba8Unorm_54x16_pitch_tight_plus1 PASS 864 texels exact
|
||||
CASE linear_rgba8Unorm_54x16_pitch_tight_plus2 PASS 864 texels exact
|
||||
CASE linear_bgra8Unorm_54x16_pitch_tight_plus1 PASS 864 texels exact
|
||||
CASE linear_bgra8Unorm_54x16_pitch_tight_plus2 PASS 864 texels exact
|
||||
CASE incremental_r8Unorm_compute_first_read PASS region A present, region B still zero
|
||||
CASE incremental_r8Unorm_compute_append_visible PASS post-read append visible
|
||||
CASE incremental_r8Unorm_compute_untouched_stable PASS region A unchanged
|
||||
CASE incremental_r8Unorm_compute_rewrite_visible PASS rewrite visible
|
||||
CASE incremental_a8Unorm_compute_first_read PASS region A present, region B still zero
|
||||
CASE incremental_a8Unorm_compute_append_visible PASS post-read append visible
|
||||
CASE incremental_a8Unorm_compute_untouched_stable PASS region A unchanged
|
||||
CASE incremental_a8Unorm_compute_rewrite_visible PASS rewrite visible
|
||||
CASE incremental_rg8Unorm_compute_first_read PASS region A present, region B still zero
|
||||
CASE incremental_rg8Unorm_compute_append_visible PASS post-read append visible
|
||||
CASE incremental_rg8Unorm_compute_untouched_stable PASS region A unchanged
|
||||
CASE incremental_rg8Unorm_compute_rewrite_visible PASS rewrite visible
|
||||
CASE incremental_rgba8Unorm_compute_first_read PASS region A present, region B still zero
|
||||
CASE incremental_rgba8Unorm_compute_append_visible PASS post-read append visible
|
||||
CASE incremental_rgba8Unorm_compute_untouched_stable PASS region A unchanged
|
||||
CASE incremental_rgba8Unorm_compute_rewrite_visible PASS rewrite visible
|
||||
CASE incremental_bgra8Unorm_compute_first_read PASS region A present, region B still zero
|
||||
CASE incremental_bgra8Unorm_compute_append_visible PASS post-read append visible
|
||||
CASE incremental_bgra8Unorm_compute_untouched_stable PASS region A unchanged
|
||||
CASE incremental_bgra8Unorm_compute_rewrite_visible PASS rewrite visible
|
||||
CASE rt_pipeline PASS solid_fs pipeline built
|
||||
CASE rt_render_then_sample PASS 4096 texels are the drawn colour
|
||||
CASE rt_blit_to_buffer PASS 4096 texels exact through blit
|
||||
CASE msaa4_color_store_no_resolve PASS 64 pixels retained four distinct samples
|
||||
CASE msaa4_color_store_host_sample_count PASS 64 pixels retained four distinct samples
|
||||
CASE depth_attachment_clear_without_test_state PASS stored depth clear rejected the later draw
|
||||
CASE depth_test_less_without_attachment PASS z=0 compared against the absent attachment value
|
||||
CASE depth_test_equal_without_attachment PASS z=0 compared against the absent attachment value
|
||||
CASE depth_test_greater_without_attachment PASS z=0 compared against the absent attachment value
|
||||
CASE depth_test_never_without_attachment PASS z=0 compared against the absent attachment value
|
||||
CASE depth_test_always_without_attachment PASS z=0 compared against the absent attachment value
|
||||
CASE stencil_attachment_clear_without_test_state PASS stored stencil clear passed the later equal test
|
||||
CASE stencil_only_attachment_clear_without_test_state PASS stored stencil-only clear passed the later equal test
|
||||
CASE stencil_test_equal_without_attachment_depth_false PASS reference zero compared against implicit stencil zero
|
||||
CASE stencil_test_not_equal_without_attachment_depth_false PASS reference zero compared against implicit stencil zero
|
||||
CASE stencil_test_equal_without_attachment_depth_true PASS reference zero compared against implicit stencil zero
|
||||
CASE stencil_test_not_equal_without_attachment_depth_true PASS reference zero compared against implicit stencil zero
|
||||
CASE combined_depth_stencil_default_buffer_copy_selects_depth PASS default copies selected depth and preserved stencil
|
||||
CASE mip_chain_create PASS levels=7
|
||||
CASE mip_fetch_level_0_size64 PASS 4096 texels are level 0's marker
|
||||
CASE mip_sample_level_0_size64 PASS 4096 texels are level 0's marker
|
||||
CASE mip_fetch_level_1_size32 PASS 1024 texels are level 1's marker
|
||||
CASE mip_sample_level_1_size32 PASS 1024 texels are level 1's marker
|
||||
CASE mip_fetch_level_2_size16 PASS 256 texels are level 2's marker
|
||||
CASE mip_sample_level_2_size16 PASS 256 texels are level 2's marker
|
||||
CASE mip_fetch_level_3_size8 PASS 64 texels are level 3's marker
|
||||
CASE mip_sample_level_3_size8 PASS 64 texels are level 3's marker
|
||||
CASE mip_fetch_level_4_size4 PASS 16 texels are level 4's marker
|
||||
CASE mip_sample_level_4_size4 PASS 16 texels are level 4's marker
|
||||
CASE mip_fetch_level_5_size2 PASS 4 texels are level 5's marker
|
||||
CASE mip_sample_level_5_size2 PASS 4 texels are level 5's marker
|
||||
CASE mip_fetch_level_6_size1 PASS 1 texels are level 6's marker
|
||||
CASE mip_sample_level_6_size1 PASS 1 texels are level 6's marker
|
||||
CASE mip_blit_level_0_size64 PASS 4096 texels are level 0's marker
|
||||
CASE mip_blit_level_1_size32 PASS 1024 texels are level 1's marker
|
||||
CASE mip_blit_level_2_size16 PASS 256 texels are level 2's marker
|
||||
CASE mip_blit_level_3_size8 PASS 64 texels are level 3's marker
|
||||
CASE mip_blit_level_4_size4 PASS 16 texels are level 4's marker
|
||||
CASE mip_blit_level_5_size2 PASS 4 texels are level 5's marker
|
||||
CASE mip_blit_level_6_size1 PASS 1 texels are level 6's marker
|
||||
CASE vb_first_submission_left PASS geometry landed in the left half
|
||||
CASE vb_second_submission_right PASS geometry landed in the right half
|
||||
CASE vb_third_submission_left_again PASS geometry landed in the left half
|
||||
CASE fb_offset_0 PASS slot 0 at offset 0 reached the fragment stage
|
||||
CASE fb_offset_256 PASS slot 1 at offset 256 reached the fragment stage
|
||||
CASE fb_offset_512 PASS slot 2 at offset 512 reached the fragment stage
|
||||
CASE fb_rebound_between_draws PASS each draw read the offset bound before it
|
||||
CASE render_barrier_resource_fragment PASS 8 alternating producer/consumer rounds were visible
|
||||
CASE compute_barrier_resource PASS 8 alternating concurrent producer/consumer rounds were visible
|
||||
CASE compute_barrier_scope_buffers PASS 8 alternating concurrent producer/consumer rounds were visible
|
||||
CASE compute_dispatch_threadgroups_indirect PASS groups=[3,2,1] local=[4,2,1] grid=[12, 4, 1] first_bad=none
|
||||
CASE synchronize_resource_gpu_to_cpu PASS managed/shared GPU writes visible to CPU after synchronize
|
||||
CASE heap_texture_alias_lifecycle PASS one live range was released, reused at offset=0, and addressed as the replacement
|
||||
CASE heap_texture_placement_overlap PASS two live definitions at offset=0 executed sequentially and addressed the replacement
|
||||
CASE heap_texture_placement_overlap_incompatible_widths PASS two live textures of different bit widths at offset=0 each addressed their own definition
|
||||
CASE buffer_backed_alias_incompatible_widths PASS every byte the rgba16Float alias wrote reached the rgba8Unorm one
|
||||
CASE buffer_backed_alias_partial_row_range PASS the four-row write landed on exactly its own rows of the wide alias
|
||||
CASE ebl_same_bind_second_encoder PASS the binding re-issued on the second encoder is the one that drew
|
||||
CASE ebl_changed_bind_second_encoder PASS the binding re-issued on the second encoder is the one that drew
|
||||
CASE ebl_same_bind_second_command_buffer PASS the binding re-issued on the second encoder is the one that drew
|
||||
CASE command_buffer_same_queue_order PASS producer=4 consumer=4 ordered=true
|
||||
CASE command_buffer_same_queue_completion_publication PASS published=[1, 2]
|
||||
CASE command_buffer_empty_completion PASS status=4 callback=true
|
||||
CASE command_buffer_independent_queue_publication PASS independent_published_before_signal=true
|
||||
CASE command_buffer_scheduled_before_completed PASS publications=["scheduled", "completed"]
|
||||
CASE command_buffer_default_retains_resource PASS retained_while_pending=true status=4
|
||||
CASE indirect_command_reset_copy_optimize PASS baseline=[11, 22, 33] mutated=[11, 0, 33]
|
||||
CASE pipeline_information_lifetime PASS compute_max=1024 width=32 static_plain=0 static_declared=80 render_imageblock=4
|
||||
CASE texture_view_identity_64x32_base PASS 64x32 slice=0 matched
|
||||
CASE texture_view_identity_64x32_view PASS 64x32 slice=0 matched
|
||||
CASE texture_view_identity_256x64_base PASS 256x64 slice=0 matched
|
||||
CASE texture_view_identity_256x64_view PASS 256x64 slice=0 matched
|
||||
CASE texture_view_array_slice_64x32x3_s0 PASS 64x32 slice=0 matched
|
||||
CASE texture_view_array_slice_64x32x3_s1 PASS 64x32 slice=1 matched
|
||||
CASE texture_view_array_slice_64x32x3_s2 PASS 64x32 slice=2 matched
|
||||
CASE texture_view_over_surface_64x32_base PASS 64x32 slice=0 matched
|
||||
CASE texture_view_over_surface_64x32_view PASS 64x32 slice=0 matched
|
||||
CASE self_copy_overlap_row_shift_14 PASS the overlapping copy read its source before writing its destination
|
||||
CASE self_copy_overlap_column_shift_12 PASS the overlapping copy read its source before writing its destination
|
||||
CASE self_copy_disjoint_control PASS the overlapping copy read its source before writing its destination
|
||||
CASE texture_view_over_surface_256x64_base PASS 256x64 slice=0 matched
|
||||
CASE texture_view_over_surface_256x64_view PASS 256x64 slice=0 matched
|
||||
CASE fragsample_a8Unorm_54x16_pitch_64_first_draw PASS 864 texels exact through the rasterizer
|
||||
CASE fragsample_a8Unorm_54x16_pitch_64_after_cpu_rewrite PASS 864 texels exact through the rasterizer
|
||||
CASE fragsample_a8Unorm_218x16_pitch_256_first_draw PASS 3488 texels exact through the rasterizer
|
||||
CASE fragsample_a8Unorm_218x16_pitch_256_after_cpu_rewrite PASS 3488 texels exact through the rasterizer
|
||||
CASE fragsample_a8Unorm_85x85_pitch_128_first_draw PASS 7225 texels exact through the rasterizer
|
||||
CASE fragsample_a8Unorm_85x85_pitch_128_after_cpu_rewrite PASS 7225 texels exact through the rasterizer
|
||||
CASE fragsample_rgba8Unorm_64x16_pitch_tight_first_draw PASS 1024 texels exact through the rasterizer
|
||||
CASE fragsample_rgba8Unorm_64x16_pitch_tight_after_cpu_rewrite PASS 1024 texels exact through the rasterizer
|
||||
CASE fragsample_bgra8Unorm_60x8_pitch_256_first_draw PASS 480 texels exact through the rasterizer
|
||||
CASE fragsample_bgra8Unorm_60x8_pitch_256_after_cpu_rewrite PASS 480 texels exact through the rasterizer
|
||||
CASE fragsample_a8Unorm_54x16_pitch_tight_plus1_first_draw PASS 864 texels exact through the rasterizer
|
||||
CASE fragsample_a8Unorm_54x16_pitch_tight_plus1_after_cpu_rewrite PASS 864 texels exact through the rasterizer
|
||||
CASE fragsample_bgra8Unorm_54x16_pitch_tight_plus1_first_draw PASS 864 texels exact through the rasterizer
|
||||
CASE fragsample_bgra8Unorm_54x16_pitch_tight_plus1_after_cpu_rewrite PASS 864 texels exact through the rasterizer
|
||||
CASE incremental_r8Unorm_fragment_first_read PASS region A present, region B still zero
|
||||
CASE incremental_r8Unorm_fragment_append_visible PASS post-read append visible
|
||||
CASE incremental_r8Unorm_fragment_untouched_stable PASS region A unchanged
|
||||
CASE incremental_r8Unorm_fragment_rewrite_visible PASS rewrite visible
|
||||
CASE incremental_a8Unorm_fragment_first_read PASS region A present, region B still zero
|
||||
CASE incremental_a8Unorm_fragment_append_visible PASS post-read append visible
|
||||
CASE incremental_a8Unorm_fragment_untouched_stable PASS region A unchanged
|
||||
CASE incremental_a8Unorm_fragment_rewrite_visible PASS rewrite visible
|
||||
CASE incremental_rg8Unorm_fragment_first_read PASS region A present, region B still zero
|
||||
CASE incremental_rg8Unorm_fragment_append_visible PASS post-read append visible
|
||||
CASE incremental_rg8Unorm_fragment_untouched_stable PASS region A unchanged
|
||||
CASE incremental_rg8Unorm_fragment_rewrite_visible PASS rewrite visible
|
||||
CASE incremental_rgba8Unorm_fragment_first_read PASS region A present, region B still zero
|
||||
CASE incremental_rgba8Unorm_fragment_append_visible PASS post-read append visible
|
||||
CASE incremental_rgba8Unorm_fragment_untouched_stable PASS region A unchanged
|
||||
CASE incremental_rgba8Unorm_fragment_rewrite_visible PASS rewrite visible
|
||||
CASE incremental_bgra8Unorm_fragment_first_read PASS region A present, region B still zero
|
||||
CASE incremental_bgra8Unorm_fragment_append_visible PASS post-read append visible
|
||||
CASE incremental_bgra8Unorm_fragment_untouched_stable PASS region A unchanged
|
||||
CASE incremental_bgra8Unorm_fragment_rewrite_visible PASS rewrite visible
|
||||
CASE replace_r8Unorm_fragment_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_r8Unorm_fragment_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_r8Unorm_fragment_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_r8Unorm_fragment_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE replace_a8Unorm_fragment_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_a8Unorm_fragment_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_a8Unorm_fragment_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_a8Unorm_fragment_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE replace_rg8Unorm_fragment_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_rg8Unorm_fragment_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_rg8Unorm_fragment_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_rg8Unorm_fragment_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE replace_rgba8Unorm_fragment_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_rgba8Unorm_fragment_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_rgba8Unorm_fragment_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_rgba8Unorm_fragment_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE replace_bgra8Unorm_fragment_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_bgra8Unorm_fragment_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_bgra8Unorm_fragment_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_bgra8Unorm_fragment_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE offset_oracle_256x16_pitch_tight_compute PASS 4096 texels at the offsets the contract names
|
||||
CASE offset_oracle_250x16_pitch_tight_compute PASS 4000 texels at the offsets the contract names
|
||||
CASE offset_oracle_218x16_pitch_tight_compute PASS 3488 texels at the offsets the contract names
|
||||
CASE offset_oracle_54x16_pitch_tight_plus1_compute PASS 864 texels at the offsets the contract names
|
||||
CASE offset_oracle_256x16_pitch_tight_fragment PASS 4096 texels at the offsets the contract names
|
||||
CASE offset_oracle_250x16_pitch_tight_fragment PASS 4000 texels at the offsets the contract names
|
||||
CASE offset_oracle_218x16_pitch_tight_fragment PASS 3488 texels at the offsets the contract names
|
||||
CASE offset_oracle_54x16_pitch_tight_plus1_fragment PASS 864 texels at the offsets the contract names
|
||||
CASE rt_width_256 PASS 4096 texels are the drawn colour
|
||||
CASE rt_width_250 PASS 4000 texels are the drawn colour
|
||||
CASE rt_width_218 PASS 3488 texels are the drawn colour
|
||||
CASE rt_width_64 PASS 1024 texels are the drawn colour
|
||||
CASE rt_width_60 PASS 960 texels are the drawn colour
|
||||
CASE rt_width_54 PASS 864 texels are the drawn colour
|
||||
CASE rt_width_63 PASS 1008 texels are the drawn colour
|
||||
CASE rt_width_57 PASS 912 texels are the drawn colour
|
||||
CASE dispatch_threads_grid_64x16_tg8 PASS 1024 threads ran and nothing outside the grid did
|
||||
CASE dispatch_threads_grid_218x16_tg8 PASS 3488 threads ran and nothing outside the grid did
|
||||
CASE dispatch_threads_grid_54x15_tg8 PASS 810 threads ran and nothing outside the grid did
|
||||
CASE dispatch_threads_grid_57x9_tg8 PASS 513 threads ran and nothing outside the grid did
|
||||
CASE dispatch_threads_grid_31x31_tg16 PASS 961 threads ran and nothing outside the grid did
|
||||
CASE cpu_write_after_render_64x32 PASS the GPU kept its half and the CPU kept its half
|
||||
CASE cpu_write_after_render_64x32_then_second_pass PASS the GPU kept its half and the CPU kept its half
|
||||
CASE cpu_write_after_render_256x64 PASS the GPU kept its half and the CPU kept its half
|
||||
CASE cpu_write_after_render_256x64_then_second_pass PASS the GPU kept its half and the CPU kept its half
|
||||
CASE offset_alias_a8Unorm_54x16_x4 PASS 4 tiles exact at their own offsets
|
||||
CASE offset_alias_rgba8Unorm_32x32_x3 PASS 3 tiles exact at their own offsets
|
||||
CASE replace_r8Unorm_compute_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_r8Unorm_compute_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_r8Unorm_compute_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_r8Unorm_compute_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE replace_a8Unorm_compute_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_a8Unorm_compute_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_a8Unorm_compute_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_a8Unorm_compute_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE replace_rg8Unorm_compute_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_rg8Unorm_compute_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_rg8Unorm_compute_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_rg8Unorm_compute_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE replace_rgba8Unorm_compute_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_rgba8Unorm_compute_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_rgba8Unorm_compute_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_rgba8Unorm_compute_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE replace_bgra8Unorm_compute_first_read PASS the replaced strip is present and the rest is still zero
|
||||
CASE replace_bgra8Unorm_compute_append_visible PASS a strip replaced after a read is visible
|
||||
CASE replace_bgra8Unorm_compute_untouched_stable PASS the glyphs already in the atlas are untouched
|
||||
CASE replace_bgra8Unorm_compute_rewrite_visible PASS a strip rewritten in place is visible
|
||||
CASE srt_draw_60x32 PASS the whole guest-backed target is the drawn colour
|
||||
CASE srt_load_preserves_60x32 PASS the second pass added to what the first pass left
|
||||
CASE srt_scissor_keeps_rest_60x32 PASS the scissored write landed on exactly its own rows
|
||||
CASE srt_sample_after_render_60x32 PASS a later pass sampled what the earlier pass rendered
|
||||
CASE srt_draw_256x64 PASS the whole guest-backed target is the drawn colour
|
||||
CASE srt_load_preserves_256x64 PASS the second pass added to what the first pass left
|
||||
CASE srt_scissor_keeps_rest_256x64 PASS the scissored write landed on exactly its own rows
|
||||
CASE srt_sample_after_render_256x64 PASS a later pass sampled what the earlier pass rendered
|
||||
CASE srt_draw_1000x40 PASS the whole guest-backed target is the drawn colour
|
||||
CASE srt_load_preserves_1000x40 PASS the second pass added to what the first pass left
|
||||
CASE srt_scissor_keeps_rest_1000x40 PASS the scissored write landed on exactly its own rows
|
||||
CASE srt_sample_after_render_1000x40 PASS a later pass sampled what the earlier pass rendered
|
||||
CASE srt_cpu_seed_then_load_60x32 PASS three loaded passes kept every texel the CPU wrote first
|
||||
CASE srt_cpu_seed_then_load_256x64 PASS three loaded passes kept every texel the CPU wrote first
|
||||
CASE srt_cpu_seed_then_load_1000x40 PASS three loaded passes kept every texel the CPU wrote first
|
||||
CASE srt_glyph_blend_60x32 PASS coverage type blended into a guest-backed layer, and the second pass kept the first
|
||||
CASE srt_glyph_blend_256x64 PASS coverage type blended into a guest-backed layer, and the second pass kept the first
|
||||
CASE srt_glyph_blend_1000x40 PASS coverage type blended into a guest-backed layer, and the second pass kept the first
|
||||
CASE biplanar_luma_64x32 PASS plane 0 reads its own 64x32 one-byte texels
|
||||
CASE biplanar_chroma_64x32 PASS plane 1 reads its own 32x16 two-byte texels
|
||||
CASE biplanar_luma_256x64 PASS plane 0 reads its own 256x64 one-byte texels
|
||||
CASE biplanar_chroma_256x64 PASS plane 1 reads its own 128x32 two-byte texels
|
||||
CASE iosrt_draw_60x32 PASS the whole IOSurface-backed target is the drawn colour
|
||||
CASE iosrt_load_preserves_60x32 PASS the second pass added to what the first pass left
|
||||
CASE iosrt_scissor_keeps_rest_60x32 PASS the scissored write landed on exactly its own rows
|
||||
CASE iosrt_glyph_blend_60x32 PASS coverage type blended into an IOSurface layer, and the second pass kept the first
|
||||
CASE iosrt_draw_256x64 PASS the whole IOSurface-backed target is the drawn colour
|
||||
CASE iosrt_load_preserves_256x64 PASS the second pass added to what the first pass left
|
||||
CASE iosrt_scissor_keeps_rest_256x64 PASS the scissored write landed on exactly its own rows
|
||||
CASE iosrt_glyph_blend_256x64 PASS coverage type blended into an IOSurface layer, and the second pass kept the first
|
||||
CASE iosrt_draw_1000x40 PASS the whole IOSurface-backed target is the drawn colour
|
||||
CASE iosrt_load_preserves_1000x40 PASS the second pass added to what the first pass left
|
||||
CASE iosrt_scissor_keeps_rest_1000x40 PASS the scissored write landed on exactly its own rows
|
||||
CASE iosrt_glyph_blend_1000x40 PASS coverage type blended into an IOSurface layer, and the second pass kept the first
|
||||
CASE srt_cpu_write_then_sample_60x32 PASS a sampled bind saw the texels the CPU wrote after the GPU rendered
|
||||
CASE iosrt_cpu_write_then_sample_60x32 PASS a sampled bind saw the texels the CPU wrote after the GPU rendered
|
||||
CASE srt_cpu_write_then_sample_256x64 PASS a sampled bind saw the texels the CPU wrote after the GPU rendered
|
||||
CASE iosrt_cpu_write_then_sample_256x64 PASS a sampled bind saw the texels the CPU wrote after the GPU rendered
|
||||
CASE srt_cpu_write_then_sample_1000x40 PASS a sampled bind saw the texels the CPU wrote after the GPU rendered
|
||||
CASE iosrt_cpu_write_then_sample_1000x40 PASS a sampled bind saw the texels the CPU wrote after the GPU rendered
|
||||
CASE srt_blit_after_render_1024x768 PASS the copy moved what the render ahead of it had written
|
||||
CASE srt_blit_after_render_1920x1080 PASS the copy moved what the render ahead of it had written
|
||||
CASE srt_blit_pipelined_1024x768_x8 PASS every frame's copy moved that frame's own pixels
|
||||
ROUTE srt_blit_iosurface_source_1024x768_x8 blit_t5_plane_device
|
||||
ROUTE srt_blit_iosurface_source_1024x768_x8 sl_gpu_landed
|
||||
CASE srt_blit_iosurface_source_1024x768_x8 PASS every surface-to-surface copy moved its own frame's pixels
|
||||
ROUTE srt_blit_iosurface_source_1920x1080_x4 blit_t5_plane_device
|
||||
ROUTE srt_blit_iosurface_source_1920x1080_x4 sl_gpu_landed
|
||||
CASE srt_blit_iosurface_source_1920x1080_x4 PASS every surface-to-surface copy moved its own frame's pixels
|
||||
CASE srt_blit_buffer_backed_512x512 PASS the copy out of a buffer-backed source moved what the render had written
|
||||
CASE command_buffer_cross_queue_shared_event_visibility PASS producer=4 consumer=4 completed_without_host_release=true visible=true
|
||||
SUMMARY cases=294 failures=0 skipped=0
|
||||
DEVICE name=Apple M4 unified=true
|
||||
@@ -1,9 +0,0 @@
|
||||
# Guest failures owned outside shader translation, on the macos-13 rail.
|
||||
#
|
||||
# One case name per line, followed by a comment naming the violated API
|
||||
# relation and the driver owner. An unexplained mismatch does not belong here:
|
||||
# establish its owner first. Remove an entry when the scorer says FIXED-DRIVER.
|
||||
#
|
||||
# This inventory is this rail's alone. A guest rail is a guest driver, so a
|
||||
# failure established on another rail says nothing about this one and may not
|
||||
# be copied across.
|
||||
@@ -1,10 +0,0 @@
|
||||
# Guest failures owned by shader translation, on the macos-13 rail.
|
||||
#
|
||||
# One case name per line, followed by a comment naming the gitignored
|
||||
# `bugs/<defect>/` handoff package that reproduces it. An unexplained mismatch
|
||||
# does not belong here: establish its owner first. Remove an entry when the
|
||||
# scorer says FIXED-TRANSLATION.
|
||||
#
|
||||
# This inventory is this rail's alone. A guest rail is a guest driver, so a
|
||||
# failure established on another rail says nothing about this one and may not
|
||||
# be copied across.
|
||||
@@ -1,56 +0,0 @@
|
||||
# Guest failures owned outside shader translation.
|
||||
#
|
||||
# One case name per line, followed by a comment naming the violated API
|
||||
# relation and the driver owner or rail. An unexplained mismatch does not
|
||||
# belong here: establish its owner first. Remove an entry when the scorer says
|
||||
# FIXED-DRIVER.
|
||||
|
||||
# A buffer-backed alias used as a compute *storage* image is refused before
|
||||
# translation (`compute_buffer_texture_storage_unsupported`). The sampled forms
|
||||
# of the same rail now execute.
|
||||
buffer_backed_alias_incompatible_widths # buffer storage image refused before translation
|
||||
buffer_backed_alias_partial_row_range # buffer storage image refused before translation
|
||||
|
||||
# The multisample pair is now split across the two inventories, which is the
|
||||
# whole reason there are two cases. This device serves the `texture2d_ms` bind
|
||||
# from the target resident, so `msaa4_color_store_host_sample_count` passes and
|
||||
# has no entry here. `msaa4_color_store_no_resolve` reads the same samples back
|
||||
# through `get_num_samples()`, which translation folds to 1, and it is recorded
|
||||
# in translation-errors.txt against its bugs/ package.
|
||||
|
||||
# Depth/stencil attachment state or contents are lost in the device model. The
|
||||
# distinguishing colour shaders pass elsewhere; the log also names a depth
|
||||
# LOAD with no resident content.
|
||||
depth_attachment_isolated_across_tasks # task-local depth content aliases or disappears
|
||||
depth_attachment_clear_without_test_state # stored depth clear is absent on later LOAD
|
||||
stencil_only_attachment_clear_without_test_state # stencil-only attachment clear is absent
|
||||
combined_depth_stencil_default_buffer_copy_selects_depth # blit selects the wrong aspect bytes
|
||||
|
||||
# `dispatchThreads` is widened to whole threadgroups by the command execution
|
||||
# rail. The divisible control passes and every non-divisible grid runs threads
|
||||
# outside the API extent.
|
||||
dispatch_threads_grid_218x16_tg8 # 96 threads ran past the requested width
|
||||
dispatch_threads_grid_54x15_tg8 # threads ran past both requested dimensions
|
||||
dispatch_threads_grid_57x9_tg8 # threads ran past both requested dimensions
|
||||
dispatch_threads_grid_31x31_tg16 # threads ran past both requested dimensions
|
||||
|
||||
# Device API/state reporting; neither result executes translated GPU code.
|
||||
indirect_command_reset_copy_optimize # device reports indirect command buffers unavailable
|
||||
pipeline_information_lifetime # pipeline construction-owned information reports zero
|
||||
|
||||
# The render path drops the declared array slice and samples slice zero.
|
||||
texture_view_array_slice_64x32x3_s1 # texture view base slice 1 dropped
|
||||
texture_view_array_slice_64x32x3_s2 # texture view base slice 2 dropped
|
||||
|
||||
# A buffer-backed render target arrives as a texture view; the target resolver
|
||||
# rejects that object type and the following shaderless blit sees untouched bytes.
|
||||
srt_blit_buffer_backed_512x512 # rt_wrong_type followed by view_desc_decode
|
||||
|
||||
# Direct indexed draw semantics. Both index widths and byte offsets match the
|
||||
# shared-shader control when baseVertex is zero. Either width fails only when
|
||||
# the signed base is -1, so the driver loses or misapplies baseVertex. General
|
||||
# non-indexed baseInstance passes; only the indexed base-instance opcode is
|
||||
# accepted without an executor and produces no pixels.
|
||||
draw_indexed_uint16_base_vertex_minus1 # signed baseVertex is lost or misapplied
|
||||
draw_indexed_uint32_offset_4_base_vertex_minus1 # signed baseVertex is lost or misapplied
|
||||
draw_indexed_two_instances_base_instance_5 # indexed base-instance opcode accepted without executor
|
||||
@@ -1,22 +0,0 @@
|
||||
# Guest failures proved to be owned by shader translation.
|
||||
#
|
||||
# One case name per line. Every active entry must name its ignored `bugs/`
|
||||
# handoff package in the comment. The scorer fails if the case starts passing,
|
||||
# because that means either the translator was repaired or the case stopped
|
||||
# reaching the translated behavior.
|
||||
|
||||
# `bugs/compute-multisample-query-reports-one/` -- a compute kernel's
|
||||
# `texture2d_ms` sample-count query is folded to the constant 1, so a loop
|
||||
# written over `get_num_samples()` runs once and every sample after zero is
|
||||
# unreachable. Present in the pinned revision and in published upstream.
|
||||
#
|
||||
# This case was carried in driver-errors.txt while this device refused the
|
||||
# multisample sampled image as `unstageable_multisampled` before translation
|
||||
# could execute -- the note kept there said so, and said the classification
|
||||
# would move when that stopped being true. It has: the bind is now served from
|
||||
# the target resident, the dispatch runs, and sample 0 reads back correctly
|
||||
# through a multisample descriptor while samples 1..3 keep the readback
|
||||
# buffer's fill. The sibling case `msaa4_color_store_host_sample_count` takes
|
||||
# the identical render and comparison through a kernel handed the count by the
|
||||
# host and passes, which is what isolates this failure to the query.
|
||||
msaa4_color_store_no_resolve # bugs/compute-multisample-query-reports-one
|
||||
@@ -1,266 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score a candidate guest run against an identified control guest run.
|
||||
|
||||
`verdict.py` answers a different question: it asks the native oracle whether a
|
||||
guest result is *right*. This asks the control whether a candidate moved
|
||||
*backwards*, which is the question a change has to answer before it may be
|
||||
committed, and it is not the same question.
|
||||
|
||||
The difference matters most where the two disagree. A rail whose debt is not yet
|
||||
classified reads as 77 unexplained failures to the oracle scorer and will do so
|
||||
until every one of them has an established owner -- which is honest, and which
|
||||
also means that scorer is red for every candidate and cannot distinguish a
|
||||
candidate that broke something from one that broke nothing. The control can. It
|
||||
already contains that debt, so a candidate reproducing it exactly has preserved
|
||||
the device's behavior whether or not anyone has yet written down whose fault it
|
||||
is.
|
||||
|
||||
The transitions are the workflow's table, mechanised:
|
||||
|
||||
control PASS -> candidate PASS preserved
|
||||
control PASS -> anything else REGRESSION
|
||||
control FAIL -> candidate FAIL, same unchanged debt
|
||||
control FAIL -> candidate PASS improvement; prune the ledger
|
||||
control FAIL -> candidate SKIP/not-run REGRESSION
|
||||
control SKIP -> candidate SKIP unchanged applicability
|
||||
control SKIP -> candidate PASS improvement
|
||||
control SKIP -> candidate FAIL/not-run REGRESSION
|
||||
name in one run only REGRESSION (coverage moved)
|
||||
name twice in either run REGRESSION (the totals lie)
|
||||
|
||||
"Same failure" is the same case, result class and typed reason; changing
|
||||
diagnostic payload alone is not a regression. Nothing in a `CASE` line separates
|
||||
reason from payload, so a changed detail on a still-failing case is reported as
|
||||
CHANGED-DETAIL and does not by itself fail the run. It is the one reading this
|
||||
tool hands back rather than decides: a payload that moved may be the same defect
|
||||
described differently, or a different defect wearing the same name, and only a
|
||||
reader who knows the case can say which.
|
||||
|
||||
The device's own log is compared too. A candidate that keeps every pixel and
|
||||
doubles the fence timeouts has moved backwards, and no case comparison can see
|
||||
it. That comparison needs more than one control, because the log is not
|
||||
reproducible the way the cases are: two back-to-back macos-13 controls of the
|
||||
same build agreed on all 290 case results exactly and still disagreed on their
|
||||
typed-reason counts, `stamp_wait_timeout` among them. So `--control` may be
|
||||
given more than once, and a repeated control establishes an envelope rather than
|
||||
a number. A candidate inside the envelope has not moved; outside it, it has.
|
||||
|
||||
One control is accepted and says so in the totals. It cannot separate a
|
||||
regression from run-to-run variance in the log, and a reader should not have to
|
||||
infer that from the absence of a second `--control`.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import re
|
||||
import sys
|
||||
|
||||
CASE = re.compile(r"^CASE (\S+) (PASS|FAIL|SKIP) ?(.*)$")
|
||||
DEVICE = re.compile(r"^DEVICE (.*)$")
|
||||
# A typed record on the always-on fail channel opens with its reason slug.
|
||||
REASON = re.compile(r"^([a-z][a-z0-9_]*) ")
|
||||
# `OFF` records are observations, not failures, and ranking them as failures is
|
||||
# a documented way to read this log wrong.
|
||||
NOT_A_FAILURE = re.compile(r"\bOFF\b")
|
||||
# The catastrophic classes the workflow names, as they appear in the log.
|
||||
CATASTROPHIC = re.compile(r"stamp_wait_timeout|device_lost|VK_ERROR_DEVICE_LOST")
|
||||
|
||||
|
||||
def parse_cases(path):
|
||||
"""Case name -> (result, detail), plus the DEVICE line and repeated names.
|
||||
|
||||
A repeated name is kept at its first sighting and reported, because the
|
||||
alternative -- letting the second overwrite the first -- is how a battery
|
||||
that reports a case twice reads as a battery that reports it once.
|
||||
"""
|
||||
cases, device, dupes = {}, None, []
|
||||
with open(path) as fh:
|
||||
for line in fh:
|
||||
line = line.rstrip("\n")
|
||||
m = DEVICE.match(line)
|
||||
if m:
|
||||
device = m.group(1)
|
||||
continue
|
||||
m = CASE.match(line)
|
||||
if not m:
|
||||
continue
|
||||
name, result, detail = m.group(1), m.group(2), m.group(3).strip()
|
||||
if name in cases:
|
||||
dupes.append(name)
|
||||
continue
|
||||
cases[name] = (result, detail)
|
||||
return cases, device, dupes
|
||||
|
||||
|
||||
def parse_device(path):
|
||||
"""Typed reason -> count, over one device log.
|
||||
|
||||
Counted, not deduplicated: the emitters deduplicate and the counters do not,
|
||||
so this is the population a reader may compare between two runs only because
|
||||
both sides are counted the same way here.
|
||||
"""
|
||||
counts = collections.Counter()
|
||||
if not path:
|
||||
return counts
|
||||
try:
|
||||
fh = open(path)
|
||||
except OSError:
|
||||
return counts
|
||||
with fh:
|
||||
for line in fh:
|
||||
if NOT_A_FAILURE.search(line):
|
||||
continue
|
||||
m = REASON.match(line)
|
||||
if m:
|
||||
counts[m.group(1)] += 1
|
||||
return counts
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument(
|
||||
"--control",
|
||||
required=True,
|
||||
action="append",
|
||||
help="identified control run's conformance.txt; repeat for an envelope",
|
||||
)
|
||||
ap.add_argument("--candidate", required=True, help="candidate run's conformance.txt")
|
||||
ap.add_argument(
|
||||
"--control-device",
|
||||
action="append",
|
||||
default=[],
|
||||
help="a control's device.log, in the same order as its --control",
|
||||
)
|
||||
ap.add_argument("--candidate-device", help="the candidate's device.log")
|
||||
ap.add_argument(
|
||||
"--quiet",
|
||||
action="store_true",
|
||||
help="print only the transitions that are not 'preserved' and the totals",
|
||||
)
|
||||
args = ap.parse_args()
|
||||
|
||||
parsed = [parse_cases(path) for path in args.control]
|
||||
control, control_dev, control_dupes = parsed[0]
|
||||
candidate, candidate_dev, candidate_dupes = parse_cases(args.candidate)
|
||||
|
||||
regressions, improvements, changed, lines = [], [], [], []
|
||||
tally = collections.Counter()
|
||||
|
||||
# A case the controls themselves disagree about has no control reading to
|
||||
# score a candidate against, and scoring it anyway would charge the
|
||||
# candidate for the rail's own variance. Drop it from the comparison and say
|
||||
# so, because a silently unscored case is the failure this whole tool is
|
||||
# about.
|
||||
unstable = set()
|
||||
for other, _, _ in parsed[1:]:
|
||||
for name in set(control) | set(other):
|
||||
if control.get(name) != other.get(name):
|
||||
unstable.add(name)
|
||||
for name in sorted(unstable):
|
||||
readings = " | ".join(str(p[0].get(name)) for p in parsed)
|
||||
changed.append(f"CONTROL-UNSTABLE {name} -- not scored; controls said {readings}")
|
||||
control.pop(name, None)
|
||||
candidate.pop(name, None)
|
||||
|
||||
for name in control_dupes:
|
||||
regressions.append(f"DUPLICATE-IN-CONTROL {name}")
|
||||
for name in candidate_dupes:
|
||||
regressions.append(f"DUPLICATE-IN-CANDIDATE {name}")
|
||||
|
||||
for name in sorted(set(control) | set(candidate)):
|
||||
before = control.get(name)
|
||||
after = candidate.get(name)
|
||||
if before is None:
|
||||
# A name the candidate reports and the control never did cannot be
|
||||
# scored as a transition. It is not a pass to be credited: there is
|
||||
# no control reading for it.
|
||||
regressions.append(f"NOT-IN-CONTROL {name} -- candidate says {after[0]}")
|
||||
continue
|
||||
if after is None:
|
||||
regressions.append(f"NOT-RUN {name} -- control said {before[0]}")
|
||||
continue
|
||||
b, a = before[0], after[0]
|
||||
if b == "PASS" and a == "PASS":
|
||||
tally["preserved"] += 1
|
||||
elif b == "PASS":
|
||||
regressions.append(f"REGRESSION {name} -- PASS -> {a}: {after[1]}")
|
||||
elif b == "FAIL" and a == "FAIL":
|
||||
tally["unchanged debt"] += 1
|
||||
if before[1] != after[1]:
|
||||
changed.append(
|
||||
f"CHANGED-DETAIL {name}\n control: {before[1]}\n candidate: {after[1]}"
|
||||
)
|
||||
elif b == "FAIL" and a == "PASS":
|
||||
improvements.append(f"IMPROVEMENT {name} -- FAIL -> PASS; prune the ledger")
|
||||
elif b == "FAIL":
|
||||
regressions.append(f"REGRESSION {name} -- FAIL -> {a}: a failure that stopped running")
|
||||
elif b == "SKIP" and a == "SKIP":
|
||||
tally["unchanged applicability"] += 1
|
||||
elif b == "SKIP" and a == "PASS":
|
||||
improvements.append(f"IMPROVEMENT {name} -- SKIP -> PASS; the case became expressible")
|
||||
else:
|
||||
regressions.append(f"REGRESSION {name} -- SKIP -> {a}: {after[1]}")
|
||||
|
||||
if control_dev != candidate_dev:
|
||||
regressions.append(
|
||||
f"DEVICE-CHANGED -- control {control_dev!r} candidate {candidate_dev!r}"
|
||||
)
|
||||
|
||||
# The envelope every control run put this reason inside. A candidate within
|
||||
# it has not moved; the width is the rail's own variance, measured rather
|
||||
# than assumed.
|
||||
before_logs = [parse_device(path) for path in args.control_device]
|
||||
after_log = parse_device(args.candidate_device)
|
||||
reasons = set(after_log)
|
||||
for log in before_logs:
|
||||
reasons |= set(log)
|
||||
for reason in sorted(reasons):
|
||||
seen = [log[reason] for log in before_logs] or [0]
|
||||
lo, hi = min(seen), max(seen)
|
||||
a = after_log[reason]
|
||||
if lo <= a <= hi:
|
||||
continue
|
||||
envelope = str(lo) if lo == hi else f"{lo}..{hi}"
|
||||
line = f"DEVICE-REASON {reason} -- control {envelope} candidate {a}"
|
||||
if a > hi and CATASTROPHIC.search(reason):
|
||||
regressions.append(line + " (a catastrophic class got worse)")
|
||||
elif a > hi:
|
||||
changed.append(line)
|
||||
else:
|
||||
improvements.append(line + " (fewer)")
|
||||
|
||||
for line in regressions:
|
||||
lines.append(line)
|
||||
for line in changed:
|
||||
lines.append(line)
|
||||
for line in improvements:
|
||||
lines.append(line)
|
||||
if not args.quiet:
|
||||
lines.append("")
|
||||
print("\n".join(lines))
|
||||
print(
|
||||
f"control {len(control)} cases from {control_dev}"
|
||||
f" ({len(parsed)} control run{'s' if len(parsed) != 1 else ''})\n"
|
||||
f"candidate {len(candidate)} cases from {candidate_dev}"
|
||||
)
|
||||
if len(before_logs) < 2:
|
||||
print(
|
||||
"note: fewer than two control device logs, so a moved typed-reason "
|
||||
"count cannot be told from run-to-run variance"
|
||||
)
|
||||
print(
|
||||
f"preserved {tally['preserved']}, "
|
||||
f"unchanged debt {tally['unchanged debt']}, "
|
||||
f"unchanged applicability {tally['unchanged applicability']}, "
|
||||
f"improvements {len(improvements)}, "
|
||||
f"changed detail {len(changed)}, "
|
||||
f"control-unstable {len(unstable)}, "
|
||||
f"regressions {len(regressions)}"
|
||||
)
|
||||
# An improvement is not a failure, but it is not nothing either: the ledger
|
||||
# it makes stale is the reader's to prune. Only a backwards move exits red.
|
||||
return 1 if regressions else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,232 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Boot one x86 rail and run the Metal conformance battery inside the guest.
|
||||
#
|
||||
# run-guest.sh <outdir>
|
||||
#
|
||||
# The same source the oracle runs, on the paravirtual device. `run-native.sh`
|
||||
# builds the x86_64 artifact that this runner sends to the rail. The same source
|
||||
# and build identity therefore feed both oracle and guest results.
|
||||
#
|
||||
# `RAIL` selects the guest rail and defaults to macos-13.
|
||||
#
|
||||
# Environment passes through, so an arm is `REIMS_VGPU_X=y run-guest.sh ...`.
|
||||
set -uo pipefail
|
||||
export LC_ALL=C
|
||||
OUT="${1:?usage: run-guest.sh <outdir>}"
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO="$(cd "$HERE/.." && pwd)"
|
||||
# A guest rail is a guest driver, so the failures a rail owns are that rail's
|
||||
# alone. Each rail therefore carries its own debt inventory, and a rail with no
|
||||
# inventory is refused rather than silently scored against another rail's debt.
|
||||
RAIL="${RAIL:-macos-13}"
|
||||
EXPECT="$HERE/expectations/$RAIL"
|
||||
if [ ! -d "$REPO/vm/disks/rails/$RAIL" ]; then
|
||||
echo "conformance: no such rail: $RAIL (see vm/boot-x86.sh --list-rails)" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [ ! -r "$EXPECT/driver-errors.txt" ] || [ ! -r "$EXPECT/translation-errors.txt" ]; then
|
||||
echo "conformance: rail $RAIL has no expectation inventory at $EXPECT" >&2
|
||||
exit 2
|
||||
fi
|
||||
RUN_KIND="${RUN_KIND:-candidate}"
|
||||
case "$RUN_KIND" in baseline|candidate) ;; *)
|
||||
echo "conformance: RUN_KIND must be baseline or candidate" >&2; exit 2 ;;
|
||||
esac
|
||||
CONFORMANCE_MODE="${CONFORMANCE_MODE:-full}"
|
||||
case "$CONFORMANCE_MODE" in
|
||||
full) CONFORMANCE_ARG="" ;;
|
||||
integer-clear) CONFORMANCE_ARG="--integer-clear-only" ;;
|
||||
topology) CONFORMANCE_ARG="--topology-only" ;;
|
||||
float-sampling) CONFORMANCE_ARG="--float-sampling-only" ;;
|
||||
indexed-draw) CONFORMANCE_ARG="--indexed-draw-only" ;;
|
||||
*) echo "conformance: CONFORMANCE_MODE must be full, integer-clear, topology, float-sampling, or indexed-draw" >&2; exit 2 ;;
|
||||
esac
|
||||
if [ "$CONFORMANCE_MODE" = "full" ]; then
|
||||
PROBE_TIMEOUT="${CONFORMANCE_TIMEOUT:-600}"
|
||||
else
|
||||
PROBE_TIMEOUT="${CONFORMANCE_TIMEOUT:-180}"
|
||||
fi
|
||||
case "$PROBE_TIMEOUT" in
|
||||
''|*[!0-9]*|0) echo "conformance: CONFORMANCE_TIMEOUT must be a positive integer" >&2; exit 2 ;;
|
||||
esac
|
||||
if [ "$CONFORMANCE_MODE" != "full" ] && [ -z "${NATIVE:-}" ]; then
|
||||
echo "conformance: NATIVE=<matching oracle output> is required for focused mode" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [ -n "${NATIVE:-}" ] && [ ! -r "$NATIVE" ]; then
|
||||
echo "conformance: oracle output is not readable: $NATIVE" >&2
|
||||
exit 2
|
||||
fi
|
||||
BIN="${CONFORMANCE_BIN:-$HERE/build/conformance-x86_64}"
|
||||
mkdir -p "$OUT"
|
||||
[ -x "$BIN" ] || {
|
||||
echo "conformance: no x86_64 battery at $BIN (run-native.sh makes it)" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
QEMU_ACTUAL="$(realpath -m "${QEMU_BIN:-$REPO/vendor/qemu/build/qemu-system-x86_64}")"
|
||||
QEMU_SOURCE_REPO="$(cd "$(dirname "$QEMU_ACTUAL")/../../.." && pwd)"
|
||||
MANIFEST="$OUT/manifest.txt"
|
||||
{
|
||||
echo "kind=$RUN_KIND"
|
||||
echo "started=$(date --iso-8601=seconds)"
|
||||
echo "pathway=x86-macos-linux-vulkan"
|
||||
echo "rail=$RAIL"
|
||||
echo "snapshot=$(readlink -f "$REPO/vm/disks/rails/$RAIL/snapshots/current")"
|
||||
echo "backend=vulkan"
|
||||
echo "attach=reims-vgpu-pci"
|
||||
echo "page_shift=12"
|
||||
echo "host=$(uname -a)"
|
||||
echo "environment_overrides_begin"
|
||||
env | grep '^REIMS_VGPU_' | sort || true
|
||||
echo "environment_overrides_end"
|
||||
echo "harness_repo=$REPO"
|
||||
echo "harness_head=$(git -C "$REPO" rev-parse HEAD)"
|
||||
echo "harness_tracked_diff_sha256=$(git -C "$REPO" diff --binary HEAD | sha256sum | awk '{print $1}')"
|
||||
echo "harness_status_begin"
|
||||
git -C "$REPO" status --short
|
||||
echo "harness_status_end"
|
||||
echo "suite_inputs_begin"
|
||||
find "$HERE/suite" -type f -print0 | sort -z | xargs -0 sha256sum
|
||||
sha256sum "$HERE/verdict.py" "$EXPECT/translation-errors.txt" \
|
||||
"$EXPECT/driver-errors.txt"
|
||||
[ ! -x "$BIN" ] || sha256sum "$BIN"
|
||||
echo "suite_inputs_end"
|
||||
echo "qemu_source_repo=$QEMU_SOURCE_REPO"
|
||||
echo "qemu_source_head=$(git -C "$QEMU_SOURCE_REPO" rev-parse HEAD)"
|
||||
echo "qemu_source_tracked_diff_sha256=$(git -C "$QEMU_SOURCE_REPO" diff --binary HEAD | sha256sum | awk '{print $1}')"
|
||||
echo "qemu_source_status_begin"
|
||||
git -C "$QEMU_SOURCE_REPO" status --short
|
||||
echo "qemu_source_status_end"
|
||||
echo "qemu_path=$QEMU_ACTUAL"
|
||||
echo "serial_path=pending; see boot_stdout_path"
|
||||
echo "boot_stdout_path=$OUT/boot-stdout.log"
|
||||
echo "fail_log_path=/tmp/reims-vgpu-fail.log"
|
||||
echo "probe=Metal conformance binary over ssh"
|
||||
echo "conformance_mode=$CONFORMANCE_MODE"
|
||||
echo "conformance_timeout_seconds=$PROBE_TIMEOUT"
|
||||
} >"$MANIFEST"
|
||||
|
||||
pkill -f 'qemu-system-x86_6[4].*reims-vgpu' 2>/dev/null
|
||||
for _ in $(seq 1 30); do
|
||||
pgrep -f 'qemu-system-x86_6[4].*reims-vgpu' >/dev/null || break
|
||||
sleep 1
|
||||
done
|
||||
rm -f /tmp/reims-vgpu-fail.log
|
||||
|
||||
echo "conformance: booting rail=$RAIL"
|
||||
TESTING_TIMEOUT="${TESTING_TIMEOUT:-1800}" \
|
||||
"$REPO/vm/boot-x86.sh" --device reims-vgpu-pci --rail "$RAIL" --testing \
|
||||
>"$OUT/boot-stdout.log" 2>&1 &
|
||||
BOOT_PID=$!
|
||||
|
||||
# Only a live device writes the fail log, so this is what says the boot is ours
|
||||
# and not a survivor holding 2222.
|
||||
for _ in $(seq 1 240); do
|
||||
[ -f /tmp/reims-vgpu-fail.log ] && break
|
||||
kill -0 "$BOOT_PID" 2>/dev/null || break
|
||||
sleep 2
|
||||
done
|
||||
[ -f /tmp/reims-vgpu-fail.log ] || { echo "device never came up"; exit 1; }
|
||||
|
||||
# Prove what the live process loaded. The hash is taken through /proc, not from
|
||||
# a filename we hope the process used.
|
||||
for _ in $(seq 1 30); do
|
||||
QEMU_PID="$(pgrep -o -f "^$QEMU_ACTUAL " 2>/dev/null || true)"
|
||||
[ -n "$QEMU_PID" ] && break
|
||||
sleep 1
|
||||
done
|
||||
[ -n "${QEMU_PID:-}" ] || { echo "could not identify the live QEMU process"; exit 1; }
|
||||
{
|
||||
echo "boot_pid=$BOOT_PID"
|
||||
echo "qemu_pid=$QEMU_PID"
|
||||
echo "qemu_loaded_path=$(readlink -f "/proc/$QEMU_PID/exe")"
|
||||
echo "qemu_loaded_sha256=$(sha256sum "/proc/$QEMU_PID/exe" | awk '{print $1}')"
|
||||
STATICLIB="$QEMU_SOURCE_REPO/target/release/libreims_vgpu.a"
|
||||
if [ -f "$STATICLIB" ]; then
|
||||
echo "staticlib_path=$STATICLIB"
|
||||
echo "staticlib_sha256=$(sha256sum "$STATICLIB" | awk '{print $1}')"
|
||||
else
|
||||
echo "staticlib=not-found"
|
||||
fi
|
||||
grep -m1 'snapshot=' "$OUT/boot-stdout.log" || true
|
||||
grep -m1 'serial →' "$OUT/boot-stdout.log" || true
|
||||
} >>"$MANIFEST"
|
||||
|
||||
"$REPO/vm/guest-authorize.sh" >"$OUT/authorize.log" 2>&1
|
||||
for _ in $(seq 1 60); do
|
||||
timeout 20 ssh -o BatchMode=yes macos-vm true 2>/dev/null && break
|
||||
sleep 5
|
||||
done
|
||||
|
||||
# Run the exact x86_64 artifact produced beside the oracle result. A rail guest
|
||||
# has no developer tools, and probing its `swiftc` shim opens the installer
|
||||
# rather than proving a compiler exists.
|
||||
timeout 60 scp -o BatchMode=yes -q "$BIN" macos-vm:/tmp/conformance || {
|
||||
echo "could not copy the battery into the guest"; exit 1; }
|
||||
ssh -o BatchMode=yes macos-vm 'shasum -a 256 /tmp/conformance' \
|
||||
| sed 's# /tmp/conformance$# guest:/tmp/conformance#' >>"$MANIFEST"
|
||||
timeout "$PROBE_TIMEOUT" ssh -o BatchMode=yes macos-vm \
|
||||
"chmod +x /tmp/conformance && /tmp/conformance $CONFORMANCE_ARG" \
|
||||
>"$OUT/conformance.txt" 2>&1
|
||||
rc=$?
|
||||
echo "conformance rc=$rc"
|
||||
cp /tmp/reims-vgpu-fail.log "$OUT/device.log" 2>/dev/null
|
||||
|
||||
PANIC=0
|
||||
if grep -q 'guest kernel panic' "$OUT/boot-stdout.log"; then
|
||||
echo "PANIC"
|
||||
PANIC=1
|
||||
else
|
||||
echo "no panic"
|
||||
fi
|
||||
|
||||
CATASTROPHIC=0
|
||||
if [ "$rc" -eq 124 ]; then
|
||||
echo "CATASTROPHIC conformance probe timed out after ${PROBE_TIMEOUT}s"
|
||||
CATASTROPHIC=1
|
||||
fi
|
||||
if grep -Eq '^(stamp_wait_timeout|.*device_lost[^=]|.*VK_ERROR_DEVICE_LOST)' "$OUT/device.log"; then
|
||||
echo "CATASTROPHIC device timeout or loss"
|
||||
CATASTROPHIC=1
|
||||
fi
|
||||
|
||||
# Score it against the oracle rather than printing 216 lines for a reader to
|
||||
# diff by eye. The baseline is the native arm when no fresher one is given;
|
||||
# `NATIVE=<file>` points at a run from the same session, which is what to use
|
||||
# when the suite has cases the baseline predates.
|
||||
NATIVE="${NATIVE:-$HERE/baselines/native-apple-m4-macos15.txt}"
|
||||
|
||||
# A narrowing switch can close the rail a case claims, so its claim not moving
|
||||
# is then the switch working rather than a case that missed its rail. Report it
|
||||
# without failing the run.
|
||||
ADVISORY=()
|
||||
env | grep -q '^REIMS_VGPU_' && ADVISORY=(--claims-advisory)
|
||||
|
||||
echo "--- verdict ---"
|
||||
python3 "$HERE/verdict.py" --native "$NATIVE" --guest "$OUT/conformance.txt" \
|
||||
--translation-errors "$EXPECT/translation-errors.txt" \
|
||||
--driver-errors "$EXPECT/driver-errors.txt" --device "$OUT/device.log" \
|
||||
"${ADVISORY[@]}" --quiet | tee "$OUT/verdict.txt"
|
||||
vrc="${PIPESTATUS[0]}"
|
||||
pkill -f 'qemu-system-x86_6[4].*reims-vgpu' 2>/dev/null
|
||||
wait "$BOOT_PID" 2>/dev/null
|
||||
boot_rc=$?
|
||||
SERIAL_PATH="$(sed -n 's/.*serial → \([^ ]*\).*/\1/p' "$OUT/boot-stdout.log" | tail -1)"
|
||||
if [ -n "$SERIAL_PATH" ] && [ -f "$SERIAL_PATH" ]; then
|
||||
cp "$SERIAL_PATH" "$OUT/serial.log"
|
||||
fi
|
||||
{
|
||||
echo "completed=$(date --iso-8601=seconds)"
|
||||
echo "conformance_rc=$rc"
|
||||
echo "verdict_rc=$vrc"
|
||||
echo "boot_rc=$boot_rc"
|
||||
echo "panic=$PANIC"
|
||||
echo "catastrophic=$CATASTROPHIC"
|
||||
} >>"$MANIFEST"
|
||||
# The battery's own exit code says a case failed; the verdict's says one failed
|
||||
# that nobody had written down. The second is the one a sweep should gate on.
|
||||
[ "$PANIC" -eq 0 ] || exit 1
|
||||
[ "$CATASTROPHIC" -eq 0 ] || exit 1
|
||||
[ "$vrc" -eq 0 ] || exit "$vrc"
|
||||
exit 0
|
||||
@@ -1,62 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build and run the battery on a native macOS host -- the oracle arm.
|
||||
#
|
||||
# run-native.sh [outdir]
|
||||
#
|
||||
# The oracle is what makes a guest failure a finding. A case that fails here is
|
||||
# a wrong expectation in the suite, not a device defect, and the only way to
|
||||
# tell those apart is to run the same source on both sides. `ORACLE` names the
|
||||
# ssh host; it needs Xcode's command line tools and nothing else.
|
||||
set -uo pipefail
|
||||
export LC_ALL=C
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
OUT="${1:-$HERE/build}"
|
||||
ORACLE="${ORACLE:-scaleway-m4-macos15}"
|
||||
CONFORMANCE_MODE="${CONFORMANCE_MODE:-full}"
|
||||
case "$CONFORMANCE_MODE" in
|
||||
full) CONFORMANCE_ARG="" ;;
|
||||
integer-clear) CONFORMANCE_ARG="--integer-clear-only" ;;
|
||||
topology) CONFORMANCE_ARG="--topology-only" ;;
|
||||
float-sampling) CONFORMANCE_ARG="--float-sampling-only" ;;
|
||||
indexed-draw) CONFORMANCE_ARG="--indexed-draw-only" ;;
|
||||
*) echo "conformance: CONFORMANCE_MODE must be full, integer-clear, topology, float-sampling, or indexed-draw" >&2; exit 2 ;;
|
||||
esac
|
||||
mkdir -p "$OUT"
|
||||
|
||||
{
|
||||
echo "kind=native-oracle"
|
||||
echo "oracle=$ORACLE"
|
||||
echo "conformance_mode=$CONFORMANCE_MODE"
|
||||
echo "started=$(date --iso-8601=seconds)"
|
||||
find "$HERE/suite" -type f -print0 | sort -z | xargs -0 sha256sum
|
||||
} >"$OUT/manifest.txt"
|
||||
|
||||
REMOTE="$(ssh "$ORACLE" 'mktemp -d /tmp/reims-vgpu-conformance.XXXXXX')" || exit 1
|
||||
case "$REMOTE" in
|
||||
/tmp/reims-vgpu-conformance.*) ;;
|
||||
*) echo "oracle returned an unsafe staging path: $REMOTE"; exit 1 ;;
|
||||
esac
|
||||
cleanup() { ssh "$ORACLE" "rm -rf -- '$REMOTE'" >/dev/null 2>&1 || true; }
|
||||
trap cleanup EXIT
|
||||
tar cf - -C "$HERE" suite | ssh "$ORACLE" "cd '$REMOTE' && tar xf -" || exit 1
|
||||
|
||||
# Also cross-compile for the x86 rails, whose guests may have no compiler. The
|
||||
# deployment target is the oldest rail this project boots.
|
||||
ssh "$ORACLE" "cd '$REMOTE' && \
|
||||
swiftc -O suite/*.swift suite/cases/*.swift -o conf-native && \
|
||||
swiftc -O -target x86_64-apple-macos11.0 suite/*.swift suite/cases/*.swift \
|
||||
-o conformance-x86_64" 2>&1 | tee "$OUT/build-native.log"
|
||||
[ "${PIPESTATUS[0]}" -eq 0 ] || { echo "native build failed"; exit 1; }
|
||||
|
||||
ssh "$ORACLE" "cd '$REMOTE' && sw_vers && uname -a && \
|
||||
shasum -a 256 conf-native conformance-x86_64" >>"$OUT/manifest.txt" || exit 1
|
||||
|
||||
ssh "$ORACLE" "cd '$REMOTE' && ./conf-native $CONFORMANCE_ARG" >"$OUT/native.txt" 2>&1
|
||||
rc=$?
|
||||
scp -q "$ORACLE:$REMOTE/conformance-x86_64" "$OUT/conformance-x86_64" || exit 1
|
||||
chmod +x "$OUT/conformance-x86_64"
|
||||
echo "native rc=$rc"
|
||||
tail -2 "$OUT/native.txt"
|
||||
echo "completed=$(date --iso-8601=seconds)" >>"$OUT/manifest.txt"
|
||||
echo "result_rc=$rc" >>"$OUT/manifest.txt"
|
||||
exit $rc
|
||||
@@ -1,109 +0,0 @@
|
||||
// A self-verifying Metal conformance battery.
|
||||
//
|
||||
// Why this exists. Every result this project has about Maps' missing type layer
|
||||
// was scored by opening a screenshot, and a screenshot names no seam: it says
|
||||
// "labels absent" for a wrong pitch, a wrong swizzle, a wrong render-target
|
||||
// round trip and a dropped draw alike. This binary asks the API directly. Each
|
||||
// case computes a value the CPU can predict exactly, the GPU produces it, and
|
||||
// the CPU compares -- so a failure names the case, the expected bytes and the
|
||||
// bytes that came back.
|
||||
//
|
||||
// It is built for two hosts and the comparison between them is the point: run
|
||||
// it on a native macOS host to establish that a case's expectation is what
|
||||
// Metal actually does, then run the same binary in the guest. A case that
|
||||
// passes natively and fails in the guest is a named device defect. A case that
|
||||
// fails on both is a wrong expectation in the suite, not a finding.
|
||||
//
|
||||
// Every case reports on one line: CASE <name> PASS|FAIL <detail>
|
||||
// and the process exits non-zero if any case failed.
|
||||
//
|
||||
// The tree, the two runners and what a case has to do to be a gate are in
|
||||
// ../README.md.
|
||||
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// `MTLCreateSystemDefaultDevice` answers nil in a session with no window server
|
||||
// attached -- which is every ssh session, and this battery is driven over ssh on
|
||||
// purpose. `MTLCopyAllDevices` enumerates the same devices without that
|
||||
// requirement, so the fallback is the contract and not a workaround.
|
||||
//
|
||||
// Initialised by a closure rather than bound by a top-level `guard` because only
|
||||
// `main.swift` may hold top-level statements once the suite is more than one
|
||||
// file. The diagnostics and the exit code are unchanged.
|
||||
let dev: MTLDevice = {
|
||||
guard let d = MTLCreateSystemDefaultDevice() ?? MTLCopyAllDevices().first else {
|
||||
print("CASE device FAIL no Metal device")
|
||||
fflush(stdout)
|
||||
exit(2)
|
||||
}
|
||||
return d
|
||||
}()
|
||||
|
||||
let queue: MTLCommandQueue = {
|
||||
guard let q = dev.makeCommandQueue() else {
|
||||
print("CASE queue FAIL \(dev.name) would not make a command queue")
|
||||
fflush(stdout)
|
||||
exit(2)
|
||||
}
|
||||
return q
|
||||
}()
|
||||
|
||||
|
||||
var failures = 0
|
||||
|
||||
var ran = 0
|
||||
|
||||
/// A case the device's own reported limits make inapplicable -- a pitch its
|
||||
/// `minimumLinearTextureAlignment` forbids, say. Not a failure: Metal would
|
||||
/// reject the descriptor on any host that reports the same limit, so there is
|
||||
/// nothing here for a device to get wrong.
|
||||
var skipped = 0
|
||||
|
||||
func skip(_ name: String, _ why: String) {
|
||||
skipped += 1
|
||||
print("CASE \(name) SKIP \(why)")
|
||||
fflush(stdout)
|
||||
}
|
||||
|
||||
/// The device rails a case claims to move, named by the counters this device
|
||||
/// reports them under.
|
||||
///
|
||||
/// A passing case that never reached the rail it was written for is the worst
|
||||
/// reading this battery produces, because it is indistinguishable from coverage.
|
||||
/// Three attempts at the regression case for the unordered host read passed on
|
||||
/// the *broken* build, each for that reason: a `.bgra8Unorm` pair at 512x512 is
|
||||
/// staged through a buffer by the guest driver, so the case exercised a rail
|
||||
/// that was never in question and reported green. It took a temporary probe
|
||||
/// inside the device to find out.
|
||||
///
|
||||
/// `verdict.py` reads these against the device's own fail log and says
|
||||
/// NOT-COVERED where a claimed counter never moved. The check is per *run* and
|
||||
/// not per case -- nothing carries a case name across into the device -- so it
|
||||
/// answers "did anything in this run reach that rail", which is the question
|
||||
/// that was being got wrong.
|
||||
///
|
||||
/// A case that claims nothing is unclaimed, not covered. Claiming a counter
|
||||
/// nobody verified moves would make this table read as coverage while measuring
|
||||
/// spelling, so claim one when it has been watched, and not before.
|
||||
func claims(_ name: String, _ counters: String...) {
|
||||
for counter in counters {
|
||||
print("ROUTE \(name) \(counter)")
|
||||
}
|
||||
fflush(stdout)
|
||||
}
|
||||
|
||||
func report(_ name: String, _ ok: Bool, _ detail: String) {
|
||||
ran += 1
|
||||
if !ok { failures += 1 }
|
||||
print("CASE \(name) \(ok ? "PASS" : "FAIL") \(detail)")
|
||||
fflush(stdout)
|
||||
}
|
||||
|
||||
func finish() -> Never {
|
||||
print("SUMMARY cases=\(ran) failures=\(failures) skipped=\(skipped)")
|
||||
print("DEVICE name=\(dev.name) unified=\(dev.hasUnifiedMemory)")
|
||||
fflush(stdout)
|
||||
exit(failures == 0 ? 0 : 1)
|
||||
}
|
||||
@@ -1,412 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shaders. Compiled from source at run time on purpose: that exercises the same
|
||||
// shader path the guest's own apps take, rather than a pre-built archive.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let shaderSource = """
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
|
||||
// Exact texel fetch. `read` bypasses the sampler, so a mismatch here is about
|
||||
// the texture's memory interpretation and nothing else.
|
||||
kernel void read_texels(texture2d<float, access::read> tex [[texture(0)]],
|
||||
device uint *out [[buffer(0)]],
|
||||
constant uint &width [[buffer(1)]],
|
||||
constant uint2 &extent [[buffer(3)]],
|
||||
device uint *ran [[buffer(4)]],
|
||||
uint2 gid [[thread_position_in_grid]]) {
|
||||
// Before the grid guard, so this says the kernel was reached
|
||||
// rather than that some thread was in range. Every thread
|
||||
// writes the same value; the race is benign and the point is
|
||||
// that a dispatch nothing refused cannot leave it zero.
|
||||
ran[0] = 1u;
|
||||
if (gid.x >= extent.x || gid.y >= extent.y) { return; }
|
||||
float4 v = tex.read(gid);
|
||||
uint r = uint(round(v.r * 255.0));
|
||||
uint g = uint(round(v.g * 255.0));
|
||||
uint b = uint(round(v.b * 255.0));
|
||||
uint a = uint(round(v.a * 255.0));
|
||||
out[gid.y * width + gid.x] = (a << 24) | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
// Preserve each sample separately. Reading through a single-sample texture
|
||||
// would make an implicit resolve indistinguishable from a correct multisample
|
||||
// store, so the sample index is part of the output address.
|
||||
kernel void read_ms_texels(texture2d_ms<float, access::read> tex [[texture(0)]],
|
||||
device uint *out [[buffer(0)]],
|
||||
constant uint &width [[buffer(1)]],
|
||||
constant uint &samples [[buffer(2)]],
|
||||
constant uint2 &extent [[buffer(3)]],
|
||||
device uint *ran [[buffer(4)]],
|
||||
uint2 gid [[thread_position_in_grid]]) {
|
||||
ran[0] = 1u;
|
||||
if (gid.x >= extent.x || gid.y >= extent.y) { return; }
|
||||
uint count = min(samples, tex.get_num_samples());
|
||||
for (uint sample = 0; sample < count; ++sample) {
|
||||
float4 v = tex.read(gid, sample);
|
||||
uint r = uint(round(v.r * 255.0));
|
||||
uint g = uint(round(v.g * 255.0));
|
||||
uint b = uint(round(v.b * 255.0));
|
||||
uint a = uint(round(v.a * 255.0));
|
||||
out[(gid.y * width + gid.x) * samples + sample] =
|
||||
(a << 24) | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
}
|
||||
|
||||
// The same readback with the sample count supplied by the host instead of
|
||||
// queried from the texture.
|
||||
//
|
||||
// `read_ms_texels` above is a witness for two independent obligations at once:
|
||||
// that a `texture2d_ms` bind is served at all, and that `get_num_samples()`
|
||||
// reports the texture's own count. A device that serves the bind correctly but
|
||||
// runs against a translator that folds the query to a constant produces the
|
||||
// same result line as a device that refused the bind outright, and the two are
|
||||
// opposite defects. This kernel drops the query so its result speaks only to
|
||||
// the first obligation; the caller already knows the count, because it created
|
||||
// the texture.
|
||||
kernel void read_ms_texels_host_count(texture2d_ms<float, access::read> tex [[texture(0)]],
|
||||
device uint *out [[buffer(0)]],
|
||||
constant uint &width [[buffer(1)]],
|
||||
constant uint &samples [[buffer(2)]],
|
||||
constant uint2 &extent [[buffer(3)]],
|
||||
device uint *ran [[buffer(4)]],
|
||||
uint2 gid [[thread_position_in_grid]]) {
|
||||
ran[0] = 1u;
|
||||
if (gid.x >= extent.x || gid.y >= extent.y) { return; }
|
||||
for (uint sample = 0; sample < samples; ++sample) {
|
||||
float4 v = tex.read(gid, sample);
|
||||
uint r = uint(round(v.r * 255.0));
|
||||
uint g = uint(round(v.g * 255.0));
|
||||
uint b = uint(round(v.b * 255.0));
|
||||
uint a = uint(round(v.a * 255.0));
|
||||
out[(gid.y * width + gid.x) * samples + sample] =
|
||||
(a << 24) | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
}
|
||||
|
||||
// The sampler path, with nearest filtering and unnormalized coordinates, so the
|
||||
// result is still exactly one texel and any difference from `read_texels` is
|
||||
// the sampler/view rather than the memory.
|
||||
kernel void sample_texels(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
device uint *out [[buffer(0)]],
|
||||
constant uint &width [[buffer(1)]],
|
||||
constant uint2 &extent [[buffer(3)]],
|
||||
device uint *ran [[buffer(4)]],
|
||||
uint2 gid [[thread_position_in_grid]]) {
|
||||
// Before the grid guard, so this says the kernel was reached
|
||||
// rather than that some thread was in range. Every thread
|
||||
// writes the same value; the race is benign and the point is
|
||||
// that a dispatch nothing refused cannot leave it zero.
|
||||
ran[0] = 1u;
|
||||
if (gid.x >= extent.x || gid.y >= extent.y) { return; }
|
||||
constexpr sampler s(coord::pixel, filter::nearest, address::clamp_to_edge);
|
||||
float4 v = tex.sample(s, float2(gid.x + 0.5, gid.y + 0.5));
|
||||
uint r = uint(round(v.r * 255.0));
|
||||
uint g = uint(round(v.g * 255.0));
|
||||
uint b = uint(round(v.b * 255.0));
|
||||
uint a = uint(round(v.a * 255.0));
|
||||
out[gid.y * width + gid.x] = (a << 24) | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
// Preserve the sampled float values themselves. Values outside [0,1] make a
|
||||
// lossy unorm fallback observable instead of letting it produce the same
|
||||
// colour by coincidence.
|
||||
kernel void sample_float4(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
device float4 *out [[buffer(0)]],
|
||||
constant uint &width [[buffer(1)]],
|
||||
device uint *ran [[buffer(4)]],
|
||||
uint gid [[thread_position_in_grid]]) {
|
||||
ran[0] = 1u;
|
||||
if (gid >= width) { return; }
|
||||
constexpr sampler s(coord::pixel, filter::nearest, address::clamp_to_edge);
|
||||
out[gid] = tex.sample(s, float2(float(gid) + 0.5f, 0.5f));
|
||||
}
|
||||
|
||||
// Read one explicit mip level.
|
||||
// `coord::pixel` may not be combined with a mip filter, and `level` is the name
|
||||
// of the LOD constructor, so the uniform is `lod` and the coordinates are
|
||||
// normalized against this level's own dimensions.
|
||||
kernel void read_level(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
device uint *out [[buffer(0)]],
|
||||
constant uint &width [[buffer(1)]],
|
||||
constant uint &lod [[buffer(2)]],
|
||||
constant uint2 &extent [[buffer(3)]],
|
||||
device uint *ran [[buffer(4)]],
|
||||
uint2 gid [[thread_position_in_grid]]) {
|
||||
// Before the grid guard, so this says the kernel was reached
|
||||
// rather than that some thread was in range. Every thread
|
||||
// writes the same value; the race is benign and the point is
|
||||
// that a dispatch nothing refused cannot leave it zero.
|
||||
ran[0] = 1u;
|
||||
if (gid.x >= extent.x || gid.y >= extent.y) { return; }
|
||||
constexpr sampler s(filter::nearest, mip_filter::nearest, address::clamp_to_edge);
|
||||
float2 dim = float2(max(1u, tex.get_width() >> lod), max(1u, tex.get_height() >> lod));
|
||||
float2 uv = (float2(gid) + 0.5f) / dim;
|
||||
float4 v = tex.sample(s, uv, level(float(lod)));
|
||||
uint r = uint(round(v.r * 255.0));
|
||||
uint g = uint(round(v.g * 255.0));
|
||||
uint b = uint(round(v.b * 255.0));
|
||||
uint a = uint(round(v.a * 255.0));
|
||||
out[gid.y * width + gid.x] = (a << 24) | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
// The same level, fetched rather than sampled. `read(coord, lod)` names the
|
||||
// level in the fetch itself, with no sampler and no LOD computation, so a
|
||||
// device that returns level 0 here has not got the level's *bytes*, while one
|
||||
// that passes here and fails `read_level` has the bytes and is losing the
|
||||
// explicit LOD on the sampling path. That is the whole difference between a
|
||||
// residency bug and a translation bug and nothing else separates them.
|
||||
kernel void fetch_level(texture2d<float, access::read> tex [[texture(0)]],
|
||||
device uint *out [[buffer(0)]],
|
||||
constant uint &width [[buffer(1)]],
|
||||
constant uint &lod [[buffer(2)]],
|
||||
constant uint2 &extent [[buffer(3)]],
|
||||
device uint *ran [[buffer(4)]],
|
||||
uint2 gid [[thread_position_in_grid]]) {
|
||||
// Before the grid guard, so this says the kernel was reached
|
||||
// rather than that some thread was in range. Every thread
|
||||
// writes the same value; the race is benign and the point is
|
||||
// that a dispatch nothing refused cannot leave it zero.
|
||||
ran[0] = 1u;
|
||||
if (gid.x >= extent.x || gid.y >= extent.y) { return; }
|
||||
float4 v = tex.read(gid, lod);
|
||||
uint r = uint(round(v.r * 255.0));
|
||||
uint g = uint(round(v.g * 255.0));
|
||||
uint b = uint(round(v.b * 255.0));
|
||||
uint a = uint(round(v.a * 255.0));
|
||||
out[gid.y * width + gid.x] = (a << 24) | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
// Every thread writes to a slot of its own, in a grid padded out to the
|
||||
// threadgroup size. `dispatchThreads` promises the grid it is given and no
|
||||
// more, so a slot outside that grid holding a marker is a thread Metal
|
||||
// promised would not run.
|
||||
kernel void grid_bounds(device uint *out [[buffer(0)]],
|
||||
constant uint &stride [[buffer(1)]],
|
||||
uint2 gid [[thread_position_in_grid]]) {
|
||||
out[gid.y * stride + gid.x] = 1u + gid.x;
|
||||
}
|
||||
|
||||
// Two dispatches in a concurrent compute encoder have no implicit dependency.
|
||||
// Each thread owns one word, so the explicit barrier is the only ordering term
|
||||
// and neither kernel relies on atomics or a cross-thread race.
|
||||
static uint compute_barrier_value(uint token, uint gid) {
|
||||
uint value = token ^ gid;
|
||||
for (uint i = 0; i < 512; ++i) {
|
||||
value = value * 1664525u + 1013904223u;
|
||||
value ^= value >> ((i & 7u) + 1u);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
kernel void compute_barrier_write(device uint *words [[buffer(0)]],
|
||||
constant uint &token [[buffer(1)]],
|
||||
uint gid [[thread_position_in_grid]]) {
|
||||
words[gid] = compute_barrier_value(token, gid);
|
||||
}
|
||||
|
||||
kernel void compute_barrier_read(device const uint *words [[buffer(0)]],
|
||||
device uint *verdict [[buffer(1)]],
|
||||
constant uint &token [[buffer(2)]],
|
||||
uint gid [[thread_position_in_grid]]) {
|
||||
verdict[gid] = words[gid] == compute_barrier_value(token, gid) ? 1u : 0u;
|
||||
}
|
||||
|
||||
kernel void sync_resource_write(device uint *words [[buffer(0)]],
|
||||
constant uint &token [[buffer(1)]],
|
||||
uint gid [[thread_position_in_grid]]) {
|
||||
words[gid] = token ^ gid;
|
||||
}
|
||||
|
||||
// The indirect arguments carry threadgroup counts, while the shader-visible
|
||||
// grid is their product with the encoded threads-per-threadgroup. Recording
|
||||
// both the grid and one marker per thread distinguishes those two quantities.
|
||||
kernel void indirect_threadgroups_write(device uint *out [[buffer(0)]],
|
||||
device uint *observed_grid [[buffer(1)]],
|
||||
constant uint &capacity [[buffer(2)]],
|
||||
device uint *ran [[buffer(4)]],
|
||||
uint3 gid [[thread_position_in_grid]],
|
||||
uint3 grid [[threads_per_grid]]) {
|
||||
ran[0] = 1u;
|
||||
observed_grid[0] = grid.x;
|
||||
observed_grid[1] = grid.y;
|
||||
observed_grid[2] = grid.z;
|
||||
uint linear = gid.x + grid.x * (gid.y + grid.y * gid.z);
|
||||
if (linear < capacity) {
|
||||
out[linear] = 0xa5000000u | linear;
|
||||
}
|
||||
}
|
||||
|
||||
// One thread per indirect command. Distinct output and value-buffer offsets
|
||||
// make reset and copy observable per command slot rather than only as a total
|
||||
// dispatch count.
|
||||
kernel void indirect_command_write(device uint *out [[buffer(0)]],
|
||||
device const uint *value [[buffer(1)]]) {
|
||||
out[0] = value[0];
|
||||
}
|
||||
|
||||
struct VOut { float4 pos [[position]]; float2 uv; };
|
||||
|
||||
struct PointOut {
|
||||
float4 pos [[position]];
|
||||
float point_size [[point_size]];
|
||||
};
|
||||
|
||||
vertex VOut topology_vs(uint vid [[vertex_id]],
|
||||
device const float2 *positions [[buffer(0)]]) {
|
||||
VOut o;
|
||||
o.pos = float4(positions[vid], 0.0, 1.0);
|
||||
o.uv = float2(0.0);
|
||||
return o;
|
||||
}
|
||||
|
||||
// The texture is vertex data by API contract, not a colour. Sampling rather
|
||||
// than reading also exercises the linear-filter capability required by this
|
||||
// format on the native upload rail.
|
||||
vertex VOut float_positions_vs(uint vid [[vertex_id]],
|
||||
texture2d<float, access::sample> positions [[texture(0)]]) {
|
||||
constexpr sampler s(filter::linear, address::clamp_to_edge);
|
||||
float u = (float(vid) + 0.5f) / 4.0f;
|
||||
float4 p = positions.sample(s, float2(u, 0.5f));
|
||||
VOut o;
|
||||
o.pos = float4(p.xy, 0.0, 1.0);
|
||||
o.uv = float2(0.0);
|
||||
return o;
|
||||
}
|
||||
|
||||
// One shader for both the non-indexed control and all indexed arms. Indexed
|
||||
// semantics therefore change only which `vid`/`iid` Metal supplies, not the
|
||||
// translation unit or vertex fetch mechanism.
|
||||
vertex VOut indexed_vs(uint vid [[vertex_id]],
|
||||
uint iid [[instance_id]],
|
||||
device const float2 *positions [[buffer(0)]]) {
|
||||
float2 p = positions[vid];
|
||||
if (iid >= 5u) {
|
||||
p.x += (float(iid) - 5.5f) * 0.9f;
|
||||
}
|
||||
VOut o;
|
||||
o.pos = float4(p, 0.0, 1.0);
|
||||
o.uv = float2(0.0);
|
||||
return o;
|
||||
}
|
||||
|
||||
// Topology cases provide clip-space positions directly. Point size is explicit
|
||||
// so the point oracle observes a small island rather than relying on a
|
||||
// device-dependent default raster size.
|
||||
vertex PointOut point_vs(uint vid [[vertex_id]],
|
||||
device const float2 *positions [[buffer(0)]]) {
|
||||
PointOut o;
|
||||
o.pos = float4(positions[vid], 0.0, 1.0);
|
||||
o.point_size = 3.0;
|
||||
return o;
|
||||
}
|
||||
|
||||
fragment float4 point_fs(PointOut in [[stage_in]]) {
|
||||
return float4(0.0, 1.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
// A full-target triangle strip driven from a vertex buffer the test owns, so a
|
||||
// wrong vertex-buffer read shows up as geometry rather than as colour.
|
||||
vertex VOut quad_vs(uint vid [[vertex_id]],
|
||||
device const float4 *verts [[buffer(0)]]) {
|
||||
VOut o;
|
||||
float4 v = verts[vid];
|
||||
o.pos = float4(v.xy, 0.0, 1.0);
|
||||
o.uv = v.zw;
|
||||
return o;
|
||||
}
|
||||
|
||||
fragment float4 solid_fs(VOut in [[stage_in]],
|
||||
constant float4 &colour [[buffer(0)]]) {
|
||||
return colour;
|
||||
}
|
||||
|
||||
// Every covered pixel receives four distinct, exact unorm samples. A backend
|
||||
// that resolves the attachment instead of storing it turns these into one
|
||||
// repeated average and cannot pass the per-sample oracle.
|
||||
fragment float4 sample_id_fs(VOut in [[stage_in]], uint sample [[sample_id]]) {
|
||||
switch (sample) {
|
||||
case 0: return float4(1.0, 0.0, 0.0, 1.0);
|
||||
case 1: return float4(0.0, 1.0, 0.0, 1.0);
|
||||
case 2: return float4(0.0, 0.0, 1.0, 1.0);
|
||||
default: return float4(1.0, 1.0, 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
// The same flat colour, made expensive on purpose.
|
||||
//
|
||||
// A race is only a test if the arm under test loses it. A solid fill of a
|
||||
// window-sized target finishes before a host-side reader can decode a copy and
|
||||
// memcpy three megabytes, so a device that reads those pixels unordered still
|
||||
// happens to read the right ones and the case passes for a reason that has
|
||||
// nothing to do with correctness. This shader gives the GPU real per-pixel work
|
||||
// so the render is still running when the copy behind it is serviced.
|
||||
//
|
||||
// The accumulator has to survive the optimizer: `acc` is compared against a
|
||||
// bound it cannot reach, so the compiler cannot fold the loop away, and the
|
||||
// colour returned is exactly `colour` on every pixel.
|
||||
fragment float4 heavy_fs(VOut in [[stage_in]],
|
||||
constant float4 &colour [[buffer(0)]]) {
|
||||
float acc = 0.0;
|
||||
for (int i = 0; i < 2048; ++i) {
|
||||
acc += fract(sin(float(i) * 12.9898 + in.pos.x * 0.017 + in.pos.y * 0.031) * 43758.5453);
|
||||
}
|
||||
float poison = (acc > 1.0e30) ? 1.0 : 0.0;
|
||||
return float4(colour.rgb + poison, colour.a);
|
||||
}
|
||||
|
||||
// A render-stage resource barrier must make every producer write visible to
|
||||
// the following fragment draw in the same encoder. Each fragment owns one
|
||||
// word, avoiding atomics and data races while making the oracle cover the
|
||||
// entire raster rather than one scheduling-sensitive fragment.
|
||||
fragment float4 render_barrier_write_fs(VOut in [[stage_in]],
|
||||
device uint *words [[buffer(0)]],
|
||||
constant uint2 ¶ms [[buffer(1)]]) {
|
||||
float acc = 0.0;
|
||||
for (int i = 0; i < 512; ++i) {
|
||||
acc += fract(sin(float(i) * 12.9898 + in.pos.x * 0.017 + in.pos.y * 0.031) * 43758.5453);
|
||||
}
|
||||
uint2 p = uint2(in.pos.xy);
|
||||
words[p.y * params.x + p.x] = params.y + uint(acc > 1.0e30);
|
||||
return float4(0.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
fragment float4 render_barrier_read_fs(VOut in [[stage_in]],
|
||||
device const uint *words [[buffer(0)]],
|
||||
constant uint2 ¶ms [[buffer(1)]]) {
|
||||
uint2 p = uint2(in.pos.xy);
|
||||
bool current = words[p.y * params.x + p.x] == params.y;
|
||||
return current ? float4(0.0, 1.0, 0.0, 1.0)
|
||||
: float4(1.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
fragment float4 tex_fs(VOut in [[stage_in]],
|
||||
texture2d<float, access::sample> tex [[texture(0)]]) {
|
||||
constexpr sampler s(filter::nearest, address::clamp_to_edge);
|
||||
return tex.sample(s, in.uv);
|
||||
}
|
||||
// Coverage type. The atlas carries a single channel, exactly as CoreText
|
||||
// rasterizes glyphs and exactly the `R8Unorm` a driven Maps boot is observed
|
||||
// binding, and the colour arrives as a constant. Premultiplied out, so the
|
||||
// pipeline below can blend it with `one / oneMinusSourceAlpha` the way a text
|
||||
// layer is composited.
|
||||
fragment float4 glyph_fs(VOut in [[stage_in]],
|
||||
texture2d<float, access::sample> atlas [[texture(0)]],
|
||||
constant float4 &colour [[buffer(0)]]) {
|
||||
constexpr sampler s(filter::nearest, address::clamp_to_edge);
|
||||
float cov = atlas.sample(s, in.uv).r;
|
||||
return float4(colour.rgb * cov, cov);
|
||||
}
|
||||
|
||||
kernel void heap_alias_fill(texture2d<float, access::write> output [[texture(0)]],
|
||||
constant float4 &value [[buffer(0)]],
|
||||
uint2 gid [[thread_position_in_grid]]) {
|
||||
if (gid.x < output.get_width() && gid.y < output.get_height()) {
|
||||
output.write(value, gid);
|
||||
}
|
||||
}
|
||||
"""
|
||||
@@ -1,238 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// Compiled on first use. `main.swift` forces it before reporting `shader_compile`
|
||||
// so the report still lands where it always did, first.
|
||||
let library: MTLLibrary = {
|
||||
do {
|
||||
return try dev.makeLibrary(source: shaderSource, options: nil)
|
||||
} catch {
|
||||
print("CASE shader_compile FAIL \(error)")
|
||||
fflush(stdout)
|
||||
exit(2)
|
||||
}
|
||||
}()
|
||||
|
||||
func pipeline(_ name: String) -> MTLComputePipelineState {
|
||||
let fn = library.makeFunction(name: name)!
|
||||
return try! dev.makeComputePipelineState(function: fn)
|
||||
}
|
||||
|
||||
let readPipe = pipeline("read_texels")
|
||||
|
||||
let readMultisamplePipe = pipeline("read_ms_texels")
|
||||
|
||||
let readMultisampleHostCountPipe = pipeline("read_ms_texels_host_count")
|
||||
|
||||
let samplePipe = pipeline("sample_texels")
|
||||
|
||||
let levelPipe = pipeline("read_level")
|
||||
|
||||
let fetchLevelPipe = pipeline("fetch_level")
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func alignUp(_ v: Int, _ a: Int) -> Int { (v + a - 1) / a * a }
|
||||
|
||||
/// How a linear case arrived at its bytes-per-row.
|
||||
///
|
||||
/// **The name has to be the derivation and not the number it came to.**
|
||||
/// `minimumLinearTextureAlignment` is 16 on an M-series device and 256 on
|
||||
/// Apple's paravirtual one, so a pitch derived from it lands on a different
|
||||
/// integer per host -- and a case named after that integer has no counterpart
|
||||
/// on the other host to be scored against. Sixty-two cases here were in that
|
||||
/// state: they ran on both, tested the same thing on both, and the native/guest
|
||||
/// comparison that makes a guest failure a finding could not pair a single one
|
||||
/// of them.
|
||||
///
|
||||
/// Carrying the derivation also puts the alignment arithmetic in one place. It
|
||||
/// used to be written out at each call site, which is the same value spelled
|
||||
/// twice with nothing checking that the two agree.
|
||||
enum Pitch {
|
||||
/// The smallest pitch this device will accept for the format.
|
||||
case tight
|
||||
/// That many whole alignment units above tight.
|
||||
case padded(rows: Int)
|
||||
/// A literal, from a guest census. Not every device can express one, and
|
||||
/// the case skips where Metal would reject the descriptor.
|
||||
case exact(Int)
|
||||
|
||||
/// The label component. `.exact` keeps the bare number because a literal
|
||||
/// pitch means the same thing on every host.
|
||||
var tag: String {
|
||||
switch self {
|
||||
case .tight: return "tight"
|
||||
case .padded(let rows): return "tight_plus\(rows)"
|
||||
case .exact(let value): return "\(value)"
|
||||
}
|
||||
}
|
||||
|
||||
func bytes(width: Int, bpp: Int, align: Int) -> Int {
|
||||
switch self {
|
||||
case .tight: return alignUp(width * bpp, align)
|
||||
case .padded(let rows): return alignUp(width * bpp, align) + rows * align
|
||||
case .exact(let value): return value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one of the texel-reading kernels over a texture and return the packed
|
||||
/// RGBA of every texel, in row-major order.
|
||||
/// `nil` means the dispatch produced nothing: the kernel never ran.
|
||||
///
|
||||
/// **A sentinel fill cannot answer this and must not be asked to.** This device
|
||||
/// refuses a dispatch on the host side, so the guest's command buffer completes
|
||||
/// clean and the output buffer keeps whatever was in it. Every case here then
|
||||
/// compares the sentinel against what it wanted and reports a *content*
|
||||
/// failure — which reads as "the device returned the wrong bytes" when the
|
||||
/// truth is that it returned none. The `offset_oracle` cases showed how far
|
||||
/// that misleads: their fill is `1 + (i % 251)`, zero means "a byte nothing in
|
||||
/// this buffer ever held", and the sentinel `0xEE` is 238, squarely inside the
|
||||
/// fill's own range. So a refused dispatch inverted to a constant read-offset
|
||||
/// of 237, every texel landed in a different delta bucket, and four cases
|
||||
/// reported `absent=0 shifted=4080` — a precise, plausible account of a defect
|
||||
/// that did not exist. No sentinel value fixes this in general: a battery whose
|
||||
/// cases cover many formats has no byte that is out of range for all of them.
|
||||
///
|
||||
/// So the kernel says so itself, in a buffer of its own.
|
||||
func readBack(_ pipe: MTLComputePipelineState,
|
||||
_ tex: MTLTexture,
|
||||
_ w: Int, _ h: Int,
|
||||
level: Int? = nil) -> [UInt32]? {
|
||||
let out = dev.makeBuffer(length: w * h * 4, options: .storageModeShared)!
|
||||
memset(out.contents(), 0xEE, w * h * 4)
|
||||
let ran = dev.makeBuffer(length: 4, options: .storageModeShared)!
|
||||
memset(ran.contents(), 0, 4)
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeComputeCommandEncoder()!
|
||||
enc.setComputePipelineState(pipe)
|
||||
enc.setTexture(tex, index: 0)
|
||||
enc.setBuffer(out, offset: 0, index: 0)
|
||||
var width = UInt32(w)
|
||||
enc.setBytes(&width, length: 4, index: 1)
|
||||
if var lvl = level.map({ UInt32($0) }) {
|
||||
enc.setBytes(&lvl, length: 4, index: 2)
|
||||
}
|
||||
var extent = SIMD2<UInt32>(UInt32(w), UInt32(h))
|
||||
enc.setBytes(&extent, length: 8, index: 3)
|
||||
enc.setBuffer(ran, offset: 0, index: 4)
|
||||
// Whole threadgroups plus an explicit guard in the kernel, deliberately
|
||||
// *not* `dispatchThreads`. The battery's own readback must not depend on
|
||||
// the thing `dispatch_threads_grid_*` is here to test: while a device runs
|
||||
// the surplus threads of a partial grid, an unguarded readback writes each
|
||||
// row's overrun into the next row's first entries and every other case in
|
||||
// this file reports that as its own failure.
|
||||
let tg = 8
|
||||
enc.dispatchThreadgroups(
|
||||
MTLSize(width: (w + tg - 1) / tg, height: (h + tg - 1) / tg, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: tg, height: tg, depth: 1))
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
if ran.contents().bindMemory(to: UInt32.self, capacity: 1)[0] == 0 { return nil }
|
||||
let p = out.contents().bindMemory(to: UInt32.self, capacity: w * h)
|
||||
return Array(UnsafeBufferPointer(start: p, count: w * h))
|
||||
}
|
||||
|
||||
/// Read every sample of a multisample texture without resolving it.
|
||||
///
|
||||
/// The output is pixel-major and then sample-major. Slots the bound image does
|
||||
/// not expose retain the sentinel, so accidentally binding a single-sample
|
||||
/// image cannot look like a valid four-sample store.
|
||||
func readBackMultisample(_ tex: MTLTexture,
|
||||
_ w: Int, _ h: Int,
|
||||
samples: Int,
|
||||
countFromTexture: Bool = true) -> [UInt32]? {
|
||||
let count = w * h * samples
|
||||
let out = dev.makeBuffer(length: count * 4, options: .storageModeShared)!
|
||||
memset(out.contents(), 0xEE, count * 4)
|
||||
let ran = dev.makeBuffer(length: 4, options: .storageModeShared)!
|
||||
memset(ran.contents(), 0, 4)
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeComputeCommandEncoder()!
|
||||
enc.setComputePipelineState(
|
||||
countFromTexture ? readMultisamplePipe : readMultisampleHostCountPipe)
|
||||
enc.setTexture(tex, index: 0)
|
||||
enc.setBuffer(out, offset: 0, index: 0)
|
||||
var width = UInt32(w)
|
||||
var sampleCount = UInt32(samples)
|
||||
var extent = SIMD2<UInt32>(UInt32(w), UInt32(h))
|
||||
enc.setBytes(&width, length: 4, index: 1)
|
||||
enc.setBytes(&sampleCount, length: 4, index: 2)
|
||||
enc.setBytes(&extent, length: 8, index: 3)
|
||||
enc.setBuffer(ran, offset: 0, index: 4)
|
||||
let tg = 8
|
||||
enc.dispatchThreadgroups(
|
||||
MTLSize(width: (w + tg - 1) / tg, height: (h + tg - 1) / tg, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: tg, height: tg, depth: 1))
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
if ran.contents().bindMemory(to: UInt32.self, capacity: 1)[0] == 0 { return nil }
|
||||
let p = out.contents().bindMemory(to: UInt32.self, capacity: count)
|
||||
return Array(UnsafeBufferPointer(start: p, count: count))
|
||||
}
|
||||
|
||||
/// A case that cannot be evaluated because the run it depends on did not
|
||||
/// happen.
|
||||
///
|
||||
/// Reported rather than dropped. A battery whose case *count* moves between two
|
||||
/// runs cannot be diffed against itself, and a name that simply stops appearing
|
||||
/// reads as a case someone deleted — which is how a refusal of one case quietly
|
||||
/// took three others out of the totals.
|
||||
func skipDependent(_ name: String, _ on: String) {
|
||||
skip(name, "not evaluated — \(on) never ran")
|
||||
}
|
||||
|
||||
/// One wording for every case, so a refusal is never mistaken for a mismatch.
|
||||
func refused(_ label: String) {
|
||||
report(label, false,
|
||||
"the readback dispatch produced nothing — the device refused it, "
|
||||
+ "or refused a bind in it; the texels below were never written")
|
||||
}
|
||||
|
||||
/// A compact map of where a case's wrong texels are. A count alone cannot tell
|
||||
/// a lost row from a lost page from scattered noise, and those are three
|
||||
/// different defects: this prints `y=<row>:<first>-<last>x<count>` per affected
|
||||
/// row so the shape is in the result line rather than in a follow-up run.
|
||||
func badMap(_ bad: [(Int, Int)], _ w: Int, _ h: Int) -> String {
|
||||
if bad.isEmpty { return "" }
|
||||
var perRow: [Int: (Int, Int, Int)] = [:] // y -> (minX, maxX, count)
|
||||
for (x, y) in bad {
|
||||
if let e = perRow[y] { perRow[y] = (min(e.0, x), max(e.1, x), e.2 + 1) }
|
||||
else { perRow[y] = (x, x, 1) }
|
||||
}
|
||||
let rows = perRow.keys.sorted()
|
||||
let shown = rows.prefix(12).map { y -> String in
|
||||
let e = perRow[y]!
|
||||
return "y=\(y):\(e.0)-\(e.1)x\(e.2)"
|
||||
}.joined(separator: " ")
|
||||
let more = rows.count > 12 ? " (+\(rows.count - 12) more rows)" : ""
|
||||
return "rows=\(rows.count)/\(h) \(shown)\(more)"
|
||||
}
|
||||
|
||||
func pack(_ r: UInt8, _ g: UInt8, _ b: UInt8, _ a: UInt8) -> UInt32 {
|
||||
(UInt32(a) << 24) | (UInt32(b) << 16) | (UInt32(g) << 8) | UInt32(r)
|
||||
}
|
||||
|
||||
func hex(_ v: UInt32) -> String { String(format: "0x%08x", v) }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// A. A linear texture over a shared buffer, per format, tight and padded pitch.
|
||||
//
|
||||
// This is the shape Maps' type layer actually has. The census of a driven boot
|
||||
// found ~90 distinct `A8Unorm` sources a boot with padded rows -- 54x16 at
|
||||
// pitch 64, 218x16 at pitch 256, 85x85 at pitch 128 -- so those exact
|
||||
// geometries are cases here rather than round numbers.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct Fmt {
|
||||
let name: String
|
||||
let mtl: MTLPixelFormat
|
||||
let bpp: Int
|
||||
/// What Metal must return for a texel whose bytes are `b`.
|
||||
let expect: ([UInt8]) -> UInt32
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// A two-plane IOSurface, read one plane at a time.
|
||||
//
|
||||
// One guest allocation carrying two textures at declared offsets, each with its
|
||||
// own extent, row pitch and pixel format. That is the shape the guest's own
|
||||
// compositor registers, and it is the shape that separates "a surface is an
|
||||
// image" from "a surface is an allocation and a plane is an image": a device
|
||||
// that gives both planes one backing has one layout to choose from and one
|
||||
// image to build, so it either renders the wrong plane's geometry or refuses
|
||||
// the second plane outright.
|
||||
//
|
||||
// Both planes are seeded from the CPU with values that are wrong for the other
|
||||
// plane, so a device that resolves plane 1 to plane 0's image fails on content
|
||||
// rather than on a refusal, and a device that refuses the second plane fails on
|
||||
// the readback. Neither can pass by accident.
|
||||
func biplanarSurfaceCase(_ w: Int, _ h: Int) {
|
||||
let dims = "\(w)x\(h)"
|
||||
let names = (luma: "biplanar_luma_\(dims)", chroma: "biplanar_chroma_\(dims)")
|
||||
|
||||
// '420f' — full-range biplanar 8-bit YCbCr. Plane 0 is one byte a texel at
|
||||
// the full extent; plane 1 is two bytes a texel at half extent in both
|
||||
// axes, which is why the two planes cannot share a layout.
|
||||
let biplanar: UInt32 = 0x3432_3066
|
||||
let cw = w / 2
|
||||
let ch = h / 2
|
||||
// The alignment is the framework's, asked for by name. A literal here
|
||||
// would be a number nobody derived and wrong on the next host.
|
||||
let lumaBytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, w)
|
||||
let chromaBytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, cw * 2)
|
||||
let lumaSize = IOSurfaceAlignProperty(kIOSurfaceAllocSize, lumaBytesPerRow * h)
|
||||
let chromaSize = IOSurfaceAlignProperty(kIOSurfaceAllocSize, chromaBytesPerRow * ch)
|
||||
let props: [IOSurfacePropertyKey: Any] = [
|
||||
.width: w,
|
||||
.height: h,
|
||||
.pixelFormat: biplanar,
|
||||
.planeInfo: [
|
||||
[
|
||||
IOSurfacePropertyKey.planeWidth: w,
|
||||
IOSurfacePropertyKey.planeHeight: h,
|
||||
IOSurfacePropertyKey.planeBytesPerRow: lumaBytesPerRow,
|
||||
IOSurfacePropertyKey.planeOffset: 0,
|
||||
IOSurfacePropertyKey.planeSize: lumaSize,
|
||||
IOSurfacePropertyKey.planeBytesPerElement: 1,
|
||||
],
|
||||
[
|
||||
IOSurfacePropertyKey.planeWidth: cw,
|
||||
IOSurfacePropertyKey.planeHeight: ch,
|
||||
IOSurfacePropertyKey.planeBytesPerRow: chromaBytesPerRow,
|
||||
IOSurfacePropertyKey.planeOffset: lumaSize,
|
||||
IOSurfacePropertyKey.planeSize: chromaSize,
|
||||
IOSurfacePropertyKey.planeBytesPerElement: 2,
|
||||
],
|
||||
],
|
||||
]
|
||||
guard let surface = IOSurface(properties: props), surface.planeCount == 2 else {
|
||||
report(names.luma, false, "no two-plane IOSurface for \(dims)")
|
||||
skipDependent(names.chroma, names.luma)
|
||||
return
|
||||
}
|
||||
|
||||
func planeTexture(_ plane: Int, _ format: MTLPixelFormat,
|
||||
_ pw: Int, _ ph: Int, _ label: String) -> MTLTexture? {
|
||||
let td = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: format, width: pw, height: ph, mipmapped: false)
|
||||
td.usage = [.shaderRead]
|
||||
td.storageMode = .shared
|
||||
guard let tex = dev.makeTexture(descriptor: td, iosurface: surface, plane: plane) else {
|
||||
report(label, false, "makeTexture(iosurface:plane:\(plane)) nil for \(dims)")
|
||||
return nil
|
||||
}
|
||||
return tex
|
||||
}
|
||||
|
||||
// The seed is a function of the plane and the coordinate, so plane 1's
|
||||
// bytes are never a value plane 0 holds at the same coordinate.
|
||||
func luma(_ x: Int, _ y: Int) -> UInt8 { UInt8((1 + x * 7 + y * 13) % 251) }
|
||||
func chromaR(_ x: Int, _ y: Int) -> UInt8 { UInt8((160 + x * 3 + y * 5) % 251) }
|
||||
func chromaG(_ x: Int, _ y: Int) -> UInt8 { UInt8((200 + x * 11 + y * 2) % 251) }
|
||||
|
||||
// The per-plane accessors are the C entry points: Swift's `IOSurface`
|
||||
// exposes only the whole-surface `baseAddress` and `bytesPerRow` as
|
||||
// properties, and on a biplanar surface those describe plane 0 alone.
|
||||
let ref = surface as IOSurfaceRef
|
||||
surface.lock(options: [], seed: nil)
|
||||
let lumaBase = IOSurfaceGetBaseAddressOfPlane(ref, 0).assumingMemoryBound(to: UInt8.self)
|
||||
let lumaPitch = IOSurfaceGetBytesPerRowOfPlane(ref, 0)
|
||||
for y in 0..<h {
|
||||
for x in 0..<w { lumaBase[y * lumaPitch + x] = luma(x, y) }
|
||||
}
|
||||
let chromaBase = IOSurfaceGetBaseAddressOfPlane(ref, 1).assumingMemoryBound(to: UInt8.self)
|
||||
let chromaPitch = IOSurfaceGetBytesPerRowOfPlane(ref, 1)
|
||||
for y in 0..<ch {
|
||||
for x in 0..<cw {
|
||||
chromaBase[y * chromaPitch + x * 2] = chromaR(x, y)
|
||||
chromaBase[y * chromaPitch + x * 2 + 1] = chromaG(x, y)
|
||||
}
|
||||
}
|
||||
surface.unlock(options: [], seed: nil)
|
||||
|
||||
if let tex = planeTexture(0, .r8Unorm, w, h, names.luma) {
|
||||
if let got = readBack(readPipe, tex, w, h) {
|
||||
var bad: [(Int, Int)] = []
|
||||
for y in 0..<h {
|
||||
for x in 0..<w where got[y * w + x] != pack(luma(x, y), 0, 0, 255) {
|
||||
bad.append((x, y))
|
||||
}
|
||||
}
|
||||
report(names.luma, bad.isEmpty,
|
||||
bad.isEmpty
|
||||
? "plane 0 reads its own \(w)x\(h) one-byte texels"
|
||||
: "wrong=\(bad.count)/\(w * h) "
|
||||
+ "first=\(hex(got[bad[0].1 * w + bad[0].0])) "
|
||||
+ "want=\(hex(pack(luma(bad[0].0, bad[0].1), 0, 0, 255)))"
|
||||
+ badMap(bad, w, h))
|
||||
} else {
|
||||
refused(names.luma)
|
||||
}
|
||||
}
|
||||
|
||||
if let tex = planeTexture(1, .rg8Unorm, cw, ch, names.chroma) {
|
||||
if let got = readBack(readPipe, tex, cw, ch) {
|
||||
var bad: [(Int, Int)] = []
|
||||
for y in 0..<ch {
|
||||
for x in 0..<cw
|
||||
where got[y * cw + x] != pack(chromaR(x, y), chromaG(x, y), 0, 255) {
|
||||
bad.append((x, y))
|
||||
}
|
||||
}
|
||||
report(names.chroma, bad.isEmpty,
|
||||
bad.isEmpty
|
||||
? "plane 1 reads its own \(cw)x\(ch) two-byte texels"
|
||||
: "wrong=\(bad.count)/\(cw * ch) "
|
||||
+ "first=\(hex(got[bad[0].1 * cw + bad[0].0])) "
|
||||
+ "want=\(hex(pack(chromaR(bad[0].0, bad[0].1), chromaG(bad[0].0, bad[0].1), 0, 255)))"
|
||||
+ badMap(bad, cw, ch))
|
||||
} else {
|
||||
refused(names.chroma)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,425 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
func blitAfterRenderCase(_ w: Int, _ h: Int) {
|
||||
let label = "srt_blit_after_render_\(w)x\(h)"
|
||||
guard let pipe = makeRenderPipeline("heavy_fs", .bgra8Unorm_srgb) else {
|
||||
report(label, false, "heavy pipeline unavailable for bgra8Unorm_srgb"); return
|
||||
}
|
||||
let sd = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm_srgb, width: w, height: h, mipmapped: false)
|
||||
sd.usage = [.renderTarget, .shaderRead]
|
||||
sd.storageMode = .shared
|
||||
guard let source = dev.makeTexture(descriptor: sd) else {
|
||||
report(label, false, "makeTexture nil for the shared \(w)x\(h) source"); return
|
||||
}
|
||||
guard let dst = makeSrgbIOSurfaceTarget(w, h, label) else { return }
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
func encodeFill(_ cb: MTLCommandBuffer, _ colour: SIMD4<Float>, draws: Int) {
|
||||
let d = MTLRenderPassDescriptor()
|
||||
d.colorAttachments[0].texture = source
|
||||
d.colorAttachments[0].loadAction = .clear
|
||||
d.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
d.colorAttachments[0].storeAction = .store
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: d)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
var c = colour
|
||||
enc.setFragmentBytes(&c, length: 16, index: 0)
|
||||
// Repeated whole-target draws, so the GPU is still working when the copy
|
||||
// behind them is decoded. One draw would leave the race to scheduling
|
||||
// luck and make the case flaky in the direction that reads as a pass.
|
||||
for _ in 0..<draws {
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
}
|
||||
enc.endEncoding()
|
||||
}
|
||||
|
||||
// 1. Red, landed. After this the source's bytes are red and nothing else.
|
||||
let first = queue.makeCommandBuffer()!
|
||||
encodeFill(first, SIMD4<Float>(1, 0, 0, 1), draws: 1)
|
||||
first.commit()
|
||||
first.waitUntilCompleted()
|
||||
|
||||
// 2. Green, committed and not waited on, then the copy in its own command
|
||||
// buffer. Queue order is what orders them; nothing else has to.
|
||||
let second = queue.makeCommandBuffer()!
|
||||
encodeFill(second, SIMD4<Float>(0, 1, 0, 1), draws: 256)
|
||||
second.commit()
|
||||
|
||||
let copyCb = queue.makeCommandBuffer()!
|
||||
let blit = copyCb.makeBlitCommandEncoder()!
|
||||
blit.copy(from: source, sourceSlice: 0, sourceLevel: 0,
|
||||
to: dst, destinationSlice: 0, destinationLevel: 0,
|
||||
sliceCount: 1, levelCount: 1)
|
||||
blit.endEncoding()
|
||||
copyCb.commit()
|
||||
copyCb.waitUntilCompleted()
|
||||
|
||||
guard let got = readBack(readPipe, dst, w, h) else { refused(label); return }
|
||||
let green = pack(0, 255, 0, 255)
|
||||
let red = pack(255, 0, 0, 255)
|
||||
var wrong: [(Int, Int)] = []
|
||||
var stale = 0
|
||||
for y in 0..<h {
|
||||
for x in 0..<w where got[y * w + x] != green {
|
||||
wrong.append((x, y))
|
||||
if got[y * w + x] == red { stale += 1 }
|
||||
}
|
||||
}
|
||||
let firstBad = wrong.first.map {
|
||||
"at=(\($0.0),\($0.1)) got=\(hex(got[$0.1 * w + $0.0]))"
|
||||
} ?? ""
|
||||
report(label, wrong.isEmpty,
|
||||
wrong.isEmpty
|
||||
? "the copy moved what the render ahead of it had written"
|
||||
: "wrong=\(wrong.count)/\(w * h) stale_previous_frame=\(stale) "
|
||||
+ "want=\(hex(green)) \(firstBad)" + badMap(wrong, w, h))
|
||||
}
|
||||
|
||||
// The same copy, run the way a compositor runs it: many frames in flight.
|
||||
//
|
||||
// The single-shot case above reaches the rail and does not fail, because one
|
||||
// render is not enough to keep the GPU busy past the point where the copy
|
||||
// behind it is serviced. A compositor never has one frame outstanding — it
|
||||
// renders a layer, copies it out, and starts the next without waiting for
|
||||
// either, so a copy is decoded while earlier frames are still executing and the
|
||||
// queue is never drained.
|
||||
//
|
||||
// Each frame gets its own colour and its own destination, so a stale read is not
|
||||
// merely "wrong" — it is identifiably *an earlier frame*, which is what the
|
||||
// report names. Nothing is waited on until every frame has been committed.
|
||||
func blitPipelinedCase(_ w: Int, _ h: Int, frames: Int) {
|
||||
let label = "srt_blit_pipelined_\(w)x\(h)_x\(frames)"
|
||||
// Host-pointer import and copying configurations reach different counters
|
||||
// here. The exact pixel relation is portable between them, but no single
|
||||
// route counter is, so this case makes no route claim.
|
||||
guard let pipe = makeRenderPipeline("heavy_fs", .bgra8Unorm_srgb) else {
|
||||
report(label, false, "heavy pipeline unavailable for bgra8Unorm_srgb"); return
|
||||
}
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
// One colour per frame, all full-intensity so the sRGB encode round-trips
|
||||
// exactly, and all distinguishable from one another.
|
||||
let palette: [(SIMD4<Float>, UInt32)] = [
|
||||
(SIMD4(1, 0, 0, 1), pack(255, 0, 0, 255)),
|
||||
(SIMD4(0, 1, 0, 1), pack(0, 255, 0, 255)),
|
||||
(SIMD4(0, 0, 1, 1), pack(0, 0, 255, 255)),
|
||||
(SIMD4(1, 1, 0, 1), pack(255, 255, 0, 255)),
|
||||
(SIMD4(1, 0, 1, 1), pack(255, 0, 255, 255)),
|
||||
(SIMD4(0, 1, 1, 1), pack(0, 255, 255, 255)),
|
||||
(SIMD4(1, 1, 1, 1), pack(255, 255, 255, 255)),
|
||||
(SIMD4(0, 0, 0, 1), pack(0, 0, 0, 255)),
|
||||
]
|
||||
|
||||
var sources: [MTLTexture] = []
|
||||
var dests: [MTLTexture] = []
|
||||
for i in 0..<frames {
|
||||
let sd = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm_srgb, width: w, height: h, mipmapped: false)
|
||||
sd.usage = [.renderTarget, .shaderRead]
|
||||
sd.storageMode = .shared
|
||||
guard let src = dev.makeTexture(descriptor: sd) else {
|
||||
report(label, false, "makeTexture nil for frame \(i)'s source"); return
|
||||
}
|
||||
guard let dst = makeSrgbIOSurfaceTarget(w, h, label) else { return }
|
||||
sources.append(src)
|
||||
dests.append(dst)
|
||||
}
|
||||
|
||||
var last: MTLCommandBuffer?
|
||||
for i in 0..<frames {
|
||||
let (colour, _) = palette[i % palette.count]
|
||||
let render = queue.makeCommandBuffer()!
|
||||
let d = MTLRenderPassDescriptor()
|
||||
d.colorAttachments[0].texture = sources[i]
|
||||
d.colorAttachments[0].loadAction = .clear
|
||||
d.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
d.colorAttachments[0].storeAction = .store
|
||||
let enc = render.makeRenderCommandEncoder(descriptor: d)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
var c = colour
|
||||
enc.setFragmentBytes(&c, length: 16, index: 0)
|
||||
for _ in 0..<96 {
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
}
|
||||
enc.endEncoding()
|
||||
render.commit()
|
||||
|
||||
let copyCb = queue.makeCommandBuffer()!
|
||||
let blit = copyCb.makeBlitCommandEncoder()!
|
||||
blit.copy(from: sources[i], sourceSlice: 0, sourceLevel: 0,
|
||||
to: dests[i], destinationSlice: 0, destinationLevel: 0,
|
||||
sliceCount: 1, levelCount: 1)
|
||||
blit.endEncoding()
|
||||
copyCb.commit()
|
||||
last = copyCb
|
||||
}
|
||||
last?.waitUntilCompleted()
|
||||
|
||||
var badFrames: [Int] = []
|
||||
var detail = ""
|
||||
for i in 0..<frames {
|
||||
guard let got = readBack(readPipe, dests[i], w, h) else { refused(label); return }
|
||||
let want = palette[i % palette.count].1
|
||||
var wrong = 0
|
||||
var sawOtherFrame = -1
|
||||
for t in 0..<(w * h) where got[t] != want {
|
||||
wrong += 1
|
||||
if sawOtherFrame < 0 {
|
||||
for (j, p) in palette.enumerated() where p.1 == got[t] { sawOtherFrame = j }
|
||||
}
|
||||
}
|
||||
if wrong > 0 {
|
||||
badFrames.append(i)
|
||||
if detail.isEmpty {
|
||||
detail = "frame=\(i) wrong=\(wrong)/\(w * h) want=\(hex(want)) "
|
||||
+ (sawOtherFrame >= 0
|
||||
? "got=another frame's colour (palette \(sawOtherFrame))"
|
||||
: "got=\(hex(got[0]))")
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, badFrames.isEmpty,
|
||||
badFrames.isEmpty
|
||||
? "every frame's copy moved that frame's own pixels"
|
||||
: "stale_frames=\(badFrames.count)/\(frames) \(detail)")
|
||||
}
|
||||
|
||||
// A buffer-backed source, which is a linear guest allocation by construction.
|
||||
//
|
||||
// A texture made from an `MTLBuffer` names its own base and row stride, so
|
||||
// unlike a plain `.shared` texture — whose layout the driver picks — it is
|
||||
// unambiguously the linear form. Both are worth having: the pair above is what
|
||||
// a compositor emits, and this is the shape that leaves the guest no room to
|
||||
// choose something else.
|
||||
//
|
||||
// # This is a second defect, and it is not the unordered read
|
||||
//
|
||||
// The case fails with every texel zero and `stale_previous_frame=0`, which looks
|
||||
// at first like the unordered read above — zero is also what pre-Store bytes
|
||||
// look like on a freshly allocated source. It is not. It fails identically with
|
||||
// the ordering in place, and the first pass here is waited on, so a racing copy
|
||||
// would have found red rather than nothing.
|
||||
//
|
||||
// The device names it on the fail channel:
|
||||
//
|
||||
// rt_resolve reason=rt_wrong_type object_type=texture_view
|
||||
//
|
||||
// A texture made from an `MTLBuffer` arrives as a texture *view*, and the
|
||||
// render-target resolver does not accept that object type as a colour
|
||||
// attachment. Every draw into one is dropped, so the guest reads back the
|
||||
// allocation untouched. Metal renders into it happily, which is why this case
|
||||
// passes natively and fails here.
|
||||
//
|
||||
// The refusal is correct behaviour for an unimplemented case — it costs the
|
||||
// guest one command and says so by name, rather than guessing. The case stays
|
||||
// red until the resolver accepts the type.
|
||||
func makeLinearTarget(_ w: Int, _ h: Int, _ label: String,
|
||||
_ format: MTLPixelFormat) -> MTLTexture? {
|
||||
let align = max(1, dev.minimumLinearTextureAlignment(for: format))
|
||||
let bpr = ((w * 4) + align - 1) / align * align
|
||||
guard let buf = dev.makeBuffer(length: bpr * h, options: .storageModeShared) else {
|
||||
report(label, false, "makeBuffer nil for a linear \(w)x\(h) target"); return nil
|
||||
}
|
||||
let td = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: format, width: w, height: h, mipmapped: false)
|
||||
td.usage = [.renderTarget, .shaderRead]
|
||||
td.storageMode = .shared
|
||||
guard let tex = buf.makeTexture(descriptor: td, offset: 0, bytesPerRow: bpr) else {
|
||||
report(label, false, "makeTexture nil for a buffer-backed \(w)x\(h) render target")
|
||||
return nil
|
||||
}
|
||||
return tex
|
||||
}
|
||||
|
||||
func blitBufferBackedCase(_ w: Int, _ h: Int) {
|
||||
let label = "srt_blit_buffer_backed_\(w)x\(h)"
|
||||
guard let pipe = makeRenderPipeline("solid_fs", .bgra8Unorm) else {
|
||||
report(label, false, "solid pipeline unavailable for bgra8Unorm"); return
|
||||
}
|
||||
guard let source = makeLinearTarget(w, h, label, .bgra8Unorm) else { return }
|
||||
guard let dst = makeIOSurfaceTarget(w, h, label) else { return }
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
func encodeFill(_ cb: MTLCommandBuffer, _ colour: SIMD4<Float>, draws: Int) {
|
||||
let d = MTLRenderPassDescriptor()
|
||||
d.colorAttachments[0].texture = source
|
||||
d.colorAttachments[0].loadAction = .clear
|
||||
d.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
d.colorAttachments[0].storeAction = .store
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: d)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
var c = colour
|
||||
enc.setFragmentBytes(&c, length: 16, index: 0)
|
||||
for _ in 0..<draws {
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
}
|
||||
enc.endEncoding()
|
||||
}
|
||||
|
||||
let first = queue.makeCommandBuffer()!
|
||||
encodeFill(first, SIMD4<Float>(1, 0, 0, 1), draws: 1)
|
||||
first.commit()
|
||||
first.waitUntilCompleted()
|
||||
|
||||
let second = queue.makeCommandBuffer()!
|
||||
encodeFill(second, SIMD4<Float>(0, 1, 0, 1), draws: 64)
|
||||
second.commit()
|
||||
|
||||
let copyCb = queue.makeCommandBuffer()!
|
||||
let blit = copyCb.makeBlitCommandEncoder()!
|
||||
blit.copy(from: source, sourceSlice: 0, sourceLevel: 0,
|
||||
to: dst, destinationSlice: 0, destinationLevel: 0,
|
||||
sliceCount: 1, levelCount: 1)
|
||||
blit.endEncoding()
|
||||
copyCb.commit()
|
||||
copyCb.waitUntilCompleted()
|
||||
|
||||
guard let got = readBack(readPipe, dst, w, h) else { refused(label); return }
|
||||
let green = pack(0, 255, 0, 255)
|
||||
let red = pack(255, 0, 0, 255)
|
||||
var wrong: [(Int, Int)] = []
|
||||
var stale = 0
|
||||
var zero = 0
|
||||
for y in 0..<h {
|
||||
for x in 0..<w where got[y * w + x] != green {
|
||||
wrong.append((x, y))
|
||||
if got[y * w + x] == red { stale += 1 }
|
||||
if got[y * w + x] == 0 { zero += 1 }
|
||||
}
|
||||
}
|
||||
let firstBad = wrong.first.map {
|
||||
"at=(\($0.0),\($0.1)) got=\(hex(got[$0.1 * w + $0.0]))"
|
||||
} ?? ""
|
||||
report(label, wrong.isEmpty,
|
||||
wrong.isEmpty
|
||||
? "the copy out of a buffer-backed source moved what the render had written"
|
||||
: "wrong=\(wrong.count)/\(w * h) stale_previous_frame=\(stale) "
|
||||
+ "never_written=\(zero) want=\(hex(green)) \(firstBad)" + badMap(wrong, w, h))
|
||||
}
|
||||
|
||||
// The same whole-plane copy with an IOSurface-backed *source*, which is the
|
||||
// shape a compositor actually emits: it renders a layer into a surface it
|
||||
// shares, then copies that surface into another one.
|
||||
//
|
||||
// # Why the source's backing is the whole case
|
||||
//
|
||||
// The two cases above give the copy a plain `.shared` source, and that is a
|
||||
// different rail inside this device: a shared texture is a linear guest
|
||||
// allocation, and the only account of its content the device had was a
|
||||
// writeback debt — "the GPU holds newer bytes than the guest pages do". Under a
|
||||
// host-pointer import there is never such a debt, because the render Store
|
||||
// wrote into the guest pages themselves. So a copy out of a surface the guest
|
||||
// had just rendered into found no GPU source, refused the GPU arm, and staged
|
||||
// every row through the host CPU — on a driven fullscreen Maps boot, on every
|
||||
// record of the boot.
|
||||
//
|
||||
// An IOSurface-backed texture is named by its surface identity instead, which
|
||||
// needs no debt, so the copy `MTLBlitCommandEncoder` puts on the GPU queue runs
|
||||
// on the GPU queue. `blit_t5_plane_device` is that account being the one that
|
||||
// answered; a run where it never moves did not put this case on the rail it was
|
||||
// written for, whatever it reported.
|
||||
//
|
||||
// Frames are pipelined for the same reason `blitPipelinedCase` pipelines them:
|
||||
// nothing is waited on until every frame is committed, so each copy is decoded
|
||||
// while the render feeding it is still executing. A device that names the wrong
|
||||
// resident does not return garbage here — it returns *another frame's colour*,
|
||||
// which is what the report says when it fails.
|
||||
func blitIOSurfaceSourceCase(_ w: Int, _ h: Int, frames: Int) {
|
||||
let label = "srt_blit_iosurface_source_\(w)x\(h)_x\(frames)"
|
||||
claims(label, "blit_t5_plane_device", "sl_gpu_landed")
|
||||
guard let pipe = makeRenderPipeline("heavy_fs", .bgra8Unorm) else {
|
||||
report(label, false, "heavy pipeline unavailable for bgra8Unorm"); return
|
||||
}
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
// Full-intensity colours only, so nothing here depends on a rounding rule,
|
||||
// and all eight distinguishable from one another.
|
||||
let palette: [(SIMD4<Float>, UInt32)] = [
|
||||
(SIMD4(1, 0, 0, 1), pack(255, 0, 0, 255)),
|
||||
(SIMD4(0, 1, 0, 1), pack(0, 255, 0, 255)),
|
||||
(SIMD4(0, 0, 1, 1), pack(0, 0, 255, 255)),
|
||||
(SIMD4(1, 1, 0, 1), pack(255, 255, 0, 255)),
|
||||
(SIMD4(1, 0, 1, 1), pack(255, 0, 255, 255)),
|
||||
(SIMD4(0, 1, 1, 1), pack(0, 255, 255, 255)),
|
||||
(SIMD4(1, 1, 1, 1), pack(255, 255, 255, 255)),
|
||||
(SIMD4(0, 0, 0, 1), pack(0, 0, 0, 255)),
|
||||
]
|
||||
|
||||
var sources: [MTLTexture] = []
|
||||
var dests: [MTLTexture] = []
|
||||
for _ in 0..<frames {
|
||||
guard let src = makeIOSurfaceTarget(w, h, label) else { return }
|
||||
guard let dst = makeIOSurfaceTarget(w, h, label) else { return }
|
||||
sources.append(src)
|
||||
dests.append(dst)
|
||||
}
|
||||
|
||||
var last: MTLCommandBuffer?
|
||||
for i in 0..<frames {
|
||||
let (colour, _) = palette[i % palette.count]
|
||||
let render = queue.makeCommandBuffer()!
|
||||
let d = MTLRenderPassDescriptor()
|
||||
d.colorAttachments[0].texture = sources[i]
|
||||
d.colorAttachments[0].loadAction = .clear
|
||||
d.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
d.colorAttachments[0].storeAction = .store
|
||||
let enc = render.makeRenderCommandEncoder(descriptor: d)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
var c = colour
|
||||
enc.setFragmentBytes(&c, length: 16, index: 0)
|
||||
for _ in 0..<96 {
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
}
|
||||
enc.endEncoding()
|
||||
render.commit()
|
||||
|
||||
let copyCb = queue.makeCommandBuffer()!
|
||||
let blit = copyCb.makeBlitCommandEncoder()!
|
||||
blit.copy(from: sources[i], sourceSlice: 0, sourceLevel: 0,
|
||||
to: dests[i], destinationSlice: 0, destinationLevel: 0,
|
||||
sliceCount: 1, levelCount: 1)
|
||||
blit.endEncoding()
|
||||
copyCb.commit()
|
||||
last = copyCb
|
||||
}
|
||||
last?.waitUntilCompleted()
|
||||
|
||||
var badFrames: [Int] = []
|
||||
var detail = ""
|
||||
for i in 0..<frames {
|
||||
guard let got = readBack(readPipe, dests[i], w, h) else { refused(label); return }
|
||||
let want = palette[i % palette.count].1
|
||||
var wrong = 0
|
||||
var sawOtherFrame = -1
|
||||
for t in 0..<(w * h) where got[t] != want {
|
||||
wrong += 1
|
||||
if sawOtherFrame < 0 {
|
||||
for (j, p) in palette.enumerated() where p.1 == got[t] { sawOtherFrame = j }
|
||||
}
|
||||
}
|
||||
if wrong > 0 {
|
||||
badFrames.append(i)
|
||||
if detail.isEmpty {
|
||||
detail = "frame=\(i) wrong=\(wrong)/\(w * h) want=\(hex(want)) "
|
||||
+ (sawOtherFrame >= 0
|
||||
? "got=another frame's colour (palette \(sawOtherFrame))"
|
||||
: "got=\(hex(got[0]))")
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, badFrames.isEmpty,
|
||||
badFrames.isEmpty
|
||||
? "every surface-to-surface copy moved its own frame's pixels"
|
||||
: "stale_frames=\(badFrames.count)/\(frames) \(detail)")
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Two textures over one buffer allocation, reading its bytes at different
|
||||
// widths.
|
||||
//
|
||||
// `makeTexture(descriptor:offset:bytesPerRow:)` on an `MTLBuffer` gives a
|
||||
// texture whose storage *is* that buffer's bytes, so two textures declared over
|
||||
// one buffer at formats of different bytes per texel are one set of bytes and
|
||||
// two texel counts. They share nothing else: their texel blocks are different
|
||||
// widths, so no copy between the images and no reinterpreting view relates
|
||||
// them, and a device that keeps a tiled image per texture has to leave the
|
||||
// texel domain entirely to make one current from the other.
|
||||
//
|
||||
// Whether that is a copy the guest is entitled to expect is the question the
|
||||
// oracle answers, and it is the reason this file exists rather than a Rust
|
||||
// test: `heap_texture_placement_overlap_incompatible_widths` covers the *heap*
|
||||
// reading of the same shape, where Metal leaves an alias's contents undefined
|
||||
// once another writes, and claims nothing about bytes crossing. Buffer-backed
|
||||
// storage is the other reading and the two must not be assumed to agree.
|
||||
//
|
||||
// The values are chosen so the expectation is bytes and never arithmetic. A
|
||||
// `rgba16Float` texel of (1, 0, 0, 1) is the four half words 0x3C00, 0x0000,
|
||||
// 0x0000, 0x3C00, which is `00 3C 00 00 00 00 00 3C` in memory. Read back as
|
||||
// `rgba8Unorm` those eight bytes are two texels, (0, 0x3C, 0, 0) and
|
||||
// (0, 0, 0, 0x3C), so the narrow texture's rows alternate between exactly two
|
||||
// values and a device that lands the bytes at the wrong offset produces
|
||||
// neither.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private func fillTexture(_ texture: MTLTexture, _ value: SIMD4<Float>) -> Bool {
|
||||
guard let commandBuffer = queue.makeCommandBuffer(),
|
||||
let encoder = commandBuffer.makeComputeCommandEncoder() else {
|
||||
return false
|
||||
}
|
||||
var color = value
|
||||
encoder.setComputePipelineState(pipeline("heap_alias_fill"))
|
||||
encoder.setTexture(texture, index: 0)
|
||||
encoder.setBytes(&color, length: MemoryLayout<SIMD4<Float>>.stride, index: 0)
|
||||
encoder.dispatchThreads(
|
||||
MTLSize(width: texture.width, height: texture.height, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: 8, height: 8, depth: 1))
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
return commandBuffer.status == .completed
|
||||
}
|
||||
|
||||
func bufferBackedAliasWidthCase() {
|
||||
let label = "buffer_backed_alias_incompatible_widths"
|
||||
let wideWidth = 64, height = 64
|
||||
let narrowWidth = 128
|
||||
let rowBytes = wideWidth * 8
|
||||
let wideAlign = dev.minimumLinearTextureAlignment(for: .rgba16Float)
|
||||
let narrowAlign = dev.minimumLinearTextureAlignment(for: .rgba8Unorm)
|
||||
guard wideAlign > 0, narrowAlign > 0,
|
||||
rowBytes % wideAlign == 0, rowBytes % narrowAlign == 0 else {
|
||||
skip(label, "a \(rowBytes)-byte row does not satisfy this device's "
|
||||
+ "minimumLinearTextureAlignment (rgba16Float=\(wideAlign), "
|
||||
+ "rgba8Unorm=\(narrowAlign))")
|
||||
return
|
||||
}
|
||||
guard let buffer = dev.makeBuffer(length: rowBytes * height,
|
||||
options: .storageModeShared) else {
|
||||
report(label, false, "the shared buffer could not be created")
|
||||
return
|
||||
}
|
||||
|
||||
let wide = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba16Float, width: wideWidth, height: height, mipmapped: false)
|
||||
wide.storageMode = .shared
|
||||
wide.usage = [.shaderRead, .shaderWrite]
|
||||
let narrow = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: narrowWidth, height: height, mipmapped: false)
|
||||
narrow.storageMode = .shared
|
||||
narrow.usage = [.shaderRead, .shaderWrite]
|
||||
|
||||
guard let wideTexture = buffer.makeTexture(descriptor: wide, offset: 0,
|
||||
bytesPerRow: rowBytes) else {
|
||||
report(label, false, "the buffer refused its rgba16Float texture")
|
||||
return
|
||||
}
|
||||
guard let narrowTexture = buffer.makeTexture(descriptor: narrow, offset: 0,
|
||||
bytesPerRow: rowBytes) else {
|
||||
report(label, false, "the buffer refused an overlapping rgba8Unorm texture")
|
||||
return
|
||||
}
|
||||
|
||||
guard fillTexture(wideTexture, SIMD4<Float>(1, 0, 0, 1)) else {
|
||||
report(label, false, "commands using the rgba16Float alias did not complete")
|
||||
return
|
||||
}
|
||||
guard let wideGot = readBack(readPipe, wideTexture, wideWidth, height) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
let red = pack(255, 0, 0, 255)
|
||||
let wideBad = wideGot.indices.filter { wideGot[$0] != red }
|
||||
guard wideBad.isEmpty else {
|
||||
report(label, false,
|
||||
"the rgba16Float alias did not read its own write: "
|
||||
+ "wrong=\(wideBad.count)/\(wideGot.count) first=\(hex(wideGot[wideBad[0]]))")
|
||||
return
|
||||
}
|
||||
|
||||
guard let narrowGot = readBack(readPipe, narrowTexture, narrowWidth, height) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
// The eight bytes of one wide texel are two narrow ones, in that order.
|
||||
let evenTexel = pack(0, 0x3C, 0, 0)
|
||||
let oddTexel = pack(0, 0, 0, 0x3C)
|
||||
var bad: [(Int, Int)] = []
|
||||
var first = ""
|
||||
for y in 0..<height {
|
||||
for x in 0..<narrowWidth {
|
||||
let want = x % 2 == 0 ? evenTexel : oddTexel
|
||||
let have = narrowGot[y * narrowWidth + x]
|
||||
if want != have {
|
||||
bad.append((x, y))
|
||||
if first.isEmpty {
|
||||
first = "first_bad=(\(x),\(y)) want=\(hex(want)) got=\(hex(have))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, bad.isEmpty,
|
||||
bad.isEmpty
|
||||
? "every byte the rgba16Float alias wrote reached the rgba8Unorm one"
|
||||
: "\(bad.count)/\(narrowWidth * height) wrong \(first) "
|
||||
+ badMap(bad, narrowWidth, height))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The same pair, with the second write covering part of one row rather than
|
||||
// the whole allocation.
|
||||
//
|
||||
// A byte range that starts and ends inside a row is a union of row segments and
|
||||
// not a rectangle in either texture's coordinates, which is the shape a device
|
||||
// translating between the two has to decompose rather than refuse. Writing the
|
||||
// narrow texture's rows 4 through 7 leaves every other row holding what the
|
||||
// wide one put there, so a device that widens the range loses those rows and a
|
||||
// device that drops it loses these.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func bufferBackedAliasPartialCase() {
|
||||
let label = "buffer_backed_alias_partial_row_range"
|
||||
let wideWidth = 64, height = 64
|
||||
let narrowWidth = 128
|
||||
let rowBytes = wideWidth * 8
|
||||
let wideAlign = dev.minimumLinearTextureAlignment(for: .rgba16Float)
|
||||
let narrowAlign = dev.minimumLinearTextureAlignment(for: .rgba8Unorm)
|
||||
guard wideAlign > 0, narrowAlign > 0,
|
||||
rowBytes % wideAlign == 0, rowBytes % narrowAlign == 0 else {
|
||||
skip(label, "a \(rowBytes)-byte row does not satisfy this device's "
|
||||
+ "minimumLinearTextureAlignment (rgba16Float=\(wideAlign), "
|
||||
+ "rgba8Unorm=\(narrowAlign))")
|
||||
return
|
||||
}
|
||||
guard let buffer = dev.makeBuffer(length: rowBytes * height,
|
||||
options: .storageModeShared) else {
|
||||
report(label, false, "the shared buffer could not be created")
|
||||
return
|
||||
}
|
||||
let wide = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba16Float, width: wideWidth, height: height, mipmapped: false)
|
||||
wide.storageMode = .shared
|
||||
wide.usage = [.shaderRead, .shaderWrite]
|
||||
let narrow = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: narrowWidth, height: 4, mipmapped: false)
|
||||
narrow.storageMode = .shared
|
||||
narrow.usage = [.shaderRead, .shaderWrite]
|
||||
|
||||
guard let wideTexture = buffer.makeTexture(descriptor: wide, offset: 0,
|
||||
bytesPerRow: rowBytes) else {
|
||||
report(label, false, "the buffer refused its rgba16Float texture")
|
||||
return
|
||||
}
|
||||
// Four rows starting at row 4, addressed as its own texture over the same
|
||||
// buffer. The offset has to satisfy the format's alignment too.
|
||||
let offset = rowBytes * 4
|
||||
guard offset % wideAlign == 0, offset % narrowAlign == 0,
|
||||
let narrowTexture = buffer.makeTexture(descriptor: narrow, offset: offset,
|
||||
bytesPerRow: rowBytes) else {
|
||||
skip(label, "a \(offset)-byte offset does not satisfy this device's "
|
||||
+ "minimumLinearTextureAlignment")
|
||||
return
|
||||
}
|
||||
|
||||
guard fillTexture(wideTexture, SIMD4<Float>(1, 0, 0, 1)),
|
||||
fillTexture(narrowTexture, SIMD4<Float>(0, 1, 0, 1)) else {
|
||||
report(label, false, "commands using one of the aliases did not complete")
|
||||
return
|
||||
}
|
||||
guard let wideGot = readBack(readPipe, wideTexture, wideWidth, height) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
|
||||
// Outside the strip the wide texture still holds its own write. Inside it,
|
||||
// the narrow one wrote (0, 1, 0, 1) as rgba8Unorm -- `00 FF 00 FF` --
|
||||
// and two of those are one wide texel, whose channels are then the half
|
||||
// words 0xFF00, 0xFF00, 0xFF00, 0xFF00. That is -0.0004... in half, which
|
||||
// clamps to 0 through the readback's unorm packing, so the strip reads
|
||||
// black and the rest reads red.
|
||||
let red = pack(255, 0, 0, 255)
|
||||
let strip = pack(0, 0, 0, 0)
|
||||
var bad: [(Int, Int)] = []
|
||||
var first = ""
|
||||
for y in 0..<height {
|
||||
for x in 0..<wideWidth {
|
||||
let want = (4..<8).contains(y) ? strip : red
|
||||
let have = wideGot[y * wideWidth + x]
|
||||
if want != have {
|
||||
bad.append((x, y))
|
||||
if first.isEmpty {
|
||||
first = "first_bad=(\(x),\(y)) want=\(hex(want)) got=\(hex(have))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, bad.isEmpty,
|
||||
bad.isEmpty
|
||||
? "the four-row write landed on exactly its own rows of the wide alias"
|
||||
: "\(bad.count)/\(wideWidth * height) wrong \(first) "
|
||||
+ badMap(bad, wideWidth, height))
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import Dispatch
|
||||
|
||||
// Two committed command buffers from one command queue execute in commit
|
||||
// order. The first produces bytes and the second consumes them; waiting only
|
||||
// for the consumer therefore observes both command buffers' effects.
|
||||
func sameQueueCommandBufferOrderCase() {
|
||||
let label = "command_buffer_same_queue_order"
|
||||
guard let source = dev.makeBuffer(length: 64, options: .storageModeShared),
|
||||
let destination = dev.makeBuffer(length: 64, options: .storageModeShared),
|
||||
let producer = queue.makeCommandBuffer(),
|
||||
let consumer = queue.makeCommandBuffer(),
|
||||
let produce = producer.makeBlitCommandEncoder(),
|
||||
let consume = consumer.makeBlitCommandEncoder()
|
||||
else {
|
||||
report(label, false, "buffers, command buffers, or blit encoders unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
source.contents().initializeMemory(as: UInt8.self, repeating: 0, count: 64)
|
||||
destination.contents().initializeMemory(as: UInt8.self, repeating: 0, count: 64)
|
||||
produce.fill(buffer: source, range: 0..<64, value: 0xa5)
|
||||
produce.endEncoding()
|
||||
consume.copy(from: source, sourceOffset: 0,
|
||||
to: destination, destinationOffset: 0, size: 64)
|
||||
consume.endEncoding()
|
||||
|
||||
producer.commit()
|
||||
consumer.commit()
|
||||
consumer.waitUntilCompleted()
|
||||
|
||||
let bytes = destination.contents().bindMemory(to: UInt8.self, capacity: 64)
|
||||
let ordered = (0..<64).allSatisfy { bytes[$0] == 0xa5 }
|
||||
let complete = producer.status == .completed && consumer.status == .completed
|
||||
report(label, ordered && complete,
|
||||
"producer=\(producer.status.rawValue) consumer=\(consumer.status.rawValue) ordered=\(ordered)")
|
||||
}
|
||||
|
||||
// Completed handlers from command buffers committed to one queue are
|
||||
// published in command-buffer order. This is a publication observation, not
|
||||
// an inference from buffer contents.
|
||||
func sameQueueCompletionPublicationCase() {
|
||||
let label = "command_buffer_same_queue_completion_publication"
|
||||
guard let first = queue.makeCommandBuffer(),
|
||||
let second = queue.makeCommandBuffer()
|
||||
else {
|
||||
report(label, false, "command buffers unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
let lock = NSLock()
|
||||
var published: [Int] = []
|
||||
first.addCompletedHandler { _ in
|
||||
lock.lock()
|
||||
published.append(1)
|
||||
lock.unlock()
|
||||
}
|
||||
second.addCompletedHandler { _ in
|
||||
lock.lock()
|
||||
published.append(2)
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
first.commit()
|
||||
second.commit()
|
||||
second.waitUntilCompleted()
|
||||
|
||||
lock.lock()
|
||||
let observed = published
|
||||
lock.unlock()
|
||||
report(label, observed == [1, 2], "published=\(observed)")
|
||||
}
|
||||
|
||||
// A command buffer with no encoders still has a scheduled/completed lifecycle
|
||||
// and callback publication obligation.
|
||||
func emptyCommandBufferCompletionCase() {
|
||||
let label = "command_buffer_empty_completion"
|
||||
guard let commandBuffer = queue.makeCommandBuffer() else {
|
||||
report(label, false, "command buffer unavailable")
|
||||
return
|
||||
}
|
||||
let lock = NSLock()
|
||||
var callback = false
|
||||
commandBuffer.addCompletedHandler { _ in
|
||||
lock.lock()
|
||||
callback = true
|
||||
lock.unlock()
|
||||
}
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
lock.lock()
|
||||
let published = callback
|
||||
lock.unlock()
|
||||
report(label, commandBuffer.status == .completed && published,
|
||||
"status=\(commandBuffer.status.rawValue) callback=\(published)")
|
||||
}
|
||||
|
||||
// An explicit shared-event edge orders work across two command queues and
|
||||
// carries the producer's writes into the consumer.
|
||||
func crossQueueSharedEventVisibilityCase() {
|
||||
let label = "command_buffer_cross_queue_shared_event_visibility"
|
||||
guard let producerQueue = dev.makeCommandQueue(),
|
||||
let consumerQueue = dev.makeCommandQueue(),
|
||||
let event = dev.makeSharedEvent(),
|
||||
let source = dev.makeBuffer(length: 64, options: .storageModeShared),
|
||||
let destination = dev.makeBuffer(length: 64, options: .storageModeShared),
|
||||
let producer = producerQueue.makeCommandBuffer(),
|
||||
let consumer = consumerQueue.makeCommandBuffer(),
|
||||
let produce = producer.makeBlitCommandEncoder()
|
||||
else {
|
||||
report(label, false, "queues, event, buffers, command buffers, or encoders unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
source.contents().initializeMemory(as: UInt8.self, repeating: 0, count: 64)
|
||||
destination.contents().initializeMemory(as: UInt8.self, repeating: 0, count: 64)
|
||||
produce.fill(buffer: source, range: 0..<64, value: 0x6d)
|
||||
produce.endEncoding()
|
||||
producer.encodeSignalEvent(event, value: 1)
|
||||
consumer.encodeWaitForEvent(event, value: 1)
|
||||
guard let consume = consumer.makeBlitCommandEncoder() else {
|
||||
report(label, false, "consumer blit encoder unavailable")
|
||||
return
|
||||
}
|
||||
consume.copy(from: source, sourceOffset: 0,
|
||||
to: destination, destinationOffset: 0, size: 64)
|
||||
consume.endEncoding()
|
||||
|
||||
// Commit the waiter first: the explicit future dependency must remain
|
||||
// valid and must not be replaced with commit-arrival order.
|
||||
let completion = DispatchSemaphore(value: 0)
|
||||
consumer.addCompletedHandler { _ in completion.signal() }
|
||||
consumer.commit()
|
||||
producer.commit()
|
||||
let completedWithoutHostRelease = completion.wait(timeout: .now() + 2) == .success
|
||||
if !completedWithoutHostRelease {
|
||||
// A waiter-first scheduling defect can park the device-wide command
|
||||
// stream. Even publishing a CPU signal may synchronously wait behind
|
||||
// that stream, so report without another device call or a join. This
|
||||
// case runs last so a broken implementation cannot hide later cases.
|
||||
report(label, false, "completed_without_host_release=false visible=false")
|
||||
return
|
||||
}
|
||||
consumer.waitUntilCompleted()
|
||||
let bytes = destination.contents().bindMemory(to: UInt8.self, capacity: 64)
|
||||
let visible = (0..<64).allSatisfy { bytes[$0] == 0x6d }
|
||||
report(label,
|
||||
completedWithoutHostRelease && visible
|
||||
&& producer.status == .completed && consumer.status == .completed,
|
||||
"producer=\(producer.status.rawValue) consumer=\(consumer.status.rawValue) "
|
||||
+ "completed_without_host_release=\(completedWithoutHostRelease) visible=\(visible)")
|
||||
}
|
||||
|
||||
// Publication is not globally serialized across independent API queues. A
|
||||
// waiter on one queue cannot prevent an empty command buffer on another queue
|
||||
// from completing and invoking its handler.
|
||||
func independentQueueCompletionPublicationCase() {
|
||||
let label = "command_buffer_independent_queue_publication"
|
||||
guard let blockedQueue = dev.makeCommandQueue(),
|
||||
let independentQueue = dev.makeCommandQueue(),
|
||||
let event = dev.makeSharedEvent(),
|
||||
let blocked = blockedQueue.makeCommandBuffer(),
|
||||
let independent = independentQueue.makeCommandBuffer()
|
||||
else {
|
||||
report(label, false, "queues, event, or command buffers unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
blocked.encodeWaitForEvent(event, value: 1)
|
||||
let completed = DispatchSemaphore(value: 0)
|
||||
independent.addCompletedHandler { _ in completed.signal() }
|
||||
blocked.commit()
|
||||
independent.commit()
|
||||
let independentPublishedFirst = completed.wait(timeout: .now() + 2) == .success
|
||||
// Always release the waiter before joining either command buffer.
|
||||
event.signaledValue = 1
|
||||
blocked.waitUntilCompleted()
|
||||
independent.waitUntilCompleted()
|
||||
report(label, independentPublishedFirst,
|
||||
"independent_published_before_signal=\(independentPublishedFirst)")
|
||||
}
|
||||
|
||||
// Scheduled publication precedes completed publication for one command
|
||||
// buffer. Both handlers are obligations even when the host completes quickly.
|
||||
func scheduledBeforeCompletedPublicationCase() {
|
||||
let label = "command_buffer_scheduled_before_completed"
|
||||
guard let commandBuffer = queue.makeCommandBuffer() else {
|
||||
report(label, false, "command buffer unavailable")
|
||||
return
|
||||
}
|
||||
let lock = NSLock()
|
||||
var publications: [String] = []
|
||||
commandBuffer.addScheduledHandler { _ in
|
||||
lock.lock()
|
||||
publications.append("scheduled")
|
||||
lock.unlock()
|
||||
}
|
||||
commandBuffer.addCompletedHandler { _ in
|
||||
lock.lock()
|
||||
publications.append("completed")
|
||||
lock.unlock()
|
||||
}
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
lock.lock()
|
||||
let observed = publications
|
||||
lock.unlock()
|
||||
report(label, observed == ["scheduled", "completed"], "publications=\(observed)")
|
||||
}
|
||||
|
||||
// A normal command buffer retains resources referenced by encoded work. The
|
||||
// event deliberately parks execution so the observation is made before GPU
|
||||
// completion rather than after an accidentally fast fill.
|
||||
func defaultCommandBufferRetainsResourceCase() {
|
||||
let label = "command_buffer_default_retains_resource"
|
||||
guard let event = dev.makeSharedEvent(),
|
||||
let commandBuffer = queue.makeCommandBuffer()
|
||||
else {
|
||||
report(label, false, "event or command buffer unavailable")
|
||||
return
|
||||
}
|
||||
var buffer: MTLBuffer? = dev.makeBuffer(length: 64, options: .storageModeShared)
|
||||
weak var retainedBuffer: MTLBuffer? = buffer
|
||||
guard buffer != nil else {
|
||||
report(label, false, "buffer unavailable")
|
||||
return
|
||||
}
|
||||
commandBuffer.encodeWaitForEvent(event, value: 1)
|
||||
var encoder: MTLBlitCommandEncoder? = commandBuffer.makeBlitCommandEncoder()
|
||||
guard encoder != nil else {
|
||||
report(label, false, "blit encoder unavailable")
|
||||
return
|
||||
}
|
||||
encoder!.fill(buffer: buffer!, range: 0..<64, value: 0x3c)
|
||||
encoder!.endEncoding()
|
||||
encoder = nil
|
||||
commandBuffer.commit()
|
||||
buffer = nil
|
||||
let retainedWhilePending = retainedBuffer != nil
|
||||
event.signaledValue = 1
|
||||
commandBuffer.waitUntilCompleted()
|
||||
report(label, retainedWhilePending && commandBuffer.status == .completed,
|
||||
"retained_while_pending=\(retainedWhilePending) status=\(commandBuffer.status.rawValue)")
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// A concurrent compute encoder promises no ordering between dispatches except
|
||||
// the dependency named here. Alternating the token makes every stale word a
|
||||
// deterministic wrong answer after the first round.
|
||||
func computeBarrierCase(resourceBarrier: Bool) {
|
||||
let label = resourceBarrier ? "compute_barrier_resource" : "compute_barrier_scope_buffers"
|
||||
let count = 8192
|
||||
let bytes = count * MemoryLayout<UInt32>.size
|
||||
let writePipe = pipeline("compute_barrier_write")
|
||||
let readPipe = pipeline("compute_barrier_read")
|
||||
|
||||
guard let words = dev.makeBuffer(length: bytes, options: .storageModePrivate),
|
||||
let verdict = dev.makeBuffer(length: bytes, options: .storageModeShared) else {
|
||||
report(label, false, "resource creation failed")
|
||||
return
|
||||
}
|
||||
|
||||
for round in 0..<8 {
|
||||
memset(verdict.contents(), 0, bytes)
|
||||
var token: UInt32 = round.isMultiple(of: 2) ? 0x13579BDF : 0x2468ACE0
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeComputeCommandEncoder(dispatchType: .concurrent)!
|
||||
enc.setComputePipelineState(writePipe)
|
||||
enc.setBuffer(words, offset: 0, index: 0)
|
||||
enc.setBytes(&token, length: MemoryLayout<UInt32>.size, index: 1)
|
||||
enc.dispatchThreadgroups(
|
||||
MTLSize(width: count / 64, height: 1, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: 64, height: 1, depth: 1))
|
||||
|
||||
if resourceBarrier {
|
||||
enc.memoryBarrier(resources: [words])
|
||||
} else {
|
||||
enc.memoryBarrier(scope: .buffers)
|
||||
}
|
||||
|
||||
enc.setComputePipelineState(readPipe)
|
||||
enc.setBuffer(words, offset: 0, index: 0)
|
||||
enc.setBuffer(verdict, offset: 0, index: 1)
|
||||
enc.setBytes(&token, length: MemoryLayout<UInt32>.size, index: 2)
|
||||
enc.dispatchThreadgroups(
|
||||
MTLSize(width: count / 64, height: 1, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: 64, height: 1, depth: 1))
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
let got = verdict.contents().bindMemory(to: UInt32.self, capacity: count)
|
||||
if let bad = (0..<count).first(where: { got[$0] != 1 }) {
|
||||
report(label, false,
|
||||
"round=\(round) word=\(bad) got=\(got[bad]) want=1")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
report(label, true, "8 alternating concurrent producer/consumer rounds were visible")
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// L. A whole-surface blit of a target the GPU has only just rendered into.
|
||||
//
|
||||
// The guest never reads the layer here — it hands both endpoints to a blit and
|
||||
// asks the device to move the pixels. Metal orders that copy against the render
|
||||
// before it: two command buffers on one queue execute in the order they were
|
||||
// committed, so the copy sees everything the render wrote.
|
||||
//
|
||||
// A device that decomposes the pair does not get that ordering for free. If the
|
||||
// render is submitted to the GPU and the copy is then serviced by reading the
|
||||
// source's bytes on the CPU, the two are racing, and the reader wins whenever
|
||||
// the GPU has not finished — which is most of the time, because submission is
|
||||
// asynchronous and the copy is decoded immediately behind it.
|
||||
//
|
||||
// # The shape is measured, not chosen
|
||||
//
|
||||
// Which copies the guest driver emits as a whole-surface texture-to-texture
|
||||
// copy, rather than staging through a buffer, is the driver's decision and not
|
||||
// something this file can assume. Earlier attempts at this case used a
|
||||
// `.bgra8Unorm` pair at 512x512 and never produced one: the driver staged every
|
||||
// one of them, so the case exercised a different rail and passed for the wrong
|
||||
// reason.
|
||||
//
|
||||
// The shape below is what a driven compositor actually emits — a linear source,
|
||||
// an IOSurface-backed destination, `BGRA8Unorm_sRGB`, one level and one slice,
|
||||
// at window and screen size. That is the pair a compositor produces when it
|
||||
// draws a layer and then copies it into the surface the window server owns.
|
||||
//
|
||||
// # Why two passes
|
||||
//
|
||||
// The first pass lands red and is waited on, so the source's bytes are known
|
||||
// and are *not* the answer. The second lands green and is not waited on before
|
||||
// the copy. A correct device puts green in the destination; one that reads the
|
||||
// source without ordering puts **red** there — the previous frame, whole and
|
||||
// undamaged, which is why this class reads as a layer showing stale content
|
||||
// rather than as corruption. `stale_previous_frame` in the failure counts
|
||||
// exactly those texels, so the report distinguishes this defect from a copy
|
||||
// that simply moved nothing.
|
||||
//
|
||||
// Full-intensity red and green round-trip an 8-bit sRGB encode exactly (0 and 1
|
||||
// are both fixed points), so the expectation is unaffected by the transfer
|
||||
// function on the attachment.
|
||||
func makeSrgbIOSurfaceTarget(_ w: Int, _ h: Int, _ label: String) -> MTLTexture? {
|
||||
let bgra: UInt32 = 0x4247_5241 // 'BGRA' as an OSType
|
||||
let props: [IOSurfacePropertyKey: Any] = [
|
||||
.width: w, .height: h, .bytesPerElement: 4, .pixelFormat: bgra,
|
||||
]
|
||||
guard let surface = IOSurface(properties: props) else {
|
||||
report(label, false, "IOSurface(properties:) nil for \(w)x\(h)"); return nil
|
||||
}
|
||||
let td = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm_srgb, width: w, height: h, mipmapped: false)
|
||||
td.usage = [.renderTarget, .shaderRead]
|
||||
td.storageMode = .shared
|
||||
guard let tex = dev.makeTexture(descriptor: td, iosurface: surface, plane: 0) else {
|
||||
report(label, false, "makeTexture(iosurface:) nil for \(w)x\(h)"); return nil
|
||||
}
|
||||
return tex
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// The fragment arm runs in section F. `texPipeline` is a top-level binding and
|
||||
// top-level code executes in order, so reading it from here answers nil and
|
||||
// every fragment case reports a refusal it never made — which is what the
|
||||
// native oracle caught when this loop ran both arms in place.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// C/D. Render-target round trips.
|
||||
//
|
||||
// Render into a texture, then (C) sample it in a later pass and (D) copy it out
|
||||
// to a buffer and check the bytes. A device that renders correctly but cannot
|
||||
// make the result readable again fails exactly one of these, which is the
|
||||
// distinction a screenshot cannot draw.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let quadVerts: [Float] = [
|
||||
// x, y, u, v -- a triangle strip covering the whole target
|
||||
-1, -1, 0, 1,
|
||||
1, -1, 1, 1,
|
||||
-1, 1, 0, 0,
|
||||
1, 1, 1, 0,
|
||||
]
|
||||
|
||||
func makeRenderPipeline(_ fragment: String, _ fmt: MTLPixelFormat) -> MTLRenderPipelineState? {
|
||||
let d = MTLRenderPipelineDescriptor()
|
||||
d.vertexFunction = library.makeFunction(name: "quad_vs")
|
||||
d.fragmentFunction = library.makeFunction(name: fragment)
|
||||
d.colorAttachments[0].pixelFormat = fmt
|
||||
return try? dev.makeRenderPipelineState(descriptor: d)
|
||||
}
|
||||
|
||||
func renderTargetCases() {
|
||||
let w = 64, h = 64
|
||||
let fmt = MTLPixelFormat.bgra8Unorm
|
||||
guard let pipe = makeRenderPipeline("solid_fs", fmt) else {
|
||||
report("rt_pipeline", false, "render pipeline creation failed"); return
|
||||
}
|
||||
report("rt_pipeline", true, "solid_fs pipeline built")
|
||||
|
||||
let td = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: fmt, width: w, height: h, mipmapped: false)
|
||||
td.usage = [.renderTarget, .shaderRead]
|
||||
td.storageMode = .private
|
||||
let rt = dev.makeTexture(descriptor: td)!
|
||||
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4, options: .storageModeShared)!
|
||||
// 0x40 red, 0x80 green, 0xC0 blue, opaque -- distinct in every channel so a
|
||||
// channel-order error is a different failure from a value error.
|
||||
var colour: [Float] = [64.0 / 255, 128.0 / 255, 192.0 / 255, 1.0]
|
||||
let wantPixel = pack(64, 128, 192, 255)
|
||||
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
enc.setFragmentBytes(&colour, length: 16, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
// C: sample the rendered target in a separate submission.
|
||||
guard let sampled = readBack(readPipe, rt, w, h) else {
|
||||
refused("rt_render_then_sample"); return
|
||||
}
|
||||
let allRight = sampled.allSatisfy { $0 == wantPixel }
|
||||
report("rt_render_then_sample", allRight,
|
||||
allRight ? "\(w * h) texels are the drawn colour"
|
||||
: "want=\(hex(wantPixel)) got=\(hex(sampled[0])) corner=\(hex(sampled[w * h - 1]))")
|
||||
|
||||
// D: copy it out to a buffer and check the bytes the CPU sees.
|
||||
let bpr = w * 4
|
||||
let out = dev.makeBuffer(length: bpr * h, options: .storageModeShared)!
|
||||
memset(out.contents(), 0xEE, bpr * h)
|
||||
let cb2 = queue.makeCommandBuffer()!
|
||||
let blit = cb2.makeBlitCommandEncoder()!
|
||||
blit.copy(from: rt, sourceSlice: 0, sourceLevel: 0,
|
||||
sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
sourceSize: MTLSize(width: w, height: h, depth: 1),
|
||||
to: out, destinationOffset: 0,
|
||||
destinationBytesPerRow: bpr, destinationBytesPerImage: bpr * h)
|
||||
blit.endEncoding()
|
||||
cb2.commit()
|
||||
cb2.waitUntilCompleted()
|
||||
let p = out.contents().bindMemory(to: UInt8.self, capacity: bpr * h)
|
||||
// bgra8 in memory: B, G, R, A
|
||||
let okBytes = (0..<(w * h)).allSatisfy { i in
|
||||
p[i * 4] == 192 && p[i * 4 + 1] == 128 && p[i * 4 + 2] == 64 && p[i * 4 + 3] == 255
|
||||
}
|
||||
report("rt_blit_to_buffer", okBytes,
|
||||
okBytes ? "\(w * h) texels exact through blit"
|
||||
: "first=[\(p[0]),\(p[1]),\(p[2]),\(p[3])] expect=[192,128,64,255]")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// E. A mip chain, level by level.
|
||||
//
|
||||
// The alias rail refuses a guest mip chain whose per-level offsets and pitches
|
||||
// the host driver lays out differently, and that refusal is correct. What has
|
||||
// never been checked is whether the levels the guest declares are *sampled*
|
||||
// correctly once the copying rail carries them, which is a different question
|
||||
// and the one a wrong level table would fail.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func mipCase() {
|
||||
let size = 64
|
||||
let levels = 7 // 64,32,16,8,4,2,1
|
||||
let d = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm,
|
||||
width: size, height: size, mipmapped: true)
|
||||
d.mipmapLevelCount = levels
|
||||
d.storageMode = .shared
|
||||
d.usage = [.shaderRead]
|
||||
guard let tex = dev.makeTexture(descriptor: d) else {
|
||||
report("mip_chain_create", false, "makeTexture nil"); return
|
||||
}
|
||||
report("mip_chain_create", tex.mipmapLevelCount == levels, "levels=\(tex.mipmapLevelCount)")
|
||||
|
||||
// Each level is filled with a constant that names the level, so a level
|
||||
// read at the wrong offset returns a neighbouring level's marker rather
|
||||
// than plausible-looking noise.
|
||||
for l in 0..<levels {
|
||||
let dim = max(1, size >> l)
|
||||
let marker = UInt8(0x10 + l * 0x11)
|
||||
let rows = [UInt8](repeating: marker, count: dim * dim * 4)
|
||||
rows.withUnsafeBytes { raw in
|
||||
tex.replace(region: MTLRegionMake2D(0, 0, dim, dim),
|
||||
mipmapLevel: l,
|
||||
withBytes: raw.baseAddress!,
|
||||
bytesPerRow: dim * 4)
|
||||
}
|
||||
}
|
||||
for l in 0..<levels {
|
||||
let dim = max(1, size >> l)
|
||||
let marker = UInt8(0x10 + l * 0x11)
|
||||
let want = pack(marker, marker, marker, marker)
|
||||
// Fetched with the level named in the fetch, then sampled with the
|
||||
// level named as an explicit LOD. Which of the two fails says whether
|
||||
// the level's bytes are missing or the LOD is.
|
||||
guard let fetched = readBack(fetchLevelPipe, tex, dim, dim, level: l) else {
|
||||
refused("mip_fetch_level_\(l)_size\(dim)")
|
||||
skipDependent("mip_sample_level_\(l)_size\(dim)",
|
||||
"mip_fetch_level_\(l)_size\(dim)")
|
||||
continue
|
||||
}
|
||||
let fOK = fetched.allSatisfy { $0 == want }
|
||||
report("mip_fetch_level_\(l)_size\(dim)", fOK,
|
||||
fOK ? "\(dim * dim) texels are level \(l)'s marker"
|
||||
: "want=\(hex(want)) got=\(hex(fetched[0]))")
|
||||
guard let got = readBack(levelPipe, tex, dim, dim, level: l) else {
|
||||
refused("mip_sample_level_\(l)_size\(dim)"); continue
|
||||
}
|
||||
let ok = got.allSatisfy { $0 == want }
|
||||
report("mip_sample_level_\(l)_size\(dim)", ok,
|
||||
ok ? "\(dim * dim) texels are level \(l)'s marker"
|
||||
: "want=\(hex(want)) got=\(hex(got[0]))")
|
||||
}
|
||||
}
|
||||
@@ -1,653 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
private func depthPipeline(_ depthFormat: MTLPixelFormat,
|
||||
stencil stencilFormat: MTLPixelFormat = .invalid) -> MTLRenderPipelineState? {
|
||||
let descriptor = MTLRenderPipelineDescriptor()
|
||||
descriptor.vertexFunction = library.makeFunction(name: "quad_vs")
|
||||
descriptor.fragmentFunction = library.makeFunction(name: "solid_fs")
|
||||
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
|
||||
descriptor.depthAttachmentPixelFormat = depthFormat
|
||||
descriptor.stencilAttachmentPixelFormat = stencilFormat
|
||||
return try? dev.makeRenderPipelineState(descriptor: descriptor)
|
||||
}
|
||||
|
||||
private func stencilTestState(_ compare: MTLCompareFunction) -> MTLDepthStencilState? {
|
||||
let face = MTLStencilDescriptor()
|
||||
face.stencilCompareFunction = compare
|
||||
face.stencilFailureOperation = .keep
|
||||
face.depthFailureOperation = .keep
|
||||
face.depthStencilPassOperation = .keep
|
||||
face.readMask = UInt32.max
|
||||
face.writeMask = 0
|
||||
let descriptor = MTLDepthStencilDescriptor()
|
||||
descriptor.depthCompareFunction = .always
|
||||
descriptor.isDepthWriteEnabled = false
|
||||
descriptor.frontFaceStencil = face
|
||||
descriptor.backFaceStencil = face
|
||||
return dev.makeDepthStencilState(descriptor: descriptor)
|
||||
}
|
||||
|
||||
private func depthTestState(_ compare: MTLCompareFunction) -> MTLDepthStencilState? {
|
||||
let descriptor = MTLDepthStencilDescriptor()
|
||||
descriptor.depthCompareFunction = compare
|
||||
descriptor.isDepthWriteEnabled = false
|
||||
return dev.makeDepthStencilState(descriptor: descriptor)
|
||||
}
|
||||
|
||||
/// With combined storage, an option-free buffer copy selects the depth plane.
|
||||
/// Seed stencil first and prove both directions leave that independent plane
|
||||
/// intact, so a packed-cell interpretation cannot accidentally pass.
|
||||
func combinedDepthStencilDefaultBufferCopyCase() {
|
||||
let label = "combined_depth_stencil_default_buffer_copy_selects_depth"
|
||||
let width = 4, height = 2, rowBytes = 256
|
||||
let descriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .depth32Float_stencil8,
|
||||
width: width,
|
||||
height: height,
|
||||
mipmapped: false)
|
||||
descriptor.usage = .renderTarget
|
||||
descriptor.storageMode = .private
|
||||
guard let texture = dev.makeTexture(descriptor: descriptor),
|
||||
let source = dev.makeBuffer(length: rowBytes * height, options: .storageModeShared),
|
||||
let stencilSource = dev.makeBuffer(length: rowBytes * height, options: .storageModeShared),
|
||||
let implicitDepth = dev.makeBuffer(length: rowBytes * height, options: .storageModeShared),
|
||||
let stencil = dev.makeBuffer(length: rowBytes * height, options: .storageModeShared) else {
|
||||
report(label, false, "combined texture or transfer buffer allocation failed")
|
||||
return
|
||||
}
|
||||
|
||||
let sourceBytes = source.contents().bindMemory(to: UInt8.self, capacity: rowBytes * height)
|
||||
let stencilSourceBytes = stencilSource.contents().bindMemory(
|
||||
to: UInt8.self, capacity: rowBytes * height)
|
||||
sourceBytes.initialize(repeating: 0, count: rowBytes * height)
|
||||
stencilSourceBytes.initialize(repeating: 0, count: rowBytes * height)
|
||||
let depthBits = Float(0.25).bitPattern.littleEndian
|
||||
for y in 0..<height {
|
||||
for x in 0..<width {
|
||||
let offset = y * rowBytes + x * 4
|
||||
sourceBytes[offset + 0] = UInt8(truncatingIfNeeded: depthBits)
|
||||
sourceBytes[offset + 1] = UInt8(truncatingIfNeeded: depthBits >> 8)
|
||||
sourceBytes[offset + 2] = UInt8(truncatingIfNeeded: depthBits >> 16)
|
||||
sourceBytes[offset + 3] = UInt8(truncatingIfNeeded: depthBits >> 24)
|
||||
stencilSourceBytes[y * rowBytes + x] = 0x5a
|
||||
}
|
||||
}
|
||||
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let blit = commandBuffer.makeBlitCommandEncoder()!
|
||||
let size = MTLSize(width: width, height: height, depth: 1)
|
||||
blit.copy(from: stencilSource,
|
||||
sourceOffset: 0,
|
||||
sourceBytesPerRow: rowBytes,
|
||||
sourceBytesPerImage: rowBytes * height,
|
||||
sourceSize: size,
|
||||
to: texture,
|
||||
destinationSlice: 0,
|
||||
destinationLevel: 0,
|
||||
destinationOrigin: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
options: .stencilFromDepthStencil)
|
||||
blit.copy(from: source,
|
||||
sourceOffset: 0,
|
||||
sourceBytesPerRow: rowBytes,
|
||||
sourceBytesPerImage: rowBytes * height,
|
||||
sourceSize: size,
|
||||
to: texture,
|
||||
destinationSlice: 0,
|
||||
destinationLevel: 0,
|
||||
destinationOrigin: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
options: [])
|
||||
blit.copy(from: texture,
|
||||
sourceSlice: 0,
|
||||
sourceLevel: 0,
|
||||
sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
sourceSize: size,
|
||||
to: implicitDepth,
|
||||
destinationOffset: 0,
|
||||
destinationBytesPerRow: rowBytes,
|
||||
destinationBytesPerImage: rowBytes * height,
|
||||
options: [])
|
||||
blit.copy(from: texture,
|
||||
sourceSlice: 0,
|
||||
sourceLevel: 0,
|
||||
sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
sourceSize: size,
|
||||
to: stencil,
|
||||
destinationOffset: 0,
|
||||
destinationBytesPerRow: rowBytes,
|
||||
destinationBytesPerImage: rowBytes * height,
|
||||
options: .stencilFromDepthStencil)
|
||||
blit.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
guard commandBuffer.status == .completed else {
|
||||
report(label, false, "default combined buffer copy status=\(commandBuffer.status.rawValue)")
|
||||
return
|
||||
}
|
||||
|
||||
let depthBytes = implicitDepth.contents().bindMemory(
|
||||
to: UInt8.self, capacity: rowBytes * height)
|
||||
let stencilBytes = stencil.contents().bindMemory(to: UInt8.self, capacity: rowBytes * height)
|
||||
var mismatch = ""
|
||||
for y in 0..<height {
|
||||
for x in 0..<width {
|
||||
let depthOffset = y * rowBytes + x * 4
|
||||
let gotDepth = UInt32(depthBytes[depthOffset + 0])
|
||||
| (UInt32(depthBytes[depthOffset + 1]) << 8)
|
||||
| (UInt32(depthBytes[depthOffset + 2]) << 16)
|
||||
| (UInt32(depthBytes[depthOffset + 3]) << 24)
|
||||
let gotStencil = stencilBytes[y * rowBytes + x]
|
||||
if gotDepth != depthBits || gotStencil != 0x5a {
|
||||
mismatch = "at=(\(x),\(y)) depth=\(hex(gotDepth)) stencil=\(hex(UInt32(gotStencil)))"
|
||||
break
|
||||
}
|
||||
}
|
||||
if !mismatch.isEmpty { break }
|
||||
}
|
||||
report(label, mismatch.isEmpty,
|
||||
mismatch.isEmpty ? "default copies selected depth and preserved stencil" : mismatch)
|
||||
}
|
||||
|
||||
private struct DepthTaskFixture {
|
||||
let pipeline: MTLRenderPipelineState
|
||||
let vertices: MTLBuffer
|
||||
let colour: MTLTexture
|
||||
let depth: MTLTexture
|
||||
}
|
||||
|
||||
/// Build the same resource sequence in each process. Metal resource namespaces
|
||||
/// are task-local, so equal construction order must still produce independent
|
||||
/// depth contents.
|
||||
private func makeDepthTaskFixture() -> DepthTaskFixture? {
|
||||
let width = 8, height = 8
|
||||
guard let pipeline = depthPipeline(.depth32Float),
|
||||
let vertices = dev.makeBuffer(bytes: quadVerts,
|
||||
length: quadVerts.count * MemoryLayout<Float>.size,
|
||||
options: .storageModeShared) else {
|
||||
return nil
|
||||
}
|
||||
let colourDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false)
|
||||
colourDescriptor.usage = [.renderTarget, .shaderRead]
|
||||
colourDescriptor.storageMode = .private
|
||||
let depthDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .depth32Float, width: width, height: height, mipmapped: false)
|
||||
depthDescriptor.usage = .renderTarget
|
||||
depthDescriptor.storageMode = .private
|
||||
guard let colour = dev.makeTexture(descriptor: colourDescriptor),
|
||||
let depth = dev.makeTexture(descriptor: depthDescriptor) else {
|
||||
return nil
|
||||
}
|
||||
return DepthTaskFixture(pipeline: pipeline, vertices: vertices,
|
||||
colour: colour, depth: depth)
|
||||
}
|
||||
|
||||
private func clearTaskDepth(_ fixture: DepthTaskFixture, _ value: Double) -> Bool {
|
||||
var discardedColour: [Float] = [0, 0, 0, 0]
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = fixture.colour
|
||||
pass.colorAttachments[0].loadAction = .dontCare
|
||||
pass.colorAttachments[0].storeAction = .dontCare
|
||||
pass.depthAttachment.texture = fixture.depth
|
||||
pass.depthAttachment.loadAction = .clear
|
||||
pass.depthAttachment.storeAction = .store
|
||||
pass.depthAttachment.clearDepth = value
|
||||
guard let commandBuffer = queue.makeCommandBuffer(),
|
||||
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass) else {
|
||||
return false
|
||||
}
|
||||
encoder.setRenderPipelineState(fixture.pipeline)
|
||||
encoder.setVertexBuffer(fixture.vertices, offset: 0, index: 0)
|
||||
encoder.setFragmentBytes(&discardedColour, length: 16, index: 0)
|
||||
encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
return commandBuffer.status == .completed
|
||||
}
|
||||
|
||||
/// Child half of `depthTaskIsolationCase`, dispatched by `main.swift` before
|
||||
/// the ordinary battery. Standard input/output form a two-message barrier, so
|
||||
/// neither process relies on scheduler timing.
|
||||
func depthTaskIsolationChild() -> Int32 {
|
||||
guard let fixture = makeDepthTaskFixture() else {
|
||||
FileHandle.standardOutput.write(Data([0]))
|
||||
return 2
|
||||
}
|
||||
guard FileHandle.standardInput.readData(ofLength: 1).count == 1 else { return 2 }
|
||||
guard clearTaskDepth(fixture, 1.0) else {
|
||||
FileHandle.standardOutput.write(Data([0]))
|
||||
return 2
|
||||
}
|
||||
FileHandle.standardOutput.write(Data([1]))
|
||||
guard FileHandle.standardInput.readData(ofLength: 1).count == 1 else { return 2 }
|
||||
withExtendedLifetime(fixture) {}
|
||||
return 0
|
||||
}
|
||||
|
||||
/// Two live Metal tasks may use equal task-local object refs concurrently.
|
||||
/// Each establishes different defined depth contents; the child overwrites its
|
||||
/// own texture between the parent's Store and Load, so a backend that keys the
|
||||
/// resident on the raw ref makes the parent's Equal test reject incorrectly.
|
||||
func depthTaskIsolationCase() {
|
||||
let label = "depth_attachment_isolated_across_tasks"
|
||||
guard let fixture = makeDepthTaskFixture(), clearTaskDepth(fixture, 0.0) else {
|
||||
report(label, false, "parent depth fixture or clear failed")
|
||||
return
|
||||
}
|
||||
|
||||
let childInput = Pipe()
|
||||
let childOutput = Pipe()
|
||||
let child = Process()
|
||||
child.executableURL = URL(fileURLWithPath: CommandLine.arguments[0])
|
||||
child.arguments = ["--depth-task-child"]
|
||||
child.standardInput = childInput
|
||||
child.standardOutput = childOutput
|
||||
do {
|
||||
try child.run()
|
||||
} catch {
|
||||
report(label, false, "child process launch failed: \(error)")
|
||||
return
|
||||
}
|
||||
childInput.fileHandleForReading.closeFile()
|
||||
childOutput.fileHandleForWriting.closeFile()
|
||||
childInput.fileHandleForWriting.write(Data([1]))
|
||||
let ready = childOutput.fileHandleForReading.readData(ofLength: 1)
|
||||
guard ready == Data([1]) else {
|
||||
child.waitUntilExit()
|
||||
report(label, false, "child depth fixture or clear failed")
|
||||
return
|
||||
}
|
||||
|
||||
var green: [Float] = [0, 1, 0, 1]
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = fixture.colour
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
pass.depthAttachment.texture = fixture.depth
|
||||
pass.depthAttachment.loadAction = .load
|
||||
pass.depthAttachment.storeAction = .dontCare
|
||||
|
||||
var encoded = false
|
||||
if let equal = depthTestState(.equal),
|
||||
let commandBuffer = queue.makeCommandBuffer(),
|
||||
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass) {
|
||||
encoder.setRenderPipelineState(fixture.pipeline)
|
||||
encoder.setDepthStencilState(equal)
|
||||
encoder.setVertexBuffer(fixture.vertices, offset: 0, index: 0)
|
||||
encoder.setFragmentBytes(&green, length: 16, index: 0)
|
||||
encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
encoded = commandBuffer.status == .completed
|
||||
}
|
||||
|
||||
childInput.fileHandleForWriting.write(Data([1]))
|
||||
childInput.fileHandleForWriting.closeFile()
|
||||
child.waitUntilExit()
|
||||
|
||||
guard encoded, let pixels = readBack(readPipe, fixture.colour, 8, 8) else {
|
||||
report(label, false, "parent load/test or readback failed")
|
||||
return
|
||||
}
|
||||
let expected = pack(0, 255, 0, 255)
|
||||
let ok = pixels.allSatisfy { $0 == expected }
|
||||
report(label, ok,
|
||||
ok ? "each task loaded its own stored depth"
|
||||
: "want=\(hex(expected)) got=\(hex(pixels[0]))")
|
||||
}
|
||||
|
||||
/// Pass attachment operations and per-draw tests are independent Metal state.
|
||||
///
|
||||
/// The first case clears/stores depth while no depth-stencil state is bound,
|
||||
/// then consumes that clear in a later pass. The second binds a rejecting depth
|
||||
/// state to a pass with no depth attachment; Metal disables the absent test, so
|
||||
/// the colour draw still lands.
|
||||
func depthStencilIndependenceCases() {
|
||||
let width = 8, height = 8
|
||||
let vertices = dev.makeBuffer(bytes: quadVerts,
|
||||
length: quadVerts.count * MemoryLayout<Float>.size,
|
||||
options: .storageModeShared)!
|
||||
let colourDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false)
|
||||
colourDescriptor.usage = [.renderTarget, .shaderRead]
|
||||
colourDescriptor.storageMode = .private
|
||||
|
||||
if let pipeline = depthPipeline(.depth32Float),
|
||||
let less = depthTestState(.less),
|
||||
let colour = dev.makeTexture(descriptor: colourDescriptor) {
|
||||
let depthDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .depth32Float, width: width, height: height, mipmapped: false)
|
||||
depthDescriptor.usage = .renderTarget
|
||||
depthDescriptor.storageMode = .private
|
||||
|
||||
if let depth = dev.makeTexture(descriptor: depthDescriptor) {
|
||||
var firstColour: [Float] = [1, 0, 0, 1]
|
||||
let first = MTLRenderPassDescriptor()
|
||||
first.colorAttachments[0].texture = colour
|
||||
first.colorAttachments[0].loadAction = .clear
|
||||
first.colorAttachments[0].storeAction = .dontCare
|
||||
first.depthAttachment.texture = depth
|
||||
first.depthAttachment.loadAction = .clear
|
||||
first.depthAttachment.storeAction = .store
|
||||
first.depthAttachment.clearDepth = 0.0
|
||||
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let firstEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: first)!
|
||||
firstEncoder.setRenderPipelineState(pipeline)
|
||||
firstEncoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
firstEncoder.setFragmentBytes(&firstColour, length: 16, index: 0)
|
||||
// Deliberately leave the depth-stencil state nil. The pass-owned
|
||||
// clear/store must still execute.
|
||||
firstEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
firstEncoder.endEncoding()
|
||||
|
||||
var secondColour: [Float] = [0, 1, 0, 1]
|
||||
let second = MTLRenderPassDescriptor()
|
||||
second.colorAttachments[0].texture = colour
|
||||
second.colorAttachments[0].loadAction = .clear
|
||||
second.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 1, alpha: 1)
|
||||
second.colorAttachments[0].storeAction = .store
|
||||
second.depthAttachment.texture = depth
|
||||
second.depthAttachment.loadAction = .load
|
||||
second.depthAttachment.storeAction = .dontCare
|
||||
|
||||
let secondEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: second)!
|
||||
secondEncoder.setRenderPipelineState(pipeline)
|
||||
secondEncoder.setDepthStencilState(less)
|
||||
secondEncoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
secondEncoder.setFragmentBytes(&secondColour, length: 16, index: 0)
|
||||
// quad_vs emits z=0. Less-than the stored clear value 0 is false,
|
||||
// so the blue pass clear must survive.
|
||||
secondEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
secondEncoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
if let pixels = readBack(readPipe, colour, width, height) {
|
||||
let expected = pack(0, 0, 255, 255)
|
||||
let ok = pixels.allSatisfy { $0 == expected }
|
||||
report("depth_attachment_clear_without_test_state", ok,
|
||||
ok ? "stored depth clear rejected the later draw"
|
||||
: "want=\(hex(expected)) got=\(hex(pixels[0]))")
|
||||
} else {
|
||||
refused("depth_attachment_clear_without_test_state")
|
||||
}
|
||||
} else {
|
||||
report("depth_attachment_clear_without_test_state", false,
|
||||
"depth32Float render-target allocation failed")
|
||||
}
|
||||
} else {
|
||||
report("depth_attachment_clear_without_test_state", false,
|
||||
"depth pipeline, state, or colour target creation failed")
|
||||
}
|
||||
|
||||
if let pipeline = depthPipeline(.invalid) {
|
||||
// Native Metal applies a bound depth comparison even without a pass
|
||||
// depth attachment. For quad_vs' z=0 the implicit comparison value is
|
||||
// 1: Less and Always pass; Equal, Greater and Never reject.
|
||||
let comparisons: [(String, MTLCompareFunction, Bool)] = [
|
||||
("less", .less, true),
|
||||
("equal", .equal, false),
|
||||
("greater", .greater, false),
|
||||
("never", .never, false),
|
||||
("always", .always, true),
|
||||
]
|
||||
for (tag, compare, shouldDraw) in comparisons {
|
||||
let label = "depth_test_\(tag)_without_attachment"
|
||||
guard let state = depthTestState(compare),
|
||||
let colour = dev.makeTexture(descriptor: colourDescriptor) else {
|
||||
report(label, false, "depth state or colour target creation failed")
|
||||
continue
|
||||
}
|
||||
var green: [Float] = [0, 1, 0, 1]
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = colour
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass)!
|
||||
encoder.setRenderPipelineState(pipeline)
|
||||
encoder.setDepthStencilState(state)
|
||||
encoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
encoder.setFragmentBytes(&green, length: 16, index: 0)
|
||||
encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
if let pixels = readBack(readPipe, colour, width, height) {
|
||||
let expected = shouldDraw ? pack(0, 255, 0, 255) : pack(0, 0, 255, 255)
|
||||
let ok = pixels.allSatisfy { $0 == expected }
|
||||
report(label, ok,
|
||||
ok ? "z=0 compared against the absent attachment value"
|
||||
: "want=\(hex(expected)) got=\(hex(pixels[0]))")
|
||||
} else {
|
||||
refused(label)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for tag in ["less", "equal", "greater", "never", "always"] {
|
||||
report("depth_test_\(tag)_without_attachment", false,
|
||||
"colour-only pipeline creation failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stencilIndependenceCases() {
|
||||
let width = 8, height = 8
|
||||
let vertices = dev.makeBuffer(bytes: quadVerts,
|
||||
length: quadVerts.count * MemoryLayout<Float>.size,
|
||||
options: .storageModeShared)!
|
||||
let colourDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false)
|
||||
colourDescriptor.usage = [.renderTarget, .shaderRead]
|
||||
colourDescriptor.storageMode = .private
|
||||
|
||||
let combinedFormat = MTLPixelFormat.depth32Float_stencil8
|
||||
if let pipeline = depthPipeline(combinedFormat, stencil: combinedFormat),
|
||||
let equal = stencilTestState(.equal),
|
||||
let colour = dev.makeTexture(descriptor: colourDescriptor) {
|
||||
let attachmentDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: combinedFormat, width: width, height: height, mipmapped: false)
|
||||
attachmentDescriptor.usage = .renderTarget
|
||||
attachmentDescriptor.storageMode = .private
|
||||
if let attachment = dev.makeTexture(descriptor: attachmentDescriptor) {
|
||||
var red: [Float] = [1, 0, 0, 1]
|
||||
let first = MTLRenderPassDescriptor()
|
||||
first.colorAttachments[0].texture = colour
|
||||
first.colorAttachments[0].loadAction = .clear
|
||||
first.colorAttachments[0].storeAction = .dontCare
|
||||
first.depthAttachment.texture = attachment
|
||||
first.depthAttachment.loadAction = .clear
|
||||
first.depthAttachment.storeAction = .store
|
||||
first.depthAttachment.clearDepth = 1.0
|
||||
first.stencilAttachment.texture = attachment
|
||||
first.stencilAttachment.loadAction = .clear
|
||||
first.stencilAttachment.storeAction = .store
|
||||
first.stencilAttachment.clearStencil = 7
|
||||
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let firstEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: first)!
|
||||
firstEncoder.setRenderPipelineState(pipeline)
|
||||
firstEncoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
firstEncoder.setFragmentBytes(&red, length: 16, index: 0)
|
||||
firstEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
firstEncoder.endEncoding()
|
||||
|
||||
var green: [Float] = [0, 1, 0, 1]
|
||||
let second = MTLRenderPassDescriptor()
|
||||
second.colorAttachments[0].texture = colour
|
||||
second.colorAttachments[0].loadAction = .clear
|
||||
second.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 1, alpha: 1)
|
||||
second.colorAttachments[0].storeAction = .store
|
||||
second.depthAttachment.texture = attachment
|
||||
second.depthAttachment.loadAction = .load
|
||||
second.depthAttachment.storeAction = .dontCare
|
||||
second.stencilAttachment.texture = attachment
|
||||
second.stencilAttachment.loadAction = .load
|
||||
second.stencilAttachment.storeAction = .dontCare
|
||||
|
||||
let secondEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: second)!
|
||||
secondEncoder.setRenderPipelineState(pipeline)
|
||||
secondEncoder.setDepthStencilState(equal)
|
||||
secondEncoder.setStencilReferenceValue(7)
|
||||
secondEncoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
secondEncoder.setFragmentBytes(&green, length: 16, index: 0)
|
||||
secondEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
secondEncoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
if let pixels = readBack(readPipe, colour, width, height) {
|
||||
let expected = pack(0, 255, 0, 255)
|
||||
let ok = pixels.allSatisfy { $0 == expected }
|
||||
report("stencil_attachment_clear_without_test_state", ok,
|
||||
ok ? "stored stencil clear passed the later equal test"
|
||||
: "want=\(hex(expected)) got=\(hex(pixels[0]))")
|
||||
} else {
|
||||
refused("stencil_attachment_clear_without_test_state")
|
||||
}
|
||||
} else {
|
||||
report("stencil_attachment_clear_without_test_state", false,
|
||||
"combined depth-stencil allocation failed")
|
||||
}
|
||||
} else {
|
||||
report("stencil_attachment_clear_without_test_state", false,
|
||||
"combined pipeline, state, or colour target creation failed")
|
||||
}
|
||||
|
||||
if let pipeline = depthPipeline(.invalid, stencil: .stencil8),
|
||||
let equal = stencilTestState(.equal),
|
||||
let colour = dev.makeTexture(descriptor: colourDescriptor) {
|
||||
let stencilDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .stencil8, width: width, height: height, mipmapped: false)
|
||||
stencilDescriptor.usage = .renderTarget
|
||||
stencilDescriptor.storageMode = .private
|
||||
if let stencil = dev.makeTexture(descriptor: stencilDescriptor) {
|
||||
var red: [Float] = [1, 0, 0, 1]
|
||||
let first = MTLRenderPassDescriptor()
|
||||
first.colorAttachments[0].texture = colour
|
||||
first.colorAttachments[0].loadAction = .clear
|
||||
first.colorAttachments[0].storeAction = .dontCare
|
||||
first.stencilAttachment.texture = stencil
|
||||
first.stencilAttachment.loadAction = .clear
|
||||
first.stencilAttachment.storeAction = .store
|
||||
first.stencilAttachment.clearStencil = 7
|
||||
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let firstEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: first)!
|
||||
firstEncoder.setRenderPipelineState(pipeline)
|
||||
firstEncoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
firstEncoder.setFragmentBytes(&red, length: 16, index: 0)
|
||||
firstEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
firstEncoder.endEncoding()
|
||||
|
||||
var green: [Float] = [0, 1, 0, 1]
|
||||
let second = MTLRenderPassDescriptor()
|
||||
second.colorAttachments[0].texture = colour
|
||||
second.colorAttachments[0].loadAction = .clear
|
||||
second.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 1, alpha: 1)
|
||||
second.colorAttachments[0].storeAction = .store
|
||||
second.stencilAttachment.texture = stencil
|
||||
second.stencilAttachment.loadAction = .load
|
||||
second.stencilAttachment.storeAction = .dontCare
|
||||
|
||||
let secondEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: second)!
|
||||
secondEncoder.setRenderPipelineState(pipeline)
|
||||
secondEncoder.setDepthStencilState(equal)
|
||||
secondEncoder.setStencilReferenceValue(7)
|
||||
secondEncoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
secondEncoder.setFragmentBytes(&green, length: 16, index: 0)
|
||||
secondEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
secondEncoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
if let pixels = readBack(readPipe, colour, width, height) {
|
||||
let expected = pack(0, 255, 0, 255)
|
||||
let ok = pixels.allSatisfy { $0 == expected }
|
||||
report("stencil_only_attachment_clear_without_test_state", ok,
|
||||
ok ? "stored stencil-only clear passed the later equal test"
|
||||
: "want=\(hex(expected)) got=\(hex(pixels[0]))")
|
||||
} else {
|
||||
refused("stencil_only_attachment_clear_without_test_state")
|
||||
}
|
||||
} else {
|
||||
report("stencil_only_attachment_clear_without_test_state", false,
|
||||
"stencil8 render-target allocation failed")
|
||||
}
|
||||
} else {
|
||||
report("stencil_only_attachment_clear_without_test_state", false,
|
||||
"stencil-only pipeline, state, or colour target creation failed")
|
||||
}
|
||||
|
||||
let variants: [(String, MTLCompareFunction, Bool)] = [
|
||||
("equal", .equal, true),
|
||||
("not_equal", .notEqual, false),
|
||||
]
|
||||
for hasDepth in [false, true] {
|
||||
let depthFormat: MTLPixelFormat = hasDepth ? .depth32Float : .invalid
|
||||
guard let pipeline = depthPipeline(depthFormat) else {
|
||||
for (tag, _, _) in variants {
|
||||
report("stencil_test_\(tag)_without_attachment_depth_\(hasDepth)", false,
|
||||
"pipeline creation failed")
|
||||
}
|
||||
continue
|
||||
}
|
||||
let depth: MTLTexture? = {
|
||||
guard hasDepth else { return nil }
|
||||
let descriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .depth32Float, width: width, height: height, mipmapped: false)
|
||||
descriptor.usage = .renderTarget
|
||||
descriptor.storageMode = .private
|
||||
return dev.makeTexture(descriptor: descriptor)
|
||||
}()
|
||||
for (tag, compare, shouldDraw) in variants {
|
||||
let label = "stencil_test_\(tag)_without_attachment_depth_\(hasDepth)"
|
||||
guard let state = stencilTestState(compare),
|
||||
let colour = dev.makeTexture(descriptor: colourDescriptor) else {
|
||||
report(label, false, "state or colour target creation failed")
|
||||
continue
|
||||
}
|
||||
var green: [Float] = [0, 1, 0, 1]
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = colour
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
if let depth {
|
||||
pass.depthAttachment.texture = depth
|
||||
pass.depthAttachment.loadAction = .clear
|
||||
pass.depthAttachment.storeAction = .dontCare
|
||||
pass.depthAttachment.clearDepth = 1.0
|
||||
}
|
||||
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass)!
|
||||
encoder.setRenderPipelineState(pipeline)
|
||||
encoder.setDepthStencilState(state)
|
||||
encoder.setStencilReferenceValue(0)
|
||||
encoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
encoder.setFragmentBytes(&green, length: 16, index: 0)
|
||||
encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
if let pixels = readBack(readPipe, colour, width, height) {
|
||||
let expected = shouldDraw ? pack(0, 255, 0, 255) : pack(0, 0, 255, 255)
|
||||
let ok = pixels.allSatisfy { $0 == expected }
|
||||
report(label, ok,
|
||||
ok ? "reference zero compared against implicit stencil zero"
|
||||
: "want=\(hex(expected)) got=\(hex(pixels[0]))")
|
||||
} else {
|
||||
refused(label)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Where an argument binding stops being in force.
|
||||
//
|
||||
// Metal scopes argument tables to the *encoder*: a binding set on one render
|
||||
// command encoder is not in force on the next one, and every encoder starts
|
||||
// with nothing bound. Every case in this battery so far rebinds inside one
|
||||
// encoder, so nothing here has ever asked what happens at the boundary.
|
||||
//
|
||||
// # Why this is a case and not a comment
|
||||
//
|
||||
// A device that wants to stop re-resolving an argument table every draw has to
|
||||
// decide when a table is "the same as last time". The cheap and exact test is
|
||||
// pointer identity on the table the guest presented -- and pointer identity is
|
||||
// blind to encoder boundaries. The same table re-presented in a *new* encoder
|
||||
// is the same allocation and a wholly different binding state, so a device that
|
||||
// compares only the table skips a bind that Metal requires, and the draw reads
|
||||
// whatever the descriptor happened to hold.
|
||||
//
|
||||
// That failure is silent. It needs the same allocation to be presented twice
|
||||
// across a boundary, which is exactly what a compositor does and exactly what
|
||||
// no existing case here constructs. The three checks below are the boundaries a
|
||||
// per-draw dirty flag can be wrong about, in increasing order of how likely a
|
||||
// device is to carry state across them:
|
||||
//
|
||||
// 1. a second encoder in the SAME command buffer, identical bind re-issued
|
||||
// 2. a second encoder in the same command buffer, DIFFERENT bind
|
||||
// 3. a second encoder in a DIFFERENT command buffer, identical bind re-issued
|
||||
//
|
||||
// Each second encoder clears the target first, so the first encoder's pixels
|
||||
// cannot stand in for the second's. A device that drops the second bind renders
|
||||
// the clear colour or a stale slot, and both are distinguishable from the
|
||||
// answer.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func encoderBindingLifetimeCase() {
|
||||
let w = 64, h = 64
|
||||
let fmt = MTLPixelFormat.bgra8Unorm
|
||||
guard let pipe = makeRenderPipeline("solid_fs", fmt) else {
|
||||
report("ebl_pipeline", false, "pipeline failed"); return
|
||||
}
|
||||
let td = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: fmt, width: w, height: h, mipmapped: false)
|
||||
td.usage = [.renderTarget, .shaderRead]
|
||||
td.storageMode = .private
|
||||
guard let rt = dev.makeTexture(descriptor: td) else {
|
||||
report("ebl_target", false, "no render target"); return
|
||||
}
|
||||
let verts = dev.makeBuffer(bytes: quadVerts,
|
||||
length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
// Two slots, exact under the unorm conversion so the expectation is a byte
|
||||
// and not a rounding argument. The clear colour is a third value, so
|
||||
// "the second encoder did not draw" is distinguishable from either slot.
|
||||
let stride = 256
|
||||
let slots: [(UInt8, UInt8, UInt8)] = [(64, 128, 192), (192, 64, 128)]
|
||||
let colours = dev.makeBuffer(length: stride * slots.count, options: .storageModeShared)!
|
||||
for (i, c) in slots.enumerated() {
|
||||
var rgba: [Float] = [Float(c.0) / 255, Float(c.1) / 255, Float(c.2) / 255, 1]
|
||||
memcpy(colours.contents().advanced(by: i * stride), &rgba, 16)
|
||||
}
|
||||
func want(_ i: Int) -> UInt32 { pack(slots[i].0, slots[i].1, slots[i].2, 255) }
|
||||
let clearPixel = pack(255, 0, 255, 255)
|
||||
|
||||
// One encoder that clears, binds `slot`, and covers the target.
|
||||
func encode(_ cb: MTLCommandBuffer, slot: Int) {
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
enc.setFragmentBuffer(colours, offset: slot * stride, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
}
|
||||
|
||||
func judge(_ label: String, _ wantSlot: Int) {
|
||||
guard let got = readBack(readPipe, rt, w, h) else { refused(label); return }
|
||||
let px = got[(h / 2) * w + (w / 2)]
|
||||
let ok = px == want(wantSlot)
|
||||
let why: String
|
||||
if px == clearPixel {
|
||||
why = "the second encoder's draw produced nothing — its bind was dropped"
|
||||
} else if px == want(1 - wantSlot) {
|
||||
why = "the second encoder rendered the other encoder's slot"
|
||||
} else {
|
||||
why = "unrecognised"
|
||||
}
|
||||
report(label, ok,
|
||||
ok ? "the binding re-issued on the second encoder is the one that drew"
|
||||
: "got=\(hex(px)) want=\(hex(want(wantSlot))) — \(why)")
|
||||
}
|
||||
|
||||
// 1. Two encoders, one command buffer, the *same* bind re-issued. A device
|
||||
// keyed on the table's identity alone sees "unchanged" and skips it.
|
||||
var cb = queue.makeCommandBuffer()!
|
||||
encode(cb, slot: 0)
|
||||
encode(cb, slot: 0)
|
||||
cb.commit(); cb.waitUntilCompleted()
|
||||
judge("ebl_same_bind_second_encoder", 0)
|
||||
|
||||
// 2. Two encoders, one command buffer, a different bind on the second. The
|
||||
// opposite error: state carried across the boundary rather than dropped.
|
||||
cb = queue.makeCommandBuffer()!
|
||||
encode(cb, slot: 0)
|
||||
encode(cb, slot: 1)
|
||||
cb.commit(); cb.waitUntilCompleted()
|
||||
judge("ebl_changed_bind_second_encoder", 1)
|
||||
|
||||
// 3. The same bind re-issued from a *different* command buffer. Metal fixes
|
||||
// the order at commit, so the second buffer's clear-and-draw is what the
|
||||
// target holds; a device that carries per-draw state across command
|
||||
// buffers is wrong here in the same way as 1 and harder to notice,
|
||||
// because the two buffers are resolved at different times.
|
||||
let first = queue.makeCommandBuffer()!
|
||||
encode(first, slot: 1)
|
||||
first.commit()
|
||||
let second = queue.makeCommandBuffer()!
|
||||
encode(second, slot: 1)
|
||||
second.commit()
|
||||
second.waitUntilCompleted()
|
||||
judge("ebl_same_bind_second_command_buffer", 1)
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
private let floatSamplePipe = pipeline("sample_float4")
|
||||
|
||||
private func floatTexture(_ values: [[Float]], label: String) -> MTLTexture? {
|
||||
let width = values.count
|
||||
let descriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba32Float, width: width, height: 1, mipmapped: false)
|
||||
descriptor.usage = [.shaderRead]
|
||||
descriptor.storageMode = .shared
|
||||
guard let texture = dev.makeTexture(descriptor: descriptor) else {
|
||||
report(label, false, "makeTexture returned nil")
|
||||
return nil
|
||||
}
|
||||
let flat = values.flatMap { $0 }
|
||||
flat.withUnsafeBytes { raw in
|
||||
texture.replace(region: MTLRegionMake2D(0, 0, width, 1),
|
||||
mipmapLevel: 0,
|
||||
withBytes: raw.baseAddress!,
|
||||
bytesPerRow: width * 16)
|
||||
}
|
||||
return texture
|
||||
}
|
||||
|
||||
private func computeFloatSampleCase(_ values: [[Float]]) {
|
||||
let width = values.count
|
||||
let name = "sample_rgba32float_compute_\(width)x1"
|
||||
guard let texture = floatTexture(values, label: name) else { return }
|
||||
let output = dev.makeBuffer(length: width * 16, options: .storageModeShared)!
|
||||
memset(output.contents(), 0xFF, width * 16)
|
||||
let ran = dev.makeBuffer(length: 4, options: .storageModeShared)!
|
||||
memset(ran.contents(), 0, 4)
|
||||
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let encoder = commandBuffer.makeComputeCommandEncoder()!
|
||||
encoder.setComputePipelineState(floatSamplePipe)
|
||||
encoder.setTexture(texture, index: 0)
|
||||
encoder.setBuffer(output, offset: 0, index: 0)
|
||||
var count = UInt32(width)
|
||||
encoder.setBytes(&count, length: 4, index: 1)
|
||||
encoder.setBuffer(ran, offset: 0, index: 4)
|
||||
encoder.dispatchThreadgroups(MTLSize(width: 1, height: 1, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: width, height: 1, depth: 1))
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
guard ran.contents().bindMemory(to: UInt32.self, capacity: 1)[0] == 1 else {
|
||||
refused(name)
|
||||
return
|
||||
}
|
||||
let expected = values.flatMap { $0 }
|
||||
let pointer = output.contents().bindMemory(to: Float.self, capacity: expected.count)
|
||||
let got = Array(UnsafeBufferPointer(start: pointer, count: expected.count))
|
||||
let ok = got == expected
|
||||
report(name, ok, ok ? "\(width) float4 texels exact"
|
||||
: "want=\(expected) got=\(got)")
|
||||
}
|
||||
|
||||
private func vertexFloatSampleCase() {
|
||||
let name = "sample_rgba32float_vertex_positions_4x1"
|
||||
let values: [[Float]] = [
|
||||
[-0.75, -0.70, 2.0, -2.0],
|
||||
[0.75, -0.70, -4.0, 4.0],
|
||||
[0.0, 0.75, 3.5, -3.5],
|
||||
[1.25, -1.5, 5.0, 6.0],
|
||||
]
|
||||
guard let texture = floatTexture(values, label: name) else { return }
|
||||
|
||||
let pipelineDescriptor = MTLRenderPipelineDescriptor()
|
||||
pipelineDescriptor.vertexFunction = library.makeFunction(name: "float_positions_vs")
|
||||
pipelineDescriptor.fragmentFunction = library.makeFunction(name: "solid_fs")
|
||||
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
|
||||
pipelineDescriptor.inputPrimitiveTopology = .triangle
|
||||
guard let pipeline = try? dev.makeRenderPipelineState(descriptor: pipelineDescriptor) else {
|
||||
report(name, false, "render pipeline creation failed")
|
||||
return
|
||||
}
|
||||
|
||||
let width = 64, height = 64
|
||||
let targetDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false)
|
||||
targetDescriptor.usage = [.renderTarget, .shaderRead]
|
||||
targetDescriptor.storageMode = .private
|
||||
let target = dev.makeTexture(descriptor: targetDescriptor)!
|
||||
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = target
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass)!
|
||||
encoder.setRenderPipelineState(pipeline)
|
||||
encoder.setVertexTexture(texture, index: 0)
|
||||
var green: [Float] = [0, 1, 0, 1]
|
||||
encoder.setFragmentBytes(&green, length: 16, index: 0)
|
||||
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
guard let pixels = readBack(readPipe, target, width, height) else {
|
||||
refused(name)
|
||||
return
|
||||
}
|
||||
let greenPixel = pack(0, 255, 0, 255)
|
||||
let blackPixel = pack(0, 0, 0, 255)
|
||||
let lit = pixels.filter { $0 == greenPixel }.count
|
||||
let centre = pixels[32 * width + 32]
|
||||
let lowerLeftInterior = pixels[43 * width + 24]
|
||||
let corner = pixels[2 * width + 2]
|
||||
let ok = (850...1400).contains(lit)
|
||||
&& centre == greenPixel
|
||||
&& lowerLeftInterior == greenPixel
|
||||
&& corner == blackPixel
|
||||
report(name, ok,
|
||||
"lit=\(lit) centre=\(hex(centre)) lower_left=\(hex(lowerLeftInterior)) corner=\(hex(corner))")
|
||||
}
|
||||
|
||||
func floatSamplingCases() {
|
||||
computeFloatSampleCase([[-2.5, 0.25, 1.5, 17.0]])
|
||||
computeFloatSampleCase([
|
||||
[-0.75, -0.70, 2.0, -2.0],
|
||||
[0.75, -0.70, -4.0, 4.0],
|
||||
[0.0, 0.75, 3.5, -3.5],
|
||||
[1.25, -1.5, 5.0, 6.0],
|
||||
])
|
||||
vertexFloatSampleCase()
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// A buffer bound to the *fragment* stage, read at several offsets, and rebound
|
||||
// between draws inside one encoder.
|
||||
//
|
||||
// Every other case that gives a fragment shader a constant hands it over with
|
||||
// `setFragmentBytes`, which is inline bytes in the command stream and a wholly
|
||||
// different path from a bound `MTLBuffer`. Nothing in the battery covered
|
||||
// `setFragmentBuffer:offset:atIndex:` at all, so a device was free to route it
|
||||
// however it liked -- and the byte source a fragment bind resolves to is not
|
||||
// something a screenshot can name, because a wrong offset produces a plausible
|
||||
// solid colour rather than a visible defect.
|
||||
//
|
||||
// Three things are checked, and the second and third are the ones with teeth:
|
||||
//
|
||||
// 1. offset 0 -- the bind resolves to the buffer's own bytes at all.
|
||||
// 2. a non-zero offset -- the window starts where the guest said, not at the
|
||||
// start of the allocation. This is the failure mode of any path that
|
||||
// resolves a bind to its backing allocation and forgets the offset.
|
||||
// 3. a rebind between two draws of one encoder -- the second draw sees the
|
||||
// second offset. A device that resolves the bind once per encoder, or
|
||||
// holds a stale resolution across the rebind, draws the first colour
|
||||
// twice and passes 1 and 2 while doing so.
|
||||
//
|
||||
// Offsets are multiples of 256 because the constant address space's minimum
|
||||
// buffer offset alignment is 256 on some macOS devices and smaller on others;
|
||||
// 256 is legal on every one of them, so the case is expressible everywhere
|
||||
// rather than being a limit test.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func fragmentBufferCase() {
|
||||
let w = 64, h = 64
|
||||
let fmt = MTLPixelFormat.bgra8Unorm
|
||||
guard let pipe = makeRenderPipeline("solid_fs", fmt) else {
|
||||
report("fb_pipeline", false, "pipeline failed"); return
|
||||
}
|
||||
let td = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: fmt, width: w, height: h, mipmapped: false)
|
||||
td.usage = [.renderTarget, .shaderRead]
|
||||
td.storageMode = .private
|
||||
guard let rt = dev.makeTexture(descriptor: td) else {
|
||||
report("fb_target", false, "no render target"); return
|
||||
}
|
||||
|
||||
let verts = dev.makeBuffer(bytes: quadVerts,
|
||||
length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
// Three colours, one per 256-byte slot. Each channel is k/255 so the
|
||||
// unorm conversion is exact and the expectation is a literal byte rather
|
||||
// than a rounding argument.
|
||||
let stride = 256
|
||||
let slots: [(UInt8, UInt8, UInt8)] = [(64, 128, 192), (192, 64, 128), (128, 192, 64)]
|
||||
let colours = dev.makeBuffer(length: stride * slots.count, options: .storageModeShared)!
|
||||
for (i, c) in slots.enumerated() {
|
||||
var rgba: [Float] = [Float(c.0) / 255, Float(c.1) / 255, Float(c.2) / 255, 1]
|
||||
memcpy(colours.contents().advanced(by: i * stride), &rgba, 16)
|
||||
}
|
||||
func want(_ i: Int) -> UInt32 {
|
||||
pack(slots[i].0, slots[i].1, slots[i].2, 255)
|
||||
}
|
||||
|
||||
// One pass, one draw, the colour taken from slot `i`.
|
||||
func drawOne(_ i: Int, _ tag: String) {
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
enc.setFragmentBuffer(colours, offset: i * stride, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
guard let got = readBack(readPipe, rt, w, h) else { refused("fb_\(tag)"); return }
|
||||
let px = got[(h / 2) * w + (w / 2)]
|
||||
let ok = px == want(i)
|
||||
report("fb_\(tag)", ok,
|
||||
ok ? "slot \(i) at offset \(i * stride) reached the fragment stage"
|
||||
: "got=\(hex(px)) want=\(hex(want(i))) at offset \(i * stride)")
|
||||
}
|
||||
|
||||
drawOne(0, "offset_0")
|
||||
drawOne(1, "offset_256")
|
||||
drawOne(2, "offset_512")
|
||||
|
||||
// Two draws in ONE encoder, each covering half the target, with the
|
||||
// fragment buffer rebound to a different offset between them. The halves
|
||||
// are read well inside their own side so rasterization edges are not the
|
||||
// test.
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
for (n, leftHalf) in [true, false].enumerated() {
|
||||
let x0: Float = leftHalf ? -1 : 0
|
||||
let x1: Float = leftHalf ? 0 : 1
|
||||
var data: [Float] = [x0, -1, 0, 1, x1, -1, 1, 1, x0, 1, 0, 0, x1, 1, 1, 0]
|
||||
// A second buffer per half would let a device resolve each bind once
|
||||
// and still pass; one buffer rebound at two offsets cannot.
|
||||
let vb = dev.makeBuffer(bytes: &data, length: 64, options: .storageModeShared)!
|
||||
enc.setVertexBuffer(vb, offset: 0, index: 0)
|
||||
enc.setFragmentBuffer(colours, offset: n * stride, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
}
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
if let got = readBack(readPipe, rt, w, h) {
|
||||
let leftPx = got[(h / 2) * w + (w / 4)]
|
||||
let rightPx = got[(h / 2) * w + (3 * w / 4)]
|
||||
let ok = leftPx == want(0) && rightPx == want(1)
|
||||
report("fb_rebound_between_draws", ok,
|
||||
ok ? "each draw read the offset bound before it"
|
||||
: "left=\(hex(leftPx)) right=\(hex(rightPx)) "
|
||||
+ "wanted left=\(hex(want(0))) right=\(hex(want(1)))")
|
||||
} else {
|
||||
refused("fb_rebound_between_draws")
|
||||
}
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
private func fillHeapTexture(_ texture: MTLTexture, _ value: SIMD4<Float>) -> Bool {
|
||||
guard let commandBuffer = queue.makeCommandBuffer(),
|
||||
let encoder = commandBuffer.makeComputeCommandEncoder() else {
|
||||
return false
|
||||
}
|
||||
var color = value
|
||||
encoder.setComputePipelineState(pipeline("heap_alias_fill"))
|
||||
encoder.setTexture(texture, index: 0)
|
||||
encoder.setBytes(&color, length: MemoryLayout<SIMD4<Float>>.stride, index: 0)
|
||||
encoder.dispatchThreads(
|
||||
MTLSize(width: texture.width, height: texture.height, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: 8, height: 8, depth: 1))
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
return commandBuffer.status == .completed
|
||||
}
|
||||
|
||||
// A one-slot automatic heap has exactly one legal reuse transition: after the
|
||||
// live texture occupying it becomes aliasable, a second compatible texture may
|
||||
// take the same offset. The final readback covers both halves of the contract:
|
||||
// the allocator reused the released range, and commands address the new
|
||||
// resource rather than stale storage owned by the old one.
|
||||
func heapTextureAliasCase() {
|
||||
let label = "heap_texture_alias_lifecycle"
|
||||
let width = 257
|
||||
let height = 193
|
||||
let descriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm,
|
||||
width: width,
|
||||
height: height,
|
||||
mipmapped: false)
|
||||
descriptor.storageMode = .private
|
||||
descriptor.usage = [.shaderRead, .shaderWrite]
|
||||
|
||||
let requirement = dev.heapTextureSizeAndAlign(descriptor: descriptor)
|
||||
guard requirement.size > 0, requirement.align > 0 else {
|
||||
skip(label, "the device reported no heap storage requirement for the texture")
|
||||
return
|
||||
}
|
||||
guard requirement.align.nonzeroBitCount == 1 else {
|
||||
report(label, false, "heap alignment is not a power of two: \(requirement.align)")
|
||||
return
|
||||
}
|
||||
|
||||
let heapDescriptor = MTLHeapDescriptor()
|
||||
heapDescriptor.type = .automatic
|
||||
heapDescriptor.storageMode = .private
|
||||
heapDescriptor.hazardTrackingMode = .untracked
|
||||
heapDescriptor.size = requirement.size
|
||||
guard let heap = dev.makeHeap(descriptor: heapDescriptor) else {
|
||||
report(label, false,
|
||||
"nonzero requirement size=\(requirement.size) align=\(requirement.align), but makeHeap returned nil")
|
||||
return
|
||||
}
|
||||
guard let first = heap.makeTexture(descriptor: descriptor) else {
|
||||
report(label, false, "the exact-size heap would not allocate its first texture")
|
||||
return
|
||||
}
|
||||
let firstOffset = first.heapOffset
|
||||
guard heap.makeTexture(descriptor: descriptor) == nil else {
|
||||
report(label, false, "a one-slot heap admitted two simultaneously live textures")
|
||||
return
|
||||
}
|
||||
guard fillHeapTexture(first, SIMD4<Float>(1, 0, 0, 1)) else {
|
||||
report(label, false, "commands using the first heap texture did not complete")
|
||||
return
|
||||
}
|
||||
|
||||
first.makeAliasable()
|
||||
guard first.isAliasable() else {
|
||||
report(label, false, "makeAliasable did not change the first texture's lifecycle state")
|
||||
return
|
||||
}
|
||||
guard let second = heap.makeTexture(descriptor: descriptor) else {
|
||||
report(label, false, "the released heap range was not reusable")
|
||||
return
|
||||
}
|
||||
guard second.heapOffset == firstOffset else {
|
||||
report(label, false,
|
||||
"the replacement moved from offset=\(firstOffset) to offset=\(second.heapOffset)")
|
||||
return
|
||||
}
|
||||
guard fillHeapTexture(second, SIMD4<Float>(0, 1, 0, 1)) else {
|
||||
report(label, false, "commands using the replacement heap texture did not complete")
|
||||
return
|
||||
}
|
||||
guard let got = readBack(readPipe, second, width, height) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
|
||||
let want = pack(0, 255, 0, 255)
|
||||
let bad = got.indices.filter { got[$0] != want }
|
||||
report(label, bad.isEmpty,
|
||||
bad.isEmpty
|
||||
? "one live range was released, reused at offset=\(second.heapOffset), and addressed as the replacement"
|
||||
: "wrong=\(bad.count)/\(got.count) first=\(hex(got[bad[0]])) want=\(hex(want))")
|
||||
}
|
||||
|
||||
// Placement heaps let the caller name overlapping ranges directly. Merely
|
||||
// creating both resources is defined; only concurrent GPU access needs an
|
||||
// explicit synchronization discipline. Keep both objects live so an
|
||||
// implementation that treats overlap as an allocator collision cannot pass by
|
||||
// retiring the first one implicitly.
|
||||
func heapTexturePlacementOverlapCase() {
|
||||
let label = "heap_texture_placement_overlap"
|
||||
let width = 64
|
||||
let height = 64
|
||||
let unorm = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm,
|
||||
width: width,
|
||||
height: height,
|
||||
mipmapped: false)
|
||||
let bgra = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm,
|
||||
width: width,
|
||||
height: height,
|
||||
mipmapped: false)
|
||||
for descriptor in [unorm, bgra] {
|
||||
descriptor.storageMode = .private
|
||||
descriptor.usage = [.shaderRead, .shaderWrite]
|
||||
}
|
||||
|
||||
let unormRequirement = dev.heapTextureSizeAndAlign(descriptor: unorm)
|
||||
let bgraRequirement = dev.heapTextureSizeAndAlign(descriptor: bgra)
|
||||
guard unormRequirement.size > 0, unormRequirement.align > 0,
|
||||
bgraRequirement.size > 0, bgraRequirement.align > 0 else {
|
||||
skip(label, "the device reported no heap storage requirement for one texture")
|
||||
return
|
||||
}
|
||||
|
||||
let heapDescriptor = MTLHeapDescriptor()
|
||||
heapDescriptor.type = .placement
|
||||
heapDescriptor.storageMode = .private
|
||||
heapDescriptor.hazardTrackingMode = .untracked
|
||||
heapDescriptor.size = max(unormRequirement.size, bgraRequirement.size)
|
||||
guard let heap = dev.makeHeap(descriptor: heapDescriptor) else {
|
||||
report(label, false, "the placement heap could not be created")
|
||||
return
|
||||
}
|
||||
guard let first = heap.makeTexture(descriptor: unorm, offset: 0) else {
|
||||
report(label, false, "the placement heap refused its first texture")
|
||||
return
|
||||
}
|
||||
guard let alias = heap.makeTexture(descriptor: bgra, offset: 0) else {
|
||||
report(label, false, "the placement heap refused a live overlapping texture")
|
||||
return
|
||||
}
|
||||
|
||||
guard fillHeapTexture(first, SIMD4<Float>(1, 0, 0, 1)) else {
|
||||
report(label, false, "commands using the first placement texture did not complete")
|
||||
return
|
||||
}
|
||||
guard let aliased = readBack(readPipe, alias, width, height) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
let blue = pack(0, 0, 255, 255)
|
||||
guard aliased.allSatisfy({ $0 == blue }) else {
|
||||
let wrong = aliased.filter { $0 != blue }
|
||||
report(label, false,
|
||||
"the BGRA alias did not observe RGBA bytes: wrong=\(wrong.count)/\(aliased.count)")
|
||||
return
|
||||
}
|
||||
guard fillHeapTexture(alias, SIMD4<Float>(0, 1, 0, 1)) else {
|
||||
report(label, false, "commands using the overlapping placement texture did not complete")
|
||||
return
|
||||
}
|
||||
guard let got = readBack(readPipe, alias, width, height) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
|
||||
let want = pack(0, 255, 0, 255)
|
||||
let bad = got.indices.filter { got[$0] != want }
|
||||
report(label, first.heapOffset == 0 && alias.heapOffset == 0 && bad.isEmpty,
|
||||
bad.isEmpty
|
||||
? "two live definitions at offset=0 executed sequentially and addressed the replacement"
|
||||
: "wrong=\(bad.count)/\(got.count) first=\(hex(got[bad[0]])) want=\(hex(want))")
|
||||
}
|
||||
|
||||
// The same overlap, between formats no single image can serve.
|
||||
//
|
||||
// `heap_texture_placement_overlap` aliases two 32-bit formats, which one
|
||||
// native image plus a reinterpreting view can answer. Nothing here can be:
|
||||
// rgba16Float and rgba8Unorm are different bit widths, so an implementation
|
||||
// that gives a range of storage one image and reinterprets it for the other
|
||||
// alias has no view to build and must refuse a binding the API defines.
|
||||
//
|
||||
// Metal leaves an alias's *contents* undefined after another alias writes, so
|
||||
// this claims nothing about bytes crossing between them. It claims only that
|
||||
// each live texture addresses its own definition: fill one, read it back, and
|
||||
// the value written through that texture is the value that texture reads.
|
||||
func heapTexturePlacementOverlapWidthCase() {
|
||||
let label = "heap_texture_placement_overlap_incompatible_widths"
|
||||
let width = 64
|
||||
let height = 64
|
||||
let wide = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba16Float,
|
||||
width: width,
|
||||
height: height,
|
||||
mipmapped: false)
|
||||
let narrow = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm,
|
||||
width: width,
|
||||
height: height,
|
||||
mipmapped: false)
|
||||
for descriptor in [wide, narrow] {
|
||||
descriptor.storageMode = .private
|
||||
descriptor.usage = [.shaderRead, .shaderWrite]
|
||||
}
|
||||
|
||||
let wideRequirement = dev.heapTextureSizeAndAlign(descriptor: wide)
|
||||
let narrowRequirement = dev.heapTextureSizeAndAlign(descriptor: narrow)
|
||||
guard wideRequirement.size > 0, wideRequirement.align > 0,
|
||||
narrowRequirement.size > 0, narrowRequirement.align > 0 else {
|
||||
skip(label, "the device reported no heap storage requirement for one texture")
|
||||
return
|
||||
}
|
||||
|
||||
let heapDescriptor = MTLHeapDescriptor()
|
||||
heapDescriptor.type = .placement
|
||||
heapDescriptor.storageMode = .private
|
||||
heapDescriptor.hazardTrackingMode = .untracked
|
||||
heapDescriptor.size = max(wideRequirement.size, narrowRequirement.size)
|
||||
guard let heap = dev.makeHeap(descriptor: heapDescriptor) else {
|
||||
report(label, false, "the placement heap could not be created")
|
||||
return
|
||||
}
|
||||
guard let wideTexture = heap.makeTexture(descriptor: wide, offset: 0) else {
|
||||
report(label, false, "the placement heap refused its rgba16Float texture")
|
||||
return
|
||||
}
|
||||
guard let narrowTexture = heap.makeTexture(descriptor: narrow, offset: 0) else {
|
||||
report(label, false, "the placement heap refused a live overlapping rgba8Unorm texture")
|
||||
return
|
||||
}
|
||||
|
||||
// Components of exactly 0 and 1 survive both storage formats and the
|
||||
// readback's fixed-point packing, so a mismatch is the alias and never the
|
||||
// arithmetic.
|
||||
guard fillHeapTexture(wideTexture, SIMD4<Float>(1, 0, 0, 1)) else {
|
||||
report(label, false, "commands using the rgba16Float alias did not complete")
|
||||
return
|
||||
}
|
||||
guard let wideGot = readBack(readPipe, wideTexture, width, height) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
let red = pack(255, 0, 0, 255)
|
||||
let wideBad = wideGot.indices.filter { wideGot[$0] != red }
|
||||
guard wideBad.isEmpty else {
|
||||
report(label, false,
|
||||
"the rgba16Float alias did not read its own write: "
|
||||
+ "wrong=\(wideBad.count)/\(wideGot.count) first=\(hex(wideGot[wideBad[0]]))")
|
||||
return
|
||||
}
|
||||
|
||||
guard fillHeapTexture(narrowTexture, SIMD4<Float>(0, 1, 0, 1)) else {
|
||||
report(label, false, "commands using the rgba8Unorm alias did not complete")
|
||||
return
|
||||
}
|
||||
guard let narrowGot = readBack(readPipe, narrowTexture, width, height) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
let green = pack(0, 255, 0, 255)
|
||||
let narrowBad = narrowGot.indices.filter { narrowGot[$0] != green }
|
||||
report(label,
|
||||
wideTexture.heapOffset == 0 && narrowTexture.heapOffset == 0 && narrowBad.isEmpty,
|
||||
narrowBad.isEmpty
|
||||
? "two live textures of different bit widths at offset=0 each addressed their own definition"
|
||||
: "the rgba8Unorm alias did not read its own write: "
|
||||
+ "wrong=\(narrowBad.count)/\(narrowGot.count) first=\(hex(narrowGot[narrowBad[0]]))")
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
private let indexedWidth = 64
|
||||
private let indexedHeight = 64
|
||||
private let indexedGreen = pack(0, 255, 0, 255)
|
||||
private let indexedBlack = pack(0, 0, 0, 255)
|
||||
|
||||
private func indexedPipeline() -> MTLRenderPipelineState? {
|
||||
let descriptor = MTLRenderPipelineDescriptor()
|
||||
descriptor.vertexFunction = library.makeFunction(name: "indexed_vs")
|
||||
descriptor.fragmentFunction = library.makeFunction(name: "solid_fs")
|
||||
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
|
||||
descriptor.inputPrimitiveTopology = .triangle
|
||||
return try? dev.makeRenderPipelineState(descriptor: descriptor)
|
||||
}
|
||||
|
||||
private func indexedPixels(name: String,
|
||||
positions: [SIMD2<Float>],
|
||||
encode: (MTLRenderCommandEncoder) -> Void) -> [UInt32]? {
|
||||
guard let pipeline = indexedPipeline() else {
|
||||
report(name, false, "render pipeline creation failed")
|
||||
return nil
|
||||
}
|
||||
let targetDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm,
|
||||
width: indexedWidth,
|
||||
height: indexedHeight,
|
||||
mipmapped: false)
|
||||
targetDescriptor.usage = [.renderTarget, .shaderRead]
|
||||
targetDescriptor.storageMode = .private
|
||||
guard let target = dev.makeTexture(descriptor: targetDescriptor),
|
||||
let vertices = dev.makeBuffer(
|
||||
bytes: positions,
|
||||
length: positions.count * MemoryLayout<SIMD2<Float>>.stride,
|
||||
options: .storageModeShared) else {
|
||||
report(name, false, "resource creation failed")
|
||||
return nil
|
||||
}
|
||||
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = target
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass)!
|
||||
encoder.setRenderPipelineState(pipeline)
|
||||
encoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
var green: [Float] = [0, 1, 0, 1]
|
||||
encoder.setFragmentBytes(&green, length: 16, index: 0)
|
||||
encode(encoder)
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
guard let pixels = readBack(readPipe, target, indexedWidth, indexedHeight) else {
|
||||
refused(name)
|
||||
return nil
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
private func instanceRelation(_ pixels: [UInt32]) -> (Bool, String) {
|
||||
let lit = pixels.filter { $0 == indexedGreen }.count
|
||||
let left = pixels[35 * indexedWidth + 18]
|
||||
let right = pixels[35 * indexedWidth + 46]
|
||||
let centre = pixels[35 * indexedWidth + 32]
|
||||
let ok = (300...520).contains(lit)
|
||||
&& left == indexedGreen
|
||||
&& right == indexedGreen
|
||||
&& centre == indexedBlack
|
||||
return (ok,
|
||||
"lit=\(lit) left=\(hex(left)) right=\(hex(right)) centre=\(hex(centre))")
|
||||
}
|
||||
|
||||
func indexedDrawCases() {
|
||||
let largeTriangle: [SIMD2<Float>] = [
|
||||
SIMD2(-0.75, -0.70), SIMD2(0.75, -0.70), SIMD2(0, 0.75),
|
||||
]
|
||||
|
||||
let controlName = "draw_nonindexed_shared_shader_control"
|
||||
guard let control = indexedPixels(name: controlName, positions: largeTriangle, encode: { encoder in
|
||||
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
|
||||
}) else { return }
|
||||
let controlLit = control.filter { $0 == indexedGreen }.count
|
||||
let controlOK = (850...1400).contains(controlLit)
|
||||
&& control[32 * indexedWidth + 32] == indexedGreen
|
||||
&& control[2 * indexedWidth + 2] == indexedBlack
|
||||
report(controlName, controlOK, "lit=\(controlLit)")
|
||||
|
||||
let uint16Name = "draw_indexed_uint16_offset_4"
|
||||
var indices16: [UInt16] = [99, 99, 0, 1, 2]
|
||||
let index16 = dev.makeBuffer(bytes: &indices16,
|
||||
length: indices16.count * MemoryLayout<UInt16>.stride,
|
||||
options: .storageModeShared)!
|
||||
if let pixels = indexedPixels(name: uint16Name, positions: largeTriangle, encode: { encoder in
|
||||
encoder.drawIndexedPrimitives(type: .triangle,
|
||||
indexCount: 3,
|
||||
indexType: .uint16,
|
||||
indexBuffer: index16,
|
||||
indexBufferOffset: 4)
|
||||
}) {
|
||||
let ok = pixels == control
|
||||
report(uint16Name, ok, ok ? "exactly matches non-indexed control"
|
||||
: "pixel differences=\(zip(pixels, control).filter { $0 != $1 }.count)")
|
||||
}
|
||||
|
||||
let uint32OffsetName = "draw_indexed_uint32_offset_4"
|
||||
var offsetIndices32: [UInt32] = [99, 0, 1, 2]
|
||||
let offsetIndex32 = dev.makeBuffer(bytes: &offsetIndices32,
|
||||
length: offsetIndices32.count * MemoryLayout<UInt32>.stride,
|
||||
options: .storageModeShared)!
|
||||
if let pixels = indexedPixels(name: uint32OffsetName, positions: largeTriangle, encode: { encoder in
|
||||
encoder.drawIndexedPrimitives(type: .triangle,
|
||||
indexCount: 3,
|
||||
indexType: .uint32,
|
||||
indexBuffer: offsetIndex32,
|
||||
indexBufferOffset: 4)
|
||||
}) {
|
||||
let ok = pixels == control
|
||||
report(uint32OffsetName, ok, ok ? "exactly matches non-indexed control"
|
||||
: "pixel differences=\(zip(pixels, control).filter { $0 != $1 }.count)")
|
||||
}
|
||||
|
||||
let baseVertexName = "draw_indexed_uint16_base_vertex_minus1"
|
||||
var baseIndices16: [UInt16] = [1, 2, 3]
|
||||
let baseIndex16 = dev.makeBuffer(bytes: &baseIndices16,
|
||||
length: baseIndices16.count * MemoryLayout<UInt16>.stride,
|
||||
options: .storageModeShared)!
|
||||
if let pixels = indexedPixels(name: baseVertexName, positions: largeTriangle, encode: { encoder in
|
||||
encoder.drawIndexedPrimitives(type: .triangle,
|
||||
indexCount: 3,
|
||||
indexType: .uint16,
|
||||
indexBuffer: baseIndex16,
|
||||
indexBufferOffset: 0,
|
||||
instanceCount: 1,
|
||||
baseVertex: -1,
|
||||
baseInstance: 0)
|
||||
}) {
|
||||
let ok = pixels == control
|
||||
report(baseVertexName, ok, ok ? "exactly matches non-indexed control"
|
||||
: "pixel differences=\(zip(pixels, control).filter { $0 != $1 }.count)")
|
||||
}
|
||||
|
||||
let uint32Name = "draw_indexed_uint32_offset_4_base_vertex_minus1"
|
||||
var indices32: [UInt32] = [99, 1, 2, 3]
|
||||
let index32 = dev.makeBuffer(bytes: &indices32,
|
||||
length: indices32.count * MemoryLayout<UInt32>.stride,
|
||||
options: .storageModeShared)!
|
||||
if let pixels = indexedPixels(name: uint32Name, positions: largeTriangle, encode: { encoder in
|
||||
encoder.drawIndexedPrimitives(type: .triangle,
|
||||
indexCount: 3,
|
||||
indexType: .uint32,
|
||||
indexBuffer: index32,
|
||||
indexBufferOffset: 4,
|
||||
instanceCount: 1,
|
||||
baseVertex: -1,
|
||||
baseInstance: 0)
|
||||
}) {
|
||||
let ok = pixels == control
|
||||
report(uint32Name, ok, ok ? "exactly matches non-indexed control"
|
||||
: "pixel differences=\(zip(pixels, control).filter { $0 != $1 }.count)")
|
||||
}
|
||||
|
||||
let instanceName = "draw_indexed_two_instances_base_instance_5"
|
||||
let smallTriangle: [SIMD2<Float>] = [
|
||||
SIMD2(-0.25, -0.40), SIMD2(0.25, -0.40), SIMD2(0, 0.40),
|
||||
]
|
||||
let nonindexedInstanceName = "draw_nonindexed_two_instances_base_instance_5"
|
||||
let nonindexedInstances = indexedPixels(
|
||||
name: nonindexedInstanceName, positions: smallTriangle, encode: { encoder in
|
||||
encoder.drawPrimitives(type: .triangle,
|
||||
vertexStart: 0,
|
||||
vertexCount: 3,
|
||||
instanceCount: 2,
|
||||
baseInstance: 5)
|
||||
})
|
||||
if let pixels = nonindexedInstances {
|
||||
let verdict = instanceRelation(pixels)
|
||||
report(nonindexedInstanceName, verdict.0, verdict.1)
|
||||
}
|
||||
|
||||
var instanceIndices: [UInt16] = [0, 1, 2]
|
||||
let instanceIndex = dev.makeBuffer(bytes: &instanceIndices,
|
||||
length: instanceIndices.count * MemoryLayout<UInt16>.stride,
|
||||
options: .storageModeShared)!
|
||||
if let pixels = indexedPixels(name: instanceName, positions: smallTriangle, encode: { encoder in
|
||||
encoder.drawIndexedPrimitives(type: .triangle,
|
||||
indexCount: 3,
|
||||
indexType: .uint16,
|
||||
indexBuffer: instanceIndex,
|
||||
indexBufferOffset: 0,
|
||||
instanceCount: 2,
|
||||
baseVertex: 0,
|
||||
baseInstance: 5)
|
||||
}) {
|
||||
let relation = instanceRelation(pixels)
|
||||
let matchesControl = nonindexedInstances.map { pixels == $0 } ?? false
|
||||
report(instanceName, relation.0 && matchesControl,
|
||||
"\(relation.1) matches_nonindexed=\(matchesControl)")
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import ObjectiveC
|
||||
|
||||
private typealias ICBRangeMessage = @convention(c) (
|
||||
AnyObject, Selector, AnyObject, NSRange
|
||||
) -> Void
|
||||
private typealias ICBCopyMessage = @convention(c) (
|
||||
AnyObject, Selector, AnyObject, NSRange, AnyObject, UInt
|
||||
) -> Void
|
||||
|
||||
private let objcMessage = dlsym(dlopen(nil, RTLD_NOW), "objc_msgSend")!
|
||||
|
||||
private func makeIndirectPipeline() -> MTLComputePipelineState? {
|
||||
let descriptor = MTLComputePipelineDescriptor()
|
||||
descriptor.computeFunction = library.makeFunction(name: "indirect_command_write")
|
||||
descriptor.supportIndirectCommandBuffers = true
|
||||
return try? dev.makeComputePipelineState(descriptor: descriptor,
|
||||
options: [], reflection: nil)
|
||||
}
|
||||
|
||||
private func resetCommands(_ encoder: MTLBlitCommandEncoder,
|
||||
_ buffer: MTLIndirectCommandBuffer,
|
||||
_ range: Range<Int>) {
|
||||
let send = unsafeBitCast(objcMessage, to: ICBRangeMessage.self)
|
||||
send(encoder as AnyObject, NSSelectorFromString("resetCommandsInBuffer:withRange:"),
|
||||
buffer as AnyObject, NSRange(location: range.lowerBound, length: range.count))
|
||||
}
|
||||
|
||||
private func optimizeCommands(_ encoder: MTLBlitCommandEncoder,
|
||||
_ buffer: MTLIndirectCommandBuffer,
|
||||
_ range: Range<Int>) {
|
||||
let send = unsafeBitCast(objcMessage, to: ICBRangeMessage.self)
|
||||
send(encoder as AnyObject, NSSelectorFromString("optimizeIndirectCommandBuffer:withRange:"),
|
||||
buffer as AnyObject, NSRange(location: range.lowerBound, length: range.count))
|
||||
}
|
||||
|
||||
private func copyCommands(_ encoder: MTLBlitCommandEncoder,
|
||||
_ source: MTLIndirectCommandBuffer,
|
||||
_ sourceRange: Range<Int>,
|
||||
_ destination: MTLIndirectCommandBuffer,
|
||||
_ destinationIndex: Int) {
|
||||
let send = unsafeBitCast(objcMessage, to: ICBCopyMessage.self)
|
||||
send(encoder as AnyObject,
|
||||
NSSelectorFromString("copyIndirectCommandBuffer:sourceRange:destination:destinationIndex:"),
|
||||
source as AnyObject,
|
||||
NSRange(location: sourceRange.lowerBound, length: sourceRange.count),
|
||||
destination as AnyObject,
|
||||
UInt(destinationIndex))
|
||||
}
|
||||
|
||||
private func makeComputeICB(_ pipe: MTLComputePipelineState,
|
||||
_ output: MTLBuffer,
|
||||
_ values: MTLBuffer,
|
||||
_ count: Int) -> MTLIndirectCommandBuffer? {
|
||||
let descriptor = MTLIndirectCommandBufferDescriptor()
|
||||
descriptor.commandTypes = .concurrentDispatch
|
||||
descriptor.inheritBuffers = false
|
||||
descriptor.inheritPipelineState = false
|
||||
descriptor.maxKernelBufferBindCount = 2
|
||||
guard let icb = dev.makeIndirectCommandBuffer(descriptor: descriptor,
|
||||
maxCommandCount: count,
|
||||
options: []) else {
|
||||
return nil
|
||||
}
|
||||
for index in 0..<count {
|
||||
let command = icb.indirectComputeCommandAt(index)
|
||||
command.setComputePipelineState(pipe)
|
||||
command.setKernelBuffer(output, offset: index * 4, at: 0)
|
||||
command.setKernelBuffer(values, offset: index * 4, at: 1)
|
||||
command.concurrentDispatchThreadgroups(MTLSize(width: 1, height: 1, depth: 1),
|
||||
threadsPerThreadgroup:
|
||||
MTLSize(width: 1, height: 1, depth: 1))
|
||||
}
|
||||
return icb
|
||||
}
|
||||
|
||||
private func executeComputeICB(_ icb: MTLIndirectCommandBuffer,
|
||||
_ output: MTLBuffer,
|
||||
_ values: MTLBuffer,
|
||||
_ count: Int) -> Bool {
|
||||
guard let commandBuffer = queue.makeCommandBuffer(),
|
||||
let encoder = commandBuffer.makeComputeCommandEncoder() else {
|
||||
return false
|
||||
}
|
||||
encoder.useResource(output, usage: .write)
|
||||
encoder.useResource(values, usage: .read)
|
||||
encoder.executeCommandsInBuffer(icb, range: 0..<count)
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
return commandBuffer.status == .completed
|
||||
}
|
||||
|
||||
func indirectCommandMutationCase() {
|
||||
let label = "indirect_command_reset_copy_optimize"
|
||||
let count = 3
|
||||
let byteCount = count * MemoryLayout<UInt32>.size
|
||||
guard let pipe = makeIndirectPipeline() else {
|
||||
report(label, false, "indirect-capable compute pipeline unavailable")
|
||||
return
|
||||
}
|
||||
guard let output = dev.makeBuffer(length: byteCount, options: .storageModeShared),
|
||||
let sourceValues = dev.makeBuffer(length: byteCount, options: .storageModeShared),
|
||||
let destinationValues = dev.makeBuffer(length: byteCount, options: .storageModeShared)
|
||||
else {
|
||||
report(label, false, "buffers unavailable")
|
||||
return
|
||||
}
|
||||
let sourceWords = sourceValues.contents().bindMemory(to: UInt32.self, capacity: count)
|
||||
let destinationWords = destinationValues.contents().bindMemory(to: UInt32.self, capacity: count)
|
||||
for index in 0..<count {
|
||||
sourceWords[index] = UInt32(11 * (index + 1))
|
||||
destinationWords[index] = UInt32(90 + index)
|
||||
}
|
||||
guard let source = makeComputeICB(pipe, output, sourceValues, count),
|
||||
let destination = makeComputeICB(pipe, output, destinationValues, count) else {
|
||||
report(label, false, "indirect command buffers unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
memset(output.contents(), 0, byteCount)
|
||||
guard executeComputeICB(source, output, sourceValues, count) else {
|
||||
report(label, false, "baseline indirect execution failed")
|
||||
return
|
||||
}
|
||||
let outputWords = output.contents().bindMemory(to: UInt32.self, capacity: count)
|
||||
let baseline = Array(UnsafeBufferPointer(start: outputWords, count: count))
|
||||
|
||||
guard let mutate = queue.makeCommandBuffer(),
|
||||
let blit = mutate.makeBlitCommandEncoder() else {
|
||||
report(label, false, "mutation blit encoder unavailable")
|
||||
return
|
||||
}
|
||||
resetCommands(blit, source, 1..<2)
|
||||
copyCommands(blit, source, 0..<count, destination, 0)
|
||||
optimizeCommands(blit, destination, 0..<count)
|
||||
blit.endEncoding()
|
||||
mutate.commit()
|
||||
mutate.waitUntilCompleted()
|
||||
guard mutate.status == .completed else {
|
||||
report(label, false, "mutation command buffer status=\(mutate.status.rawValue)")
|
||||
return
|
||||
}
|
||||
|
||||
memset(output.contents(), 0, byteCount)
|
||||
guard executeComputeICB(destination, output, destinationValues, count) else {
|
||||
report(label, false, "destination indirect execution failed")
|
||||
return
|
||||
}
|
||||
let mutated = Array(UnsafeBufferPointer(start: outputWords, count: count))
|
||||
let expectedBaseline: [UInt32] = [11, 22, 33]
|
||||
let expectedMutated: [UInt32] = [11, 0, 33]
|
||||
report(label, baseline == expectedBaseline && mutated == expectedMutated,
|
||||
"baseline=\(baseline) mutated=\(mutated)")
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// The indirect buffer begins one word into the allocation so this covers the
|
||||
// byte offset as well as the three MTLDispatchThreadgroupsIndirectArguments
|
||||
// counts. Metal multiplies those counts by threadsPerThreadgroup to form the
|
||||
// shader-visible grid.
|
||||
func indirectComputeDispatchCase() {
|
||||
let label = "compute_dispatch_threadgroups_indirect"
|
||||
let capacity = 64
|
||||
let expectedThreads = 12 * 4
|
||||
let byteCount = capacity * MemoryLayout<UInt32>.size
|
||||
|
||||
guard let output = dev.makeBuffer(length: byteCount, options: .storageModeShared),
|
||||
let observedGrid = dev.makeBuffer(length: 3 * MemoryLayout<UInt32>.size,
|
||||
options: .storageModeShared),
|
||||
let ran = dev.makeBuffer(length: MemoryLayout<UInt32>.size,
|
||||
options: .storageModeShared),
|
||||
let indirect = dev.makeBuffer(length: 5 * MemoryLayout<UInt32>.size,
|
||||
options: .storageModeShared) else {
|
||||
report(label, false, "buffer creation failed")
|
||||
return
|
||||
}
|
||||
|
||||
memset(output.contents(), 0, byteCount)
|
||||
memset(observedGrid.contents(), 0, 3 * MemoryLayout<UInt32>.size)
|
||||
memset(ran.contents(), 0, MemoryLayout<UInt32>.size)
|
||||
let arguments = indirect.contents().bindMemory(to: UInt32.self, capacity: 5)
|
||||
arguments[0] = 0xdeadbeef
|
||||
arguments[1] = 3
|
||||
arguments[2] = 2
|
||||
arguments[3] = 1
|
||||
arguments[4] = 0xcafebabe
|
||||
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeComputeCommandEncoder()!
|
||||
enc.setComputePipelineState(pipeline("indirect_threadgroups_write"))
|
||||
enc.setBuffer(output, offset: 0, index: 0)
|
||||
enc.setBuffer(observedGrid, offset: 0, index: 1)
|
||||
var outputCapacity = UInt32(capacity)
|
||||
enc.setBytes(&outputCapacity, length: MemoryLayout<UInt32>.size, index: 2)
|
||||
enc.setBuffer(ran, offset: 0, index: 4)
|
||||
enc.dispatchThreadgroups(
|
||||
indirectBuffer: indirect,
|
||||
indirectBufferOffset: MemoryLayout<UInt32>.size,
|
||||
threadsPerThreadgroup: MTLSize(width: 4, height: 2, depth: 1))
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
let ranWord = ran.contents().bindMemory(to: UInt32.self, capacity: 1)[0]
|
||||
guard ranWord != 0 else {
|
||||
report(label, false, "the indirect dispatch produced nothing — the device refused it")
|
||||
return
|
||||
}
|
||||
|
||||
let gridWords = observedGrid.contents().bindMemory(to: UInt32.self, capacity: 3)
|
||||
let grid = Array(UnsafeBufferPointer(start: gridWords, count: 3))
|
||||
let outputWords = output.contents().bindMemory(to: UInt32.self, capacity: capacity)
|
||||
let firstBad = (0..<capacity).first { index in
|
||||
let expected: UInt32 = index < expectedThreads ? 0xa5000000 | UInt32(index) : 0
|
||||
return outputWords[index] != expected
|
||||
}
|
||||
|
||||
report(label, grid == [12, 4, 1] && firstBad == nil,
|
||||
"groups=[3,2,1] local=[4,2,1] grid=\(grid) first_bad=\(firstBad.map(String.init) ?? "none")")
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// Shaderless integer attachment clears. These cases contain no guest shader,
|
||||
// so a native PASS / guest FAIL cannot be a shader-translation defect. The
|
||||
// private arm observes the stored Vulkan image through a blit; the shared arm
|
||||
// observes the clear-only publication into guest-visible texture bytes.
|
||||
|
||||
private let integerClearRed: UInt16 = 1
|
||||
private let integerClearGreen: UInt16 = 258
|
||||
|
||||
private func encodeIntegerClear(_ texture: MTLTexture, _ label: String) -> Bool {
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = texture
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(
|
||||
red: Double(integerClearRed),
|
||||
green: Double(integerClearGreen),
|
||||
blue: 0,
|
||||
alpha: 0)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
|
||||
guard let command = queue.makeCommandBuffer(),
|
||||
let encoder = command.makeRenderCommandEncoder(descriptor: pass) else {
|
||||
report(label, false, "clear-only render encoder creation failed")
|
||||
return false
|
||||
}
|
||||
encoder.endEncoding()
|
||||
command.commit()
|
||||
command.waitUntilCompleted()
|
||||
guard command.status == .completed else {
|
||||
report(label, false, "clear-only command failed: \(String(describing: command.error))")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private func verifyIntegerClear(_ words: UnsafePointer<UInt16>,
|
||||
texels: Int,
|
||||
_ label: String) {
|
||||
var first: (index: Int, red: UInt16, green: UInt16)?
|
||||
var wrong = 0
|
||||
for index in 0..<texels {
|
||||
let red = words[index * 2]
|
||||
let green = words[index * 2 + 1]
|
||||
if red != integerClearRed || green != integerClearGreen {
|
||||
wrong += 1
|
||||
if first == nil { first = (index, red, green) }
|
||||
}
|
||||
}
|
||||
if let first {
|
||||
report(label, false,
|
||||
"wrong=\(wrong)/\(texels) first=\(first.index) "
|
||||
+ "got=[\(first.red),\(first.green)] "
|
||||
+ "want=[\(integerClearRed),\(integerClearGreen)]")
|
||||
} else {
|
||||
report(label, true,
|
||||
"\(texels) RG16Uint texels retained [\(integerClearRed),\(integerClearGreen)]")
|
||||
}
|
||||
}
|
||||
|
||||
private func integerClearPrivateCase() {
|
||||
let label = "clear_only_rg16uint_private_store"
|
||||
let width = 64
|
||||
let height = 17
|
||||
let descriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rg16Uint, width: width, height: height, mipmapped: false)
|
||||
descriptor.storageMode = .private
|
||||
descriptor.usage = [.renderTarget]
|
||||
guard let texture = dev.makeTexture(descriptor: descriptor) else {
|
||||
report(label, false, "private RG16Uint render target creation failed")
|
||||
return
|
||||
}
|
||||
guard encodeIntegerClear(texture, label) else { return }
|
||||
|
||||
let bytesPerRow = width * 4
|
||||
let length = bytesPerRow * height
|
||||
guard let output = dev.makeBuffer(length: length, options: .storageModeShared),
|
||||
let command = queue.makeCommandBuffer(),
|
||||
let blit = command.makeBlitCommandEncoder() else {
|
||||
report(label, false, "private clear readback resource creation failed")
|
||||
return
|
||||
}
|
||||
memset(output.contents(), 0xEE, length)
|
||||
blit.copy(from: texture,
|
||||
sourceSlice: 0,
|
||||
sourceLevel: 0,
|
||||
sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
sourceSize: MTLSize(width: width, height: height, depth: 1),
|
||||
to: output,
|
||||
destinationOffset: 0,
|
||||
destinationBytesPerRow: bytesPerRow,
|
||||
destinationBytesPerImage: length)
|
||||
blit.endEncoding()
|
||||
command.commit()
|
||||
command.waitUntilCompleted()
|
||||
guard command.status == .completed else {
|
||||
report(label, false, "private clear blit failed: \(String(describing: command.error))")
|
||||
return
|
||||
}
|
||||
verifyIntegerClear(
|
||||
output.contents().bindMemory(to: UInt16.self, capacity: width * height * 2),
|
||||
texels: width * height,
|
||||
label)
|
||||
}
|
||||
|
||||
private func integerClearSharedCase() {
|
||||
let label = "clear_only_rg16uint_shared_store"
|
||||
let width = 60
|
||||
let height = 17
|
||||
let descriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rg16Uint, width: width, height: height, mipmapped: false)
|
||||
descriptor.storageMode = .shared
|
||||
descriptor.usage = [.renderTarget]
|
||||
guard let texture = dev.makeTexture(descriptor: descriptor) else {
|
||||
report(label, false, "shared RG16Uint render target creation failed")
|
||||
return
|
||||
}
|
||||
|
||||
let seed = [UInt16](repeating: 0xEEEE, count: width * height * 2)
|
||||
seed.withUnsafeBytes { bytes in
|
||||
texture.replace(
|
||||
region: MTLRegionMake2D(0, 0, width, height),
|
||||
mipmapLevel: 0,
|
||||
withBytes: bytes.baseAddress!,
|
||||
bytesPerRow: width * 4)
|
||||
}
|
||||
guard encodeIntegerClear(texture, label) else { return }
|
||||
|
||||
var output = [UInt16](repeating: 0xEEEE, count: width * height * 2)
|
||||
output.withUnsafeMutableBytes { bytes in
|
||||
texture.getBytes(
|
||||
bytes.baseAddress!,
|
||||
bytesPerRow: width * 4,
|
||||
from: MTLRegionMake2D(0, 0, width, height),
|
||||
mipmapLevel: 0)
|
||||
}
|
||||
output.withUnsafeBufferPointer { words in
|
||||
verifyIntegerClear(words.baseAddress!, texels: width * height, label)
|
||||
}
|
||||
}
|
||||
|
||||
func integerClearCases() {
|
||||
integerClearPrivateCase()
|
||||
integerClearSharedCase()
|
||||
}
|
||||
@@ -1,169 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
let formats: [Fmt] = [
|
||||
Fmt(name: "r8Unorm", mtl: .r8Unorm, bpp: 1) { b in pack(b[0], 0, 0, 255) },
|
||||
Fmt(name: "a8Unorm", mtl: .a8Unorm, bpp: 1) { b in pack(0, 0, 0, b[0]) },
|
||||
Fmt(name: "rg8Unorm", mtl: .rg8Unorm, bpp: 2) { b in pack(b[0], b[1], 0, 255) },
|
||||
Fmt(name: "rgba8Unorm", mtl: .rgba8Unorm, bpp: 4) { b in pack(b[0], b[1], b[2], b[3]) },
|
||||
Fmt(name: "bgra8Unorm", mtl: .bgra8Unorm, bpp: 4) { b in pack(b[2], b[1], b[0], b[3]) },
|
||||
]
|
||||
|
||||
func linearAliasCase(_ f: Fmt, _ w: Int, _ h: Int, pitch: Pitch, sampler: Bool) {
|
||||
let align = dev.minimumLinearTextureAlignment(for: f.mtl)
|
||||
let bpr = pitch.bytes(width: w, bpp: f.bpp, align: align)
|
||||
let label = "linear_\(f.name)_\(w)x\(h)_pitch_\(pitch.tag)\(sampler ? "_sampled" : "")"
|
||||
if bpr % align != 0 || bpr < w * f.bpp {
|
||||
skip(label, "pitch \(bpr) is not a multiple of this device's minimumLinearTextureAlignment=\(align)")
|
||||
return
|
||||
}
|
||||
guard let buf = dev.makeBuffer(length: bpr * h, options: .storageModeShared) else {
|
||||
report(label, false, "buffer allocation failed"); return
|
||||
}
|
||||
// Fill every byte, padding included, with a position-dependent pattern.
|
||||
// Padding gets a distinct value so a rail that folds it into the image
|
||||
// shows up as a wrong texel rather than as a plausible one.
|
||||
let base = buf.contents().bindMemory(to: UInt8.self, capacity: bpr * h)
|
||||
for y in 0..<h {
|
||||
for x in 0..<bpr {
|
||||
base[y * bpr + x] = UInt8((x &* 7 &+ y &* 13 &+ 11) & 0xFF)
|
||||
}
|
||||
}
|
||||
let d = MTLTextureDescriptor()
|
||||
d.textureType = .type2D
|
||||
d.pixelFormat = f.mtl
|
||||
d.width = w; d.height = h
|
||||
d.mipmapLevelCount = 1
|
||||
d.storageMode = .shared
|
||||
d.usage = sampler ? [.shaderRead] : [.shaderRead]
|
||||
guard let tex = buf.makeTexture(descriptor: d, offset: 0, bytesPerRow: bpr) else {
|
||||
report(label, false, "makeTexture returned nil"); return
|
||||
}
|
||||
guard let got = readBack(sampler ? samplePipe : readPipe, tex, w, h) else {
|
||||
refused(label); return
|
||||
}
|
||||
var bad: [(Int, Int)] = []
|
||||
var firstDetail = ""
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
var bytes = [UInt8](repeating: 0, count: f.bpp)
|
||||
for i in 0..<f.bpp { bytes[i] = base[y * bpr + x * f.bpp + i] }
|
||||
let want = f.expect(bytes)
|
||||
let have = got[y * w + x]
|
||||
if want != have {
|
||||
bad.append((x, y))
|
||||
if firstDetail.isEmpty {
|
||||
firstDetail = "first_bad=(\(x),\(y)) want=\(hex(want)) got=\(hex(have))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, bad.isEmpty,
|
||||
bad.isEmpty ? "\(w * h) texels exact"
|
||||
: "\(bad.count)/\(w * h) wrong \(firstDetail) \(badMap(bad, w, h))")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// B. Incremental CPU writes around GPU reads.
|
||||
//
|
||||
// The glyph-atlas pattern: draw with the texture, write more into the unused
|
||||
// part of the same allocation, draw again, through one texture that is never
|
||||
// recreated and never re-declared. The contract says the later writes are
|
||||
// visible; a rail that treats the first read as a snapshot fails here and
|
||||
// nowhere else.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The glyph-atlas lifecycle, per format and per stage.
|
||||
///
|
||||
/// Region A is written before the texture is ever read; region B only after the
|
||||
/// GPU has already read it once; then A is rewritten. One texture, never
|
||||
/// recreated, never re-declared. A rail that treats the first read as a
|
||||
/// snapshot fails here and nowhere else in this file.
|
||||
///
|
||||
/// **Run through both stages.** The type layer reaches the rasterizer as a
|
||||
/// *fragment* texture, and section F exists because a device may route a
|
||||
/// sampled guest image differently for the two stages. A compute-only version
|
||||
/// of this case cannot see a defect that lives on the draw path — and on this
|
||||
/// device `a8Unorm`, the format the type layer uses, is refused on the compute
|
||||
/// sampled rail outright, so the compute arm of the one format that matters
|
||||
/// most produces no reading at all. The fragment arm is the one that can.
|
||||
func incrementalCase(_ f: Fmt, viaFragment: Bool) {
|
||||
let w = 64, h = 32, half = 16
|
||||
let stage = viaFragment ? "fragment" : "compute"
|
||||
let prefix = "incremental_\(f.name)_\(stage)"
|
||||
let names = (first: "\(prefix)_first_read",
|
||||
append: "\(prefix)_append_visible",
|
||||
stable: "\(prefix)_untouched_stable",
|
||||
rewrite: "\(prefix)_rewrite_visible")
|
||||
let align = dev.minimumLinearTextureAlignment(for: f.mtl)
|
||||
let bpr = alignUp(w * f.bpp, align)
|
||||
guard let buf = dev.makeBuffer(length: bpr * h, options: .storageModeShared) else {
|
||||
report(names.first, false, "buffer allocation failed"); return
|
||||
}
|
||||
let base = buf.contents().bindMemory(to: UInt8.self, capacity: bpr * h)
|
||||
memset(buf.contents(), 0, bpr * h)
|
||||
|
||||
// Byte values chosen so no two phases share one, and none is zero: zero is
|
||||
// what an untouched region must read as, so a phase marker that collided
|
||||
// with it could not tell "not yet written" from "written and lost".
|
||||
let markA: UInt8 = 0x41, markB: UInt8 = 0x5A, markRewrite: UInt8 = 0x77
|
||||
func fill(_ rows: Range<Int>, _ value: UInt8) {
|
||||
for y in rows { for x in 0..<bpr { base[y * bpr + x] = value } }
|
||||
}
|
||||
func texel(_ value: UInt8) -> UInt32 { f.expect([UInt8](repeating: value, count: f.bpp)) }
|
||||
func read(_ tex: MTLTexture) -> [UInt32]? {
|
||||
viaFragment ? fragmentSample(tex, w, h) : readBack(readPipe, tex, w, h)
|
||||
}
|
||||
func rows(_ got: [UInt32], _ range: Range<Int>, _ want: UInt32) -> Bool {
|
||||
range.allSatisfy { y in (0..<w).allSatisfy { x in got[y * w + x] == want } }
|
||||
}
|
||||
|
||||
fill(0..<half, markA)
|
||||
let d = MTLTextureDescriptor()
|
||||
d.textureType = .type2D; d.pixelFormat = f.mtl
|
||||
d.width = w; d.height = h; d.mipmapLevelCount = 1
|
||||
d.storageMode = .shared; d.usage = [.shaderRead]
|
||||
guard let tex = buf.makeTexture(descriptor: d, offset: 0, bytesPerRow: bpr) else {
|
||||
report(names.first, false, "makeTexture nil"); return
|
||||
}
|
||||
|
||||
guard let first = read(tex) else {
|
||||
refused(names.first)
|
||||
for dependent in [names.append, names.stable, names.rewrite] {
|
||||
skipDependent(dependent, names.first)
|
||||
}
|
||||
return
|
||||
}
|
||||
let aOK = rows(first, 0..<half, texel(markA))
|
||||
let bZero = rows(first, half..<h, texel(0))
|
||||
report(names.first, aOK && bZero,
|
||||
aOK && bZero ? "region A present, region B still zero"
|
||||
: "A_ok=\(aOK) B_zero=\(bZero) sample=\(hex(first[0])) "
|
||||
+ "want_A=\(hex(texel(markA))) want_B=\(hex(texel(0)))")
|
||||
|
||||
// Region B: written only after the GPU has already read this texture once.
|
||||
fill(half..<h, markB)
|
||||
guard let second = read(tex) else {
|
||||
refused(names.append)
|
||||
skipDependent(names.stable, names.append)
|
||||
skipDependent(names.rewrite, names.append)
|
||||
return
|
||||
}
|
||||
let bNow = rows(second, half..<h, texel(markB))
|
||||
let aStill = rows(second, 0..<half, texel(markA))
|
||||
report(names.append, bNow,
|
||||
bNow ? "post-read append visible"
|
||||
: "append not visible, got=\(hex(second[half * w])) want=\(hex(texel(markB)))")
|
||||
report(names.stable, aStill,
|
||||
aStill ? "region A unchanged"
|
||||
: "region A moved, got=\(hex(second[0])) want=\(hex(texel(markA)))")
|
||||
|
||||
// And a rewrite of a region already read twice.
|
||||
fill(0..<half, markRewrite)
|
||||
guard let third = read(tex) else { refused(names.rewrite); return }
|
||||
let rewrite = rows(third, 0..<half, texel(markRewrite))
|
||||
report(names.rewrite, rewrite,
|
||||
rewrite ? "rewrite visible"
|
||||
: "rewrite not visible, got=\(hex(third[0])) want=\(hex(texel(markRewrite)))")
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
/// The same chain, uploaded by a blit from a buffer rather than by
|
||||
/// `replace(region:mipmapLevel:)`. Two different routes reach a level's
|
||||
/// storage, and a device can lose one and keep the other -- which is the
|
||||
/// difference between a broken texture-write path and a texture that has no
|
||||
/// levels above zero at all.
|
||||
func mipBlitCase() {
|
||||
let size = 64
|
||||
let levels = 7
|
||||
let d = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm,
|
||||
width: size, height: size, mipmapped: true)
|
||||
d.mipmapLevelCount = levels
|
||||
d.storageMode = .private
|
||||
d.usage = [.shaderRead, .shaderWrite]
|
||||
guard let tex = dev.makeTexture(descriptor: d) else {
|
||||
report("mip_blit_create", false, "makeTexture nil"); return
|
||||
}
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let blit = cb.makeBlitCommandEncoder()!
|
||||
var staging: [MTLBuffer] = []
|
||||
for l in 0..<levels {
|
||||
let dim = max(1, size >> l)
|
||||
let marker = UInt8(0x10 + l * 0x11)
|
||||
let bpr = dim * 4
|
||||
let buf = dev.makeBuffer(length: bpr * dim, options: .storageModeShared)!
|
||||
memset(buf.contents(), Int32(marker), bpr * dim)
|
||||
staging.append(buf)
|
||||
blit.copy(from: buf, sourceOffset: 0,
|
||||
sourceBytesPerRow: bpr, sourceBytesPerImage: bpr * dim,
|
||||
sourceSize: MTLSize(width: dim, height: dim, depth: 1),
|
||||
to: tex, destinationSlice: 0, destinationLevel: l,
|
||||
destinationOrigin: MTLOrigin(x: 0, y: 0, z: 0))
|
||||
}
|
||||
blit.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
for l in 0..<levels {
|
||||
let dim = max(1, size >> l)
|
||||
let marker = UInt8(0x10 + l * 0x11)
|
||||
let want = pack(marker, marker, marker, marker)
|
||||
guard let got = readBack(fetchLevelPipe, tex, dim, dim, level: l) else {
|
||||
refused("mip_blit_level_\(l)_size\(dim)"); continue
|
||||
}
|
||||
let ok = got.allSatisfy { $0 == want }
|
||||
report("mip_blit_level_\(l)_size\(dim)", ok,
|
||||
ok ? "\(dim * dim) texels are level \(l)'s marker"
|
||||
: "want=\(hex(want)) got=\(hex(got[0]))")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// F. Vertex-buffer content across submissions.
|
||||
//
|
||||
// A draw's geometry comes out of a buffer the guest owns and rewrites between
|
||||
// frames. If a device caches that window and serves a stale copy, the geometry
|
||||
// is drawn in last frame's place -- which for a label layer means glyph quads
|
||||
// landing where nothing is composited, i.e. absence over correct terrain.
|
||||
// Two submissions with different vertex data, each verified.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func vertexBufferCase() {
|
||||
let w = 64, h = 64
|
||||
let fmt = MTLPixelFormat.bgra8Unorm
|
||||
guard let pipe = makeRenderPipeline("solid_fs", fmt) else {
|
||||
report("vb_pipeline", false, "pipeline failed"); return
|
||||
}
|
||||
let td = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: fmt, width: w, height: h, mipmapped: false)
|
||||
td.usage = [.renderTarget, .shaderRead]
|
||||
td.storageMode = .private
|
||||
let rt = dev.makeTexture(descriptor: td)!
|
||||
let verts = dev.makeBuffer(length: 4 * 4 * 4, options: .storageModeShared)!
|
||||
var colour: [Float] = [1, 1, 1, 1]
|
||||
|
||||
// Draw a strip covering only the requested x half, then check which half of
|
||||
// the target changed.
|
||||
func drawHalf(_ leftHalf: Bool, _ tag: String) {
|
||||
let x0: Float = leftHalf ? -1 : 0
|
||||
let x1: Float = leftHalf ? 0 : 1
|
||||
let data: [Float] = [x0, -1, 0, 1, x1, -1, 1, 1, x0, 1, 0, 0, x1, 1, 1, 0]
|
||||
memcpy(verts.contents(), data, data.count * 4)
|
||||
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
enc.setFragmentBytes(&colour, length: 16, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
guard let got = readBack(readPipe, rt, w, h) else {
|
||||
refused("vb_\(tag)"); return
|
||||
}
|
||||
let white = pack(255, 255, 255, 255)
|
||||
let black = pack(0, 0, 0, 255)
|
||||
// Sample well inside each half so rasterization edges are not the test.
|
||||
let leftPx = got[(h / 2) * w + (w / 4)]
|
||||
let rightPx = got[(h / 2) * w + (3 * w / 4)]
|
||||
let want = leftHalf ? (white, black) : (black, white)
|
||||
let ok = leftPx == want.0 && rightPx == want.1
|
||||
report("vb_\(tag)", ok,
|
||||
ok ? "geometry landed in the \(leftHalf ? "left" : "right") half"
|
||||
: "left=\(hex(leftPx)) right=\(hex(rightPx)) wanted left=\(hex(want.0)) right=\(hex(want.1))")
|
||||
}
|
||||
drawHalf(true, "first_submission_left")
|
||||
drawHalf(false, "second_submission_right")
|
||||
drawHalf(true, "third_submission_left_again")
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
/// A Store-only multisample attachment remains a multisample texture after its
|
||||
/// encoder ends. Four unequal samples make preservation distinguishable from
|
||||
/// an implicit resolve, and the later command buffer forces the observation
|
||||
/// across the encoder/submission lifetime boundary.
|
||||
/// Both multisample-store cases run the same render and differ only in where the
|
||||
/// readback kernel's sample count comes from. See `read_ms_texels_host_count`
|
||||
/// for why that difference is worth two cases: one result line cannot say
|
||||
/// whether a device served the `texture2d_ms` bind, because a bind that was
|
||||
/// refused and a bind whose sample count came back as 1 both leave samples 1
|
||||
/// and up unwritten.
|
||||
func multisampleStoreCase() {
|
||||
multisampleStoreCase(label: "msaa4_color_store_no_resolve", countFromTexture: true)
|
||||
multisampleStoreCase(label: "msaa4_color_store_host_sample_count", countFromTexture: false)
|
||||
}
|
||||
|
||||
func multisampleStoreCase(label: String, countFromTexture: Bool) {
|
||||
let w = 8, h = 8, samples = 4
|
||||
guard dev.supportsTextureSampleCount(samples) else {
|
||||
skip(label, "device does not report 4x texture sampling")
|
||||
return
|
||||
}
|
||||
|
||||
let descriptor = MTLRenderPipelineDescriptor()
|
||||
descriptor.vertexFunction = library.makeFunction(name: "quad_vs")
|
||||
descriptor.fragmentFunction = library.makeFunction(name: "sample_id_fs")
|
||||
descriptor.colorAttachments[0].pixelFormat = .rgba8Unorm
|
||||
descriptor.rasterSampleCount = samples
|
||||
guard let renderPipeline = try? dev.makeRenderPipelineState(descriptor: descriptor) else {
|
||||
report(label, false, "4x render pipeline creation failed")
|
||||
return
|
||||
}
|
||||
|
||||
let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false)
|
||||
textureDescriptor.textureType = .type2DMultisample
|
||||
textureDescriptor.sampleCount = samples
|
||||
textureDescriptor.storageMode = .private
|
||||
textureDescriptor.usage = [.renderTarget, .shaderRead]
|
||||
guard let texture = dev.makeTexture(descriptor: textureDescriptor),
|
||||
let vertices = dev.makeBuffer(bytes: quadVerts,
|
||||
length: quadVerts.count * MemoryLayout<Float>.size,
|
||||
options: .storageModeShared) else {
|
||||
report(label, false, "4x resource creation failed")
|
||||
return
|
||||
}
|
||||
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = texture
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let producer = queue.makeCommandBuffer()!
|
||||
let render = producer.makeRenderCommandEncoder(descriptor: pass)!
|
||||
render.setRenderPipelineState(renderPipeline)
|
||||
render.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
render.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
render.endEncoding()
|
||||
producer.commit()
|
||||
producer.waitUntilCompleted()
|
||||
|
||||
guard let got = readBackMultisample(texture, w, h, samples: samples,
|
||||
countFromTexture: countFromTexture) else {
|
||||
refused(label)
|
||||
return
|
||||
}
|
||||
let expected = [
|
||||
pack(255, 0, 0, 255),
|
||||
pack(0, 255, 0, 255),
|
||||
pack(0, 0, 255, 255),
|
||||
pack(255, 255, 255, 255),
|
||||
]
|
||||
var wrong = 0
|
||||
var first: (pixel: Int, sample: Int, got: UInt32, want: UInt32)?
|
||||
var badPixels: [(Int, Int)] = []
|
||||
for pixel in 0..<(w * h) {
|
||||
var pixelWrong = false
|
||||
for sample in 0..<samples {
|
||||
let index = pixel * samples + sample
|
||||
if got[index] != expected[sample] {
|
||||
wrong += 1
|
||||
pixelWrong = true
|
||||
if first == nil {
|
||||
first = (pixel, sample, got[index], expected[sample])
|
||||
}
|
||||
}
|
||||
}
|
||||
if pixelWrong { badPixels.append((pixel % w, pixel / w)) }
|
||||
}
|
||||
|
||||
if let first {
|
||||
report(label, false,
|
||||
"wrong=\(wrong)/\(got.count) first_pixel=\(first.pixel) "
|
||||
+ "sample=\(first.sample) got=\(hex(first.got)) want=\(hex(first.want)) "
|
||||
+ badMap(badPixels, w, h))
|
||||
} else {
|
||||
report(label, true, "\(w * h) pixels retained four distinct samples")
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// H. `replaceRegion:` into a sampled texture, sub-rect, across submissions.
|
||||
//
|
||||
// Section B writes an atlas through the `MTLBuffer` its texture aliases. That
|
||||
// is one of the two ways a glyph atlas is filled and it is not the one a
|
||||
// CPU-rasterized layer uses: CoreGraphics rasterizes into its own bitmap and
|
||||
// the result reaches Metal through
|
||||
// `-[MTLTexture replaceRegion:mipmapLevel:withBytes:bytesPerRow:]`, on a plain
|
||||
// texture with no buffer behind it. That is a different record on the wire and
|
||||
// a different rail in the device, and nothing in this file reached it except
|
||||
// inside the mip cases, where a separate defect masks the result.
|
||||
//
|
||||
// The sub-rect is the point. An atlas grows by replacing the strip it just
|
||||
// rasterized, leaving every glyph already in it untouched, so a rail that
|
||||
// re-uploads the whole texture, or uploads the strip to the wrong origin, or
|
||||
// drops the second replace because it already has the resource resident, loses
|
||||
// exactly the glyphs that were there before — which is type that renders once
|
||||
// and then does not.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func replaceRegionCase(_ f: Fmt, viaFragment: Bool) {
|
||||
let w = 64, h = 32, half = 16
|
||||
let stage = viaFragment ? "fragment" : "compute"
|
||||
let prefix = "replace_\(f.name)_\(stage)"
|
||||
let names = (first: "\(prefix)_first_read",
|
||||
append: "\(prefix)_append_visible",
|
||||
stable: "\(prefix)_untouched_stable",
|
||||
rewrite: "\(prefix)_rewrite_visible")
|
||||
|
||||
let d = MTLTextureDescriptor()
|
||||
d.textureType = .type2D; d.pixelFormat = f.mtl
|
||||
d.width = w; d.height = h; d.mipmapLevelCount = 1
|
||||
// Not buffer-backed, and not `.private`: `replaceRegion` is a CPU write and
|
||||
// needs storage the CPU can reach. This is what a rasterized atlas is.
|
||||
d.storageMode = .shared; d.usage = [.shaderRead]
|
||||
guard let tex = dev.makeTexture(descriptor: d) else {
|
||||
report(names.first, false, "makeTexture nil"); return
|
||||
}
|
||||
|
||||
let markA: UInt8 = 0x41, markB: UInt8 = 0x5A, markRewrite: UInt8 = 0x77
|
||||
// Every texel of the strip, tight — `replaceRegion` takes the caller's own
|
||||
// pitch and has no alignment rule of its own.
|
||||
func replace(_ y0: Int, _ rows: Int, _ value: UInt8) {
|
||||
let pitch = w * f.bpp
|
||||
let bytes = [UInt8](repeating: value, count: pitch * rows)
|
||||
bytes.withUnsafeBytes { raw in
|
||||
tex.replace(region: MTLRegionMake2D(0, y0, w, rows),
|
||||
mipmapLevel: 0, withBytes: raw.baseAddress!, bytesPerRow: pitch)
|
||||
}
|
||||
}
|
||||
func texel(_ value: UInt8) -> UInt32 { f.expect([UInt8](repeating: value, count: f.bpp)) }
|
||||
func read() -> [UInt32]? {
|
||||
viaFragment ? fragmentSample(tex, w, h) : readBack(readPipe, tex, w, h)
|
||||
}
|
||||
func rows(_ got: [UInt32], _ range: Range<Int>, _ want: UInt32) -> Bool {
|
||||
range.allSatisfy { y in (0..<w).allSatisfy { x in got[y * w + x] == want } }
|
||||
}
|
||||
// Where a wrong sub-rect landed, which a count alone cannot say.
|
||||
func wrongRows(_ got: [UInt32], _ range: Range<Int>, _ want: UInt32) -> String {
|
||||
let bad = range.filter { y in !(0..<w).allSatisfy { x in got[y * w + x] == want } }
|
||||
guard let firstBad = bad.first else { return "" }
|
||||
return " wrong_rows=\(bad.count)/\(range.count) first=\(firstBad) " +
|
||||
"got=\(hex(got[firstBad * w])) want=\(hex(want))"
|
||||
}
|
||||
|
||||
// A texture from `makeTexture` has undefined contents, so region B is
|
||||
// written once here to establish a known floor. Only the *later* writes are
|
||||
// the thing under test.
|
||||
replace(0, h, 0)
|
||||
replace(0, half, markA)
|
||||
guard let first = read() else {
|
||||
refused(names.first)
|
||||
for dependent in [names.append, names.stable, names.rewrite] {
|
||||
skipDependent(dependent, names.first)
|
||||
}
|
||||
return
|
||||
}
|
||||
let aOK = rows(first, 0..<half, texel(markA))
|
||||
let bZero = rows(first, half..<h, texel(0))
|
||||
report(names.first, aOK && bZero,
|
||||
aOK && bZero ? "the replaced strip is present and the rest is still zero"
|
||||
: "A_ok=\(aOK) B_zero=\(bZero)"
|
||||
+ wrongRows(first, 0..<half, texel(markA))
|
||||
+ wrongRows(first, half..<h, texel(0)))
|
||||
|
||||
// The atlas grows: a strip replaced after the GPU has already sampled it.
|
||||
replace(half, h - half, markB)
|
||||
guard let second = read() else {
|
||||
refused(names.append)
|
||||
skipDependent(names.stable, names.append)
|
||||
skipDependent(names.rewrite, names.append)
|
||||
return
|
||||
}
|
||||
report(names.append, rows(second, half..<h, texel(markB)),
|
||||
rows(second, half..<h, texel(markB))
|
||||
? "a strip replaced after a read is visible"
|
||||
: "append not visible" + wrongRows(second, half..<h, texel(markB)))
|
||||
report(names.stable, rows(second, 0..<half, texel(markA)),
|
||||
rows(second, 0..<half, texel(markA))
|
||||
? "the glyphs already in the atlas are untouched"
|
||||
: "the earlier strip moved" + wrongRows(second, 0..<half, texel(markA)))
|
||||
|
||||
// And a strip rewritten in place, which is how an atlas recycles a slot.
|
||||
replace(0, half, markRewrite)
|
||||
guard let third = read() else { refused(names.rewrite); return }
|
||||
report(names.rewrite, rows(third, 0..<half, texel(markRewrite)),
|
||||
rows(third, 0..<half, texel(markRewrite))
|
||||
? "a strip rewritten in place is visible"
|
||||
: "rewrite not visible" + wrongRows(third, 0..<half, texel(markRewrite)))
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
/// Pipeline information is construction-owned state. In particular, the
|
||||
/// indirect-command support bit follows the descriptor used to compile the
|
||||
/// object, while static threadgroup memory follows the compiled kernel rather
|
||||
/// than a device-wide limit.
|
||||
func pipelineInformationCase() {
|
||||
let name = "pipeline_information_lifetime"
|
||||
let source = """
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
|
||||
kernel void plain_kernel(device uint *out [[buffer(0)]],
|
||||
uint tid [[thread_position_in_grid]]) {
|
||||
if (tid == 0) out[0] = 1;
|
||||
}
|
||||
|
||||
kernel void static_kernel(device uint *out [[buffer(0)]],
|
||||
uint tid [[thread_position_in_grid]]) {
|
||||
threadgroup uint values[17];
|
||||
if (tid < 17) values[tid] = tid;
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
if (tid == 0) out[0] = values[16];
|
||||
}
|
||||
|
||||
struct VertexOut { float4 position [[position]]; };
|
||||
vertex VertexOut info_vertex(uint id [[vertex_id]]) {
|
||||
VertexOut out;
|
||||
out.position = float4(id == 0 ? -1.0 : 1.0,
|
||||
id == 2 ? 1.0 : -1.0, 0.0, 1.0);
|
||||
return out;
|
||||
}
|
||||
fragment float4 info_fragment() { return float4(1.0); }
|
||||
"""
|
||||
|
||||
do {
|
||||
let infoLibrary = try dev.makeLibrary(source: source, options: nil)
|
||||
func compute(_ function: String, _ indirect: Bool) throws -> MTLComputePipelineState {
|
||||
let descriptor = MTLComputePipelineDescriptor()
|
||||
descriptor.computeFunction = infoLibrary.makeFunction(name: function)
|
||||
descriptor.supportIndirectCommandBuffers = indirect
|
||||
return try dev.makeComputePipelineState(
|
||||
descriptor: descriptor,
|
||||
options: [],
|
||||
reflection: nil)
|
||||
}
|
||||
func render(_ indirect: Bool) throws -> MTLRenderPipelineState {
|
||||
let descriptor = MTLRenderPipelineDescriptor()
|
||||
descriptor.vertexFunction = infoLibrary.makeFunction(name: "info_vertex")
|
||||
descriptor.fragmentFunction = infoLibrary.makeFunction(name: "info_fragment")
|
||||
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
|
||||
descriptor.supportIndirectCommandBuffers = indirect
|
||||
return try dev.makeRenderPipelineState(descriptor: descriptor)
|
||||
}
|
||||
|
||||
let plain = try compute("plain_kernel", false)
|
||||
let staticMemory = try compute("static_kernel", false)
|
||||
let indirectCompute = try compute("plain_kernel", true)
|
||||
let directRender = try render(false)
|
||||
let indirectRender = try render(true)
|
||||
let ok = plain.maxTotalThreadsPerThreadgroup > 0
|
||||
&& plain.threadExecutionWidth > 0
|
||||
&& plain.staticThreadgroupMemoryLength < staticMemory.staticThreadgroupMemoryLength
|
||||
&& !plain.supportIndirectCommandBuffers
|
||||
&& indirectCompute.supportIndirectCommandBuffers
|
||||
&& !directRender.supportIndirectCommandBuffers
|
||||
&& indirectRender.supportIndirectCommandBuffers
|
||||
&& directRender.imageblockSampleLength > 0
|
||||
report(
|
||||
name,
|
||||
ok,
|
||||
"compute_max=\(plain.maxTotalThreadsPerThreadgroup) "
|
||||
+ "width=\(plain.threadExecutionWidth) "
|
||||
+ "static_plain=\(plain.staticThreadgroupMemoryLength) "
|
||||
+ "static_declared=\(staticMemory.staticThreadgroupMemoryLength) "
|
||||
+ "render_imageblock=\(directRender.imageblockSampleLength)")
|
||||
} catch {
|
||||
report(name, false, "pipeline creation failed: \(error)")
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// A producer and consumer in one render encoder, separated only by the
|
||||
// resource barrier whose contract is under test. Alternating the token makes a
|
||||
// stale value a defined wrong answer after the first round.
|
||||
func renderBarrierCase() {
|
||||
let w = 256, h = 256
|
||||
let fmt = MTLPixelFormat.bgra8Unorm
|
||||
guard let writePipe = makeRenderPipeline("render_barrier_write_fs", fmt),
|
||||
let consumerPipe = makeRenderPipeline("render_barrier_read_fs", fmt) else {
|
||||
report("render_barrier_resource_fragment", false, "pipeline failed")
|
||||
return
|
||||
}
|
||||
|
||||
let targetDesc = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: fmt, width: w, height: h, mipmapped: false)
|
||||
targetDesc.usage = [.renderTarget, .shaderRead]
|
||||
targetDesc.storageMode = .private
|
||||
guard let target = dev.makeTexture(descriptor: targetDesc),
|
||||
let words = dev.makeBuffer(length: w * h * MemoryLayout<UInt32>.size,
|
||||
options: .storageModePrivate),
|
||||
let vertices = dev.makeBuffer(bytes: quadVerts,
|
||||
length: quadVerts.count * MemoryLayout<Float>.size,
|
||||
options: .storageModeShared) else {
|
||||
report("render_barrier_resource_fragment", false, "resource creation failed")
|
||||
return
|
||||
}
|
||||
|
||||
let green = pack(0, 255, 0, 255)
|
||||
for round in 0..<8 {
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = target
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
|
||||
var params = SIMD2<UInt32>(UInt32(w), round.isMultiple(of: 2) ? 0x13579BDF : 0x2468ACE0)
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
enc.setFragmentBuffer(words, offset: 0, index: 0)
|
||||
enc.setFragmentBytes(¶ms, length: MemoryLayout<SIMD2<UInt32>>.size, index: 1)
|
||||
|
||||
enc.setRenderPipelineState(writePipe)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.memoryBarrier(resources: [words], after: .fragment, before: .fragment)
|
||||
enc.setRenderPipelineState(consumerPipe)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
guard let got = readBack(readPipe, target, w, h) else {
|
||||
refused("render_barrier_resource_fragment")
|
||||
return
|
||||
}
|
||||
if let bad = got.firstIndex(where: { $0 != green }) {
|
||||
report("render_barrier_resource_fragment", false,
|
||||
"round=\(round) pixel=\(bad) got=\(hex(got[bad])) want=\(hex(green))")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
report("render_barrier_resource_fragment", true,
|
||||
"8 alternating producer/consumer rounds were visible")
|
||||
}
|
||||
@@ -1,423 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// One pass over `rt`. `scissor` nil means the whole target.
|
||||
func sharedTargetPass(_ rt: MTLTexture, _ pipe: MTLRenderPipelineState,
|
||||
_ verts: MTLBuffer, _ colour: SIMD4<Float>,
|
||||
load: Bool, clear: MTLClearColor, scissor: MTLScissorRect?) {
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = load ? .load : .clear
|
||||
pass.colorAttachments[0].clearColor = clear
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
var c = colour
|
||||
enc.setFragmentBytes(&c, length: 16, index: 0)
|
||||
if let s = scissor { enc.setScissorRect(s) }
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
}
|
||||
|
||||
let magenta = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
|
||||
let magentaTexel = pack(255, 0, 255, 255)
|
||||
|
||||
let greenTexel = pack(0, 255, 0, 255)
|
||||
|
||||
let blueTexel = pack(0, 0, 255, 255)
|
||||
|
||||
func sharedTargetCases(_ w: Int, _ h: Int) {
|
||||
let dims = "\(w)x\(h)"
|
||||
let names = (draw: "srt_draw_\(dims)",
|
||||
load: "srt_load_preserves_\(dims)",
|
||||
scissor: "srt_scissor_keeps_rest_\(dims)",
|
||||
sample: "srt_sample_after_render_\(dims)")
|
||||
|
||||
guard let pipe = solidPipeline else {
|
||||
for n in [names.draw, names.load, names.scissor, names.sample] {
|
||||
report(n, false, "solid pipeline unavailable")
|
||||
}
|
||||
return
|
||||
}
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
// 1. Does a draw into guest-owned pages land at all.
|
||||
guard let rt = sharedRenderTarget(w, h, names.draw) else {
|
||||
for n in [names.load, names.scissor, names.sample] { skipDependent(n, names.draw) }
|
||||
return
|
||||
}
|
||||
sharedTargetPass(rt, pipe, verts, SIMD4<Float>(0, 1, 0, 1),
|
||||
load: false, clear: magenta, scissor: nil)
|
||||
guard let drawn = readBack(readPipe, rt, w, h) else {
|
||||
refused(names.draw)
|
||||
for n in [names.load, names.scissor, names.sample] { skipDependent(n, names.draw) }
|
||||
return
|
||||
}
|
||||
var drawBad: [(Int, Int)] = []
|
||||
for y in 0..<h { for x in 0..<w where drawn[y * w + x] != greenTexel {
|
||||
drawBad.append((x, y)) } }
|
||||
report(names.draw, drawBad.isEmpty,
|
||||
drawBad.isEmpty ? "the whole guest-backed target is the drawn colour"
|
||||
: "wrong=\(drawBad.count)/\(w * h) "
|
||||
+ "first=\(hex(drawn[drawBad[0].1 * w + drawBad[0].0])) "
|
||||
+ "want=\(hex(greenTexel))" + badMap(drawBad, w, h))
|
||||
|
||||
// 2. A second pass with `.load` over the bottom half must leave the top
|
||||
// half exactly as the first pass left it. A device that seeds `.load`
|
||||
// from a copy taken before the first pass loses the top half here.
|
||||
guard let rt2 = sharedRenderTarget(w, h, names.load) else {
|
||||
for n in [names.scissor, names.sample] { skipDependent(n, names.load) }
|
||||
return
|
||||
}
|
||||
let half = h / 2
|
||||
sharedTargetPass(rt2, pipe, verts, SIMD4<Float>(0, 1, 0, 1), load: false,
|
||||
clear: magenta, scissor: MTLScissorRect(x: 0, y: 0, width: w, height: half))
|
||||
sharedTargetPass(rt2, pipe, verts, SIMD4<Float>(0, 0, 1, 1), load: true,
|
||||
clear: magenta,
|
||||
scissor: MTLScissorRect(x: 0, y: half, width: w, height: h - half))
|
||||
if let got = readBack(readPipe, rt2, w, h) {
|
||||
var topBad: [(Int, Int)] = []
|
||||
var botBad: [(Int, Int)] = []
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let have = got[y * w + x]
|
||||
if y < half {
|
||||
if have != greenTexel { topBad.append((x, y)) }
|
||||
} else if have != blueTexel { botBad.append((x, y)) }
|
||||
}
|
||||
}
|
||||
let ok = topBad.isEmpty && botBad.isEmpty
|
||||
report(names.load, ok,
|
||||
ok ? "the second pass added to what the first pass left"
|
||||
: "first_pass_lost=\(topBad.count) second_pass_wrong=\(botBad.count)"
|
||||
+ badMap(topBad, w, h))
|
||||
} else {
|
||||
refused(names.load)
|
||||
}
|
||||
|
||||
// 3. A scissored write into the middle of a loaded target. Only that
|
||||
// rectangle may change; a stride the guest never agreed to shows up as
|
||||
// the green landing on the wrong rows, which the untouched-count says.
|
||||
guard let rt3 = sharedRenderTarget(w, h, names.scissor) else {
|
||||
skipDependent(names.sample, names.scissor); return
|
||||
}
|
||||
sharedTargetPass(rt3, pipe, verts, SIMD4<Float>(1, 0, 1, 1),
|
||||
load: false, clear: magenta, scissor: nil)
|
||||
let rx = w / 4, ry = h / 4
|
||||
let rw = max(1, w / 2), rh = max(1, h / 2)
|
||||
sharedTargetPass(rt3, pipe, verts, SIMD4<Float>(0, 1, 0, 1), load: true, clear: magenta,
|
||||
scissor: MTLScissorRect(x: rx, y: ry, width: rw, height: rh))
|
||||
if let got = readBack(readPipe, rt3, w, h) {
|
||||
var inBad: [(Int, Int)] = []
|
||||
var outBad: [(Int, Int)] = []
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let inside = x >= rx && x < rx + rw && y >= ry && y < ry + rh
|
||||
let have = got[y * w + x]
|
||||
if inside {
|
||||
if have != greenTexel { inBad.append((x, y)) }
|
||||
} else if have != magentaTexel { outBad.append((x, y)) }
|
||||
}
|
||||
}
|
||||
let ok = inBad.isEmpty && outBad.isEmpty
|
||||
report(names.scissor, ok,
|
||||
ok ? "the scissored write landed on exactly its own rows"
|
||||
: "rect_wrong=\(inBad.count) outside_clobbered=\(outBad.count) "
|
||||
+ "rect=(\(rx),\(ry) \(rw)x\(rh))" + badMap(outBad, w, h))
|
||||
} else {
|
||||
refused(names.scissor)
|
||||
}
|
||||
|
||||
// 4. The crossover: the same allocation, rendered into by one pass and
|
||||
// sampled by the next. A device that keeps a target and a sampled view
|
||||
// of one allocation as two images has to make the render visible to the
|
||||
// read, and this is the case that says whether it did.
|
||||
guard let texPipe = texPipeline else {
|
||||
report(names.sample, false, "texture pipeline unavailable"); return
|
||||
}
|
||||
guard let src = sharedRenderTarget(w, h, names.sample) else { return }
|
||||
sharedTargetPass(src, pipe, verts, SIMD4<Float>(0, 1, 0, 1),
|
||||
load: false, clear: magenta, scissor: nil)
|
||||
let dd = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false)
|
||||
dd.usage = [.renderTarget, .shaderRead]
|
||||
dd.storageMode = .private
|
||||
guard let dst = dev.makeTexture(descriptor: dd) else {
|
||||
report(names.sample, false, "makeTexture nil for the private destination"); return
|
||||
}
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = dst
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = magenta
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(texPipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
enc.setFragmentTexture(src, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
if let got = readBack(readPipe, dst, w, h) {
|
||||
var bad: [(Int, Int)] = []
|
||||
for y in 0..<h { for x in 0..<w where got[y * w + x] != greenTexel {
|
||||
bad.append((x, y)) } }
|
||||
report(names.sample, bad.isEmpty,
|
||||
bad.isEmpty ? "a later pass sampled what the earlier pass rendered"
|
||||
: "wrong=\(bad.count)/\(w * h) "
|
||||
+ "first=\(hex(got[bad[0].1 * w + bad[0].0])) "
|
||||
+ "want=\(hex(greenTexel))" + badMap(bad, w, h))
|
||||
} else {
|
||||
refused(names.sample)
|
||||
}
|
||||
}
|
||||
|
||||
// A guest-backed target whose content the CPU wrote before any GPU pass.
|
||||
//
|
||||
// This is the case the four above cannot reach. `srt_load_preserves` starts its
|
||||
// first pass with `.clear`, so the target's prior content is this device's own
|
||||
// and a rail that discards it on the way in still passes. A compositor's layer
|
||||
// is the other order: CoreText rasterizes glyphs into the layer's bytes, and
|
||||
// only then does the GPU composite over it with `.load`.
|
||||
//
|
||||
// A Vulkan image bound over memory that already holds data does not inherit
|
||||
// that data -- the contents are undefined until something writes them -- so a
|
||||
// device that aliases guest pages has to seed the first `.load` from those
|
||||
// pages explicitly and may skip the seed on later ones. Both sides of that
|
||||
// boundary are here: round 0 crosses the first-load seed, rounds 1 and 2 cross
|
||||
// whatever the device does once it believes the image is authoritative.
|
||||
//
|
||||
// Everything CPU-written that a round did not draw over must survive every
|
||||
// round. Losing it is a layer that renders its GPU geometry and drops the type
|
||||
// the CPU put there, with no refusal anywhere.
|
||||
func sharedTargetCpuSeedCase(_ w: Int, _ h: Int) {
|
||||
let label = "srt_cpu_seed_then_load_\(w)x\(h)"
|
||||
guard let pipe = solidPipeline else { report(label, false, "solid pipeline unavailable"); return }
|
||||
guard let rt = sharedRenderTarget(w, h, label) else { return }
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
// 1. The CPU writes every texel, before the GPU has touched the target.
|
||||
let bpr = w * 4
|
||||
var cpu = [UInt8](repeating: 0, count: bpr * h)
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let o = y * bpr + x * 4
|
||||
cpu[o] = UInt8((x &* 7 &+ y &* 13 &+ 1) & 0xFF)
|
||||
cpu[o + 1] = UInt8((x &+ y &* 5) & 0xFF)
|
||||
cpu[o + 2] = 0x40
|
||||
cpu[o + 3] = 0xFF
|
||||
}
|
||||
}
|
||||
cpu.withUnsafeBytes { raw in
|
||||
rt.replace(region: MTLRegionMake2D(0, 0, w, h), mipmapLevel: 0,
|
||||
withBytes: raw.baseAddress!, bytesPerRow: bpr)
|
||||
}
|
||||
|
||||
// 2. Three `.load` passes, each over one horizontal band, leaving the last
|
||||
// band CPU-only for the whole case.
|
||||
let band = max(1, h / 4)
|
||||
let drawn: [UInt32] = [greenTexel, blueTexel, pack(255, 0, 255, 255)]
|
||||
let colours: [SIMD4<Float>] = [SIMD4(0, 1, 0, 1), SIMD4(0, 0, 1, 1), SIMD4(1, 0, 1, 1)]
|
||||
for round in 0..<3 {
|
||||
sharedTargetPass(rt, pipe, verts, colours[round], load: true,
|
||||
clear: magenta,
|
||||
scissor: MTLScissorRect(x: 0, y: round * band,
|
||||
width: w, height: band))
|
||||
}
|
||||
|
||||
guard let got = readBack(readPipe, rt, w, h) else { refused(label); return }
|
||||
var gpuBad: [(Int, Int)] = []
|
||||
var cpuBad: [(Int, Int)] = []
|
||||
var firstCpu = ""
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let have = got[y * w + x]
|
||||
let round = y / band
|
||||
if round < 3 {
|
||||
if have != drawn[round] { gpuBad.append((x, y)) }
|
||||
} else {
|
||||
let o = y * bpr + x * 4
|
||||
let want = pack(cpu[o], cpu[o + 1], cpu[o + 2], cpu[o + 3])
|
||||
if have != want {
|
||||
cpuBad.append((x, y))
|
||||
if firstCpu.isEmpty {
|
||||
firstCpu = "at=(\(x),\(y)) want=\(hex(want)) got=\(hex(have))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = gpuBad.isEmpty && cpuBad.isEmpty
|
||||
report(label, ok,
|
||||
ok ? "three loaded passes kept every texel the CPU wrote first"
|
||||
: "cpu_written_lost=\(cpuBad.count) gpu_bands_wrong=\(gpuBad.count) \(firstCpu) "
|
||||
+ badMap(cpuBad, w, h))
|
||||
}
|
||||
|
||||
// Type composited into a guest-backed layer.
|
||||
//
|
||||
// Everything in section I draws flat colour with blending off, and a driven
|
||||
// Maps boot shows that is not where its type layer goes: it binds `R8Unorm`
|
||||
// coverage atlases -- 128x128 and a scatter of 6x15, 10x1, 5x11 glyph
|
||||
// bitmaps -- and blends them into a layer. Those atlases are sampled
|
||||
// identically whether or not the device imports render targets, so whatever is
|
||||
// lost is lost on the way *into* the layer, and this is the case shaped like
|
||||
// that draw: a single-channel source, a premultiplied blend, and a
|
||||
// guest-backed destination that accumulates across passes.
|
||||
//
|
||||
// The second pass is the half that a flat-colour case cannot stand in for. A
|
||||
// text layer is built by blending over what is already there, so a rail that
|
||||
// loses the destination on the way into a blended `.load` pass loses the type
|
||||
// drawn before it while every solid draw in this file still passes.
|
||||
func makeGlyphPipeline(_ fmt: MTLPixelFormat) -> MTLRenderPipelineState? {
|
||||
let d = MTLRenderPipelineDescriptor()
|
||||
d.vertexFunction = library.makeFunction(name: "quad_vs")
|
||||
d.fragmentFunction = library.makeFunction(name: "glyph_fs")
|
||||
let a = d.colorAttachments[0]!
|
||||
a.pixelFormat = fmt
|
||||
a.isBlendingEnabled = true
|
||||
a.rgbBlendOperation = .add
|
||||
a.alphaBlendOperation = .add
|
||||
a.sourceRGBBlendFactor = .one
|
||||
a.sourceAlphaBlendFactor = .one
|
||||
a.destinationRGBBlendFactor = .oneMinusSourceAlpha
|
||||
a.destinationAlphaBlendFactor = .oneMinusSourceAlpha
|
||||
return try? dev.makeRenderPipelineState(descriptor: d)
|
||||
}
|
||||
|
||||
let glyphPipeline = makeGlyphPipeline(.rgba8Unorm)
|
||||
|
||||
func sharedTargetGlyphCase(_ w: Int, _ h: Int) {
|
||||
let label = "srt_glyph_blend_\(w)x\(h)"
|
||||
guard let pipe = glyphPipeline else {
|
||||
report(label, false, "glyph pipeline unavailable"); return
|
||||
}
|
||||
// A single-channel coverage atlas in guest-visible storage, binary so the
|
||||
// expected blend has no rounding to argue about and a shear shows up as a
|
||||
// moved checker rather than as a slightly wrong colour.
|
||||
let ad = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .r8Unorm, width: w, height: h, mipmapped: false)
|
||||
ad.usage = [.shaderRead]
|
||||
ad.storageMode = .shared
|
||||
guard let atlas = dev.makeTexture(descriptor: ad) else {
|
||||
report(label, false, "makeTexture nil for the coverage atlas"); return
|
||||
}
|
||||
var cov = [UInt8](repeating: 0, count: w * h)
|
||||
for y in 0..<h {
|
||||
for x in 0..<w { cov[y * w + x] = ((x / 3) + (y / 3)) % 2 == 0 ? 255 : 0 }
|
||||
}
|
||||
cov.withUnsafeBytes { raw in
|
||||
atlas.replace(region: MTLRegionMake2D(0, 0, w, h), mipmapLevel: 0,
|
||||
withBytes: raw.baseAddress!, bytesPerRow: w)
|
||||
}
|
||||
|
||||
guard let rt = sharedRenderTarget(w, h, label) else { return }
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
func blend(_ colour: SIMD4<Float>, load: Bool, scissor: MTLScissorRect?) {
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = load ? .load : .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
enc.setFragmentTexture(atlas, index: 0)
|
||||
var c = colour
|
||||
enc.setFragmentBytes(&c, length: 16, index: 0)
|
||||
if let s = scissor { enc.setScissorRect(s) }
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
}
|
||||
|
||||
// 1. Green type over an opaque black layer.
|
||||
blend(SIMD4<Float>(0, 1, 0, 1), load: false, scissor: nil)
|
||||
// 2. Blue type over the top half, loading what pass 1 left.
|
||||
let half = h / 2
|
||||
blend(SIMD4<Float>(0, 0, 1, 1), load: true,
|
||||
scissor: MTLScissorRect(x: 0, y: 0, width: w, height: half))
|
||||
|
||||
guard let got = readBack(readPipe, rt, w, h) else { refused(label); return }
|
||||
let black = pack(0, 0, 0, 255)
|
||||
var bad: [(Int, Int)] = []
|
||||
var first = ""
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let on = cov[y * w + x] == 255
|
||||
let want: UInt32
|
||||
if !on {
|
||||
want = black
|
||||
} else if y < half {
|
||||
want = pack(0, 0, 255, 255)
|
||||
} else {
|
||||
want = pack(0, 255, 0, 255)
|
||||
}
|
||||
let have = got[y * w + x]
|
||||
if have != want {
|
||||
bad.append((x, y))
|
||||
if first.isEmpty { first = "at=(\(x),\(y)) want=\(hex(want)) got=\(hex(have))" }
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, bad.isEmpty,
|
||||
bad.isEmpty ? "coverage type blended into a guest-backed layer, and the second pass kept the first"
|
||||
: "wrong=\(bad.count)/\(w * h) \(first)" + badMap(bad, w, h))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// J. Render targets backed by an IOSurface.
|
||||
//
|
||||
// Section I creates its guest-backed targets as plain `.shared` textures, and a
|
||||
// driven Maps boot says that is not what its layers are: every `pass_target`
|
||||
// this device logs carries a mapping id, which a plain shared texture never
|
||||
// has. A layer that another process composites is an IOSurface, the texture is
|
||||
// created over it with `makeTexture(descriptor:iosurface:plane:)`, and the
|
||||
// device routes it through a different rail from the one section I exercises --
|
||||
// its own resident registry, its own sample rung, its own serialized plane
|
||||
// view.
|
||||
//
|
||||
// So section I's fifteen green cases say nothing about the rail Maps' type
|
||||
// layer is actually composited on. These are the same four questions plus the
|
||||
// blend, asked of the target the app really uses.
|
||||
//
|
||||
// The surface picks its own `bytesPerRow`, which is the point of asking at
|
||||
// these widths: 60 and 1000 texels are 240 and 4000 bytes and IOSurface will
|
||||
// pad both, so the texture's stride is one the test never chose and any rail
|
||||
// that assumes a tight row has somewhere to go wrong.
|
||||
func makeIOSurfaceTarget(_ w: Int, _ h: Int, _ label: String) -> MTLTexture? {
|
||||
// 'BGRA' as an OSType, which is what IOSurface's pixel-format key takes.
|
||||
let bgra: UInt32 = 0x4247_5241
|
||||
let props: [IOSurfacePropertyKey: Any] = [
|
||||
.width: w,
|
||||
.height: h,
|
||||
.bytesPerElement: 4,
|
||||
.pixelFormat: bgra,
|
||||
]
|
||||
guard let surface = IOSurface(properties: props) else {
|
||||
report(label, false, "IOSurface(properties:) nil for \(w)x\(h)")
|
||||
return nil
|
||||
}
|
||||
let td = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm, width: w, height: h, mipmapped: false)
|
||||
td.usage = [.renderTarget, .shaderRead]
|
||||
td.storageMode = .shared
|
||||
guard let tex = dev.makeTexture(descriptor: td, iosurface: surface, plane: 0) else {
|
||||
report(label, false, "makeTexture(iosurface:) nil for \(w)x\(h)")
|
||||
return nil
|
||||
}
|
||||
return tex
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// BGRA in memory, so the packed comparison value has to swap to match
|
||||
// `read_texels`, which reports the sampled RGBA.
|
||||
func iosurfaceCases(_ w: Int, _ h: Int) {
|
||||
let dims = "\(w)x\(h)"
|
||||
let names = (draw: "iosrt_draw_\(dims)",
|
||||
load: "iosrt_load_preserves_\(dims)",
|
||||
scissor: "iosrt_scissor_keeps_rest_\(dims)",
|
||||
glyph: "iosrt_glyph_blend_\(dims)")
|
||||
guard let solid = makeRenderPipeline("solid_fs", .bgra8Unorm) else {
|
||||
for n in [names.draw, names.load, names.scissor, names.glyph] {
|
||||
report(n, false, "solid pipeline unavailable for bgra8Unorm")
|
||||
}
|
||||
return
|
||||
}
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
func pass(_ rt: MTLTexture, _ pipe: MTLRenderPipelineState,
|
||||
_ colour: SIMD4<Float>, load: Bool, scissor: MTLScissorRect?,
|
||||
atlas: MTLTexture?) {
|
||||
let d = MTLRenderPassDescriptor()
|
||||
d.colorAttachments[0].texture = rt
|
||||
d.colorAttachments[0].loadAction = load ? .load : .clear
|
||||
d.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
d.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: d)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
if let atlas { enc.setFragmentTexture(atlas, index: 0) }
|
||||
var c = colour
|
||||
enc.setFragmentBytes(&c, length: 16, index: 0)
|
||||
if let s = scissor { enc.setScissorRect(s) }
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
}
|
||||
|
||||
// 1. A draw into an IOSurface-backed target.
|
||||
guard let rt = makeIOSurfaceTarget(w, h, names.draw) else {
|
||||
for n in [names.load, names.scissor, names.glyph] { skipDependent(n, names.draw) }
|
||||
return
|
||||
}
|
||||
pass(rt, solid, SIMD4<Float>(0, 1, 0, 1), load: false, scissor: nil, atlas: nil)
|
||||
guard let drawn = readBack(readPipe, rt, w, h) else {
|
||||
refused(names.draw)
|
||||
for n in [names.load, names.scissor, names.glyph] { skipDependent(n, names.draw) }
|
||||
return
|
||||
}
|
||||
var bad: [(Int, Int)] = []
|
||||
for y in 0..<h { for x in 0..<w where drawn[y * w + x] != greenTexel { bad.append((x, y)) } }
|
||||
report(names.draw, bad.isEmpty,
|
||||
bad.isEmpty ? "the whole IOSurface-backed target is the drawn colour"
|
||||
: "wrong=\(bad.count)/\(w * h) "
|
||||
+ "first=\(hex(drawn[bad[0].1 * w + bad[0].0])) want=\(hex(greenTexel))"
|
||||
+ badMap(bad, w, h))
|
||||
|
||||
// 2. A second pass over the bottom half must keep the first pass's top half.
|
||||
guard let rt2 = makeIOSurfaceTarget(w, h, names.load) else {
|
||||
for n in [names.scissor, names.glyph] { skipDependent(n, names.load) }
|
||||
return
|
||||
}
|
||||
let half = h / 2
|
||||
pass(rt2, solid, SIMD4<Float>(0, 1, 0, 1), load: false,
|
||||
scissor: MTLScissorRect(x: 0, y: 0, width: w, height: half), atlas: nil)
|
||||
pass(rt2, solid, SIMD4<Float>(0, 0, 1, 1), load: true,
|
||||
scissor: MTLScissorRect(x: 0, y: half, width: w, height: h - half), atlas: nil)
|
||||
if let got = readBack(readPipe, rt2, w, h) {
|
||||
var top: [(Int, Int)] = []
|
||||
var bot: [(Int, Int)] = []
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let have = got[y * w + x]
|
||||
if y < half { if have != greenTexel { top.append((x, y)) } }
|
||||
else if have != blueTexel { bot.append((x, y)) }
|
||||
}
|
||||
}
|
||||
let ok = top.isEmpty && bot.isEmpty
|
||||
report(names.load, ok,
|
||||
ok ? "the second pass added to what the first pass left"
|
||||
: "first_pass_lost=\(top.count) second_pass_wrong=\(bot.count)"
|
||||
+ badMap(top, w, h))
|
||||
} else { refused(names.load) }
|
||||
|
||||
// 3. A scissored write into the middle of a loaded IOSurface target.
|
||||
guard let rt3 = makeIOSurfaceTarget(w, h, names.scissor) else {
|
||||
skipDependent(names.glyph, names.scissor); return
|
||||
}
|
||||
pass(rt3, solid, SIMD4<Float>(1, 0, 1, 1), load: false, scissor: nil, atlas: nil)
|
||||
let rx = w / 4, ry = h / 4, rw = max(1, w / 2), rh = max(1, h / 2)
|
||||
pass(rt3, solid, SIMD4<Float>(0, 1, 0, 1), load: true,
|
||||
scissor: MTLScissorRect(x: rx, y: ry, width: rw, height: rh), atlas: nil)
|
||||
if let got = readBack(readPipe, rt3, w, h) {
|
||||
var inside: [(Int, Int)] = []
|
||||
var outside: [(Int, Int)] = []
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let within = x >= rx && x < rx + rw && y >= ry && y < ry + rh
|
||||
let have = got[y * w + x]
|
||||
if within { if have != greenTexel { inside.append((x, y)) } }
|
||||
else if have != magentaTexel { outside.append((x, y)) }
|
||||
}
|
||||
}
|
||||
let ok = inside.isEmpty && outside.isEmpty
|
||||
report(names.scissor, ok,
|
||||
ok ? "the scissored write landed on exactly its own rows"
|
||||
: "rect_wrong=\(inside.count) outside_clobbered=\(outside.count) "
|
||||
+ "rect=(\(rx),\(ry) \(rw)x\(rh))" + badMap(outside, w, h))
|
||||
} else { refused(names.scissor) }
|
||||
|
||||
// 4. Coverage type blended into the IOSurface layer, twice, the second
|
||||
// loading the first. This is the draw Maps' type layer actually makes.
|
||||
guard let glyph = makeGlyphPipeline(.bgra8Unorm) else {
|
||||
report(names.glyph, false, "glyph pipeline unavailable for bgra8Unorm"); return
|
||||
}
|
||||
let ad = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .r8Unorm, width: w, height: h, mipmapped: false)
|
||||
ad.usage = [.shaderRead]
|
||||
ad.storageMode = .shared
|
||||
guard let atlas = dev.makeTexture(descriptor: ad) else {
|
||||
report(names.glyph, false, "makeTexture nil for the coverage atlas"); return
|
||||
}
|
||||
var cov = [UInt8](repeating: 0, count: w * h)
|
||||
for y in 0..<h { for x in 0..<w { cov[y * w + x] = ((x / 3) + (y / 3)) % 2 == 0 ? 255 : 0 } }
|
||||
cov.withUnsafeBytes { raw in
|
||||
atlas.replace(region: MTLRegionMake2D(0, 0, w, h), mipmapLevel: 0,
|
||||
withBytes: raw.baseAddress!, bytesPerRow: w)
|
||||
}
|
||||
guard let rt4 = makeIOSurfaceTarget(w, h, names.glyph) else { return }
|
||||
pass(rt4, glyph, SIMD4<Float>(0, 1, 0, 1), load: false, scissor: nil, atlas: atlas)
|
||||
pass(rt4, glyph, SIMD4<Float>(0, 0, 1, 1), load: true,
|
||||
scissor: MTLScissorRect(x: 0, y: 0, width: w, height: half), atlas: atlas)
|
||||
if let got = readBack(readPipe, rt4, w, h) {
|
||||
var wrong: [(Int, Int)] = []
|
||||
var first = ""
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let on = cov[y * w + x] == 255
|
||||
// A texel the type does not cover keeps this section's clear,
|
||||
// which is magenta. Expecting magenta rather than black is also
|
||||
// what makes the check say something: black is what a target
|
||||
// nobody wrote looks like, so a case that expected it would pass
|
||||
// on a layer that was never rendered into at all.
|
||||
let want = !on ? magentaTexel
|
||||
: (y < half ? pack(0, 0, 255, 255) : pack(0, 255, 0, 255))
|
||||
let have = got[y * w + x]
|
||||
if have != want {
|
||||
wrong.append((x, y))
|
||||
if first.isEmpty { first = "at=(\(x),\(y)) want=\(hex(want)) got=\(hex(have))" }
|
||||
}
|
||||
}
|
||||
}
|
||||
report(names.glyph, wrong.isEmpty,
|
||||
wrong.isEmpty
|
||||
? "coverage type blended into an IOSurface layer, and the second pass kept the first"
|
||||
: "wrong=\(wrong.count)/\(w * h) \(first)" + badMap(wrong, w, h))
|
||||
} else { refused(names.glyph) }
|
||||
}
|
||||
|
||||
// K. The CPU writes a layer the GPU already rendered into, and the GPU samples it.
|
||||
//
|
||||
// Section I and J both stop one step short of the shape a compositor actually
|
||||
// runs. `cpu_write_after_render` writes the layer from the CPU and then reads
|
||||
// it back with a compute kernel; `srt_sample_after_render` samples the layer but
|
||||
// only ever sees texels the GPU itself drew. Neither one asks the question a
|
||||
// text layer asks: after the CPU has written bytes into an allocation the GPU
|
||||
// has already rendered into, does a *sampled bind* in a later render pass see
|
||||
// them?
|
||||
//
|
||||
// The two reads are not interchangeable. A compute kernel reading a texture and
|
||||
// a fragment shader sampling one are different binds, and a device that keeps a
|
||||
// device-local image for an allocation it renders into may serve one from guest
|
||||
// pages and the other from that image. A guest CPU store into its own RAM is
|
||||
// invisible to the host -- no page fault, no command, nothing to observe -- so
|
||||
// an image the device believes is authoritative stays stale with nothing
|
||||
// anywhere reporting a loss.
|
||||
//
|
||||
// That is the whole failure mode this case exists for, and it is what a layer
|
||||
// losing its type looks like: the GPU-drawn geometry in the layer is correct
|
||||
// because the device drew it, and only the CPU-written half is missing.
|
||||
func cpuWriteThenSampleCase(_ w: Int, _ h: Int, iosurface: Bool) {
|
||||
let rail = iosurface ? "iosrt" : "srt"
|
||||
let label = "\(rail)_cpu_write_then_sample_\(w)x\(h)"
|
||||
guard let pipe = iosurface ? makeRenderPipeline("solid_fs", .bgra8Unorm)
|
||||
: solidPipeline else {
|
||||
report(label, false, "solid pipeline unavailable"); return
|
||||
}
|
||||
guard let texPipe = texPipeline else {
|
||||
report(label, false, "texture pipeline unavailable"); return
|
||||
}
|
||||
guard let layer = iosurface ? makeIOSurfaceTarget(w, h, label)
|
||||
: sharedRenderTarget(w, h, label) else { return }
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
// 1. The GPU renders the whole layer green. After this the device has an
|
||||
// image for the allocation and every byte in it is the device's own.
|
||||
sharedTargetPass(layer, pipe, verts, SIMD4<Float>(0, 1, 0, 1),
|
||||
load: false, clear: magenta, scissor: nil)
|
||||
|
||||
// 2. The CPU writes the bottom half opaque red, the way CoreText rasterizes
|
||||
// glyphs into a layer's bytes. `.shared` is BGRA in memory on the
|
||||
// IOSurface rail and RGBA on the other, so the channel order follows the
|
||||
// format rather than the case.
|
||||
let half = max(1, h / 2)
|
||||
let rows = h - half
|
||||
let bpr = w * 4
|
||||
var cpu = [UInt8](repeating: 0, count: bpr * rows)
|
||||
for i in 0..<(w * rows) {
|
||||
let o = i * 4
|
||||
if iosurface { cpu[o] = 0; cpu[o + 1] = 0; cpu[o + 2] = 255 }
|
||||
else { cpu[o] = 255; cpu[o + 1] = 0; cpu[o + 2] = 0 }
|
||||
cpu[o + 3] = 255
|
||||
}
|
||||
cpu.withUnsafeBytes { raw in
|
||||
layer.replace(region: MTLRegionMake2D(0, half, w, rows), mipmapLevel: 0,
|
||||
withBytes: raw.baseAddress!, bytesPerRow: bpr)
|
||||
}
|
||||
|
||||
// 3. A later render pass samples the layer into a private destination --
|
||||
// the compositor's read, not a compute read-back of the layer itself.
|
||||
let dd = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false)
|
||||
dd.usage = [.renderTarget, .shaderRead]
|
||||
dd.storageMode = .private
|
||||
guard let dst = dev.makeTexture(descriptor: dd) else {
|
||||
report(label, false, "makeTexture nil for the private destination"); return
|
||||
}
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = dst
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = magenta
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(texPipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
enc.setFragmentTexture(layer, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
guard let got = readBack(readPipe, dst, w, h) else { refused(label); return }
|
||||
let redTexel = pack(255, 0, 0, 255)
|
||||
var gpuBad: [(Int, Int)] = []
|
||||
var cpuBad: [(Int, Int)] = []
|
||||
var firstCpu = ""
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let have = got[y * w + x]
|
||||
if y < half {
|
||||
if have != greenTexel { gpuBad.append((x, y)) }
|
||||
} else if have != redTexel {
|
||||
cpuBad.append((x, y))
|
||||
if firstCpu.isEmpty {
|
||||
firstCpu = "at=(\(x),\(y)) want=\(hex(redTexel)) got=\(hex(have))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = gpuBad.isEmpty && cpuBad.isEmpty
|
||||
report(label, ok,
|
||||
ok ? "a sampled bind saw the texels the CPU wrote after the GPU rendered"
|
||||
: "cpu_written_unseen=\(cpuBad.count)/\(w * rows) "
|
||||
+ "gpu_drawn_wrong=\(gpuBad.count)/\(w * half) \(firstCpu)"
|
||||
+ badMap(cpuBad, w, h))
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// I. Render targets the guest allocated in its own memory.
|
||||
//
|
||||
// Every render target above this line is `.private`, so the device allocates it
|
||||
// and the guest never names the pages behind it. That is one of the two kinds
|
||||
// of render target a compositing app uses and it is not the interesting one: a
|
||||
// layer that the CPU also rasterizes into, or that another process composites,
|
||||
// is `.shared`, and its bytes are guest memory the device may bind a Vulkan
|
||||
// image directly over instead of copying.
|
||||
//
|
||||
// Those are two different rails with two different failure modes, and until
|
||||
// this section the battery had exactly one case on the second of them
|
||||
// (`cpu_write_after_render`, section F5). A whole rail behind one case is not
|
||||
// coverage -- it is a single sample that happens to pass, which is what let a
|
||||
// live defect sit under 173 green cases.
|
||||
//
|
||||
// The four questions below are the ones a direct binding over guest pages can
|
||||
// answer differently from a copy, in the order they get harder:
|
||||
//
|
||||
// draw -- does rendering into guest-owned pages land at all,
|
||||
// load -- does a second pass see what the first one left, or does the
|
||||
// seed for `.load` overwrite it with a stale copy,
|
||||
// scissor -- does a partial write land on the right rows, which is where a
|
||||
// row pitch the guest did not agree to shows up as a shear,
|
||||
// sample -- does a later pass sampling that same texture read what was
|
||||
// rendered, which is the crossover between "this is a target"
|
||||
// and "this is a source" over one allocation.
|
||||
//
|
||||
// The widths are chosen so the row pitch cannot be assumed: 60 and 1000 texels
|
||||
// are 240 and 4000 bytes, neither a multiple of the 256-byte linear alignment
|
||||
// this device reports, so any rail that confuses the guest's stride with a
|
||||
// padded one puts the pixels somewhere this section can see.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func sharedRenderTarget(_ w: Int, _ h: Int, _ label: String) -> MTLTexture? {
|
||||
let rd = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false)
|
||||
rd.usage = [.renderTarget, .shaderRead]
|
||||
rd.storageMode = .shared
|
||||
guard let rt = dev.makeTexture(descriptor: rd) else {
|
||||
report(label, false, "makeTexture nil for a shared \(w)x\(h) render target")
|
||||
return nil
|
||||
}
|
||||
return rt
|
||||
}
|
||||
@@ -1,421 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
func fragmentAliasCase(_ f: Fmt, _ w: Int, _ h: Int, pitch: Pitch) {
|
||||
let align = dev.minimumLinearTextureAlignment(for: f.mtl)
|
||||
let bpr = pitch.bytes(width: w, bpp: f.bpp, align: align)
|
||||
let label = "fragsample_\(f.name)_\(w)x\(h)_pitch_\(pitch.tag)"
|
||||
// This case reports under two names, so every exit from it has to report
|
||||
// under both. A skip that names only `label` emits one line where a host
|
||||
// that runs the case emits two, and the two runs then pair up on neither.
|
||||
let arms = ["first_draw", "after_cpu_rewrite"]
|
||||
func bailAll(skipping: Bool, _ why: String) {
|
||||
for arm in arms {
|
||||
if skipping { skip("\(label)_\(arm)", why) }
|
||||
else { report("\(label)_\(arm)", false, why) }
|
||||
}
|
||||
}
|
||||
if bpr % align != 0 || bpr < w * f.bpp {
|
||||
bailAll(skipping: true, "pitch \(bpr) is not a multiple of this device's minimumLinearTextureAlignment=\(align)")
|
||||
return
|
||||
}
|
||||
guard let buf = dev.makeBuffer(length: bpr * h, options: .storageModeShared) else {
|
||||
bailAll(skipping: false, "buffer allocation failed"); return
|
||||
}
|
||||
let base = buf.contents().bindMemory(to: UInt8.self, capacity: bpr * h)
|
||||
for y in 0..<h { for x in 0..<bpr { base[y * bpr + x] = UInt8((x &* 5 &+ y &* 17 &+ 3) & 0xFF) } }
|
||||
let d = MTLTextureDescriptor()
|
||||
d.textureType = .type2D; d.pixelFormat = f.mtl
|
||||
d.width = w; d.height = h; d.mipmapLevelCount = 1
|
||||
d.storageMode = .shared; d.usage = [.shaderRead]
|
||||
guard let tex = buf.makeTexture(descriptor: d, offset: 0, bytesPerRow: bpr) else {
|
||||
bailAll(skipping: false, "makeTexture nil"); return
|
||||
}
|
||||
|
||||
func check(_ tag: String, _ expectByte: (Int, Int) -> [UInt8]) {
|
||||
guard let got = fragmentSample(tex, w, h) else {
|
||||
report("\(label)_\(tag)", false, "render pipeline unavailable"); return
|
||||
}
|
||||
var bad: [(Int, Int)] = []
|
||||
var first = ""
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let want = f.expect(expectByte(x, y))
|
||||
let have = got[y * w + x]
|
||||
if want != have {
|
||||
bad.append((x, y))
|
||||
if first.isEmpty { first = "first_bad=(\(x),\(y)) want=\(hex(want)) got=\(hex(have))" }
|
||||
}
|
||||
}
|
||||
}
|
||||
report("\(label)_\(tag)", bad.isEmpty,
|
||||
bad.isEmpty ? "\(w * h) texels exact through the rasterizer"
|
||||
: "\(bad.count)/\(w * h) wrong \(first) \(badMap(bad, w, h))")
|
||||
}
|
||||
|
||||
check("first_draw") { x, y in
|
||||
(0..<f.bpp).map { base[y * bpr + x * f.bpp + $0] }
|
||||
}
|
||||
// Rewrite every byte, with the texture already drawn with once and never
|
||||
// re-declared. This is the glyph atlas being refilled between frames.
|
||||
for y in 0..<h { for x in 0..<bpr { base[y * bpr + x] = UInt8((x &* 3 &+ y &* 29 &+ 200) & 0xFF) } }
|
||||
check("after_cpu_rewrite") { x, y in
|
||||
(0..<f.bpp).map { base[y * bpr + x * f.bpp + $0] }
|
||||
}
|
||||
}
|
||||
|
||||
let texPipeline = makeRenderPipeline("tex_fs", .rgba8Unorm)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// F2. The same alias, filled so that every byte names its own offset.
|
||||
//
|
||||
// A wrong-pitch read, a wrong-offset read and a byte that simply is not there
|
||||
// are three different defects and the pattern fills above cannot tell them
|
||||
// apart -- a mismatch says "not what I wrote" and stops. Here byte `i` holds
|
||||
// `1 + (i % 251)`, so a returned value inverts to a source offset modulo 251,
|
||||
// and the *difference* between the offset the contract names and the offset the
|
||||
// device read is the finding. 251 is the largest prime below 256, so the cycle
|
||||
// never divides a row pitch and an alias off by a row is not congruent to one
|
||||
// that is exact. Zero is outside the fill's range entirely, so it means the
|
||||
// device returned a byte nothing in this buffer ever held.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func offsetOracleCase(_ w: Int, _ h: Int, pitch: Pitch, viaFragment: Bool) {
|
||||
let f = formats[1] // a8Unorm: one byte per texel, so a texel *is* an offset
|
||||
let align = dev.minimumLinearTextureAlignment(for: f.mtl)
|
||||
let bpr = pitch.bytes(width: w, bpp: f.bpp, align: align)
|
||||
let label = "offset_oracle_\(w)x\(h)_pitch_\(pitch.tag)\(viaFragment ? "_fragment" : "_compute")"
|
||||
if bpr % align != 0 || bpr < w {
|
||||
skip(label, "pitch \(bpr) is not a multiple of this device's minimumLinearTextureAlignment=\(align)")
|
||||
return
|
||||
}
|
||||
guard let buf = dev.makeBuffer(length: bpr * h, options: .storageModeShared) else {
|
||||
report(label, false, "buffer allocation failed"); return
|
||||
}
|
||||
let base = buf.contents().bindMemory(to: UInt8.self, capacity: bpr * h)
|
||||
for i in 0..<(bpr * h) { base[i] = UInt8(1 + (i % 251)) }
|
||||
let d = MTLTextureDescriptor()
|
||||
d.textureType = .type2D; d.pixelFormat = f.mtl
|
||||
d.width = w; d.height = h; d.mipmapLevelCount = 1
|
||||
d.storageMode = .shared; d.usage = [.shaderRead]
|
||||
guard let tex = buf.makeTexture(descriptor: d, offset: 0, bytesPerRow: bpr) else {
|
||||
report(label, false, "makeTexture nil"); return
|
||||
}
|
||||
let got: [UInt32]?
|
||||
if viaFragment { got = fragmentSample(tex, w, h) } else { got = readBack(readPipe, tex, w, h) }
|
||||
// The reading this whole case exists to make trustworthy: without the
|
||||
// kernel's own run witness a refused dispatch arrived here as a buffer full
|
||||
// of `0xEE`, which inverts to a valid-looking source offset and reported as
|
||||
// `absent=0 shifted=4080`. See `readBack`.
|
||||
guard let got else { refused(label); return }
|
||||
|
||||
var absent: [(Int, Int)] = []
|
||||
var deltas: [Int: Int] = [:] // (read offset - contract offset) mod 251 -> count
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let a = Int((got[y * w + x] >> 24) & 0xFF)
|
||||
if a == 0 { absent.append((x, y)); continue }
|
||||
let readOffset = (a - 1) % 251
|
||||
let wantOffset = (y * bpr + x) % 251
|
||||
let delta = ((readOffset - wantOffset) % 251 + 251) % 251
|
||||
if delta != 0 { deltas[delta, default: 0] += 1 }
|
||||
}
|
||||
}
|
||||
let ok = absent.isEmpty && deltas.isEmpty
|
||||
var detail = "\(w * h) texels at the offsets the contract names"
|
||||
if !ok {
|
||||
let top = deltas.sorted { $0.value > $1.value }.prefix(4)
|
||||
.map { "delta=\($0.key)x\($0.value)" }.joined(separator: " ")
|
||||
detail = "absent=\(absent.count) shifted=\(deltas.values.reduce(0, +)) \(top) "
|
||||
+ badMap(absent, w, h)
|
||||
}
|
||||
report(label, ok, detail)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// F3. A render target whose width is not a multiple of eight.
|
||||
//
|
||||
// Every failing case above lost exactly `alignUp(w, 8) - w` columns, and the
|
||||
// two that passed were the two whose width was already a multiple of eight.
|
||||
// That is a property of the *target*, not of the alias being sampled, so this
|
||||
// draws a flat colour with no texture bound at all: if it fails the same way,
|
||||
// nothing about buffer-backed textures is involved and the finding is about
|
||||
// render-target width.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func targetWidthCase(_ w: Int, _ h: Int) {
|
||||
guard let pipe = solidPipeline else {
|
||||
report("rt_width_\(w)", false, "solid pipeline unavailable"); return
|
||||
}
|
||||
let rd = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false)
|
||||
rd.usage = [.renderTarget, .shaderRead]
|
||||
rd.storageMode = .private
|
||||
guard let rt = dev.makeTexture(descriptor: rd) else {
|
||||
report("rt_width_\(w)", false, "makeTexture nil"); return
|
||||
}
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
// Cleared to a colour that is neither the drawn colour nor zero, so a
|
||||
// failing texel says which of "never drawn" and "never anything" it is.
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
var colour = SIMD4<Float>(0, 1, 0, 1)
|
||||
enc.setFragmentBytes(&colour, length: 16, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
guard let got = readBack(readPipe, rt, w, h) else {
|
||||
refused("rt_width_\(w)"); return
|
||||
}
|
||||
let want = pack(0, 255, 0, 255)
|
||||
let clear = pack(255, 0, 255, 255)
|
||||
var bad: [(Int, Int)] = []
|
||||
var zero = 0, cleared = 0
|
||||
for y in 0..<h {
|
||||
for x in 0..<w where got[y * w + x] != want {
|
||||
bad.append((x, y))
|
||||
if got[y * w + x] == 0 { zero += 1 }
|
||||
if got[y * w + x] == clear { cleared += 1 }
|
||||
}
|
||||
}
|
||||
let pad = alignUp(w, 8) - w
|
||||
report("rt_width_\(w)", bad.isEmpty,
|
||||
bad.isEmpty ? "\(w * h) texels are the drawn colour"
|
||||
: "\(bad.count)/\(w * h) wrong zero=\(zero) still_clear=\(cleared) "
|
||||
+ "alignUp(w,8)-w=\(pad) \(badMap(bad, w, h))")
|
||||
}
|
||||
|
||||
let solidPipeline = makeRenderPipeline("solid_fs", .rgba8Unorm)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// F4. `dispatchThreads` must run the grid it is given and not one thread more.
|
||||
//
|
||||
// `dispatchThreads:threadsPerThreadgroup:` takes a thread count, not a
|
||||
// threadgroup count, and Metal is required to launch exactly that many threads
|
||||
// however badly the count divides the threadgroup. A device that rounds the
|
||||
// grid up to whole threadgroups instead runs extra threads with a
|
||||
// `thread_position_in_grid` outside the grid, and every one of them is a stray
|
||||
// write at whatever address the shader computes from it.
|
||||
//
|
||||
// Nothing about this is visible in a shader that is careful, which is why it
|
||||
// hides: the damage lands in the *caller's* buffer, at the addresses just past
|
||||
// each row, and those are the addresses the next row occupies. That is exactly
|
||||
// the shape `rt_width_*` reports -- the first `alignUp(w, 8) - w` texels of a
|
||||
// row, zeroed at random, with row zero always intact because nothing is
|
||||
// dispatched before it.
|
||||
//
|
||||
// Here each thread owns a slot in a grid padded to the threadgroup size, so a
|
||||
// stray thread cannot overwrite a real one and the evidence survives.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func gridBoundsCase(_ w: Int, _ h: Int, _ tg: Int) {
|
||||
let label = "dispatch_threads_grid_\(w)x\(h)_tg\(tg)"
|
||||
let pipe = pipeline("grid_bounds")
|
||||
let stride = alignUp(w, tg)
|
||||
let rows = alignUp(h, tg)
|
||||
let out = dev.makeBuffer(length: stride * rows * 4, options: .storageModeShared)!
|
||||
memset(out.contents(), 0, stride * rows * 4)
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeComputeCommandEncoder()!
|
||||
enc.setComputePipelineState(pipe)
|
||||
enc.setBuffer(out, offset: 0, index: 0)
|
||||
var strideU = UInt32(stride)
|
||||
enc.setBytes(&strideU, length: 4, index: 1)
|
||||
enc.dispatchThreads(MTLSize(width: w, height: h, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: tg, height: tg, depth: 1))
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
let p = out.contents().bindMemory(to: UInt32.self, capacity: stride * rows)
|
||||
var missing = 0 // inside the grid and never written
|
||||
var strayX = 0 // x >= w
|
||||
var strayY = 0 // y >= h
|
||||
var firstStray = ""
|
||||
for y in 0..<rows {
|
||||
for x in 0..<stride {
|
||||
let v = p[y * stride + x]
|
||||
let inGrid = x < w && y < h
|
||||
if inGrid {
|
||||
if v != UInt32(1 + x) { missing += 1 }
|
||||
} else if v != 0 {
|
||||
if x >= w { strayX += 1 } else { strayY += 1 }
|
||||
if firstStray.isEmpty { firstStray = "first_stray=(\(x),\(y))=\(v)" }
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = missing == 0 && strayX == 0 && strayY == 0
|
||||
report(label, ok,
|
||||
ok ? "\(w * h) threads ran and nothing outside the grid did"
|
||||
: "missing=\(missing) stray_past_width=\(strayX) stray_past_height=\(strayY) \(firstStray)")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// F5. A CPU write into a texture the GPU has already rendered into.
|
||||
//
|
||||
// This is the shape of a compositor that draws its geometry on the GPU and
|
||||
// rasterizes its type on the CPU, into one shared texture. Metal's contract is
|
||||
// that both writers land: the render pass owns what it drew, the CPU owns what
|
||||
// it wrote afterwards, and a later read sees each in the region it wrote.
|
||||
//
|
||||
// A device that keeps its own copy of the target and writes that copy back into
|
||||
// the guest's pages after the fact destroys the second writer's bytes and
|
||||
// nothing reports it. The failure is content, and content is what no counter in
|
||||
// this project measures -- so it is asked here directly, and asked in both
|
||||
// orders, because a writeback landing late and a writeback landing early are
|
||||
// different bugs with the same symptom.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func cpuWriteAfterRenderCase(_ w: Int, _ h: Int, secondPass: Bool) {
|
||||
let label = "cpu_write_after_render_\(w)x\(h)\(secondPass ? "_then_second_pass" : "")"
|
||||
guard let pipe = solidPipeline else { report(label, false, "solid pipeline unavailable"); return }
|
||||
let rd = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false)
|
||||
rd.usage = [.renderTarget, .shaderRead]
|
||||
// Shared, so the CPU can write it and the GPU can render into it -- which
|
||||
// is the whole point and is what a compositor's own surfaces are.
|
||||
rd.storageMode = .shared
|
||||
guard let rt = dev.makeTexture(descriptor: rd) else {
|
||||
report(label, false, "makeTexture nil"); return
|
||||
}
|
||||
let verts = dev.makeBuffer(bytes: quadVerts, length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
|
||||
func draw(_ colour: SIMD4<Float>, load: Bool) {
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = load ? .load : .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
var c = colour
|
||||
enc.setFragmentBytes(&c, length: 16, index: 0)
|
||||
// Only the top half, so the bottom half is the CPU's alone and a
|
||||
// whole-target writeback is the only thing that could reach it.
|
||||
enc.setScissorRect(MTLScissorRect(x: 0, y: 0, width: w, height: h / 2))
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
}
|
||||
|
||||
// 1. The GPU renders into the top half.
|
||||
draw(SIMD4<Float>(0, 1, 0, 1), load: false)
|
||||
|
||||
// 2. The CPU rasterizes into the bottom half, after the pass completed.
|
||||
let bottom = h / 2
|
||||
let bpr = w * 4
|
||||
var rows = [UInt8](repeating: 0, count: bpr * (h - bottom))
|
||||
for y in 0..<(h - bottom) {
|
||||
for x in 0..<w {
|
||||
let o = y * bpr + x * 4
|
||||
rows[o] = UInt8((x &* 7 &+ y &* 3 &+ 1) & 0xFF)
|
||||
rows[o + 1] = 0x20
|
||||
rows[o + 2] = 0x40
|
||||
rows[o + 3] = 0xFF
|
||||
}
|
||||
}
|
||||
rows.withUnsafeBytes { raw in
|
||||
rt.replace(region: MTLRegionMake2D(0, bottom, w, h - bottom),
|
||||
mipmapLevel: 0, withBytes: raw.baseAddress!, bytesPerRow: bpr)
|
||||
}
|
||||
|
||||
// 3. Optionally another pass over the top half only. A device that reloads
|
||||
// its own stale copy for `.load` and stores the whole target back is
|
||||
// caught here and not by the first arm.
|
||||
if secondPass { draw(SIMD4<Float>(0, 0, 1, 1), load: true) }
|
||||
|
||||
guard let got = readBack(readPipe, rt, w, h) else {
|
||||
refused(label); return
|
||||
}
|
||||
let drawn = secondPass ? pack(0, 0, 255, 255) : pack(0, 255, 0, 255)
|
||||
var topBad: [(Int, Int)] = []
|
||||
var cpuBad: [(Int, Int)] = []
|
||||
var cpuFirst = ""
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let have = got[y * w + x]
|
||||
if y < bottom {
|
||||
if have != drawn { topBad.append((x, y)) }
|
||||
} else {
|
||||
let o = (y - bottom) * bpr + x * 4
|
||||
let want = pack(rows[o], rows[o + 1], rows[o + 2], rows[o + 3])
|
||||
if have != want {
|
||||
cpuBad.append((x, y))
|
||||
if cpuFirst.isEmpty {
|
||||
cpuFirst = "at=(\(x),\(y)) want=\(hex(want)) got=\(hex(have))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = topBad.isEmpty && cpuBad.isEmpty
|
||||
report(label, ok,
|
||||
ok ? "the GPU kept its half and the CPU kept its half"
|
||||
: "gpu_half_wrong=\(topBad.count) cpu_half_wrong=\(cpuBad.count) \(cpuFirst) "
|
||||
+ badMap(cpuBad, w, h))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// G. A linear alias at a non-zero offset into its allocation.
|
||||
//
|
||||
// A glyph atlas is a sub-range of a larger buffer, so the offset is part of the
|
||||
// contract. A device that resolves the allocation but drops the offset reads
|
||||
// the right pages and the wrong bytes, which looks exactly like corruption.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func offsetAliasCase(_ f: Fmt, _ w: Int, _ h: Int, tiles: Int) {
|
||||
let align = dev.minimumLinearTextureAlignment(for: f.mtl)
|
||||
let bpr = alignUp(w * f.bpp, align)
|
||||
let stride = alignUp(bpr * h, max(align, 256))
|
||||
let label = "offset_alias_\(f.name)_\(w)x\(h)_x\(tiles)"
|
||||
guard let buf = dev.makeBuffer(length: stride * tiles, options: .storageModeShared) else {
|
||||
report(label, false, "buffer allocation failed"); return
|
||||
}
|
||||
let base = buf.contents().bindMemory(to: UInt8.self, capacity: stride * tiles)
|
||||
for i in 0..<(stride * tiles) { base[i] = UInt8((i &* 31 &+ 7) & 0xFF) }
|
||||
|
||||
var bad = 0
|
||||
var first = ""
|
||||
for t in 0..<tiles {
|
||||
let off = stride * t
|
||||
let d = MTLTextureDescriptor()
|
||||
d.textureType = .type2D; d.pixelFormat = f.mtl
|
||||
d.width = w; d.height = h; d.mipmapLevelCount = 1
|
||||
d.storageMode = .shared; d.usage = [.shaderRead]
|
||||
guard let tex = buf.makeTexture(descriptor: d, offset: off, bytesPerRow: bpr) else {
|
||||
report(label, false, "makeTexture nil at offset \(off)"); return
|
||||
}
|
||||
guard let got = readBack(readPipe, tex, w, h) else {
|
||||
refused(label); return
|
||||
}
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let bytes = (0..<f.bpp).map { base[off + y * bpr + x * f.bpp + $0] }
|
||||
let want = f.expect(bytes)
|
||||
if got[y * w + x] != want {
|
||||
bad += 1
|
||||
if first.isEmpty {
|
||||
first = "tile=\(t) offset=\(off) at=(\(x),\(y)) want=\(hex(want)) got=\(hex(got[y * w + x]))"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, bad == 0,
|
||||
bad == 0 ? "\(tiles) tiles exact at their own offsets" : "\(bad) wrong \(first)")
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// One texture copied onto itself, with the source and destination rectangles
|
||||
// overlapping.
|
||||
//
|
||||
// `copyFromTexture:toTexture:` naming one texture twice at different origins is
|
||||
// a shape the guest issues: a driven Maps interaction on the macos-13 rail
|
||||
// produces it several times a boot, both as a horizontal shift inside one row
|
||||
// and as a one-texel column shifted down a dozen rows. Nothing in the encoder
|
||||
// refuses it, so the guest treats the copy as complete.
|
||||
//
|
||||
// What the overlapping texels are afterwards is the question, and it has one
|
||||
// answer rather than being undefined: measured on Apple silicon, the whole
|
||||
// source region is read before any destination byte is written. A row-at-a-time
|
||||
// implementation gets a different answer whenever a destination row precedes a
|
||||
// source row it still has to read, which is exactly what both live shapes do.
|
||||
//
|
||||
// So the expectation below is computed against a pristine snapshot of the
|
||||
// source. `disjoint` is the control: there the two readings agree, so a device
|
||||
// that refuses every self-copy fails it too and a device that only mishandles
|
||||
// the overlap does not — which is what tells the two apart.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private func texelPattern(_ x: Int, _ y: Int) -> UInt32 {
|
||||
// Distinct per texel within the sizes used here, so a copy that lands the
|
||||
// wrong source texel is visible rather than aliasing onto the right value.
|
||||
pack(UInt8(x & 0xFF), UInt8(y & 0xFF), UInt8((x &* 7 &+ y &* 31) & 0xFF), 255)
|
||||
}
|
||||
|
||||
private func selfCopyCase(_ label: String,
|
||||
width: Int, height: Int,
|
||||
src: MTLOrigin, dst: MTLOrigin, region: MTLSize) {
|
||||
let bpr = width * 4
|
||||
let d = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: width, height: height, mipmapped: false)
|
||||
d.storageMode = .shared
|
||||
d.usage = [.shaderRead, .shaderWrite]
|
||||
guard let tex = dev.makeTexture(descriptor: d) else {
|
||||
report(label, false, "makeTexture nil for the shared \(width)x\(height) image")
|
||||
return
|
||||
}
|
||||
|
||||
// An ordinary image, not one declared over a buffer: the copy below is the
|
||||
// only thing this case asks the device to do with it, and the readback is
|
||||
// the suite's usual one rather than a buffer-backed bind.
|
||||
var seed = [UInt32](repeating: 0, count: width * height)
|
||||
for y in 0..<height {
|
||||
for x in 0..<width { seed[y * width + x] = texelPattern(x, y) }
|
||||
}
|
||||
seed.withUnsafeBytes { raw in
|
||||
tex.replace(region: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0,
|
||||
withBytes: raw.baseAddress!, bytesPerRow: bpr)
|
||||
}
|
||||
|
||||
// Source-snapshot semantics: every destination texel takes the source as it
|
||||
// stood before the copy, never a byte this copy has already written.
|
||||
var want = [UInt32](repeating: 0, count: width * height)
|
||||
for y in 0..<height {
|
||||
for x in 0..<width { want[y * width + x] = texelPattern(x, y) }
|
||||
}
|
||||
for dy in 0..<region.height {
|
||||
for dx in 0..<region.width {
|
||||
want[(dst.y + dy) * width + dst.x + dx] = texelPattern(src.x + dx, src.y + dy)
|
||||
}
|
||||
}
|
||||
|
||||
guard let cb = queue.makeCommandBuffer(), let blit = cb.makeBlitCommandEncoder() else {
|
||||
report(label, false, "no blit encoder"); return
|
||||
}
|
||||
blit.copy(from: tex, sourceSlice: 0, sourceLevel: 0, sourceOrigin: src, sourceSize: region,
|
||||
to: tex, destinationSlice: 0, destinationLevel: 0, destinationOrigin: dst)
|
||||
blit.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
if let e = cb.error {
|
||||
report(label, false, "the blit encoder refused a copy the guest treats as "
|
||||
+ "complete: \(e.localizedDescription)")
|
||||
return
|
||||
}
|
||||
|
||||
guard let got = readBack(readPipe, tex, width, height) else { refused(label); return }
|
||||
var bad: [(Int, Int)] = []
|
||||
var first = ""
|
||||
var unmoved = 0
|
||||
for y in 0..<height {
|
||||
for x in 0..<width where got[y * width + x] != want[y * width + x] {
|
||||
bad.append((x, y))
|
||||
// The destination still holding what it held before the copy is the
|
||||
// signature of a dropped copy, as against a mis-ordered one.
|
||||
if got[y * width + x] == texelPattern(x, y) { unmoved += 1 }
|
||||
if first.isEmpty {
|
||||
first = "first=(\(x),\(y)) want=\(hex(want[y * width + x])) "
|
||||
+ "got=\(hex(got[y * width + x]))"
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, bad.isEmpty,
|
||||
bad.isEmpty
|
||||
? "the overlapping copy read its source before writing its destination"
|
||||
: "wrong=\(bad.count)/\(width * height) still_pre_copy=\(unmoved) \(first)"
|
||||
+ badMap(bad, width, height))
|
||||
}
|
||||
|
||||
/// A row copied onto itself 14 texels to the right — the destination overwrites
|
||||
/// source texels the same row still has to read.
|
||||
func selfCopyOverlapRowShiftCase() {
|
||||
selfCopyCase("self_copy_overlap_row_shift_14",
|
||||
width: 128, height: 32,
|
||||
src: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
dst: MTLOrigin(x: 14, y: 0, z: 0),
|
||||
region: MTLSize(width: 20, height: 1, depth: 1))
|
||||
}
|
||||
|
||||
/// A one-texel column shifted twelve rows down — a top-down row loop overwrites
|
||||
/// rows 12 through 16 before it reads them.
|
||||
func selfCopyOverlapColumnShiftCase() {
|
||||
selfCopyCase("self_copy_overlap_column_shift_12",
|
||||
width: 256, height: 32,
|
||||
src: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
dst: MTLOrigin(x: 0, y: 12, z: 0),
|
||||
region: MTLSize(width: 1, height: 17, depth: 1))
|
||||
}
|
||||
|
||||
/// The control: the same call shape with rectangles that do not intersect, where
|
||||
/// both readings agree. A device that refuses every self-copy fails this too.
|
||||
func selfCopyDisjointCase() {
|
||||
selfCopyCase("self_copy_disjoint_control",
|
||||
width: 128, height: 32,
|
||||
src: MTLOrigin(x: 0, y: 0, z: 0),
|
||||
dst: MTLOrigin(x: 64, y: 0, z: 0),
|
||||
region: MTLSize(width: 20, height: 1, depth: 1))
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// `synchronizeResource:` is a no-op on unified memory and the explicit
|
||||
// GPU-to-CPU visibility operation for managed memory. The storage mode follows
|
||||
// the device topology, but the contract asserted by the case is identical: CPU
|
||||
// reads after command-buffer completion observe the preceding GPU writes.
|
||||
func synchronizeResourceCase() {
|
||||
let label = "synchronize_resource_gpu_to_cpu"
|
||||
let count = 4096
|
||||
let bytes = count * MemoryLayout<UInt32>.size
|
||||
let options: MTLResourceOptions = dev.hasUnifiedMemory
|
||||
? .storageModeShared
|
||||
: .storageModeManaged
|
||||
guard let words = dev.makeBuffer(length: bytes, options: options) else {
|
||||
report(label, false, "buffer creation failed")
|
||||
return
|
||||
}
|
||||
|
||||
memset(words.contents(), 0, bytes)
|
||||
if !dev.hasUnifiedMemory {
|
||||
words.didModifyRange(0..<bytes)
|
||||
}
|
||||
var token: UInt32 = 0x6A09E667
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let compute = cb.makeComputeCommandEncoder()!
|
||||
compute.setComputePipelineState(pipeline("sync_resource_write"))
|
||||
compute.setBuffer(words, offset: 0, index: 0)
|
||||
compute.setBytes(&token, length: MemoryLayout<UInt32>.size, index: 1)
|
||||
compute.dispatchThreads(MTLSize(width: count, height: 1, depth: 1),
|
||||
threadsPerThreadgroup: MTLSize(width: 64, height: 1, depth: 1))
|
||||
compute.endEncoding()
|
||||
|
||||
let blit = cb.makeBlitCommandEncoder()!
|
||||
blit.synchronize(resource: words)
|
||||
blit.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
|
||||
let got = words.contents().bindMemory(to: UInt32.self, capacity: count)
|
||||
if let bad = (0..<count).first(where: { got[$0] != token ^ UInt32($0) }) {
|
||||
report(label, false,
|
||||
"word=\(bad) got=\(hex(got[bad])) want=\(hex(token ^ UInt32(bad)))")
|
||||
return
|
||||
}
|
||||
report(label, true, "managed/shared GPU writes visible to CPU after synchronize")
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// A texture view bound as a shader resource.
|
||||
//
|
||||
// `makeTextureView` produces a texture object that owns no storage of its own:
|
||||
// it names a base texture's storage through a possibly different format, type,
|
||||
// level range, slice range or channel swizzle. Nothing else in this battery
|
||||
// binds one, and a view is not an incidental shape --- it is how a guest reads
|
||||
// one slice of an array, one level of a chain, or one channel order of an
|
||||
// allocation it does not own.
|
||||
//
|
||||
// The rail it exercises is the one a device gets wrong by building the view a
|
||||
// second image instead of naming the base's. That failure is not subtle when it
|
||||
// happens: the bind refuses, and every later command on the same channel refuses
|
||||
// behind it. But a device can also *silently* substitute --- read the base at
|
||||
// the wrong slice, or ignore the swizzle --- and only a predicted value catches
|
||||
// that. Each case here fills its base from the CPU with a pattern that differs
|
||||
// per texel and per slice, so a view that lands on the wrong storage, the wrong
|
||||
// slice, or the wrong channel order reports which.
|
||||
|
||||
/// The colour this battery expects at one texel of one slice.
|
||||
///
|
||||
/// Distinct in x, in y and in slice, so a view that reads the right texels of
|
||||
/// the wrong slice is not mistaken for a pass.
|
||||
private func viewTexel(_ x: Int, _ y: Int, _ slice: Int) -> (UInt8, UInt8, UInt8, UInt8) {
|
||||
(UInt8((x &* 7 &+ 11) & 0xFF),
|
||||
UInt8((y &* 13 &+ 29) & 0xFF),
|
||||
UInt8((slice &* 61 &+ 5) & 0xFF),
|
||||
0xFF)
|
||||
}
|
||||
|
||||
/// Fill one slice of a `.bgra8Unorm` texture from the CPU.
|
||||
private func fillViewSlice(_ tex: MTLTexture, _ w: Int, _ h: Int, slice: Int) {
|
||||
var bytes = [UInt8](repeating: 0, count: w * h * 4)
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let (r, g, b, a) = viewTexel(x, y, slice)
|
||||
let o = (y * w + x) * 4
|
||||
// `.bgra8Unorm` orders the bytes blue, green, red, alpha.
|
||||
bytes[o] = b; bytes[o + 1] = g; bytes[o + 2] = r; bytes[o + 3] = a
|
||||
}
|
||||
}
|
||||
bytes.withUnsafeBytes { raw in
|
||||
tex.replace(region: MTLRegionMake2D(0, 0, w, h),
|
||||
mipmapLevel: 0, slice: slice,
|
||||
withBytes: raw.baseAddress!,
|
||||
bytesPerRow: w * 4, bytesPerImage: w * h * 4)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one texture through `read_texels` and score it against `viewTexel`.
|
||||
private func checkViewReads(_ label: String, _ tex: MTLTexture,
|
||||
_ w: Int, _ h: Int, slice: Int) {
|
||||
guard let got = readBack(readPipe, tex, w, h) else {
|
||||
report(label, false, "compute readback never ran"); return
|
||||
}
|
||||
var bad: [(Int, Int)] = []
|
||||
var firstDetail = ""
|
||||
for y in 0..<h {
|
||||
for x in 0..<w {
|
||||
let (r, g, b, a) = viewTexel(x, y, slice)
|
||||
let want = pack(r, g, b, a)
|
||||
if got[y * w + x] != want {
|
||||
if bad.isEmpty {
|
||||
firstDetail = " first=(\(x),\(y)) want=\(hex(want)) got=\(hex(got[y * w + x]))"
|
||||
}
|
||||
bad.append((x, y))
|
||||
}
|
||||
}
|
||||
}
|
||||
report(label, bad.isEmpty,
|
||||
bad.isEmpty ? "\(w)x\(h) slice=\(slice) matched"
|
||||
: "\(badMap(bad, w, h))\(firstDetail)")
|
||||
}
|
||||
|
||||
/// A view over a plain private-storage 2D texture, identical in every
|
||||
/// parameter to its base.
|
||||
///
|
||||
/// The narrowest possible view, and therefore the one whose failure can only be
|
||||
/// the view mechanism: same format, same type, one level, one slice. A device
|
||||
/// that gives the view an image of its own fails here and nowhere earlier.
|
||||
func textureViewIdentityCase(_ w: Int, _ h: Int) {
|
||||
let label = "texture_view_identity_\(w)x\(h)"
|
||||
let d = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm, width: w, height: h, mipmapped: false)
|
||||
d.usage = [.shaderRead]
|
||||
d.storageMode = .shared
|
||||
guard let base = dev.makeTexture(descriptor: d) else {
|
||||
report(label, false, "makeTexture nil for \(w)x\(h)"); return
|
||||
}
|
||||
fillViewSlice(base, w, h, slice: 0)
|
||||
guard let view = base.makeTextureView(pixelFormat: .bgra8Unorm) else {
|
||||
report(label, false, "makeTextureView nil"); return
|
||||
}
|
||||
// The base first: if the base itself does not read back, the view's result
|
||||
// says nothing about views.
|
||||
checkViewReads("\(label)_base", base, w, h, slice: 0)
|
||||
checkViewReads("\(label)_view", view, w, h, slice: 0)
|
||||
}
|
||||
|
||||
/// A view of one slice of a 2D array, bound as a 2D texture.
|
||||
///
|
||||
/// Every slice carries a different pattern, so a view that reads the base's
|
||||
/// slice zero whatever it was asked for fails with a full-surface mismatch
|
||||
/// rather than passing on a texture whose slices happen to agree.
|
||||
func textureViewArraySliceCase(_ w: Int, _ h: Int, slices: Int) {
|
||||
let label = "texture_view_array_slice_\(w)x\(h)x\(slices)"
|
||||
let d = MTLTextureDescriptor()
|
||||
d.textureType = .type2DArray
|
||||
d.pixelFormat = .bgra8Unorm
|
||||
d.width = w; d.height = h; d.arrayLength = slices; d.mipmapLevelCount = 1
|
||||
d.usage = [.shaderRead]
|
||||
d.storageMode = .shared
|
||||
guard let base = dev.makeTexture(descriptor: d) else {
|
||||
report(label, false, "makeTexture nil for \(w)x\(h)x\(slices)"); return
|
||||
}
|
||||
for slice in 0..<slices { fillViewSlice(base, w, h, slice: slice) }
|
||||
for slice in 0..<slices {
|
||||
guard let view = base.makeTextureView(
|
||||
pixelFormat: .bgra8Unorm, textureType: .type2D,
|
||||
levels: 0..<1, slices: slice..<(slice + 1)) else {
|
||||
report("\(label)_s\(slice)", false, "makeTextureView nil"); return
|
||||
}
|
||||
checkViewReads("\(label)_s\(slice)", view, w, h, slice: slice)
|
||||
}
|
||||
}
|
||||
|
||||
/// A view over an IOSurface-backed texture.
|
||||
///
|
||||
/// The base owns a surface plane rather than an ordinary allocation, and the
|
||||
/// image belongs to the plane. A device that decides which resource owns an
|
||||
/// image by walking the view chain rather than by asking who owns the storage
|
||||
/// lands the view on the surface, which owns no image at all, and refuses.
|
||||
func textureViewOverSurfaceCase(_ w: Int, _ h: Int) {
|
||||
let label = "texture_view_over_surface_\(w)x\(h)"
|
||||
let bgra: UInt32 = 0x4247_5241 // 'BGRA' as an OSType
|
||||
let props: [IOSurfacePropertyKey: Any] = [
|
||||
.width: w, .height: h, .bytesPerElement: 4, .pixelFormat: bgra,
|
||||
]
|
||||
guard let surface = IOSurface(properties: props) else {
|
||||
report(label, false, "IOSurface(properties:) nil for \(w)x\(h)"); return
|
||||
}
|
||||
let d = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm, width: w, height: h, mipmapped: false)
|
||||
d.usage = [.shaderRead]
|
||||
d.storageMode = .shared
|
||||
guard let base = dev.makeTexture(descriptor: d, iosurface: surface, plane: 0) else {
|
||||
report(label, false, "makeTexture(iosurface:) nil for \(w)x\(h)"); return
|
||||
}
|
||||
fillViewSlice(base, w, h, slice: 0)
|
||||
guard let view = base.makeTextureView(pixelFormat: .bgra8Unorm) else {
|
||||
report(label, false, "makeTextureView nil"); return
|
||||
}
|
||||
checkViewReads("\(label)_base", base, w, h, slice: 0)
|
||||
checkViewReads("\(label)_view", view, w, h, slice: 0)
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
|
||||
// Primitive topology has two independently supplied terms: the pipeline's
|
||||
// topology class and the draw call's concrete primitive type. Each case keeps
|
||||
// those terms consistent and checks a spatial relation that a different
|
||||
// primitive cannot satisfy.
|
||||
|
||||
private let topologyWidth = 64
|
||||
private let topologyHeight = 64
|
||||
private let topologyGreen = pack(0, 255, 0, 255)
|
||||
private let topologyBlack = pack(0, 0, 0, 255)
|
||||
|
||||
private func topologyPipeline(vertex: String,
|
||||
class topologyClass: MTLPrimitiveTopologyClass)
|
||||
-> MTLRenderPipelineState? {
|
||||
let descriptor = MTLRenderPipelineDescriptor()
|
||||
descriptor.vertexFunction = library.makeFunction(name: vertex)
|
||||
descriptor.fragmentFunction = library.makeFunction(
|
||||
name: vertex == "point_vs" ? "point_fs" : "solid_fs")
|
||||
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
|
||||
descriptor.inputPrimitiveTopology = topologyClass
|
||||
return try? dev.makeRenderPipelineState(descriptor: descriptor)
|
||||
}
|
||||
|
||||
private func topologyPixels(name: String,
|
||||
positions: [SIMD2<Float>],
|
||||
primitive: MTLPrimitiveType,
|
||||
topologyClass: MTLPrimitiveTopologyClass,
|
||||
point: Bool = false) -> [UInt32]? {
|
||||
let vertexName = point ? "point_vs" : "topology_vs"
|
||||
guard let pipeline = topologyPipeline(vertex: vertexName, class: topologyClass) else {
|
||||
report(name, false, "render pipeline creation failed")
|
||||
return nil
|
||||
}
|
||||
|
||||
let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .bgra8Unorm,
|
||||
width: topologyWidth,
|
||||
height: topologyHeight,
|
||||
mipmapped: false)
|
||||
textureDescriptor.usage = [.renderTarget, .shaderRead]
|
||||
textureDescriptor.storageMode = .private
|
||||
guard let target = dev.makeTexture(descriptor: textureDescriptor),
|
||||
let vertices = dev.makeBuffer(bytes: positions,
|
||||
length: positions.count * MemoryLayout<SIMD2<Float>>.stride,
|
||||
options: .storageModeShared) else {
|
||||
report(name, false, "resource creation failed")
|
||||
return nil
|
||||
}
|
||||
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = target
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
|
||||
let commandBuffer = queue.makeCommandBuffer()!
|
||||
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass)!
|
||||
encoder.setRenderPipelineState(pipeline)
|
||||
encoder.setVertexBuffer(vertices, offset: 0, index: 0)
|
||||
if !point {
|
||||
var colour: [Float] = [0, 1, 0, 1]
|
||||
encoder.setFragmentBytes(&colour, length: 16, index: 0)
|
||||
}
|
||||
encoder.drawPrimitives(type: primitive, vertexStart: 0, vertexCount: positions.count)
|
||||
encoder.endEncoding()
|
||||
commandBuffer.commit()
|
||||
commandBuffer.waitUntilCompleted()
|
||||
|
||||
guard let pixels = readBack(readPipe, target, topologyWidth, topologyHeight) else {
|
||||
refused(name)
|
||||
return nil
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
private func lit(_ pixel: UInt32) -> Bool { pixel == topologyGreen }
|
||||
|
||||
private func pointTopologyCase() {
|
||||
let name = "topology_point_three_islands"
|
||||
let positions: [SIMD2<Float>] = [
|
||||
SIMD2(-0.65, -0.65),
|
||||
SIMD2(0.65, -0.65),
|
||||
SIMD2(0.0, 0.65),
|
||||
]
|
||||
guard let pixels = topologyPixels(name: name, positions: positions,
|
||||
primitive: .point, topologyClass: .point,
|
||||
point: true) else { return }
|
||||
let count = pixels.filter { lit($0) }.count
|
||||
let thirds = [
|
||||
pixels[53 * topologyWidth + 11],
|
||||
pixels[53 * topologyWidth + 52],
|
||||
pixels[11 * topologyWidth + 32],
|
||||
].filter { lit($0) }.count
|
||||
let ok = (9...60).contains(count) && thirds == 3
|
||||
report(name, ok, "lit=\(count) point_centres=\(thirds)/3")
|
||||
}
|
||||
|
||||
private func lineTopologyCase() {
|
||||
let name = "topology_line_horizontal"
|
||||
let positions = [SIMD2<Float>(-0.8, 0), SIMD2<Float>(0.8, 0)]
|
||||
guard let pixels = topologyPixels(name: name, positions: positions,
|
||||
primitive: .line, topologyClass: .line) else { return }
|
||||
let litRows = Set((0..<topologyHeight).filter { y in
|
||||
pixels[(y * topologyWidth)..<((y + 1) * topologyWidth)].contains(where: lit)
|
||||
})
|
||||
let count = pixels.filter { lit($0) }.count
|
||||
let ok = (32...128).contains(count) && (1...2).contains(litRows.count)
|
||||
report(name, ok, "lit=\(count) rows=\(litRows.sorted())")
|
||||
}
|
||||
|
||||
private func lineStripTopologyCase() {
|
||||
let name = "topology_line_strip_two_arms"
|
||||
let positions: [SIMD2<Float>] = [
|
||||
SIMD2(-0.75, -0.7), SIMD2(0, 0.7), SIMD2(0.75, -0.7),
|
||||
]
|
||||
guard let pixels = topologyPixels(name: name, positions: positions,
|
||||
primitive: .lineStrip, topologyClass: .line) else { return }
|
||||
var left = 0
|
||||
var right = 0
|
||||
for y in 0..<topologyHeight {
|
||||
for x in 0..<topologyWidth where lit(pixels[y * topologyWidth + x]) {
|
||||
if x < topologyWidth / 2 { left += 1 } else { right += 1 }
|
||||
}
|
||||
}
|
||||
let total = left + right
|
||||
let ok = left >= 20 && right >= 20 && (60...180).contains(total)
|
||||
report(name, ok, "lit=\(total) left=\(left) right=\(right)")
|
||||
}
|
||||
|
||||
private func triangleTopologyCase() {
|
||||
let name = "topology_triangle_filled"
|
||||
let positions: [SIMD2<Float>] = [
|
||||
SIMD2(-0.8, -0.7), SIMD2(0.8, -0.7), SIMD2(0, 0.8),
|
||||
]
|
||||
guard let pixels = topologyPixels(name: name, positions: positions,
|
||||
primitive: .triangle, topologyClass: .triangle) else { return }
|
||||
let count = pixels.filter { lit($0) }.count
|
||||
let centre = pixels[32 * topologyWidth + 32]
|
||||
let corner = pixels[2 * topologyWidth + 2]
|
||||
let ok = (900...1600).contains(count) && lit(centre) && corner == topologyBlack
|
||||
report(name, ok, "lit=\(count) centre=\(hex(centre)) corner=\(hex(corner))")
|
||||
}
|
||||
|
||||
func topologyCases() {
|
||||
pointTopologyCase()
|
||||
lineTopologyCase()
|
||||
lineStripTopologyCase()
|
||||
triangleTopologyCase()
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// F. The same linear alias, bound to a *fragment* stage in a render pass.
|
||||
//
|
||||
// Every case above reads the alias from a compute kernel. Type is not drawn
|
||||
// that way: a glyph atlas reaches the rasterizer as a fragment texture, and a
|
||||
// device may route a sampled guest image differently for the two stages. If a
|
||||
// linear alias is exact under `read_texels` and wrong here, the seam is the
|
||||
// stage binding and not the memory interpretation, which is a distinction no
|
||||
// screenshot and no compute-only battery can draw.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Draw a full-target quad sampling `tex` into a fresh `rgba8Unorm` target of
|
||||
/// the same size, and return the target's texels. With nearest filtering and a
|
||||
/// target sized to the texture, pixel (x, y) samples texel (x, y) exactly.
|
||||
func fragmentSample(_ tex: MTLTexture, _ w: Int, _ h: Int) -> [UInt32]? {
|
||||
guard let pipe = texPipeline else { return nil }
|
||||
let rd = MTLTextureDescriptor.texture2DDescriptor(
|
||||
pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false)
|
||||
rd.usage = [.renderTarget, .shaderRead]
|
||||
rd.storageMode = .private
|
||||
guard let rt = dev.makeTexture(descriptor: rd) else { return nil }
|
||||
let verts = dev.makeBuffer(bytes: quadVerts,
|
||||
length: quadVerts.count * 4,
|
||||
options: .storageModeShared)!
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = rt
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(red: 1, green: 0, blue: 1, alpha: 1)
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
let cb = queue.makeCommandBuffer()!
|
||||
let enc = cb.makeRenderCommandEncoder(descriptor: pass)!
|
||||
enc.setRenderPipelineState(pipe)
|
||||
enc.setVertexBuffer(verts, offset: 0, index: 0)
|
||||
enc.setFragmentTexture(tex, index: 0)
|
||||
enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
|
||||
enc.endEncoding()
|
||||
cb.commit()
|
||||
cb.waitUntilCompleted()
|
||||
return readBack(readPipe, rt, w, h)
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
// The battery’s running order. Every case invocation lives here and nowhere
|
||||
// else: Swift permits top-level statements in `main.swift` alone, so a case that
|
||||
// is not called from this file cannot run at all. The "a case nobody called
|
||||
// reports nothing, and the totals do not notice" trap is closed by construction
|
||||
// rather than by remembering.
|
||||
|
||||
import Metal
|
||||
import Foundation
|
||||
import IOSurface
|
||||
|
||||
if CommandLine.arguments.contains("--depth-task-child") {
|
||||
exit(depthTaskIsolationChild())
|
||||
}
|
||||
|
||||
if CommandLine.arguments.contains("--integer-clear-only") {
|
||||
integerClearCases()
|
||||
finish()
|
||||
}
|
||||
|
||||
if CommandLine.arguments.contains("--topology-only") {
|
||||
_ = library
|
||||
report("shader_compile", true, "runtime library built")
|
||||
topologyCases()
|
||||
finish()
|
||||
}
|
||||
|
||||
if CommandLine.arguments.contains("--float-sampling-only") {
|
||||
_ = library
|
||||
report("shader_compile", true, "runtime library built")
|
||||
floatSamplingCases()
|
||||
finish()
|
||||
}
|
||||
|
||||
if CommandLine.arguments.contains("--indexed-draw-only") {
|
||||
_ = library
|
||||
report("shader_compile", true, "runtime library built")
|
||||
indexedDrawCases()
|
||||
finish()
|
||||
}
|
||||
|
||||
// Shaderless by construction. A mismatch in either case is driver-owned, and
|
||||
// still runs if a later shader-library build exposes a translator failure.
|
||||
integerClearCases()
|
||||
|
||||
// `library` is lazily initialised now that it lives in a declaration
|
||||
// file, so force the build before the line that reports it.
|
||||
_ = library
|
||||
report("shader_compile", true, "runtime library built")
|
||||
|
||||
topologyCases()
|
||||
|
||||
floatSamplingCases()
|
||||
|
||||
indexedDrawCases()
|
||||
|
||||
depthTaskIsolationCase()
|
||||
|
||||
for f in formats {
|
||||
linearAliasCase(f, 64, 16, pitch: .tight, sampler: false)
|
||||
linearAliasCase(f, 64, 16, pitch: .tight, sampler: true)
|
||||
}
|
||||
|
||||
// The label-layer geometries, from a driven boot's own census. Their pitches
|
||||
// are the guest's, so a device whose `minimumLinearTextureAlignment` forbids
|
||||
// one skips it -- Metal itself would reject the descriptor there, and the
|
||||
// alignment differs by device (16 on an M-series host, 256 on Apple's
|
||||
// paravirtual one), so a literal pitch is not portable and must not be a
|
||||
// failure where it is simply not expressible.
|
||||
linearAliasCase(formats[1], 54, 16, pitch: .exact(64), sampler: false)
|
||||
|
||||
linearAliasCase(formats[1], 54, 16, pitch: .exact(64), sampler: true)
|
||||
|
||||
linearAliasCase(formats[1], 218, 16, pitch: .exact(256), sampler: false)
|
||||
|
||||
linearAliasCase(formats[1], 85, 85, pitch: .exact(128), sampler: false)
|
||||
|
||||
linearAliasCase(formats[0], 128, 16, pitch: .exact(128), sampler: false)
|
||||
|
||||
linearAliasCase(formats[4], 60, 8, pitch: .exact(256), sampler: false)
|
||||
|
||||
// The same shapes with the padding expressed against whatever this device's
|
||||
// alignment actually is, so every host runs a padded-pitch case whatever its
|
||||
// limit. One alignment unit of padding beyond tight, and then two.
|
||||
for f in formats {
|
||||
for rows in 1...2 {
|
||||
linearAliasCase(f, 54, 16, pitch: .padded(rows: rows), sampler: false)
|
||||
}
|
||||
}
|
||||
|
||||
for f in formats {
|
||||
incrementalCase(f, viaFragment: false)
|
||||
}
|
||||
|
||||
renderTargetCases()
|
||||
|
||||
multisampleStoreCase()
|
||||
|
||||
depthStencilIndependenceCases()
|
||||
|
||||
stencilIndependenceCases()
|
||||
|
||||
combinedDepthStencilDefaultBufferCopyCase()
|
||||
|
||||
mipCase()
|
||||
|
||||
mipBlitCase()
|
||||
|
||||
vertexBufferCase()
|
||||
|
||||
fragmentBufferCase()
|
||||
renderBarrierCase()
|
||||
computeBarrierCase(resourceBarrier: true)
|
||||
computeBarrierCase(resourceBarrier: false)
|
||||
indirectComputeDispatchCase()
|
||||
synchronizeResourceCase()
|
||||
heapTextureAliasCase()
|
||||
heapTexturePlacementOverlapCase()
|
||||
heapTexturePlacementOverlapWidthCase()
|
||||
bufferBackedAliasWidthCase()
|
||||
bufferBackedAliasPartialCase()
|
||||
encoderBindingLifetimeCase()
|
||||
sameQueueCommandBufferOrderCase()
|
||||
sameQueueCompletionPublicationCase()
|
||||
emptyCommandBufferCompletionCase()
|
||||
independentQueueCompletionPublicationCase()
|
||||
scheduledBeforeCompletedPublicationCase()
|
||||
defaultCommandBufferRetainsResourceCase()
|
||||
indirectCommandMutationCase()
|
||||
pipelineInformationCase()
|
||||
|
||||
// A bound texture view names its base's storage. Identity first, so a failure
|
||||
// there is the view mechanism and nothing else; then a slice of an array, which
|
||||
// says the view reached the right storage and not merely some storage; then a
|
||||
// view over a surface plane, where the resource that owns the image is not the
|
||||
// one at the end of the view chain.
|
||||
textureViewIdentityCase(64, 32)
|
||||
textureViewIdentityCase(256, 64)
|
||||
textureViewArraySliceCase(64, 32, slices: 3)
|
||||
textureViewOverSurfaceCase(64, 32)
|
||||
selfCopyOverlapRowShiftCase()
|
||||
selfCopyOverlapColumnShiftCase()
|
||||
selfCopyDisjointCase()
|
||||
textureViewOverSurfaceCase(256, 64)
|
||||
|
||||
if texPipeline == nil {
|
||||
report("fragsample_pipeline", false, "tex_fs pipeline would not build")
|
||||
} else {
|
||||
fragmentAliasCase(formats[1], 54, 16, pitch: .exact(64)) // the label geometry
|
||||
fragmentAliasCase(formats[1], 218, 16, pitch: .exact(256))
|
||||
fragmentAliasCase(formats[1], 85, 85, pitch: .exact(128))
|
||||
fragmentAliasCase(formats[3], 64, 16, pitch: .tight) // rgba8, tight
|
||||
fragmentAliasCase(formats[4], 60, 8, pitch: .exact(256)) // bgra8, padded
|
||||
// And once more with the padding derived from this device's own limit, so
|
||||
// a host whose alignment skipped the literal pitches above still runs a
|
||||
// padded fragment-sampled alias.
|
||||
for f in [formats[1], formats[4]] {
|
||||
fragmentAliasCase(f, 54, 16, pitch: .padded(rows: 1))
|
||||
}
|
||||
}
|
||||
|
||||
// The glyph-atlas lifecycle from section B, now through the stage the type
|
||||
// layer actually uses. This is the arm that can see a defect on the draw path,
|
||||
// and for `a8Unorm` it is the only arm that produces a reading at all.
|
||||
for f in formats {
|
||||
incrementalCase(f, viaFragment: true)
|
||||
}
|
||||
|
||||
// The same lifecycle again, filled by `replaceRegion:` rather than through a
|
||||
// buffer alias — section H says why the two are different rails. Declared
|
||||
// there, invoked here, because the fragment arm needs `texPipeline`.
|
||||
for f in formats {
|
||||
replaceRegionCase(f, viaFragment: true)
|
||||
}
|
||||
|
||||
// Tight and padded, read both ways, so the pitch is the only thing that varies
|
||||
// between a passing case and a failing one.
|
||||
// 256 and 250 rather than the device's alignment and six under it: at one byte
|
||||
// per texel both round up to a tight pitch of 256 on a device that aligns to 16
|
||||
// and on one that aligns to 256, so the pair means "no padding" and "six bytes
|
||||
// of padding" on either host and the two runs pair up by name.
|
||||
for viaFragment in [false, true] {
|
||||
offsetOracleCase(256, 16, pitch: .tight, viaFragment: viaFragment)
|
||||
offsetOracleCase(250, 16, pitch: .tight, viaFragment: viaFragment)
|
||||
offsetOracleCase(218, 16, pitch: .tight, viaFragment: viaFragment)
|
||||
offsetOracleCase(54, 16, pitch: .padded(rows: 1), viaFragment: viaFragment)
|
||||
}
|
||||
|
||||
for w in [256, 250, 218, 64, 60, 54, 63, 57] { targetWidthCase(w, 16) }
|
||||
|
||||
// A width that divides the threadgroup and one that does not, in both axes.
|
||||
gridBoundsCase(64, 16, 8)
|
||||
|
||||
gridBoundsCase(218, 16, 8)
|
||||
|
||||
gridBoundsCase(54, 15, 8)
|
||||
|
||||
gridBoundsCase(57, 9, 8)
|
||||
|
||||
gridBoundsCase(31, 31, 16)
|
||||
|
||||
cpuWriteAfterRenderCase(64, 32, secondPass: false)
|
||||
|
||||
cpuWriteAfterRenderCase(64, 32, secondPass: true)
|
||||
|
||||
cpuWriteAfterRenderCase(256, 64, secondPass: false)
|
||||
|
||||
cpuWriteAfterRenderCase(256, 64, secondPass: true)
|
||||
|
||||
offsetAliasCase(formats[1], 54, 16, tiles: 4)
|
||||
|
||||
offsetAliasCase(formats[3], 32, 32, tiles: 3)
|
||||
|
||||
for f in formats {
|
||||
replaceRegionCase(f, viaFragment: false)
|
||||
}
|
||||
|
||||
sharedTargetCases(60, 32)
|
||||
|
||||
sharedTargetCases(256, 64)
|
||||
|
||||
sharedTargetCases(1000, 40)
|
||||
|
||||
sharedTargetCpuSeedCase(60, 32)
|
||||
|
||||
sharedTargetCpuSeedCase(256, 64)
|
||||
|
||||
sharedTargetCpuSeedCase(1000, 40)
|
||||
|
||||
sharedTargetGlyphCase(60, 32)
|
||||
|
||||
sharedTargetGlyphCase(256, 64)
|
||||
|
||||
sharedTargetGlyphCase(1000, 40)
|
||||
|
||||
biplanarSurfaceCase(64, 32)
|
||||
|
||||
biplanarSurfaceCase(256, 64)
|
||||
|
||||
iosurfaceCases(60, 32)
|
||||
|
||||
iosurfaceCases(256, 64)
|
||||
|
||||
iosurfaceCases(1000, 40)
|
||||
|
||||
for (cw, ch) in [(60, 32), (256, 64), (1000, 40)] {
|
||||
cpuWriteThenSampleCase(cw, ch, iosurface: false)
|
||||
cpuWriteThenSampleCase(cw, ch, iosurface: true)
|
||||
}
|
||||
|
||||
blitAfterRenderCase(1024, 768)
|
||||
|
||||
blitAfterRenderCase(1920, 1080)
|
||||
|
||||
blitPipelinedCase(1024, 768, frames: 8)
|
||||
|
||||
blitIOSurfaceSourceCase(1024, 768, frames: 8)
|
||||
|
||||
blitIOSurfaceSourceCase(1920, 1080, frames: 4)
|
||||
|
||||
blitBufferBackedCase(512, 512)
|
||||
|
||||
// A device-wide waiter-first scheduling defect can stop all later work, so
|
||||
// this bounded probe deliberately closes the battery.
|
||||
crossQueueSharedEventVisibilityCase()
|
||||
|
||||
finish()
|
||||
@@ -1,76 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Behavioral tests for conformance failure ownership."""
|
||||
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
VERDICT = Path(__file__).resolve().parents[1] / "verdict.py"
|
||||
|
||||
|
||||
class VerdictOwnershipTests(unittest.TestCase):
|
||||
def run_verdict(self, translation: str = "", driver: str = "", guest: str = "FAIL"):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
native = root / "native.txt"
|
||||
guest_run = root / "guest.txt"
|
||||
translation_errors = root / "translation-errors.txt"
|
||||
driver_errors = root / "driver-errors.txt"
|
||||
native.write_text("CASE sample PASS oracle\nDEVICE native\n")
|
||||
guest_run.write_text(f"CASE sample {guest} guest\nDEVICE guest\n")
|
||||
translation_errors.write_text(translation)
|
||||
driver_errors.write_text(driver)
|
||||
return subprocess.run(
|
||||
[
|
||||
"python3",
|
||||
str(VERDICT),
|
||||
"--native",
|
||||
str(native),
|
||||
"--guest",
|
||||
str(guest_run),
|
||||
"--translation-errors",
|
||||
str(translation_errors),
|
||||
"--driver-errors",
|
||||
str(driver_errors),
|
||||
"--quiet",
|
||||
],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
def test_translation_failure_is_named_and_accepted(self):
|
||||
result = self.run_verdict(translation="sample # package=sample-query\n")
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("translation sample", result.stdout)
|
||||
self.assertIn("active translation failures 1/1, active driver failures 0/0", result.stdout)
|
||||
|
||||
def test_driver_failure_is_named_and_accepted(self):
|
||||
result = self.run_verdict(driver="sample # clear publication ordering\n")
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("driver sample", result.stdout)
|
||||
self.assertIn("active translation failures 0/0, active driver failures 1/1", result.stdout)
|
||||
|
||||
def test_one_failure_cannot_have_two_owners(self):
|
||||
result = self.run_verdict(
|
||||
translation="sample # package=sample-query\n",
|
||||
driver="sample # publication ordering\n",
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("DUPLICATE-CLASSIFICATION sample", result.stdout)
|
||||
|
||||
def test_unclassified_guest_failure_remains_a_regression(self):
|
||||
result = self.run_verdict()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("REGRESSION sample", result.stdout)
|
||||
|
||||
def test_passing_known_failure_is_stale(self):
|
||||
result = self.run_verdict(driver="sample # publication ordering\n", guest="PASS")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("FIXED-DRIVER sample", result.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,206 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score a guest run against the native one, and against what is already known.
|
||||
|
||||
The battery prints one line per case and a reader compares two runs by eye. That
|
||||
works until the counts stop matching, and then it does not work at all: a case
|
||||
that stopped being invoked and a case that started failing look the same in a
|
||||
summary line, and the interesting one is the one nobody notices.
|
||||
|
||||
The rules are the README's table, mechanised. Read them in the order they fire,
|
||||
because the first two say a reading is *not* about this device:
|
||||
|
||||
native FAIL the expectation in the suite is wrong. Not a finding, and
|
||||
every guest reading of that case is meaningless until it
|
||||
is fixed.
|
||||
native missing the case ran in the guest and never natively. There is no
|
||||
oracle for it, so its guest result says nothing.
|
||||
guest missing a case the oracle ran and the guest did not report at
|
||||
all. Either it was never invoked or the run died mid-way.
|
||||
guest FAIL, classified
|
||||
a defect already written down as translator- or
|
||||
driver-owned. Report its owner without failing.
|
||||
guest FAIL, new a regression, and the reason this tool exits non-zero.
|
||||
guest PASS, classified
|
||||
the inventory is stale. Also non-zero: an inventory
|
||||
nobody prunes stops being a list of defects and becomes
|
||||
a list of cases nobody looks at.
|
||||
guest SKIP the device's own reported limits make the case
|
||||
inexpressible. Never a failure.
|
||||
|
||||
And one more, which needs the device's own fail log rather than the two runs.
|
||||
A case may print `ROUTE <case> <counter>` to claim the device rail it was
|
||||
written to move. If the counter never moves in the whole run, the case is
|
||||
NOT-COVERED however green it is -- three attempts at the regression case for
|
||||
the unordered host read passed on the broken build for exactly that reason.
|
||||
The check is per run, not per case: nothing carries a case name into the
|
||||
device. A narrowing `REIMS_VGPU_*` switch can close the rail a claim names
|
||||
legitimately, so `--claims-advisory` reports those without failing the run.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
|
||||
CASE = re.compile(r"^CASE (\S+) (PASS|FAIL|SKIP) ?(.*)$")
|
||||
ROUTE = re.compile(r"^ROUTE (\S+) (\S+)$")
|
||||
DEVICE = re.compile(r"^DEVICE (.*)$")
|
||||
|
||||
|
||||
def parse(path):
|
||||
"""Case name -> (verdict, detail), the DEVICE line, duplicates, route claims.
|
||||
|
||||
A case name repeats when a battery is edited badly; keep the first and say
|
||||
so rather than letting the later one overwrite it silently.
|
||||
"""
|
||||
cases, device, dupes, routes = {}, None, [], {}
|
||||
with open(path) as fh:
|
||||
for line in fh:
|
||||
line = line.rstrip("\n")
|
||||
m = ROUTE.match(line)
|
||||
if m:
|
||||
routes.setdefault(m.group(1), []).append(m.group(2))
|
||||
continue
|
||||
m = CASE.match(line)
|
||||
if m:
|
||||
if m.group(1) in cases:
|
||||
dupes.append(m.group(1))
|
||||
else:
|
||||
cases[m.group(1)] = (m.group(2), m.group(3))
|
||||
continue
|
||||
m = DEVICE.match(line)
|
||||
if m:
|
||||
device = m.group(1)
|
||||
return cases, device, dupes, routes
|
||||
|
||||
|
||||
def expectations(path):
|
||||
"""Known guest failures: one case name a line, `#` starts a comment."""
|
||||
known = {}
|
||||
if not path:
|
||||
return known
|
||||
try:
|
||||
fh = open(path)
|
||||
except FileNotFoundError:
|
||||
return known
|
||||
with fh:
|
||||
for line in fh:
|
||||
body, _, why = line.partition("#")
|
||||
name = body.strip()
|
||||
if name:
|
||||
known[name] = why.strip()
|
||||
return known
|
||||
|
||||
|
||||
def counters_that_moved(path):
|
||||
"""Every `name=<non-zero>` this device reported anywhere in its fail log.
|
||||
|
||||
Deliberately not a sum. A counter is per-census-window for some records and
|
||||
a cumulative high-water for others, and the question here is only whether
|
||||
the rail was reached at all, which both spellings answer the same way.
|
||||
"""
|
||||
moved = set()
|
||||
if not path:
|
||||
return None
|
||||
try:
|
||||
fh = open(path, errors="replace")
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
with fh:
|
||||
for line in fh:
|
||||
for name, value in re.findall(r"([a-z][a-z_0-9]*)=([0-9]+)", line):
|
||||
if value != "0":
|
||||
moved.add(name)
|
||||
return moved
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--native", required=True, help="the oracle run, or a baseline")
|
||||
ap.add_argument("--guest", required=True)
|
||||
ap.add_argument("--translation-errors", required=True,
|
||||
help="translator-owned failures, each backed by a bugs/ package")
|
||||
ap.add_argument("--driver-errors", required=True,
|
||||
help="non-translation device failures")
|
||||
ap.add_argument("--device", help="the device's own fail log, for route claims")
|
||||
ap.add_argument("--claims-advisory", action="store_true",
|
||||
help="report an unmoved route claim without failing the run; "
|
||||
"what to pass when a narrowing REIMS_VGPU_* switch is set")
|
||||
ap.add_argument("--quiet", action="store_true", help="only the lines that matter")
|
||||
args = ap.parse_args()
|
||||
|
||||
native, native_dev, native_dupes, _ = parse(args.native)
|
||||
guest, guest_dev, guest_dupes, claims = parse(args.guest)
|
||||
translation = expectations(args.translation_errors)
|
||||
driver = expectations(args.driver_errors)
|
||||
moved = counters_that_moved(args.device)
|
||||
|
||||
rows, bad = [], 0
|
||||
active_translation = 0
|
||||
active_driver = 0
|
||||
for name in sorted(set(native) | set(guest)):
|
||||
n = native.get(name)
|
||||
g = guest.get(name)
|
||||
detail = (g or n or ("", ""))[1]
|
||||
if n and n[0] == "FAIL":
|
||||
verdict, note = "SUITE-BUG", "fails on the oracle: the expectation is wrong"
|
||||
elif not n:
|
||||
verdict, note = "NO-ORACLE", "never ran natively, so the guest result says nothing"
|
||||
elif not g:
|
||||
verdict, note = "NOT-RUN", "the oracle ran it and the guest did not report it"
|
||||
elif g[0] == "SKIP":
|
||||
verdict, note = "skip", detail
|
||||
elif g[0] == "FAIL" and name in translation:
|
||||
verdict, note = "translation", translation[name] or detail
|
||||
active_translation += 1
|
||||
elif g[0] == "FAIL" and name in driver:
|
||||
verdict, note = "driver", driver[name] or detail
|
||||
active_driver += 1
|
||||
elif g[0] == "FAIL":
|
||||
verdict, note = "REGRESSION", detail
|
||||
elif name in translation:
|
||||
verdict = "FIXED-TRANSLATION"
|
||||
note = "passes now; remove it from the translation inventory"
|
||||
elif name in driver:
|
||||
verdict = "FIXED-DRIVER"
|
||||
note = "passes now; remove it from the driver inventory"
|
||||
elif moved is not None and name in claims and not all(
|
||||
c in moved for c in claims[name]):
|
||||
missing = [c for c in claims[name] if c not in moved]
|
||||
verdict = "not-covered" if args.claims_advisory else "NOT-COVERED"
|
||||
note = "passed without moving " + ", ".join(missing)
|
||||
else:
|
||||
verdict, note = "ok", ""
|
||||
if verdict.isupper() or verdict in ("translation", "driver", "not-covered"):
|
||||
bad += verdict.isupper()
|
||||
rows.append((verdict, name, note))
|
||||
elif not args.quiet:
|
||||
rows.append((verdict, name, note))
|
||||
|
||||
for name in sorted(set(native_dupes) | set(guest_dupes)):
|
||||
rows.append(("DUPLICATE", name, "reported twice in one run"))
|
||||
bad += 1
|
||||
|
||||
for name in sorted(set(translation) & set(driver)):
|
||||
rows.append(("DUPLICATE-CLASSIFICATION", name,
|
||||
"listed as both translator- and driver-owned"))
|
||||
bad += 1
|
||||
|
||||
width = max((len(r[0]) for r in rows), default=0)
|
||||
for verdict, name, note in rows:
|
||||
print(f"{verdict:<{width}} {name}" + (f" -- {note}" if note else ""))
|
||||
|
||||
print()
|
||||
print(f"native {len(native)} cases from {native_dev or 'an unnamed device'}")
|
||||
print(f"guest {len(guest)} cases from {guest_dev or 'an unnamed device'}")
|
||||
claimed = len(claims)
|
||||
if moved is None:
|
||||
print(f"{claimed} cases claim a device rail; no fail log given to check them")
|
||||
else:
|
||||
print(f"{claimed} cases claim a device rail")
|
||||
print(f"active translation failures {active_translation}/{len(translation)}, "
|
||||
f"active driver failures {active_driver}/{len(driver)}, unexplained {bad}")
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Generated
+2094
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,41 @@
|
||||
# reims-ctl: creates, boots and manages macOS VMs on QEMU's apple-gfx (README.md). It links
|
||||
# nothing of the library: it runs the QEMU that scripts/install-ctl.sh builds on it. Its own
|
||||
# workspace, so it builds without the rest of the tree (or the metal2vulkan the library's
|
||||
# workspace fetches).
|
||||
[package]
|
||||
name = "reims-ctl"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.98.1"
|
||||
publish = false
|
||||
license = "GPL-2.0-or-later OR LGPL-3.0-or-later"
|
||||
description = "Create, boot and manage macOS VMs on QEMU with reims-vgpu"
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
clap = { version = "4.6.7", features = ["derive", "env", "wrap_help"] }
|
||||
crc32fast = "1.5.2"
|
||||
flate2 = "1.1.10"
|
||||
libc = "0.2.190"
|
||||
ratatui = "0.30.2"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.153"
|
||||
shlex = "2.0.1"
|
||||
toml = "1.1.2"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Lists the host's Vulkan GPUs; `loaded` opens the Vulkan loader at run time, so the binary
|
||||
# needs no Vulkan to start.
|
||||
ash = { version = "0.38", default-features = false, features = ["std", "loaded"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Installs macOS from an IPSW into a new VM (vz.rs): only Virtualization.framework restores one.
|
||||
block2 = "0.6.2"
|
||||
objc2 = "0.6.5"
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSError", "NSString", "NSURL", "NSData", "NSProgress", "NSObject", "NSArray", "NSRunLoop", "NSDate"] }
|
||||
objc2-virtualization = "0.3.2"
|
||||
|
||||
[profile.release]
|
||||
debug = "line-tables-only"
|
||||
@@ -0,0 +1,2 @@
|
||||
# reims-ctl's own: the repository root's bans (architecture 17.4) are the library's, whose
|
||||
# threads, locks and clocks come from its platform. reims-ctl links nothing of the library.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,579 @@
|
||||
//! A form for the interface: text, path, choice and toggle fields, some shown only for some
|
||||
//! answers of another field (`show_if`).
|
||||
//!
|
||||
//! Keys: Up and Down (or Tab and Shift-Tab) move between fields; Left and Right, or Space,
|
||||
//! change a choice or toggle; typing edits text; Tab in a path field completes it as a shell
|
||||
//! would, and moves on when there is nothing to complete; Enter moves on, and on the last field
|
||||
//! submits; Ctrl-S submits from anywhere; Esc cancels.
|
||||
|
||||
use ratatui::Frame;
|
||||
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
use ratatui::style::{Color, Modifier, Style, Stylize};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub enum Value {
|
||||
Text {
|
||||
text: String,
|
||||
cursor: usize,
|
||||
placeholder: String,
|
||||
path: bool,
|
||||
},
|
||||
Choice {
|
||||
options: Vec<(String, String)>,
|
||||
index: usize,
|
||||
},
|
||||
Toggle(bool),
|
||||
}
|
||||
|
||||
pub struct Field {
|
||||
pub key: &'static str,
|
||||
pub label: String,
|
||||
pub help: String,
|
||||
pub value: Value,
|
||||
pub show_if: Option<(&'static str, Vec<&'static str>)>,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
pub fn text(key: &'static str, label: &str, value: &str, help: &str) -> Field {
|
||||
Field {
|
||||
key,
|
||||
label: label.into(),
|
||||
help: help.into(),
|
||||
value: Value::Text {
|
||||
text: value.into(),
|
||||
cursor: value.chars().count(),
|
||||
placeholder: String::new(),
|
||||
path: false,
|
||||
},
|
||||
show_if: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(key: &'static str, label: &str, value: &str, help: &str) -> Field {
|
||||
let mut f = Field::text(key, label, value, help);
|
||||
if let Value::Text { path, .. } = &mut f.value {
|
||||
*path = true;
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
pub fn choice(
|
||||
key: &'static str,
|
||||
label: &str,
|
||||
options: Vec<(String, String)>,
|
||||
selected: &str,
|
||||
help: &str,
|
||||
) -> Field {
|
||||
let index = options
|
||||
.iter()
|
||||
.position(|(id, _)| id == selected)
|
||||
.unwrap_or(0);
|
||||
Field {
|
||||
key,
|
||||
label: label.into(),
|
||||
help: help.into(),
|
||||
value: Value::Choice { options, index },
|
||||
show_if: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toggle(key: &'static str, label: &str, on: bool, help: &str) -> Field {
|
||||
Field {
|
||||
key,
|
||||
label: label.into(),
|
||||
help: help.into(),
|
||||
value: Value::Toggle(on),
|
||||
show_if: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn placeholder(mut self, p: &str) -> Field {
|
||||
if let Value::Text { placeholder, .. } = &mut self.value {
|
||||
*placeholder = p.into();
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn show_if(mut self, key: &'static str, values: &[&'static str]) -> Field {
|
||||
self.show_if = Some((key, values.to_vec()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn opts(list: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
list.iter()
|
||||
.map(|(a, b)| (a.to_string(), b.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub struct Form {
|
||||
pub title: String,
|
||||
pub fields: Vec<Field>,
|
||||
pub focus: usize,
|
||||
pub error: Option<String>,
|
||||
pub submit: String,
|
||||
}
|
||||
|
||||
pub enum Event {
|
||||
None,
|
||||
Submit,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
impl Form {
|
||||
pub fn new(title: &str, submit: &str, fields: Vec<Field>) -> Form {
|
||||
Form {
|
||||
title: title.into(),
|
||||
fields,
|
||||
focus: 0,
|
||||
error: None,
|
||||
submit: submit.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(&self, i: usize) -> bool {
|
||||
match &self.fields[i].show_if {
|
||||
None => true,
|
||||
Some((key, values)) => {
|
||||
let Some(j) = self.fields.iter().position(|f| f.key == *key) else {
|
||||
return true;
|
||||
};
|
||||
self.shown(j) && values.iter().any(|v| self.choice_at(j) == *v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visible(&self) -> Vec<usize> {
|
||||
(0..self.fields.len()).filter(|&i| self.shown(i)).collect()
|
||||
}
|
||||
|
||||
pub fn is_shown(&self, key: &str) -> bool {
|
||||
self.fields
|
||||
.iter()
|
||||
.position(|f| f.key == key)
|
||||
.is_some_and(|i| self.shown(i))
|
||||
}
|
||||
|
||||
fn choice_at(&self, i: usize) -> String {
|
||||
match &self.fields[i].value {
|
||||
Value::Choice { options, index } => {
|
||||
options.get(*index).map(|o| o.0.clone()).unwrap_or_default()
|
||||
}
|
||||
Value::Toggle(b) => if *b { "yes" } else { "no" }.into(),
|
||||
Value::Text { text, .. } => text.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn field(&self, key: &str) -> Option<&Field> {
|
||||
self.fields.iter().find(|f| f.key == key)
|
||||
}
|
||||
|
||||
/// A text field's value, trimmed; empty when hidden.
|
||||
pub fn text(&self, key: &str) -> String {
|
||||
if !self.is_shown(key) {
|
||||
return String::new();
|
||||
}
|
||||
match self.field(key).map(|f| &f.value) {
|
||||
Some(Value::Text { text, .. }) => text.trim().to_string(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn choice(&self, key: &str) -> String {
|
||||
self.fields
|
||||
.iter()
|
||||
.position(|f| f.key == key)
|
||||
.map(|i| self.choice_at(i))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn toggle(&self, key: &str) -> bool {
|
||||
matches!(self.field(key).map(|f| &f.value), Some(Value::Toggle(true)))
|
||||
}
|
||||
|
||||
/// Replaces a choice's options, keeping its selection where it remains.
|
||||
pub fn set_options(&mut self, key: &str, new: Vec<(String, String)>) {
|
||||
if let Some(f) = self.fields.iter_mut().find(|f| f.key == key)
|
||||
&& let Value::Choice { options, index } = &mut f.value
|
||||
{
|
||||
let cur = options.get(*index).map(|o| o.0.clone());
|
||||
*index = cur
|
||||
.and_then(|c| new.iter().position(|o| o.0 == c))
|
||||
.unwrap_or(0);
|
||||
*options = new;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn focused_key(&self) -> &'static str {
|
||||
self.fields[self.focus].key
|
||||
}
|
||||
|
||||
fn move_focus(&mut self, forward: bool) {
|
||||
let v = self.visible();
|
||||
if v.is_empty() {
|
||||
return;
|
||||
}
|
||||
let pos = v.iter().position(|&i| i == self.focus).unwrap_or(0);
|
||||
let next = if forward {
|
||||
(pos + 1) % v.len()
|
||||
} else {
|
||||
(pos + v.len() - 1) % v.len()
|
||||
};
|
||||
self.focus = v[next];
|
||||
}
|
||||
|
||||
fn at_last(&self) -> bool {
|
||||
self.visible().last() == Some(&self.focus)
|
||||
}
|
||||
|
||||
pub fn handle_key(&mut self, k: KeyEvent) -> Event {
|
||||
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
|
||||
if !self.visible().contains(&self.focus) {
|
||||
self.focus = self.visible().first().copied().unwrap_or(0);
|
||||
}
|
||||
match k.code {
|
||||
KeyCode::Esc => return Event::Cancel,
|
||||
KeyCode::Char('s') if ctrl => return Event::Submit,
|
||||
KeyCode::Char('c') if ctrl => return Event::Cancel,
|
||||
KeyCode::Up | KeyCode::BackTab => {
|
||||
self.move_focus(false);
|
||||
return Event::None;
|
||||
}
|
||||
KeyCode::Down => {
|
||||
self.move_focus(true);
|
||||
return Event::None;
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
if self.at_last() {
|
||||
return Event::Submit;
|
||||
}
|
||||
self.move_focus(true);
|
||||
return Event::None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.error = None;
|
||||
let field = &mut self.fields[self.focus];
|
||||
match &mut field.value {
|
||||
Value::Choice { options, index } => match k.code {
|
||||
KeyCode::Left => {
|
||||
*index = (*index + options.len().max(1) - 1) % options.len().max(1)
|
||||
}
|
||||
KeyCode::Right | KeyCode::Char(' ') => *index = (*index + 1) % options.len().max(1),
|
||||
KeyCode::Tab => self.move_focus(true),
|
||||
_ => {}
|
||||
},
|
||||
Value::Toggle(b) => match k.code {
|
||||
KeyCode::Left | KeyCode::Right | KeyCode::Char(' ') => *b = !*b,
|
||||
KeyCode::Char('y') => *b = true,
|
||||
KeyCode::Char('n') => *b = false,
|
||||
KeyCode::Tab => self.move_focus(true),
|
||||
_ => {}
|
||||
},
|
||||
Value::Text {
|
||||
text, cursor, path, ..
|
||||
} => {
|
||||
let byte =
|
||||
|t: &str, c: usize| t.char_indices().nth(c).map(|(i, _)| i).unwrap_or(t.len());
|
||||
match k.code {
|
||||
KeyCode::Char('a') if ctrl => *cursor = 0,
|
||||
KeyCode::Char('e') if ctrl => *cursor = text.chars().count(),
|
||||
KeyCode::Char('u') if ctrl => {
|
||||
text.clear();
|
||||
*cursor = 0;
|
||||
}
|
||||
KeyCode::Char('w') if ctrl => {
|
||||
let b = byte(text, *cursor);
|
||||
let head = text[..b].trim_end_matches('/');
|
||||
let cut = head.rfind(['/', ' ']).map(|i| i + 1).unwrap_or(0);
|
||||
text.replace_range(cut..b, "");
|
||||
*cursor = text[..cut].chars().count();
|
||||
}
|
||||
KeyCode::Char(c) if !ctrl => {
|
||||
let b = byte(text, *cursor);
|
||||
text.insert(b, c);
|
||||
*cursor += 1;
|
||||
}
|
||||
KeyCode::Backspace if *cursor > 0 => {
|
||||
let b = byte(text, *cursor - 1);
|
||||
text.remove(b);
|
||||
*cursor -= 1;
|
||||
}
|
||||
KeyCode::Delete if *cursor < text.chars().count() => {
|
||||
let b = byte(text, *cursor);
|
||||
text.remove(b);
|
||||
}
|
||||
KeyCode::Left => *cursor = cursor.saturating_sub(1),
|
||||
KeyCode::Right => *cursor = (*cursor + 1).min(text.chars().count()),
|
||||
KeyCode::Home => *cursor = 0,
|
||||
KeyCode::End => *cursor = text.chars().count(),
|
||||
KeyCode::Tab => {
|
||||
if *path && let Some(done) = complete(text) {
|
||||
*text = done;
|
||||
*cursor = text.chars().count();
|
||||
} else {
|
||||
self.move_focus(true);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::None
|
||||
}
|
||||
|
||||
pub fn render(&self, f: &mut Frame, area: Rect) {
|
||||
let visible = self.visible();
|
||||
let width = area.width.saturating_sub(4).clamp(area.width.min(40), 110);
|
||||
let help = &self.fields[self.focus].help;
|
||||
let help_lines = wrap_count(help, width.saturating_sub(4)) as u16;
|
||||
let rows = visible.len() as u16;
|
||||
let height = (rows + help_lines + 6 + u16::from(self.error.is_some()) * 2)
|
||||
.min(area.height.saturating_sub(2))
|
||||
.max(8);
|
||||
let popup = area.centered(Constraint::Length(width), Constraint::Length(height));
|
||||
f.render_widget(Clear, popup);
|
||||
let block = Block::bordered()
|
||||
.title(Line::from(format!(" {} ", self.title)).bold())
|
||||
.title_bottom(
|
||||
Line::from(format!(
|
||||
" Enter next · Ctrl-S {} · Esc cancel ",
|
||||
self.submit
|
||||
))
|
||||
.dim(),
|
||||
)
|
||||
.border_style(Style::new().fg(Color::Cyan));
|
||||
let inner = block.inner(popup);
|
||||
f.render_widget(block, popup);
|
||||
let [list_area, help_area] = Layout::vertical([
|
||||
Constraint::Min(1),
|
||||
Constraint::Length(help_lines + 1 + u16::from(self.error.is_some()) * 2),
|
||||
])
|
||||
.areas(inner);
|
||||
|
||||
let label_w = 26u16.min(list_area.width / 2);
|
||||
let n = list_area.height as usize;
|
||||
let pos = visible.iter().position(|&i| i == self.focus).unwrap_or(0);
|
||||
let start = if pos >= n { pos + 1 - n } else { 0 };
|
||||
for (row, &i) in visible.iter().enumerate().skip(start).take(n) {
|
||||
let fld = &self.fields[i];
|
||||
let y = list_area.y + (row - start) as u16;
|
||||
let focused = i == self.focus;
|
||||
let label_style = if focused {
|
||||
Style::new().fg(Color::Cyan).add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::new()
|
||||
};
|
||||
let marker = if focused { "› " } else { " " };
|
||||
let label = Paragraph::new(Line::from(vec![
|
||||
Span::styled(marker, label_style),
|
||||
Span::styled(fld.label.clone(), label_style),
|
||||
]));
|
||||
f.render_widget(
|
||||
label,
|
||||
Rect {
|
||||
x: list_area.x,
|
||||
y,
|
||||
width: label_w,
|
||||
height: 1,
|
||||
},
|
||||
);
|
||||
let vx = list_area.x + label_w;
|
||||
let vw = list_area.width.saturating_sub(label_w);
|
||||
let value_area = Rect {
|
||||
x: vx,
|
||||
y,
|
||||
width: vw,
|
||||
height: 1,
|
||||
};
|
||||
match &fld.value {
|
||||
Value::Text {
|
||||
text,
|
||||
cursor,
|
||||
placeholder,
|
||||
..
|
||||
} => {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let w = vw.saturating_sub(1) as usize;
|
||||
let off = (*cursor).saturating_sub(w);
|
||||
let shown: String = chars.iter().skip(off).take(w).collect();
|
||||
let line = if text.is_empty() {
|
||||
Line::from(Span::styled(
|
||||
placeholder.clone(),
|
||||
Style::new().dim().italic(),
|
||||
))
|
||||
} else {
|
||||
Line::from(shown)
|
||||
};
|
||||
let style = if focused {
|
||||
Style::new().bg(Color::Indexed(236))
|
||||
} else {
|
||||
Style::new()
|
||||
};
|
||||
f.render_widget(Paragraph::new(line).style(style), value_area);
|
||||
if focused {
|
||||
f.set_cursor_position((vx + (*cursor - off) as u16, y));
|
||||
}
|
||||
}
|
||||
Value::Choice { options, index } => {
|
||||
let label = options.get(*index).map(|o| o.1.clone()).unwrap_or_default();
|
||||
let text = if focused && options.len() > 1 {
|
||||
format!("◀ {label} ▶")
|
||||
} else {
|
||||
label
|
||||
};
|
||||
let style = if focused {
|
||||
Style::new().fg(Color::Yellow)
|
||||
} else {
|
||||
Style::new()
|
||||
};
|
||||
f.render_widget(Paragraph::new(text).style(style), value_area);
|
||||
}
|
||||
Value::Toggle(b) => {
|
||||
let text = if *b { "[x] yes" } else { "[ ] no" };
|
||||
let style = if focused {
|
||||
Style::new().fg(Color::Yellow)
|
||||
} else {
|
||||
Style::new()
|
||||
};
|
||||
f.render_widget(Paragraph::new(text).style(style), value_area);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut lines = Vec::new();
|
||||
if let Some(e) = &self.error {
|
||||
lines.push(Line::from(Span::styled(
|
||||
e.clone(),
|
||||
Style::new().fg(Color::Red).bold(),
|
||||
)));
|
||||
lines.push(Line::from(""));
|
||||
}
|
||||
lines.push(Line::from(Span::styled(help.clone(), Style::new().dim())));
|
||||
f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), help_area);
|
||||
}
|
||||
}
|
||||
|
||||
fn wrap_count(s: &str, width: u16) -> usize {
|
||||
let w = width.max(10) as usize;
|
||||
s.lines()
|
||||
.map(|l| l.chars().count().div_ceil(w).max(1))
|
||||
.sum::<usize>()
|
||||
.max(1)
|
||||
}
|
||||
|
||||
/// `text` completed as a path, as a shell's Tab would: the one match whole (a directory with
|
||||
/// its `/`), or the matches' longest common prefix. None when nothing would change.
|
||||
pub fn complete(text: &str) -> Option<String> {
|
||||
let typed = text.to_string();
|
||||
let expanded = crate::paths::expand(&typed);
|
||||
let exp = expanded.to_string_lossy().into_owned();
|
||||
let (dir, prefix) = if exp.ends_with('/') {
|
||||
(PathBuf::from(&exp), String::new())
|
||||
} else {
|
||||
let p = Path::new(&exp);
|
||||
let dir = p
|
||||
.parent()
|
||||
.map(Path::to_path_buf)
|
||||
.filter(|d| !d.as_os_str().is_empty())
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
(
|
||||
dir,
|
||||
p.file_name()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
};
|
||||
let mut matches: Vec<(String, bool)> = std::fs::read_dir(&dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
(name.starts_with(&prefix) && (!name.starts_with('.') || prefix.starts_with('.')))
|
||||
.then(|| (name, e.path().is_dir()))
|
||||
})
|
||||
.collect();
|
||||
if matches.is_empty() {
|
||||
return None;
|
||||
}
|
||||
matches.sort();
|
||||
let completion = if matches.len() == 1 {
|
||||
let (name, is_dir) = &matches[0];
|
||||
format!("{name}{}", if *is_dir { "/" } else { "" })
|
||||
} else {
|
||||
let first = &matches[0].0;
|
||||
let mut n = first.len();
|
||||
for (m, _) in &matches[1..] {
|
||||
n = n.min(
|
||||
first
|
||||
.bytes()
|
||||
.zip(m.bytes())
|
||||
.take_while(|(a, b)| a == b)
|
||||
.count(),
|
||||
);
|
||||
}
|
||||
first[..n].to_string()
|
||||
};
|
||||
let addition = completion.strip_prefix(&prefix)?;
|
||||
if addition.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{typed}{addition}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn completes_paths() {
|
||||
let d = std::env::temp_dir().join(format!("reims-ctl-complete-{}", std::process::id()));
|
||||
std::fs::create_dir_all(d.join("opencore-dir")).unwrap();
|
||||
std::fs::write(d.join("opencore.qcow2"), b"").unwrap();
|
||||
std::fs::write(d.join("other.img"), b"").unwrap();
|
||||
let base = format!("{}/", d.display());
|
||||
assert_eq!(
|
||||
complete(&format!("{base}ot")),
|
||||
Some(format!("{base}other.img"))
|
||||
);
|
||||
assert_eq!(
|
||||
complete(&format!("{base}op")),
|
||||
Some(format!("{base}opencore"))
|
||||
);
|
||||
assert_eq!(
|
||||
complete(&format!("{base}opencore-")),
|
||||
Some(format!("{base}opencore-dir/"))
|
||||
);
|
||||
assert_eq!(complete(&format!("{base}zz")), None);
|
||||
std::fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_fields_read_empty_and_are_skipped() {
|
||||
let mut f = Form::new(
|
||||
"t",
|
||||
"save",
|
||||
vec![
|
||||
Field::choice(
|
||||
"kind",
|
||||
"Disk",
|
||||
opts(&[("new", "New"), ("existing", "Existing")]),
|
||||
"new",
|
||||
"",
|
||||
),
|
||||
Field::text("size", "Size", "128G", "").show_if("kind", &["new"]),
|
||||
Field::path("path", "Path", "/x", "").show_if("kind", &["existing"]),
|
||||
],
|
||||
);
|
||||
assert_eq!(f.text("size"), "128G");
|
||||
assert_eq!(f.text("path"), "");
|
||||
f.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE));
|
||||
assert_eq!(f.choice("kind"), "existing");
|
||||
assert_eq!(f.text("size"), "");
|
||||
f.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
|
||||
assert_eq!(f.focused_key(), "path");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! The host's GPUs a VM can be given.
|
||||
//!
|
||||
//! On Linux the library runs on Vulkan, and picks the first discrete GPU, then the first
|
||||
//! integrated one, in the loader's order. A VM can name another: its Vulkan driver's manifest
|
||||
//! (an ICD JSON file, which `VK_DRIVER_FILES` limits the loader to) and, where that driver
|
||||
//! drives several GPUs, the PCI device ID (`VK_LOADER_DEVICE_ID_FILTER`). The list comes from
|
||||
//! asking each manifest's driver in a child process (`reims-ctl __vulkan-probe`), so a driver
|
||||
//! that hangs or crashes costs only that one.
|
||||
//!
|
||||
//! On macOS the library runs on the system's default Metal device; there is nothing to choose.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GpuInfo {
|
||||
pub name: String,
|
||||
pub vendor_id: u32,
|
||||
pub device_id: u32,
|
||||
/// discrete, integrated, virtual, cpu or other.
|
||||
pub kind: String,
|
||||
pub driver_file: PathBuf,
|
||||
/// Whether another GPU shares the driver (the device ID then picks it).
|
||||
#[serde(default)]
|
||||
pub shares_driver: bool,
|
||||
}
|
||||
|
||||
impl GpuInfo {
|
||||
pub fn label(&self) -> String {
|
||||
let file = self
|
||||
.driver_file
|
||||
.file_name()
|
||||
.map(|f| f.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
format!("{} ({}, {file})", self.name, self.kind)
|
||||
}
|
||||
|
||||
pub fn to_config(&self) -> crate::vm::Gpu {
|
||||
crate::vm::Gpu {
|
||||
driver_file: Some(self.driver_file.clone()),
|
||||
device_id: self.shares_driver.then_some(self.device_id),
|
||||
name: Some(self.name.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Vulkan driver manifests the loader would read, in its search order (the Khronos loader's
|
||||
/// Linux search paths).
|
||||
pub fn icd_files() -> Vec<PathBuf> {
|
||||
let home = crate::paths::home();
|
||||
let env_list = |var: &str, default: &str| -> Vec<PathBuf> {
|
||||
std::env::var(var)
|
||||
.ok()
|
||||
.filter(|v| !v.is_empty())
|
||||
.unwrap_or_else(|| default.to_string())
|
||||
.split(':')
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.collect()
|
||||
};
|
||||
let mut dirs = Vec::new();
|
||||
dirs.push(
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| home.join(".config")),
|
||||
);
|
||||
dirs.extend(env_list("XDG_CONFIG_DIRS", "/etc/xdg"));
|
||||
dirs.push("/etc".into());
|
||||
dirs.push(
|
||||
std::env::var_os("XDG_DATA_HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| home.join(".local/share")),
|
||||
);
|
||||
dirs.extend(env_list("XDG_DATA_DIRS", "/usr/local/share:/usr/share"));
|
||||
let mut files = Vec::new();
|
||||
for d in dirs {
|
||||
let Ok(rd) = std::fs::read_dir(d.join("vulkan/icd.d")) else {
|
||||
continue;
|
||||
};
|
||||
let mut here: Vec<PathBuf> = rd
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "json"))
|
||||
.collect();
|
||||
here.sort();
|
||||
for p in here {
|
||||
if !files.contains(&p) {
|
||||
files.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
/// The host's GPUs, each with the driver manifest that reaches it.
|
||||
pub fn list() -> Vec<GpuInfo> {
|
||||
if !cfg!(target_os = "linux") {
|
||||
return Vec::new();
|
||||
}
|
||||
let Ok(exe) = std::env::current_exe() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let handles: Vec<_> = icd_files()
|
||||
.into_iter()
|
||||
.map(|file| {
|
||||
let exe = exe.clone();
|
||||
std::thread::spawn(move || probe(&exe, &file))
|
||||
})
|
||||
.collect();
|
||||
let mut gpus: Vec<GpuInfo> = handles
|
||||
.into_iter()
|
||||
.filter_map(|h| h.join().ok())
|
||||
.flatten()
|
||||
.collect();
|
||||
// One GPU can be reached through two manifests (a 32-bit and a 64-bit one, say): keep the
|
||||
// first.
|
||||
let mut seen = Vec::new();
|
||||
gpus.retain(|g| {
|
||||
let key = (
|
||||
g.vendor_id,
|
||||
g.device_id,
|
||||
g.name.clone(),
|
||||
g.driver_file.file_name().map(|f| f.to_os_string()),
|
||||
);
|
||||
if seen.contains(&key) {
|
||||
false
|
||||
} else {
|
||||
seen.push(key);
|
||||
true
|
||||
}
|
||||
});
|
||||
let counts: Vec<usize> = gpus
|
||||
.iter()
|
||||
.map(|g| {
|
||||
gpus.iter()
|
||||
.filter(|o| o.driver_file == g.driver_file)
|
||||
.count()
|
||||
})
|
||||
.collect();
|
||||
for (g, n) in gpus.iter_mut().zip(counts) {
|
||||
g.shares_driver = n > 1;
|
||||
}
|
||||
let rank = |k: &str| match k {
|
||||
"discrete" => 0,
|
||||
"integrated" => 1,
|
||||
"virtual" => 2,
|
||||
"other" => 3,
|
||||
_ => 4,
|
||||
};
|
||||
gpus.sort_by_key(|g| rank(&g.kind));
|
||||
gpus
|
||||
}
|
||||
|
||||
fn probe(exe: &std::path::Path, file: &std::path::Path) -> Vec<GpuInfo> {
|
||||
use std::process::{Command, Stdio};
|
||||
let child = Command::new(exe)
|
||||
.arg("__vulkan-probe")
|
||||
.env("VK_DRIVER_FILES", file)
|
||||
.env("VK_ICD_FILENAMES", file)
|
||||
.env("VK_LOADER_LAYERS_DISABLE", "~all~")
|
||||
.env_remove("VK_LOADER_DEVICE_ID_FILTER")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn();
|
||||
let Ok(mut child) = child else {
|
||||
return Vec::new();
|
||||
};
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) if std::time::Instant::now() < deadline => {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50))
|
||||
}
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
use std::io::Read;
|
||||
let _ = child.stdout.take().map(|mut s| s.read_to_string(&mut out));
|
||||
out.lines()
|
||||
.filter_map(|l| serde_json::from_str::<GpuInfo>(l).ok())
|
||||
.map(|mut g| {
|
||||
g.driver_file = file.to_path_buf();
|
||||
g
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `reims-ctl __vulkan-probe`: one JSON line per physical device the loader finds.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn probe_main() -> i32 {
|
||||
use ash::vk;
|
||||
// SAFETY: loads the system's Vulkan loader; the calls below follow the API's rules.
|
||||
unsafe {
|
||||
let Ok(entry) = ash::Entry::load() else {
|
||||
return 1;
|
||||
};
|
||||
let app = vk::ApplicationInfo::default().api_version(vk::make_api_version(0, 1, 1, 0));
|
||||
let ci = vk::InstanceCreateInfo::default().application_info(&app);
|
||||
let Ok(instance) = entry.create_instance(&ci, None) else {
|
||||
return 1;
|
||||
};
|
||||
if let Ok(devices) = instance.enumerate_physical_devices() {
|
||||
for pd in devices {
|
||||
let p = instance.get_physical_device_properties(pd);
|
||||
let name = p
|
||||
.device_name_as_c_str()
|
||||
.map(|c| c.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let kind = match p.device_type {
|
||||
vk::PhysicalDeviceType::DISCRETE_GPU => "discrete",
|
||||
vk::PhysicalDeviceType::INTEGRATED_GPU => "integrated",
|
||||
vk::PhysicalDeviceType::VIRTUAL_GPU => "virtual",
|
||||
vk::PhysicalDeviceType::CPU => "cpu",
|
||||
_ => "other",
|
||||
};
|
||||
let info = GpuInfo {
|
||||
name,
|
||||
vendor_id: p.vendor_id,
|
||||
device_id: p.device_id,
|
||||
kind: kind.into(),
|
||||
driver_file: PathBuf::new(),
|
||||
shares_driver: false,
|
||||
};
|
||||
println!("{}", serde_json::to_string(&info).unwrap());
|
||||
}
|
||||
}
|
||||
instance.destroy_instance(None);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn probe_main() -> i32 {
|
||||
1
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! The host reims-ctl runs on, and the machine profiles it can run there.
|
||||
//!
|
||||
//! A profile is one QEMU machine for one guest architecture: its binary, accelerator, devices
|
||||
//! and what it can attach. Each host supports the profiles [`Profile::supported_on`] lists:
|
||||
//! - macOS on arm64: [`Profile::VmappleArm64`], QEMU's `vmapple` machine on HVF, the machine
|
||||
//! Virtualization.framework gives an arm64 macOS guest, with `apple-gfx-mmio`;
|
||||
//! - Linux on x86-64: [`Profile::Q35X86_64`], `q35` on KVM, booted through OpenCore, with
|
||||
//! `apple-gfx-pci`.
|
||||
//!
|
||||
//! 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`.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Os {
|
||||
Mac,
|
||||
Linux,
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Arch {
|
||||
Aarch64,
|
||||
X86_64,
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Host {
|
||||
pub os: Os,
|
||||
pub arch: Arch,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
pub fn current() -> Host {
|
||||
let os = if cfg!(target_os = "macos") {
|
||||
Os::Mac
|
||||
} else if cfg!(target_os = "linux") {
|
||||
Os::Linux
|
||||
} else {
|
||||
Os::Other
|
||||
};
|
||||
let arch = if cfg!(target_arch = "aarch64") {
|
||||
Arch::Aarch64
|
||||
} else if cfg!(target_arch = "x86_64") {
|
||||
Arch::X86_64
|
||||
} else {
|
||||
Arch::Other
|
||||
};
|
||||
Host { os, arch }
|
||||
}
|
||||
|
||||
pub fn default_profile(self) -> Option<Profile> {
|
||||
Profile::supported_on(self).first().copied()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Host {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let os = match self.os {
|
||||
Os::Mac => "macOS",
|
||||
Os::Linux => "Linux",
|
||||
Os::Other => std::env::consts::OS,
|
||||
};
|
||||
let arch = match self.arch {
|
||||
Arch::Aarch64 => "arm64",
|
||||
Arch::X86_64 => "x86-64",
|
||||
Arch::Other => std::env::consts::ARCH,
|
||||
};
|
||||
write!(f, "{os} on {arch}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Profile {
|
||||
#[serde(rename = "vmapple-arm64")]
|
||||
VmappleArm64,
|
||||
#[serde(rename = "q35-x86_64")]
|
||||
Q35X86_64,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn supported_on(host: Host) -> &'static [Profile] {
|
||||
match (host.os, host.arch) {
|
||||
(Os::Mac, Arch::Aarch64) => &[Profile::VmappleArm64],
|
||||
(Os::Linux, Arch::X86_64) => &[Profile::Q35X86_64],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Profile::VmappleArm64 => "vmapple-arm64",
|
||||
Profile::Q35X86_64 => "q35-x86_64",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn describe(self) -> &'static str {
|
||||
match self {
|
||||
Profile::VmappleArm64 => "arm64 macOS guest (vmapple, HVF)",
|
||||
Profile::Q35X86_64 => "x86-64 macOS guest (q35 and OpenCore, KVM)",
|
||||
}
|
||||
}
|
||||
|
||||
/// The QEMU binary's name in the install's `bin`.
|
||||
pub fn qemu_binary(self) -> &'static str {
|
||||
match self {
|
||||
Profile::VmappleArm64 => "qemu-system-aarch64",
|
||||
Profile::Q35X86_64 => "qemu-system-x86_64",
|
||||
}
|
||||
}
|
||||
|
||||
/// The accelerator on `host`.
|
||||
pub fn accel(self, host: Host) -> &'static str {
|
||||
match (self, host.os) {
|
||||
// vendor/qemu's 4a2e2b3967 boots vmapple guests with the in-kernel GIC.
|
||||
(Profile::VmappleArm64, _) => "hvf,kernel-irqchip=on",
|
||||
(Profile::Q35X86_64, Os::Mac) => "hvf",
|
||||
(Profile::Q35X86_64, _) => "kvm",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the guest's RAM must be a shared memfd: the library on Linux builds its views of
|
||||
/// guest pages from the file behind the RAM, and refuses RAM without one.
|
||||
pub fn memfd_ram(self, host: Host) -> bool {
|
||||
host.os == Os::Linux
|
||||
}
|
||||
|
||||
/// Whether a Vulkan GPU can be chosen: the library runs on Vulkan on Linux, and on Metal's
|
||||
/// default device on macOS.
|
||||
pub fn gpu_choice(self, host: Host) -> bool {
|
||||
host.os == Os::Linux
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Profile {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.id())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_supported_host_has_one_profile() {
|
||||
let mac = Host {
|
||||
os: Os::Mac,
|
||||
arch: Arch::Aarch64,
|
||||
};
|
||||
let linux = Host {
|
||||
os: Os::Linux,
|
||||
arch: Arch::X86_64,
|
||||
};
|
||||
assert_eq!(mac.default_profile(), Some(Profile::VmappleArm64));
|
||||
assert_eq!(linux.default_profile(), Some(Profile::Q35X86_64));
|
||||
assert_eq!(
|
||||
Host {
|
||||
os: Os::Linux,
|
||||
arch: Arch::Aarch64
|
||||
}
|
||||
.default_profile(),
|
||||
None
|
||||
);
|
||||
assert!(Profile::Q35X86_64.memfd_ram(linux));
|
||||
assert!(!Profile::VmappleArm64.memfd_ram(mac));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! What scripts/install-ctl.sh installed: `install.toml` in the config directory names the
|
||||
//! repository it built from, and the QEMU builds live in the data directory's `qemu/<build>`,
|
||||
//! each a whole install prefix (QEMU finds its data files relative to its binary), with
|
||||
//! `qemu/current` linking the newest. An update installs a new build beside the others and moves
|
||||
//! the link, so a running VM's binary is never written.
|
||||
//!
|
||||
//! `REIMS_CTL_QEMU` names a QEMU binary to use instead (a build tree's, such as `make qemu`'s
|
||||
//! `build/qemu/qemu-system-aarch64`); `qemu-img` is taken from beside it.
|
||||
|
||||
use crate::host::Profile;
|
||||
use crate::paths;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Install {
|
||||
/// The reims-vgpu checkout the install built from, which `update` pulls.
|
||||
pub repo: PathBuf,
|
||||
/// Its commit at the install.
|
||||
#[serde(default)]
|
||||
pub commit: String,
|
||||
/// The QEMU build installed (a directory under the data directory's `qemu`).
|
||||
#[serde(default)]
|
||||
pub qemu: PathBuf,
|
||||
#[serde(default)]
|
||||
pub installed_at: String,
|
||||
}
|
||||
|
||||
impl Install {
|
||||
pub fn load() -> Option<Install> {
|
||||
let text = std::fs::read_to_string(paths::install_file()).ok()?;
|
||||
toml::from_str(&text).ok()
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let file = paths::install_file();
|
||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
||||
std::fs::write(&file, toml::to_string_pretty(self)?)
|
||||
.with_context(|| format!("write {}", file.display()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The QEMU binary for `profile`.
|
||||
pub fn qemu_binary(profile: Profile) -> Result<PathBuf> {
|
||||
if let Some(p) = std::env::var_os("REIMS_CTL_QEMU") {
|
||||
return Ok(PathBuf::from(p));
|
||||
}
|
||||
let bin = paths::qemu_root()
|
||||
.join("current/bin")
|
||||
.join(profile.qemu_binary());
|
||||
if !bin.exists() {
|
||||
bail!(
|
||||
"QEMU is not installed ({} is missing): run scripts/install-ctl.sh in your reims-vgpu \
|
||||
checkout, or set REIMS_CTL_QEMU to a qemu-system binary",
|
||||
bin.display()
|
||||
);
|
||||
}
|
||||
Ok(bin)
|
||||
}
|
||||
|
||||
/// The QEMU binary for `profile`, or where it would be, for printing a command.
|
||||
pub fn qemu_binary_or_default(profile: Profile) -> PathBuf {
|
||||
qemu_binary(profile).unwrap_or_else(|_| {
|
||||
paths::qemu_root()
|
||||
.join("current/bin")
|
||||
.join(profile.qemu_binary())
|
||||
})
|
||||
}
|
||||
|
||||
/// `qemu-img`, beside the QEMU binary.
|
||||
pub fn qemu_img(profile: Profile) -> Result<PathBuf> {
|
||||
let bin = qemu_binary(profile)?;
|
||||
let img = bin.with_file_name("qemu-img");
|
||||
if !img.exists() {
|
||||
bail!(
|
||||
"{} is missing: reinstall with scripts/install-ctl.sh",
|
||||
img.display()
|
||||
);
|
||||
}
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
/// QEMU's data directory for `qemu`: `share/qemu` in an install prefix, or `qemu-bundle`'s in
|
||||
/// a build tree.
|
||||
pub fn qemu_data_dir(qemu: &Path) -> Option<PathBuf> {
|
||||
let dir = qemu.parent()?;
|
||||
let installed = dir.parent()?.join("share/qemu");
|
||||
if installed.is_dir() {
|
||||
return Some(installed);
|
||||
}
|
||||
let bundle = dir.join("qemu-bundle");
|
||||
if bundle.is_dir() {
|
||||
// The bundle mirrors the configured prefix: find its share/qemu.
|
||||
let mut stack = vec![bundle];
|
||||
while let Some(d) = stack.pop() {
|
||||
if d.ends_with("share/qemu") {
|
||||
return Some(d);
|
||||
}
|
||||
if let Ok(rd) = std::fs::read_dir(&d) {
|
||||
stack.extend(rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The audio backends `qemu` was built with (`-audiodev help`), cached per binary.
|
||||
pub fn audio_backends(qemu: &Path) -> Vec<String> {
|
||||
static CACHE: OnceLock<Mutex<HashMap<PathBuf, Vec<String>>>> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(Default::default);
|
||||
if let Some(v) = cache.lock().unwrap().get(qemu) {
|
||||
return v.clone();
|
||||
}
|
||||
let out = std::process::Command::new(qemu)
|
||||
.args(["-audiodev", "help"])
|
||||
.output();
|
||||
let list: Vec<String> = match out {
|
||||
Ok(o) => String::from_utf8_lossy(&o.stdout)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty() && !l.contains(' ') && !l.ends_with(':'))
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
cache
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(qemu.to_path_buf(), list.clone());
|
||||
list
|
||||
}
|
||||
|
||||
/// The audio backend to use where the VM names none: the host's native one, among those built.
|
||||
pub fn default_audio_backend(available: &[String]) -> String {
|
||||
let wanted: &[&str] = if cfg!(target_os = "macos") {
|
||||
&["coreaudio"]
|
||||
} else {
|
||||
&["pipewire", "pa", "alsa", "sdl"]
|
||||
};
|
||||
for w in wanted {
|
||||
if available.iter().any(|a| a == w) {
|
||||
return (*w).into();
|
||||
}
|
||||
}
|
||||
if available.is_empty() {
|
||||
// QEMU could not be asked (not installed yet): its usual choice.
|
||||
return if cfg!(target_os = "macos") {
|
||||
"coreaudio"
|
||||
} else {
|
||||
"pipewire"
|
||||
}
|
||||
.into();
|
||||
}
|
||||
"none".into()
|
||||
}
|
||||
|
||||
/// `qemu --version`'s first line.
|
||||
pub fn qemu_version(qemu: &Path) -> Option<String> {
|
||||
let o = std::process::Command::new(qemu)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.ok()?;
|
||||
String::from_utf8_lossy(&o.stdout)
|
||||
.lines()
|
||||
.next()
|
||||
.map(String::from)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn audio_backend_prefers_the_native_one() {
|
||||
let v = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(
|
||||
default_audio_backend(&v(&["none", "coreaudio"])),
|
||||
"coreaudio"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
default_audio_backend(&v(&["none", "alsa", "pa", "pipewire"])),
|
||||
"pipewire"
|
||||
);
|
||||
assert_eq!(default_audio_backend(&v(&["none", "alsa"])), "alsa");
|
||||
}
|
||||
assert_eq!(default_audio_backend(&v(&["none", "dbus"])), "none");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
//! Bug reports: a zip of a VM's logs, its settings, the exact QEMU command and what the host
|
||||
//! is, in the downloads folder, for someone to attach to a report.
|
||||
|
||||
use crate::host::{Host, Os};
|
||||
use crate::runtime;
|
||||
use crate::vm::Vm;
|
||||
use anyhow::{Context, Result};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// The most of one log a report takes: its end.
|
||||
const LOG_CAP: u64 = 64 << 20;
|
||||
|
||||
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());
|
||||
zip.add(
|
||||
&format!("{prefix}/system.txt"),
|
||||
system_info(host).as_bytes(),
|
||||
)?;
|
||||
if let Ok(t) = std::fs::read(vm.dir.join(crate::vm::CONFIG_FILE)) {
|
||||
zip.add(&format!("{prefix}/vm.toml"), &t)?;
|
||||
}
|
||||
if let Ok(inv) = runtime::invocation_for_print(vm, host) {
|
||||
zip.add(
|
||||
&format!("{prefix}/launch.sh"),
|
||||
inv.shell_script("the QEMU command reims-ctl runs")
|
||||
.as_bytes(),
|
||||
)?;
|
||||
}
|
||||
let state = match runtime::pid(vm) {
|
||||
Some(p) => format!("running, pid {p}\n"),
|
||||
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
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_file())
|
||||
.collect();
|
||||
files.sort();
|
||||
for f in files {
|
||||
let data = read_tail(&f, LOG_CAP)?;
|
||||
zip.add(
|
||||
&format!("{prefix}/logs/{}", f.file_name().unwrap().to_string_lossy()),
|
||||
&data,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
zip.finish()?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn read_tail(p: &Path, cap: u64) -> Result<Vec<u8>> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut f = std::fs::File::open(p)?;
|
||||
let len = f.metadata()?.len();
|
||||
if len > cap {
|
||||
f.seek(SeekFrom::Start(len - cap))?;
|
||||
}
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b)?;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
fn run(cmd: &str, args: &[&str]) -> String {
|
||||
match Command::new(cmd).args(args).output() {
|
||||
Ok(o) => {
|
||||
let mut s = String::from_utf8_lossy(&o.stdout).into_owned();
|
||||
if !o.status.success() {
|
||||
s.push_str(&String::from_utf8_lossy(&o.stderr));
|
||||
}
|
||||
s.trim_end().to_string()
|
||||
}
|
||||
Err(e) => format!("({cmd}: {e})"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the host is: the parts a report about a guest's graphics needs.
|
||||
pub fn system_info(host: Host) -> 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 {}\nhost {host}", env!("CARGO_PKG_VERSION")),
|
||||
);
|
||||
if let Some(i) = crate::install::Install::load() {
|
||||
section(
|
||||
"install",
|
||||
format!(
|
||||
"repo {}\ncommit {}\nqemu {}\ninstalled {}",
|
||||
i.repo.display(),
|
||||
i.commit,
|
||||
i.qemu.display(),
|
||||
i.installed_at
|
||||
),
|
||||
);
|
||||
}
|
||||
if let Some(profile) = host.default_profile()
|
||||
&& let Ok(q) = crate::install::qemu_binary(profile)
|
||||
{
|
||||
section(
|
||||
"qemu",
|
||||
format!(
|
||||
"{}\n{}\naudio backends: {}",
|
||||
q.display(),
|
||||
crate::install::qemu_version(&q).unwrap_or_default(),
|
||||
crate::install::audio_backends(&q).join(", ")
|
||||
),
|
||||
);
|
||||
}
|
||||
section("uname", run("uname", &["-a"]));
|
||||
match host.os {
|
||||
Os::Mac => {
|
||||
section("sw_vers", run("sw_vers", &[]));
|
||||
section(
|
||||
"cpu",
|
||||
run(
|
||||
"sysctl",
|
||||
&["machdep.cpu.brand_string", "hw.ncpu", "hw.memsize"],
|
||||
),
|
||||
);
|
||||
section("displays", run("system_profiler", &["SPDisplaysDataType"]));
|
||||
}
|
||||
Os::Linux => {
|
||||
section(
|
||||
"os-release",
|
||||
std::fs::read_to_string("/etc/os-release").unwrap_or_default(),
|
||||
);
|
||||
section(
|
||||
"cpu",
|
||||
run(
|
||||
"sh",
|
||||
&[
|
||||
"-c",
|
||||
"grep -m1 'model name' /proc/cpuinfo; echo \"cpus: $(nproc)\"; grep MemTotal /proc/meminfo",
|
||||
],
|
||||
),
|
||||
);
|
||||
section(
|
||||
"pci display devices",
|
||||
run(
|
||||
"sh",
|
||||
&[
|
||||
"-c",
|
||||
"lspci -nnk 2>/dev/null | grep -A3 -iE 'vga|3d|display'",
|
||||
],
|
||||
),
|
||||
);
|
||||
let gpus = crate::gpu::list()
|
||||
.iter()
|
||||
.map(|g| {
|
||||
format!(
|
||||
"{} [{:04x}:{:04x}] {}",
|
||||
g.label(),
|
||||
g.vendor_id,
|
||||
g.device_id,
|
||||
g.driver_file.display()
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
section("vulkan gpus", gpus.join("\n"));
|
||||
section(
|
||||
"vulkaninfo --summary",
|
||||
run(
|
||||
"sh",
|
||||
&[
|
||||
"-c",
|
||||
"command -v vulkaninfo >/dev/null && vulkaninfo --summary 2>&1 | head -80",
|
||||
],
|
||||
),
|
||||
);
|
||||
section(
|
||||
"nvidia",
|
||||
run(
|
||||
"sh",
|
||||
&[
|
||||
"-c",
|
||||
"command -v nvidia-smi >/dev/null && nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv",
|
||||
],
|
||||
),
|
||||
);
|
||||
section(
|
||||
"kernel",
|
||||
run(
|
||||
"sh",
|
||||
&[
|
||||
"-c",
|
||||
"cat /proc/sys/vm/max_map_count; ls -l /dev/kvm; id; cat /proc/cmdline",
|
||||
],
|
||||
),
|
||||
);
|
||||
section(
|
||||
"session",
|
||||
format!(
|
||||
"XDG_SESSION_TYPE={}\nWAYLAND_DISPLAY={}\nDISPLAY={}",
|
||||
std::env::var("XDG_SESSION_TYPE").unwrap_or_default(),
|
||||
std::env::var("WAYLAND_DISPLAY").unwrap_or_default(),
|
||||
std::env::var("DISPLAY").unwrap_or_default()
|
||||
),
|
||||
);
|
||||
}
|
||||
Os::Other => {}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// A zip archive, written as it goes: deflated entries, no ZIP64 (each entry is capped well
|
||||
/// below 4 GiB).
|
||||
struct Zip {
|
||||
file: std::io::BufWriter<std::fs::File>,
|
||||
offset: u32,
|
||||
central: Vec<u8>,
|
||||
count: u16,
|
||||
dos_time: u16,
|
||||
dos_date: u16,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Zip {
|
||||
fn create(path: &Path) -> Result<Zip> {
|
||||
let file =
|
||||
std::fs::File::create(path).with_context(|| format!("create {}", path.display()))?;
|
||||
let (dos_time, dos_date) = dos_now();
|
||||
Ok(Zip {
|
||||
file: std::io::BufWriter::new(file),
|
||||
offset: 0,
|
||||
central: Vec::new(),
|
||||
count: 0,
|
||||
dos_time,
|
||||
dos_date,
|
||||
path: path.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
fn add(&mut self, name: &str, data: &[u8]) -> Result<()> {
|
||||
let crc = crc32fast::hash(data);
|
||||
let mut enc =
|
||||
flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
enc.write_all(data)?;
|
||||
let comp = enc.finish()?;
|
||||
let name_b = name.as_bytes();
|
||||
let mut h = Vec::new();
|
||||
h.extend_from_slice(&0x04034b50u32.to_le_bytes());
|
||||
h.extend_from_slice(&20u16.to_le_bytes()); // version needed
|
||||
h.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 names
|
||||
h.extend_from_slice(&8u16.to_le_bytes()); // deflate
|
||||
h.extend_from_slice(&self.dos_time.to_le_bytes());
|
||||
h.extend_from_slice(&self.dos_date.to_le_bytes());
|
||||
h.extend_from_slice(&crc.to_le_bytes());
|
||||
h.extend_from_slice(&(comp.len() as u32).to_le_bytes());
|
||||
h.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
h.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
|
||||
h.extend_from_slice(&0u16.to_le_bytes());
|
||||
h.extend_from_slice(name_b);
|
||||
self.file.write_all(&h)?;
|
||||
self.file.write_all(&comp)?;
|
||||
|
||||
let c = &mut self.central;
|
||||
c.extend_from_slice(&0x02014b50u32.to_le_bytes());
|
||||
c.extend_from_slice(&0x031eu16.to_le_bytes()); // made by: Unix, 3.0
|
||||
c.extend_from_slice(&20u16.to_le_bytes());
|
||||
c.extend_from_slice(&0x0800u16.to_le_bytes());
|
||||
c.extend_from_slice(&8u16.to_le_bytes());
|
||||
c.extend_from_slice(&self.dos_time.to_le_bytes());
|
||||
c.extend_from_slice(&self.dos_date.to_le_bytes());
|
||||
c.extend_from_slice(&crc.to_le_bytes());
|
||||
c.extend_from_slice(&(comp.len() as u32).to_le_bytes());
|
||||
c.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
c.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
|
||||
c.extend_from_slice(&[0; 8]); // extra, comment, disk, internal attributes
|
||||
c.extend_from_slice(&((0o100644u32) << 16).to_le_bytes()); // external: a regular file
|
||||
c.extend_from_slice(&self.offset.to_le_bytes());
|
||||
c.extend_from_slice(name_b);
|
||||
|
||||
self.offset += (h.len() + comp.len()) as u32;
|
||||
self.count += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Result<()> {
|
||||
let cd_offset = self.offset;
|
||||
self.file.write_all(&self.central)?;
|
||||
let mut e = Vec::new();
|
||||
e.extend_from_slice(&0x06054b50u32.to_le_bytes());
|
||||
e.extend_from_slice(&[0; 4]);
|
||||
e.extend_from_slice(&self.count.to_le_bytes());
|
||||
e.extend_from_slice(&self.count.to_le_bytes());
|
||||
e.extend_from_slice(&(self.central.len() as u32).to_le_bytes());
|
||||
e.extend_from_slice(&cd_offset.to_le_bytes());
|
||||
e.extend_from_slice(&0u16.to_le_bytes());
|
||||
self.file.write_all(&e)?;
|
||||
self.file
|
||||
.flush()
|
||||
.with_context(|| format!("write {}", self.path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn dos_now() -> (u16, u16) {
|
||||
// SAFETY: as in runtime::now_stamp.
|
||||
unsafe {
|
||||
let t = libc::time(std::ptr::null_mut());
|
||||
let mut tm: libc::tm = std::mem::zeroed();
|
||||
libc::localtime_r(&t, &mut tm);
|
||||
let time =
|
||||
((tm.tm_hour as u16) << 11) | ((tm.tm_min as u16) << 5) | ((tm.tm_sec as u16) / 2);
|
||||
let date = (((tm.tm_year - 80).max(0) as u16) << 9)
|
||||
| (((tm.tm_mon + 1) as u16) << 5)
|
||||
| tm.tm_mday as u16;
|
||||
(time, date)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zip_is_readable_by_unzip() {
|
||||
let dir = std::env::temp_dir().join(format!("reims-ctl-zip-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let p = dir.join("t.zip");
|
||||
let mut z = Zip::create(&p).unwrap();
|
||||
z.add("a/one.txt", b"hello hello hello").unwrap();
|
||||
z.add("a/two.txt", &vec![b'x'; 100_000]).unwrap();
|
||||
z.finish().unwrap();
|
||||
if let Ok(o) = Command::new("unzip").arg("-t").arg(&p).output() {
|
||||
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stdout));
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! reims-ctl: creates, boots and manages macOS VMs on QEMU's apple-gfx, on the QEMU
|
||||
//! scripts/install-ctl.sh builds with reims-vgpu. With no command it opens its interactive
|
||||
//! interface.
|
||||
|
||||
mod cli;
|
||||
mod create;
|
||||
mod form;
|
||||
mod gpu;
|
||||
mod host;
|
||||
mod install;
|
||||
mod logs;
|
||||
mod paths;
|
||||
mod qemu;
|
||||
mod qmp;
|
||||
mod runtime;
|
||||
mod tui;
|
||||
mod update;
|
||||
mod vm;
|
||||
mod vz;
|
||||
|
||||
use clap::Parser;
|
||||
|
||||
fn main() {
|
||||
quiet_on_closed_stdout();
|
||||
let cli = cli::Cli::parse();
|
||||
match cli::main(cli) {
|
||||
Ok(code) => std::process::exit(code),
|
||||
Err(e) => {
|
||||
eprintln!("reims-ctl: {e:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Output piped into a reader that stops early (`reims-ctl list | head -1`) ends the process
|
||||
/// quietly with 141, the status of a death by SIGPIPE, rather than as println!'s panic. SIGPIPE
|
||||
/// itself stays ignored, as Rust leaves it, so a write to a QMP socket whose QEMU just exited
|
||||
/// is an error the caller handles rather than a signal that ends the interactive interface.
|
||||
fn quiet_on_closed_stdout() {
|
||||
let default = std::panic::take_hook();
|
||||
let closed = format!("(os error {})", libc::EPIPE);
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
let msg = info
|
||||
.payload()
|
||||
.downcast_ref::<String>()
|
||||
.map(String::as_str)
|
||||
.unwrap_or_default();
|
||||
if msg.starts_with("failed printing to stdout") && msg.contains(&closed) {
|
||||
std::process::exit(141);
|
||||
}
|
||||
default(info);
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Where reims-ctl keeps things, the same on macOS and Linux (the XDG layout), so the paths
|
||||
//! carry no spaces and a printed QEMU command reads the same on both:
|
||||
//! - `$XDG_CONFIG_HOME/reims-ctl` (`~/.config/reims-ctl`): `vms.toml`, the VMs this user has,
|
||||
//! each by its name and directory, and `install.toml`, what scripts/install-ctl.sh installed;
|
||||
//! - `$XDG_DATA_HOME/reims-ctl` (`~/.local/share/reims-ctl`): `vms/<name>`, the default home of
|
||||
//! a new VM, and `qemu/<build>`, the QEMU builds, `qemu/current` naming the newest;
|
||||
//! - the runtime directory, for a QMP socket whose path in the VM's directory would be too long
|
||||
//! for a Unix socket: `$XDG_RUNTIME_DIR/reims-ctl`, else `$TMPDIR/reims-ctl-<uid>`.
|
||||
//!
|
||||
//! `REIMS_CTL_CONFIG_DIR` and `REIMS_CTL_DATA_DIR` replace the first two (tests use them).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub fn home() -> PathBuf {
|
||||
std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/"))
|
||||
}
|
||||
|
||||
fn xdg(var: &str, fallback: &str) -> PathBuf {
|
||||
match std::env::var_os(var) {
|
||||
Some(v) if Path::new(&v).is_absolute() => PathBuf::from(v),
|
||||
_ => home().join(fallback),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config_dir() -> PathBuf {
|
||||
match std::env::var_os("REIMS_CTL_CONFIG_DIR") {
|
||||
Some(v) => PathBuf::from(v),
|
||||
None => xdg("XDG_CONFIG_HOME", ".config").join("reims-ctl"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn data_dir() -> PathBuf {
|
||||
match std::env::var_os("REIMS_CTL_DATA_DIR") {
|
||||
Some(v) => PathBuf::from(v),
|
||||
None => xdg("XDG_DATA_HOME", ".local/share").join("reims-ctl"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_vms_dir() -> PathBuf {
|
||||
data_dir().join("vms")
|
||||
}
|
||||
|
||||
pub fn qemu_root() -> PathBuf {
|
||||
data_dir().join("qemu")
|
||||
}
|
||||
|
||||
pub fn registry_file() -> PathBuf {
|
||||
config_dir().join("vms.toml")
|
||||
}
|
||||
|
||||
pub fn install_file() -> PathBuf {
|
||||
config_dir().join("install.toml")
|
||||
}
|
||||
|
||||
pub fn runtime_dir() -> PathBuf {
|
||||
if let Some(v) = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| Path::new(v).is_absolute()) {
|
||||
return PathBuf::from(v).join("reims-ctl");
|
||||
}
|
||||
let tmp = std::env::var_os("TMPDIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/tmp"));
|
||||
// SAFETY: getuid has no preconditions.
|
||||
tmp.join(format!("reims-ctl-{}", unsafe { libc::getuid() }))
|
||||
}
|
||||
|
||||
/// Where a bug report's zip goes: `$XDG_DOWNLOAD_DIR`, else `~/Downloads`, else the home.
|
||||
pub fn downloads_dir() -> PathBuf {
|
||||
if let Some(v) = std::env::var_os("XDG_DOWNLOAD_DIR").filter(|v| Path::new(v).is_absolute()) {
|
||||
return PathBuf::from(v);
|
||||
}
|
||||
let d = home().join("Downloads");
|
||||
if d.is_dir() { d } else { home() }
|
||||
}
|
||||
|
||||
/// `~` and `~/...` expanded, the rest as given.
|
||||
pub fn expand(p: &str) -> PathBuf {
|
||||
let p = p.trim();
|
||||
if p == "~" {
|
||||
home()
|
||||
} else if let Some(rest) = p.strip_prefix("~/") {
|
||||
home().join(rest)
|
||||
} else {
|
||||
PathBuf::from(p)
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` made absolute against the current directory, `~` expanded, without resolving links.
|
||||
pub fn absolute(p: &str) -> PathBuf {
|
||||
let e = expand(p);
|
||||
if e.is_absolute() {
|
||||
e
|
||||
} else {
|
||||
std::env::current_dir().map(|d| d.join(&e)).unwrap_or(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` with the home shown as `~`, for display.
|
||||
pub fn tilde(p: &Path) -> String {
|
||||
let h = home();
|
||||
match p.strip_prefix(&h) {
|
||||
Ok(rest) if !h.as_os_str().is_empty() && h != Path::new("/") => {
|
||||
if rest.as_os_str().is_empty() {
|
||||
"~".into()
|
||||
} else {
|
||||
format!("~/{}", rest.display())
|
||||
}
|
||||
}
|
||||
_ => p.display().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn expand_takes_the_tilde_only_at_the_start() {
|
||||
let h = home();
|
||||
assert_eq!(expand("~"), h);
|
||||
assert_eq!(expand("~/vms/a"), h.join("vms/a"));
|
||||
assert_eq!(expand("/a/~/b"), PathBuf::from("/a/~/b"));
|
||||
assert_eq!(expand("~user/x"), PathBuf::from("~user/x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tilde_shows_paths_under_home() {
|
||||
let h = home();
|
||||
assert_eq!(tilde(&h.join("a/b")), "~/a/b");
|
||||
assert_eq!(tilde(Path::new("/elsewhere/x")), "/elsewhere/x");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,634 @@
|
||||
//! The QEMU command line a VM runs: one [`Invocation`], which `start` runs and `command`
|
||||
//! prints as a shell script, so a printed script runs the VM exactly as reims-ctl does.
|
||||
//!
|
||||
//! Every profile gets:
|
||||
//! - the library's window for each display: `-display none` with `REIMS_VGPU_WINDOW` unset
|
||||
//! (`0` would keep apple-gfx headless), never a window of QEMU's own;
|
||||
//! - a QMP socket (`-qmp`), through which reims-ctl stops the VM and changes its CD;
|
||||
//! - QEMU's pid file;
|
||||
//! - user networking with virtio-net, and an optional SSH port forward;
|
||||
//! - a USB Audio Class device on the host's audio backend: x86-64 macOS 26 has no Intel HDA
|
||||
//! driver, and Safari's Media Source players fail without an output device;
|
||||
//! - with logs on: the library's log (`REIMS_VGPU_LOG`), the serial console, timestamps.
|
||||
//!
|
||||
//! `q35-x86_64` follows the command line the x86-64 guests were measured on (docs/qemu.md):
|
||||
//! RAM as a shared memfd, which the library on Linux requires; the keyboard and tablet on a
|
||||
//! qemu-xhci controller, since on ICH9's EHCI the guest stops re-arming a device's interrupt
|
||||
//! transfers under GPU load and its input freezes; fixed PCI addresses (the AHCI controller at
|
||||
//! slot 2, where OpenCore's boot entries name it).
|
||||
//!
|
||||
//! `vmapple-arm64` follows scripts/run_vmapple.sh.
|
||||
|
||||
use crate::host::{Host, Os, Profile};
|
||||
use crate::vm::{MediaKind, Vm};
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Virtualization.framework's boot ROM for vmapple machines.
|
||||
pub const AVPBOOTER: &str =
|
||||
"/System/Library/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Invocation {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
/// Variables set for QEMU.
|
||||
pub env: Vec<(String, String)>,
|
||||
/// Variables removed from QEMU's environment.
|
||||
pub unset: Vec<String>,
|
||||
}
|
||||
|
||||
pub struct Ctx {
|
||||
pub host: Host,
|
||||
pub qemu: PathBuf,
|
||||
/// The audio backend for a VM that names none.
|
||||
pub audio_backend: String,
|
||||
}
|
||||
|
||||
/// A value inside a QEMU option list: commas doubled.
|
||||
pub fn opt(s: &str) -> String {
|
||||
s.replace(',', ",,")
|
||||
}
|
||||
|
||||
fn optp(p: &Path) -> String {
|
||||
opt(&p.to_string_lossy())
|
||||
}
|
||||
|
||||
pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result<Invocation> {
|
||||
let c = &vm.config;
|
||||
let mut a: Vec<String> = Vec::new();
|
||||
let mut push = |xs: &[&str]| a.extend(xs.iter().map(|s| s.to_string()));
|
||||
push(&["-name", &c.name]);
|
||||
match c.profile {
|
||||
Profile::Q35X86_64 => q35(vm, ctx, &mut a)?,
|
||||
Profile::VmappleArm64 => vmapple(vm, ctx, &mut a)?,
|
||||
}
|
||||
common(vm, ctx, &mut a)?;
|
||||
a.extend(c.extra_args.iter().cloned());
|
||||
|
||||
let mut env = Vec::new();
|
||||
let mut unset = vec!["REIMS_VGPU_WINDOW".to_string()];
|
||||
if c.logs.enabled {
|
||||
env.push(("REIMS_VGPU_LOG".into(), c.logs.level.clone()));
|
||||
} else {
|
||||
unset.push("REIMS_VGPU_LOG".into());
|
||||
}
|
||||
if c.display.borderless {
|
||||
env.push(("REIMS_VGPU_WINDOW_BORDERLESS".into(), "1".into()));
|
||||
}
|
||||
if let Some(r) = c.display.refresh {
|
||||
env.push(("REIMS_VGPU_WINDOW_REFRESH".into(), r.to_string()));
|
||||
}
|
||||
if c.profile.gpu_choice(ctx.host)
|
||||
&& let Some(f) = &c.gpu.driver_file
|
||||
{
|
||||
// The loader reads VK_DRIVER_FILES; loaders before 1.3.207 read VK_ICD_FILENAMES.
|
||||
let f = f.to_string_lossy().into_owned();
|
||||
env.push(("VK_DRIVER_FILES".into(), f.clone()));
|
||||
env.push(("VK_ICD_FILENAMES".into(), f));
|
||||
if let Some(id) = c.gpu.device_id {
|
||||
env.push(("VK_LOADER_DEVICE_ID_FILTER".into(), format!("{id:#06x}")));
|
||||
}
|
||||
}
|
||||
for (k, v) in &c.extra_env {
|
||||
env.retain(|(ek, _)| ek != k);
|
||||
unset.retain(|u| u != k);
|
||||
env.push((k.clone(), v.clone()));
|
||||
}
|
||||
Ok(Invocation {
|
||||
program: ctx.qemu.clone(),
|
||||
args: a,
|
||||
env,
|
||||
unset,
|
||||
})
|
||||
}
|
||||
|
||||
fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
let c = &vm.config;
|
||||
let q = c.q35.as_ref().context("no [q35] settings")?;
|
||||
let mem = format!("{}M", c.memory_mib);
|
||||
let mut push = |xs: &[&str]| a.extend(xs.iter().map(|s| s.to_string()));
|
||||
if c.profile.memfd_ram(ctx.host) {
|
||||
push(&["-machine", "q35,memory-backend=ram"]);
|
||||
push(&[
|
||||
"-object",
|
||||
&format!("memory-backend-memfd,id=ram,size={mem},share=on"),
|
||||
]);
|
||||
} else {
|
||||
push(&["-machine", "q35"]);
|
||||
}
|
||||
push(&["-accel", c.profile.accel(ctx.host), "-m", &mem]);
|
||||
let mut cpu = format!(
|
||||
"{},kvm=on,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on",
|
||||
q.cpu_model
|
||||
);
|
||||
if !q.cpu_flags.trim().is_empty() {
|
||||
cpu.push(',');
|
||||
cpu.push_str(q.cpu_flags.trim());
|
||||
}
|
||||
push(&["-cpu", &cpu]);
|
||||
push(&[
|
||||
"-smp",
|
||||
&format!("{0},sockets=1,cores={0},threads=1", c.cpus),
|
||||
]);
|
||||
push(&[
|
||||
"-global",
|
||||
"ICH9-LPC.acpi-pci-hotplug-with-bridge-support=off",
|
||||
]);
|
||||
push(&[
|
||||
"-device",
|
||||
"pcie-root-port,bus=pcie.0,addr=0x1,slot=1,x-speed=16,x-width=32",
|
||||
]);
|
||||
if let Some(osk) = q.osk.as_deref().filter(|s| !s.is_empty()) {
|
||||
push(&["-device", &format!("isa-applesmc,osk={}", opt(osk))]);
|
||||
}
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!(
|
||||
"if=pflash,format=raw,readonly=on,file={}",
|
||||
optp(&vm.path(&q.firmware_code))
|
||||
),
|
||||
]);
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!(
|
||||
"if=pflash,format=raw,file={}",
|
||||
optp(&vm.path(&q.firmware_vars))
|
||||
),
|
||||
]);
|
||||
push(&["-smbios", "type=2"]);
|
||||
push(&["-device", "ich9-ahci,id=sata,addr=0x2"]);
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!(
|
||||
"id=opencore,if=none,format={},file={}",
|
||||
q.opencore_format.as_str(),
|
||||
optp(&vm.path(&q.opencore))
|
||||
),
|
||||
]);
|
||||
push(&["-device", "ide-hd,bus=sata.2,drive=opencore,bootindex=1"]);
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!(
|
||||
"id=disk,if=none,format={},file={}",
|
||||
c.disk_format.as_str(),
|
||||
optp(&vm.disk())
|
||||
),
|
||||
]);
|
||||
push(&[
|
||||
"-device",
|
||||
&format!("ide-hd,bus=sata.{},drive=disk,rotation_rate=1", q.disk_port),
|
||||
]);
|
||||
// The installer's port: the next after the disk's, past OpenCore's.
|
||||
let media_port = if q.disk_port == 4 { 5 } else { 4 };
|
||||
let kind = q
|
||||
.installer
|
||||
.as_deref()
|
||||
.map(|p| q.installer_kind.unwrap_or_else(|| MediaKind::for_path(p)));
|
||||
match (q.installer.as_deref(), kind) {
|
||||
(Some(p), Some(MediaKind::Disk)) => {
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!(
|
||||
"id=installer,if=none,format=raw,snapshot=on,file={}",
|
||||
optp(p)
|
||||
),
|
||||
]);
|
||||
push(&[
|
||||
"-device",
|
||||
&format!("ide-hd,bus=sata.{media_port},drive=installer"),
|
||||
]);
|
||||
}
|
||||
(p, _) => {
|
||||
// A CD drive, empty or with the installer's disc, so a disc can go in while it runs.
|
||||
let file = p.map(|p| format!(",file={}", optp(p))).unwrap_or_default();
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!("id=cd,if=none,media=cdrom,readonly=on{file}"),
|
||||
]);
|
||||
push(&[
|
||||
"-device",
|
||||
&format!("ide-cd,bus=sata.{media_port},drive=cd,id=cdrom"),
|
||||
]);
|
||||
}
|
||||
}
|
||||
if c.network.enabled {
|
||||
push(&["-netdev", &netdev(vm)]);
|
||||
push(&[
|
||||
"-device",
|
||||
&format!(
|
||||
"virtio-net-pci,netdev=net0,id=net0,mac={},addr=0x3",
|
||||
c.network.mac
|
||||
),
|
||||
]);
|
||||
}
|
||||
push(&["-vga", "none"]);
|
||||
let mut gfx = format!(
|
||||
"apple-gfx-pci,id=gfx,bus=pcie.0,addr=0x4,displays={}",
|
||||
c.display.count
|
||||
);
|
||||
gfx.push_str(&format!(",resolution={}", c.display.qemu_resolution()?));
|
||||
push(&["-device", &gfx]);
|
||||
push(&[
|
||||
"-device",
|
||||
"qemu-xhci,id=xhci,addr=0x5,conditional-intr-mapping=on",
|
||||
]);
|
||||
push(&[
|
||||
"-device",
|
||||
"usb-kbd,id=kbd,bus=xhci.0",
|
||||
"-device",
|
||||
"usb-tablet,id=tablet,bus=xhci.0",
|
||||
]);
|
||||
if c.audio.enabled {
|
||||
push(&["-audiodev", &audiodev(vm, ctx)]);
|
||||
push(&["-device", "usb-audio,id=audio,audiodev=snd0,bus=xhci.0"]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn vmapple(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
let c = &vm.config;
|
||||
let v = c.vmapple.as_ref().context("no [vmapple] settings")?;
|
||||
let aux = vm.aux_trimmed().context("no auxiliary storage")?;
|
||||
let disk = vm.disk();
|
||||
let mut push = |xs: &[&str]| a.extend(xs.iter().map(|s| s.to_string()));
|
||||
push(&["-accel", c.profile.accel(ctx.host)]);
|
||||
push(&["-M", &format!("vmapple,uuid={}", v.ecid)]);
|
||||
push(&[
|
||||
"-m",
|
||||
&format!("{}M", c.memory_mib),
|
||||
"-smp",
|
||||
&c.cpus.to_string(),
|
||||
]);
|
||||
push(&["-bios", AVPBOOTER]);
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!("file={},if=pflash,format=raw", optp(&aux)),
|
||||
]);
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!("file={},if=pflash,format=raw", optp(&disk)),
|
||||
]);
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!("file={},if=none,id=aux,format=raw", optp(&aux)),
|
||||
]);
|
||||
push(&[
|
||||
"-drive",
|
||||
&format!("file={},if=none,id=root,format=raw", optp(&disk)),
|
||||
]);
|
||||
push(&["-device", "vmapple-virtio-blk-pci,variant=aux,drive=aux"]);
|
||||
push(&["-device", "vmapple-virtio-blk-pci,variant=root,drive=root"]);
|
||||
if c.network.enabled {
|
||||
push(&["-netdev", &netdev(vm)]);
|
||||
push(&[
|
||||
"-device",
|
||||
&format!("virtio-net-pci,netdev=net0,mac={}", c.network.mac),
|
||||
]);
|
||||
}
|
||||
push(&[
|
||||
"-global",
|
||||
&format!("apple-gfx-mmio.displays={}", c.display.count),
|
||||
]);
|
||||
push(&[
|
||||
"-global",
|
||||
&format!("apple-gfx-mmio.resolution={}", c.display.qemu_resolution()?),
|
||||
]);
|
||||
if c.audio.enabled {
|
||||
// On the USB bus of the machine's own xHCI controller, its only one.
|
||||
push(&["-audiodev", &audiodev(vm, ctx)]);
|
||||
push(&["-device", "usb-audio,id=audio,audiodev=snd0"]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn netdev(vm: &Vm) -> String {
|
||||
let mut n = "user,id=net0,ipv6=off".to_string();
|
||||
if let Some(p) = vm.config.network.ssh_port {
|
||||
n.push_str(&format!(",hostfwd=tcp:127.0.0.1:{p}-:22"));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn audiodev(vm: &Vm, ctx: &Ctx) -> String {
|
||||
let backend = vm
|
||||
.config
|
||||
.audio
|
||||
.backend
|
||||
.as_deref()
|
||||
.unwrap_or(&ctx.audio_backend);
|
||||
format!("{},id=snd0", opt(backend))
|
||||
}
|
||||
|
||||
fn common(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
|
||||
let c = &vm.config;
|
||||
let mut push = |xs: &[&str]| a.extend(xs.iter().map(|s| s.to_string()));
|
||||
push(&["-display", "none"]);
|
||||
if c.logs.enabled {
|
||||
push(&["-serial", &format!("file:{}", vm.serial_log().display())]);
|
||||
push(&["-msg", "timestamp=on"]);
|
||||
} else {
|
||||
push(&["-serial", "none"]);
|
||||
}
|
||||
push(&["-monitor", "none"]);
|
||||
push(&[
|
||||
"-qmp",
|
||||
&format!("unix:{},server=on,wait=off", optp(&vm.qmp_socket())),
|
||||
]);
|
||||
push(&["-pidfile", &vm.pidfile().to_string_lossy()]);
|
||||
let _ = ctx;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Invocation {
|
||||
/// A `std::process::Command` running it.
|
||||
pub fn command(&self) -> std::process::Command {
|
||||
let mut cmd = std::process::Command::new(&self.program);
|
||||
cmd.args(&self.args);
|
||||
for k in &self.unset {
|
||||
cmd.env_remove(k);
|
||||
}
|
||||
for (k, v) in &self.env {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// A POSIX shell script that runs it, an option and its value to a line.
|
||||
pub fn shell_script(&self, comment: &str) -> String {
|
||||
let mut s = String::from("#!/bin/sh\n");
|
||||
for line in comment.lines() {
|
||||
s.push_str("# ");
|
||||
s.push_str(line);
|
||||
s.push('\n');
|
||||
}
|
||||
for k in &self.unset {
|
||||
s.push_str(&format!("unset {k}\n"));
|
||||
}
|
||||
for (k, v) in &self.env {
|
||||
s.push_str(&format!("export {k}={}\n", quote(v)));
|
||||
}
|
||||
s.push_str("exec ");
|
||||
s.push_str("e(&self.program.to_string_lossy()));
|
||||
let mut i = 0;
|
||||
while i < self.args.len() {
|
||||
s.push_str(" \\\n ");
|
||||
s.push_str("e(&self.args[i]));
|
||||
if self.args[i].starts_with('-')
|
||||
&& i + 1 < self.args.len()
|
||||
&& !self.args[i + 1].starts_with('-')
|
||||
{
|
||||
s.push(' ');
|
||||
s.push_str("e(&self.args[i + 1]));
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
pub fn quote(s: &str) -> String {
|
||||
shlex::try_quote(s)
|
||||
.map(|c| c.into_owned())
|
||||
.unwrap_or_else(|_| format!("'{}'", s.replace('\'', "'\\''")))
|
||||
}
|
||||
|
||||
/// The host OS's name, as a short word, for messages.
|
||||
pub fn os_word(host: Host) -> &'static str {
|
||||
match host.os {
|
||||
Os::Mac => "macOS",
|
||||
Os::Linux => "Linux",
|
||||
Os::Other => "this OS",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::host::Arch;
|
||||
use crate::vm::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn linux() -> Host {
|
||||
Host {
|
||||
os: Os::Linux,
|
||||
arch: Arch::X86_64,
|
||||
}
|
||||
}
|
||||
|
||||
fn mac() -> Host {
|
||||
Host {
|
||||
os: Os::Mac,
|
||||
arch: Arch::Aarch64,
|
||||
}
|
||||
}
|
||||
|
||||
fn q35_vm() -> Vm {
|
||||
Vm {
|
||||
dir: "/vms/t".into(),
|
||||
config: VmConfig {
|
||||
name: "t".into(),
|
||||
profile: Profile::Q35X86_64,
|
||||
cpus: 6,
|
||||
memory_mib: 12288,
|
||||
disk: "disk.qcow2".into(),
|
||||
disk_format: ImageFormat::Qcow2,
|
||||
stop_timeout_secs: 90,
|
||||
extra_args: vec![],
|
||||
display: Display::default(),
|
||||
gpu: Gpu::default(),
|
||||
audio: Audio::default(),
|
||||
network: Network {
|
||||
enabled: true,
|
||||
mac: "52:54:00:aa:bb:cc".into(),
|
||||
ssh_port: Some(2326),
|
||||
},
|
||||
logs: Logs::default(),
|
||||
q35: Some(Q35 {
|
||||
opencore: "opencore.qcow2".into(),
|
||||
opencore_format: ImageFormat::Qcow2,
|
||||
firmware_code: "OVMF_CODE.fd".into(),
|
||||
firmware_vars: "OVMF_VARS.fd".into(),
|
||||
installer: None,
|
||||
installer_kind: None,
|
||||
cpu_model: default_cpu_model(),
|
||||
cpu_flags: default_cpu_flags(),
|
||||
osk: Some("key,with,commas".into()),
|
||||
disk_port: 3,
|
||||
}),
|
||||
vmapple: None,
|
||||
extra_env: BTreeMap::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn ctx(host: Host) -> Ctx {
|
||||
Ctx {
|
||||
host,
|
||||
qemu: "/q/bin/qemu".into(),
|
||||
audio_backend: "pipewire".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn has(args: &[String], pair: &[&str]) -> bool {
|
||||
args.windows(pair.len())
|
||||
.any(|w| w.iter().zip(pair).all(|(a, b)| a == b))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn q35_on_linux_has_the_measured_devices() {
|
||||
let inv = invocation(&q35_vm(), &ctx(linux())).unwrap();
|
||||
let a = &inv.args;
|
||||
for pair in [
|
||||
&["-machine", "q35,memory-backend=ram"][..],
|
||||
&[
|
||||
"-object",
|
||||
"memory-backend-memfd,id=ram,size=12288M,share=on",
|
||||
],
|
||||
&["-accel", "kvm", "-m", "12288M"],
|
||||
&["-smp", "6,sockets=1,cores=6,threads=1"],
|
||||
&["-device", "isa-applesmc,osk=key,,with,,commas"],
|
||||
&[
|
||||
"-drive",
|
||||
"if=pflash,format=raw,readonly=on,file=/vms/t/OVMF_CODE.fd",
|
||||
],
|
||||
&["-device", "ich9-ahci,id=sata,addr=0x2"],
|
||||
&["-device", "ide-hd,bus=sata.2,drive=opencore,bootindex=1"],
|
||||
&["-device", "ide-hd,bus=sata.3,drive=disk,rotation_rate=1"],
|
||||
&["-drive", "id=cd,if=none,media=cdrom,readonly=on"],
|
||||
&[
|
||||
"-netdev",
|
||||
"user,id=net0,ipv6=off,hostfwd=tcp:127.0.0.1:2326-:22",
|
||||
],
|
||||
&[
|
||||
"-device",
|
||||
"apple-gfx-pci,id=gfx,bus=pcie.0,addr=0x4,displays=1,resolution=1920x1080",
|
||||
],
|
||||
&[
|
||||
"-device",
|
||||
"qemu-xhci,id=xhci,addr=0x5,conditional-intr-mapping=on",
|
||||
],
|
||||
&["-audiodev", "pipewire,id=snd0"],
|
||||
&["-device", "usb-audio,id=audio,audiodev=snd0,bus=xhci.0"],
|
||||
&["-display", "none"],
|
||||
&["-qmp", "unix:/vms/t/qmp.sock,server=on,wait=off"],
|
||||
&["-pidfile", "/vms/t/qemu.pid"],
|
||||
] {
|
||||
assert!(has(a, pair), "missing {pair:?} in {a:?}");
|
||||
}
|
||||
assert!(!a.iter().any(|x| x == "-usb"), "no EHCI");
|
||||
assert!(inv.unset.contains(&"REIMS_VGPU_WINDOW".to_string()));
|
||||
assert!(inv.unset.contains(&"REIMS_VGPU_LOG".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installer_disk_goes_on_its_own_port_through_an_overlay() {
|
||||
let mut vm = q35_vm();
|
||||
let q = vm.config.q35.as_mut().unwrap();
|
||||
q.installer = Some("/isos/Base,System.img".into());
|
||||
q.installer_kind = Some(MediaKind::Disk);
|
||||
let a = invocation(&vm, &ctx(linux())).unwrap().args;
|
||||
assert!(has(
|
||||
&a,
|
||||
&[
|
||||
"-drive",
|
||||
"id=installer,if=none,format=raw,snapshot=on,file=/isos/Base,,System.img"
|
||||
]
|
||||
));
|
||||
assert!(has(&a, &["-device", "ide-hd,bus=sata.4,drive=installer"]));
|
||||
let q = vm.config.q35.as_mut().unwrap();
|
||||
q.installer = Some("/isos/x.iso".into());
|
||||
q.installer_kind = None;
|
||||
let a = invocation(&vm, &ctx(linux())).unwrap().args;
|
||||
assert!(has(
|
||||
&a,
|
||||
&[
|
||||
"-drive",
|
||||
"id=cd,if=none,media=cdrom,readonly=on,file=/isos/x.iso"
|
||||
]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logs_gpu_and_window_settings_reach_the_environment() {
|
||||
let mut vm = q35_vm();
|
||||
vm.config.logs = Logs {
|
||||
enabled: true,
|
||||
level: "debug".into(),
|
||||
};
|
||||
vm.config.display.borderless = true;
|
||||
vm.config.display.refresh = Some(120);
|
||||
vm.config.gpu = Gpu {
|
||||
driver_file: Some("/icd/nvidia.json".into()),
|
||||
device_id: Some(0x2204),
|
||||
name: None,
|
||||
};
|
||||
vm.config
|
||||
.extra_env
|
||||
.insert("REIMS_VGPU_LOG".into(), "trace".into());
|
||||
let inv = invocation(&vm, &ctx(linux())).unwrap();
|
||||
let env: BTreeMap<_, _> = inv.env.iter().cloned().collect();
|
||||
assert_eq!(env["REIMS_VGPU_LOG"], "trace");
|
||||
assert_eq!(env["REIMS_VGPU_WINDOW_BORDERLESS"], "1");
|
||||
assert_eq!(env["REIMS_VGPU_WINDOW_REFRESH"], "120");
|
||||
assert_eq!(env["VK_DRIVER_FILES"], "/icd/nvidia.json");
|
||||
assert_eq!(env["VK_LOADER_DEVICE_ID_FILTER"], "0x2204");
|
||||
assert!(has(&inv.args, &["-serial", "file:/vms/t/logs/serial.log"]));
|
||||
assert!(has(&inv.args, &["-msg", "timestamp=on"]));
|
||||
assert!(!inv.unset.contains(&"REIMS_VGPU_LOG".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vmapple_follows_run_vmapple_sh() {
|
||||
let mut vm = q35_vm();
|
||||
vm.config.profile = Profile::VmappleArm64;
|
||||
vm.config.q35 = None;
|
||||
vm.config.disk = "disk.img".into();
|
||||
vm.config.disk_format = ImageFormat::Raw;
|
||||
vm.config.vmapple = Some(Vmapple {
|
||||
aux: "aux.img".into(),
|
||||
ecid: 1234,
|
||||
});
|
||||
vm.config.display.count = 2;
|
||||
let mut c = ctx(mac());
|
||||
c.audio_backend = "coreaudio".into();
|
||||
let a = invocation(&vm, &c).unwrap().args;
|
||||
for pair in [
|
||||
&["-accel", "hvf,kernel-irqchip=on"][..],
|
||||
&["-M", "vmapple,uuid=1234"],
|
||||
&["-bios", AVPBOOTER],
|
||||
&["-drive", "file=/vms/t/aux.img.trimmed,if=pflash,format=raw"],
|
||||
&["-drive", "file=/vms/t/disk.img,if=none,id=root,format=raw"],
|
||||
&["-device", "vmapple-virtio-blk-pci,variant=root,drive=root"],
|
||||
&["-global", "apple-gfx-mmio.displays=2"],
|
||||
&["-global", "apple-gfx-mmio.resolution=1920x1080"],
|
||||
&["-audiodev", "coreaudio,id=snd0"],
|
||||
] {
|
||||
assert!(has(&a, pair), "missing {pair:?} in {a:?}");
|
||||
}
|
||||
assert!(!a.iter().any(|x| x.contains("memfd")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_script_quotes_and_pairs() {
|
||||
let inv = Invocation {
|
||||
program: "/q/qemu".into(),
|
||||
args: vec![
|
||||
"-name".into(),
|
||||
"a b".into(),
|
||||
"-S".into(),
|
||||
"-m".into(),
|
||||
"8G".into(),
|
||||
],
|
||||
env: vec![("X".into(), "1 2".into())],
|
||||
unset: vec!["Y".into()],
|
||||
};
|
||||
let s = inv.shell_script("hello");
|
||||
assert_eq!(
|
||||
s,
|
||||
"#!/bin/sh\n# hello\nunset Y\nexport X='1 2'\nexec /q/qemu \\\n -name 'a b' \\\n -S \\\n -m 8G\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! A QMP client: one command at a time over the VM's Unix socket, events skipped.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::{Value, json};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
pub struct Qmp {
|
||||
reader: BufReader<UnixStream>,
|
||||
writer: UnixStream,
|
||||
}
|
||||
|
||||
impl Qmp {
|
||||
pub fn connect(socket: &Path, timeout: Duration) -> Result<Qmp> {
|
||||
let s = UnixStream::connect(socket)
|
||||
.with_context(|| format!("connect to {}", socket.display()))?;
|
||||
s.set_read_timeout(Some(timeout))?;
|
||||
s.set_write_timeout(Some(timeout))?;
|
||||
let mut q = Qmp {
|
||||
reader: BufReader::new(s.try_clone()?),
|
||||
writer: s,
|
||||
};
|
||||
let greeting = q.read()?;
|
||||
if greeting.get("QMP").is_none() {
|
||||
bail!("{} is not a QMP socket", socket.display());
|
||||
}
|
||||
q.execute("qmp_capabilities", None)?;
|
||||
Ok(q)
|
||||
}
|
||||
|
||||
fn read(&mut self) -> Result<Value> {
|
||||
let mut line = String::new();
|
||||
if self.reader.read_line(&mut line)? == 0 {
|
||||
bail!("QMP closed the connection");
|
||||
}
|
||||
Ok(serde_json::from_str(&line)?)
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, command: &str, arguments: Option<Value>) -> Result<Value> {
|
||||
let mut msg = json!({ "execute": command });
|
||||
if let Some(a) = arguments {
|
||||
msg["arguments"] = a;
|
||||
}
|
||||
let mut bytes = serde_json::to_vec(&msg)?;
|
||||
bytes.push(b'\n');
|
||||
self.writer.write_all(&bytes)?;
|
||||
loop {
|
||||
let v = self.read()?;
|
||||
if let Some(r) = v.get("return") {
|
||||
return Ok(r.clone());
|
||||
}
|
||||
if let Some(e) = v.get("error") {
|
||||
let desc = e.get("desc").and_then(Value::as_str).unwrap_or("error");
|
||||
bail!("QMP {command}: {desc}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one command on the VM's socket.
|
||||
pub fn run(socket: &Path, command: &str, arguments: Option<Value>) -> Result<Value> {
|
||||
Qmp::connect(socket, Duration::from_secs(10))?.execute(command, arguments)
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
//! Starting, finding and stopping a VM's QEMU.
|
||||
//!
|
||||
//! QEMU runs detached: in a session of its own (so closing the terminal does not end it), and
|
||||
//! reparented away from reims-ctl by a double fork (so a TUI that stays open never holds an
|
||||
//! exited QEMU as a zombie). Its pid is the one QEMU writes to the VM's `qemu.pid`, counted only
|
||||
//! while that process runs and its command line names the pid file, so a stale file or a reused
|
||||
//! pid is never taken for the VM. A VM started from a printed script is found the same way.
|
||||
//!
|
||||
//! QEMU's stdout and stderr go to `logs/qemu.log`, kept for the last five starts
|
||||
//! (`qemu.1.log`, ...), the serial console's likewise.
|
||||
|
||||
use crate::host::{Host, Os, Profile};
|
||||
use crate::qemu::{self, Ctx, Invocation};
|
||||
use crate::qmp;
|
||||
use crate::vm::{MediaKind, Vm};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::json;
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// QEMU's pid, while it runs.
|
||||
pub fn pid(vm: &Vm) -> Option<i32> {
|
||||
let pid: i32 = std::fs::read_to_string(vm.pidfile())
|
||||
.ok()?
|
||||
.trim()
|
||||
.parse()
|
||||
.ok()?;
|
||||
if pid <= 0 || !alive(pid) {
|
||||
return None;
|
||||
}
|
||||
let pidfile = vm.pidfile();
|
||||
let needle = pidfile.as_os_str().as_encoded_bytes();
|
||||
let cmd = cmdline(pid)?;
|
||||
cmd.windows(needle.len())
|
||||
.any(|w| w == needle)
|
||||
.then_some(pid)
|
||||
}
|
||||
|
||||
fn alive(pid: i32) -> bool {
|
||||
// SAFETY: signal 0 only checks the pid.
|
||||
let r = unsafe { libc::kill(pid, 0) };
|
||||
r == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn cmdline(pid: i32) -> Option<Vec<u8>> {
|
||||
let b = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
|
||||
// A zombie's command line is empty.
|
||||
(!b.is_empty()).then_some(b)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn cmdline(pid: i32) -> Option<Vec<u8>> {
|
||||
let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid];
|
||||
let mut size: libc::size_t = 0;
|
||||
// SAFETY: a size query; mib names a valid sysctl.
|
||||
if unsafe {
|
||||
libc::sysctl(
|
||||
mib.as_mut_ptr(),
|
||||
3,
|
||||
std::ptr::null_mut(),
|
||||
&mut size,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
} != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut buf = vec![0u8; size];
|
||||
// SAFETY: buf holds size bytes.
|
||||
if unsafe {
|
||||
libc::sysctl(
|
||||
mib.as_mut_ptr(),
|
||||
3,
|
||||
buf.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
} != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
buf.truncate(size);
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
|
||||
fn cmdline(_pid: i32) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn running(vm: &Vm) -> bool {
|
||||
pid(vm).is_some()
|
||||
}
|
||||
|
||||
/// What is wrong with the host or the VM's files for a start, if anything.
|
||||
pub fn preflight(vm: &Vm, host: Host) -> Result<()> {
|
||||
let c = &vm.config;
|
||||
c.check()?;
|
||||
if !crate::host::Profile::supported_on(host).contains(&c.profile) {
|
||||
bail!("{} is a {} VM, which {host} cannot run", c.name, c.profile);
|
||||
}
|
||||
let need = |p: &Path, what: &str| -> Result<()> {
|
||||
if !p.exists() {
|
||||
bail!("{what} {} is missing", p.display());
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
need(&vm.disk(), "the disk")?;
|
||||
match c.profile {
|
||||
Profile::Q35X86_64 => {
|
||||
let q = c.q35.as_ref().unwrap();
|
||||
need(&vm.path(&q.opencore), "the OpenCore image")?;
|
||||
need(&vm.path(&q.firmware_code), "the firmware")?;
|
||||
need(&vm.path(&q.firmware_vars), "the firmware variables")?;
|
||||
if let Some(i) = &q.installer {
|
||||
need(i, "the installer")?;
|
||||
}
|
||||
}
|
||||
Profile::VmappleArm64 => {
|
||||
need(
|
||||
Path::new(qemu::AVPBOOTER),
|
||||
"Virtualization.framework's boot ROM",
|
||||
)?;
|
||||
let v = c.vmapple.as_ref().unwrap();
|
||||
need(&vm.path(&v.aux), "the auxiliary storage")?;
|
||||
}
|
||||
}
|
||||
if host.os == Os::Linux {
|
||||
let kvm = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open("/dev/kvm");
|
||||
if let Err(e) = kvm {
|
||||
bail!(
|
||||
"/dev/kvm cannot be opened ({e}): enable virtualization in the firmware, and add \
|
||||
yourself to the kvm group (sudo usermod -aG kvm $USER, then log in again)"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Warnings about the host for a start that would still work.
|
||||
pub fn warnings(vm: &Vm, host: Host) -> Vec<String> {
|
||||
let mut w = Vec::new();
|
||||
if host.os == Os::Linux {
|
||||
// docs/qemu.md, "Linux hosts: vm.max_map_count": guest memory views take a mapping per
|
||||
// run of 16 KiB pages; the stock 65,530 holds about 770 MiB of them.
|
||||
if let Some(n) = std::fs::read_to_string("/proc/sys/vm/max_map_count")
|
||||
.ok()
|
||||
.and_then(|s| s.trim().parse::<u64>().ok())
|
||||
{
|
||||
let want = (vm.config.memory_mib * 64).max(262_144) + 16_384 + 65_536;
|
||||
if n < want {
|
||||
w.push(format!(
|
||||
"vm.max_map_count is {n}: a {} GiB guest needs about {want}. Raise it with \
|
||||
sudo sysctl -w vm.max_map_count=1048576 (and in /etc/sysctl.d to keep it)",
|
||||
vm.config.memory_mib / 1024
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// Keeps the last five of a log: `x.log` becomes `x.1.log`, and so on.
|
||||
fn rotate(path: &Path) {
|
||||
let stem = path.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
let dir = path.parent().unwrap();
|
||||
let nth = |n: u32| dir.join(format!("{stem}.{n}.log"));
|
||||
let _ = std::fs::remove_file(nth(4));
|
||||
for n in (1..4).rev() {
|
||||
let _ = std::fs::rename(nth(n), nth(n + 1));
|
||||
}
|
||||
let _ = std::fs::rename(path, nth(1));
|
||||
}
|
||||
|
||||
/// Writes the trimmed auxiliary storage a vmapple VM boots, if missing: the image without its
|
||||
/// first 16 KiB block (docs/system/arm/vmapple.rst in vendor/qemu).
|
||||
pub fn ensure_aux_trimmed(vm: &Vm) -> Result<()> {
|
||||
let Some(trimmed) = vm.aux_trimmed() else {
|
||||
return Ok(());
|
||||
};
|
||||
if trimmed.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let aux = vm.path(&vm.config.vmapple.as_ref().unwrap().aux);
|
||||
let mut src = std::fs::File::open(&aux).with_context(|| format!("open {}", aux.display()))?;
|
||||
src.seek(SeekFrom::Start(0x4000))?;
|
||||
let tmp = trimmed.with_extension("trimmed.tmp");
|
||||
let mut dst = std::fs::File::create(&tmp)?;
|
||||
std::io::copy(&mut src, &mut dst)?;
|
||||
dst.sync_all()?;
|
||||
std::fs::rename(&tmp, &trimmed)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn context(vm: &Vm, host: Host) -> Result<Ctx> {
|
||||
let qemu = crate::install::qemu_binary(vm.config.profile)?;
|
||||
let backends = crate::install::audio_backends(&qemu);
|
||||
let audio_backend = crate::install::default_audio_backend(&backends);
|
||||
if vm.config.audio.enabled
|
||||
&& let Some(b) = &vm.config.audio.backend
|
||||
&& !backends.is_empty()
|
||||
&& !backends.contains(b)
|
||||
{
|
||||
bail!(
|
||||
"this QEMU has no {b} audio backend; it has {}",
|
||||
backends.join(", ")
|
||||
);
|
||||
}
|
||||
Ok(Ctx {
|
||||
host,
|
||||
qemu,
|
||||
audio_backend,
|
||||
})
|
||||
}
|
||||
|
||||
/// The invocation `start` would run, with QEMU's real path where it is installed.
|
||||
pub fn invocation_for_print(vm: &Vm, host: Host) -> Result<Invocation> {
|
||||
let ctx = context(vm, host).unwrap_or_else(|_| {
|
||||
let qemu = crate::install::qemu_binary_or_default(vm.config.profile);
|
||||
Ctx {
|
||||
host,
|
||||
qemu,
|
||||
audio_backend: crate::install::default_audio_backend(&[]),
|
||||
}
|
||||
});
|
||||
qemu::invocation(vm, &ctx)
|
||||
}
|
||||
|
||||
pub fn now_stamp(fmt: &str) -> String {
|
||||
// SAFETY: time and localtime_r fill the structs given; strftime writes at most buf's size.
|
||||
unsafe {
|
||||
let t = libc::time(std::ptr::null_mut());
|
||||
let mut tm: libc::tm = std::mem::zeroed();
|
||||
libc::localtime_r(&t, &mut tm);
|
||||
let mut buf = [0u8; 64];
|
||||
let f = std::ffi::CString::new(fmt).unwrap();
|
||||
let n = libc::strftime(buf.as_mut_ptr().cast(), buf.len(), f.as_ptr(), &tm);
|
||||
String::from_utf8_lossy(&buf[..n]).into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the VM, and returns QEMU's pid once QMP answers.
|
||||
pub fn start(vm: &Vm, host: Host) -> Result<i32> {
|
||||
if let Some(p) = pid(vm) {
|
||||
bail!("{} already runs (pid {p})", vm.name());
|
||||
}
|
||||
preflight(vm, host)?;
|
||||
if vm.config.profile == Profile::VmappleArm64 {
|
||||
ensure_aux_trimmed(vm)?;
|
||||
}
|
||||
let ctx = context(vm, host)?;
|
||||
let inv = qemu::invocation(vm, &ctx)?;
|
||||
|
||||
let logs = vm.logs_dir();
|
||||
std::fs::create_dir_all(&logs)?;
|
||||
rotate(&vm.qemu_log());
|
||||
if vm.config.logs.enabled {
|
||||
rotate(&vm.serial_log());
|
||||
}
|
||||
let sock = vm.qmp_socket();
|
||||
if let Some(d) = sock.parent() {
|
||||
std::fs::create_dir_all(d)?;
|
||||
}
|
||||
let _ = std::fs::remove_file(&sock);
|
||||
let _ = std::fs::remove_file(vm.pidfile());
|
||||
|
||||
let mut log = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(vm.qemu_log())?;
|
||||
writeln!(
|
||||
log,
|
||||
"reims-ctl {} started {} at {}",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
vm.name(),
|
||||
now_stamp("%Y-%m-%d %H:%M:%S %z")
|
||||
)?;
|
||||
log.write_all(inv.shell_script("the command").as_bytes())?;
|
||||
writeln!(log, "----")?;
|
||||
let err = log.try_clone()?;
|
||||
|
||||
let mut cmd = inv.command();
|
||||
cmd.current_dir(&vm.dir)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(log)
|
||||
.stderr(err);
|
||||
// SAFETY: only async-signal-safe calls between fork and exec: setsid, fork, _exit.
|
||||
unsafe {
|
||||
cmd.pre_exec(|| {
|
||||
if libc::setsid() < 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
match libc::fork() {
|
||||
-1 => Err(std::io::Error::last_os_error()),
|
||||
0 => Ok(()),
|
||||
_ => libc::_exit(0),
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.with_context(|| format!("run {}", inv.program.display()))?;
|
||||
let _ = child.wait();
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
let mut seen = false;
|
||||
loop {
|
||||
if let Some(p) = pid(vm) {
|
||||
seen = true;
|
||||
if qmp::Qmp::connect(&sock, Duration::from_secs(2)).is_ok() {
|
||||
return Ok(p);
|
||||
}
|
||||
} else if seen || Instant::now() > deadline - Duration::from_secs(50) {
|
||||
// QEMU wrote its pid file and exited, or never wrote it.
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
if pid(vm).is_none() {
|
||||
bail!("QEMU exited:\n{}", tail(&vm.qemu_log(), 15));
|
||||
}
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
match pid(vm) {
|
||||
Some(p) => return Ok(p),
|
||||
None => bail!("QEMU did not start:\n{}", tail(&vm.qemu_log(), 15)),
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(150));
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the VM: macOS's Control-Option-Command-Power on the USB keyboard ("quit all apps,
|
||||
/// then shut down", which asks about unsaved documents), then, a third of `timeout` in, the
|
||||
/// machine's power button (ACPI's on q35, a GPIO on vmapple), and at `timeout` a power-off; with
|
||||
/// `force`, the power-off at once. `progress` hears each step.
|
||||
///
|
||||
/// The keys come first because the power button alone does not shut a guest down: a macOS 26
|
||||
/// vmapple guest did nothing with vmapple's in 90 s, where the keys shut it down in under 6 s
|
||||
/// (2026-10-11, M3 Max).
|
||||
pub fn stop(vm: &Vm, force: bool, timeout: Duration, mut progress: impl FnMut(&str)) -> Result<()> {
|
||||
let Some(p) = pid(vm) else {
|
||||
progress("not running");
|
||||
return Ok(());
|
||||
};
|
||||
let sock = vm.qmp_socket();
|
||||
if !force {
|
||||
let chord: Vec<_> = ["ctrl", "alt", "meta_l", "power"]
|
||||
.iter()
|
||||
.map(|k| json!({ "type": "qcode", "data": k }))
|
||||
.collect();
|
||||
let keys = json!({ "keys": chord, "hold-time": 200 });
|
||||
let asked = match qmp::run(&sock, "send-key", Some(keys)) {
|
||||
Ok(_) => {
|
||||
progress("asked the guest to shut down (Control-Option-Command-Power)");
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
progress(&format!("{e}"));
|
||||
false
|
||||
}
|
||||
};
|
||||
let start = Instant::now();
|
||||
let mut button = false;
|
||||
while start.elapsed() < timeout {
|
||||
if !alive(p) {
|
||||
progress("shut down");
|
||||
return Ok(());
|
||||
}
|
||||
if !button && (!asked || start.elapsed() >= timeout / 3) {
|
||||
button = true;
|
||||
if qmp::run(&sock, "system_powerdown", None).is_ok() {
|
||||
progress("still running: pressed its power button");
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
progress("the guest did not shut down in time: powering off");
|
||||
}
|
||||
power_off(vm, p, &mut progress)
|
||||
}
|
||||
|
||||
fn power_off(vm: &Vm, p: i32, progress: &mut impl FnMut(&str)) -> Result<()> {
|
||||
let _ = qmp::run(&vm.qmp_socket(), "quit", None);
|
||||
if wait_gone(p, Duration::from_secs(10)) {
|
||||
progress("powered off");
|
||||
return Ok(());
|
||||
}
|
||||
// SAFETY: p is our QEMU's pid, checked by pid().
|
||||
unsafe { libc::kill(p, libc::SIGTERM) };
|
||||
if wait_gone(p, Duration::from_secs(5)) {
|
||||
progress("powered off (SIGTERM)");
|
||||
return Ok(());
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe { libc::kill(p, libc::SIGKILL) };
|
||||
if wait_gone(p, Duration::from_secs(5)) {
|
||||
progress("killed (SIGKILL)");
|
||||
return Ok(());
|
||||
}
|
||||
bail!("QEMU (pid {p}) did not exit")
|
||||
}
|
||||
|
||||
fn wait_gone(p: i32, t: Duration) -> bool {
|
||||
let deadline = Instant::now() + t;
|
||||
while Instant::now() < deadline {
|
||||
if !alive(p) {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
!alive(p)
|
||||
}
|
||||
|
||||
/// Puts `path` in the running VM's CD drive, or empties it (`None`).
|
||||
pub fn change_cd(vm: &Vm, path: Option<&Path>) -> Result<()> {
|
||||
let q = vm
|
||||
.config
|
||||
.q35
|
||||
.as_ref()
|
||||
.context("only q35 VMs have a CD drive")?;
|
||||
if q.installer_kind == Some(MediaKind::Disk) && q.installer.is_some() {
|
||||
bail!("the installer is attached as a disk, which changes at the next start");
|
||||
}
|
||||
let sock = vm.qmp_socket();
|
||||
match path {
|
||||
Some(p) => qmp::run(
|
||||
&sock,
|
||||
"blockdev-change-medium",
|
||||
Some(
|
||||
json!({ "id": "cdrom", "filename": p.to_string_lossy(), "format": "raw", "read-only-mode": "read-only" }),
|
||||
),
|
||||
)?,
|
||||
None => qmp::run(
|
||||
&sock,
|
||||
"eject",
|
||||
Some(json!({ "id": "cdrom", "force": true })),
|
||||
)?,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The last `n` lines of a text file.
|
||||
pub fn tail(path: &Path, n: usize) -> String {
|
||||
let Ok(mut f) = std::fs::File::open(path) else {
|
||||
return String::new();
|
||||
};
|
||||
let len = f.metadata().map(|m| m.len()).unwrap_or(0);
|
||||
let start = len.saturating_sub(64 * 1024);
|
||||
let _ = f.seek(SeekFrom::Start(start));
|
||||
let mut buf = Vec::new();
|
||||
let _ = f.read_to_end(&mut buf);
|
||||
let text = String::from_utf8_lossy(&buf);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines[lines.len().saturating_sub(n)..].join("\n")
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,28 @@
|
||||
//! Self-update: the checkout reims-ctl was installed from pulls, and scripts/install-ctl.sh
|
||||
//! builds and installs the new reims-ctl and QEMU. The new QEMU goes beside the old one, so
|
||||
//! running VMs keep theirs; the new reims-ctl replaces this binary, so restart it afterwards.
|
||||
|
||||
use crate::install::Install;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::process::Command;
|
||||
|
||||
pub fn update() -> Result<()> {
|
||||
let i = Install::load().context(
|
||||
"no install record: run scripts/install-ctl.sh in your reims-vgpu checkout once, and \
|
||||
reims-ctl update can use it from then on",
|
||||
)?;
|
||||
let script = i.repo.join("scripts/install-ctl.sh");
|
||||
if !script.is_file() {
|
||||
bail!("{} is missing: was the checkout moved?", script.display());
|
||||
}
|
||||
let status = Command::new("bash")
|
||||
.arg(&script)
|
||||
.arg("--update")
|
||||
.current_dir(&i.repo)
|
||||
.status()
|
||||
.context("run bash")?;
|
||||
if !status.success() {
|
||||
bail!("the update failed (exit {})", status.code().unwrap_or(-1));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
//! A VM: its directory, and the settings in its `vm.toml`.
|
||||
//!
|
||||
//! A VM's directory holds its `vm.toml`, its disks (unless a disk was used in place), its
|
||||
//! 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.
|
||||
|
||||
use crate::host::Profile;
|
||||
use crate::paths;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const CONFIG_FILE: &str = "vm.toml";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct VmConfig {
|
||||
pub name: String,
|
||||
pub profile: Profile,
|
||||
pub cpus: u32,
|
||||
pub memory_mib: u64,
|
||||
/// The system disk, relative to the VM's directory unless absolute.
|
||||
pub disk: PathBuf,
|
||||
#[serde(default)]
|
||||
pub disk_format: ImageFormat,
|
||||
/// How long `stop` waits for the guest to shut down before it powers the VM off.
|
||||
#[serde(default = "default_stop_timeout")]
|
||||
pub stop_timeout_secs: u64,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub extra_args: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub display: Display,
|
||||
#[serde(default)]
|
||||
pub gpu: Gpu,
|
||||
#[serde(default)]
|
||||
pub audio: Audio,
|
||||
#[serde(default)]
|
||||
pub network: Network,
|
||||
#[serde(default)]
|
||||
pub logs: Logs,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub q35: Option<Q35>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub vmapple: Option<Vmapple>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub extra_env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn default_stop_timeout() -> u64 {
|
||||
90
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ImageFormat {
|
||||
#[default]
|
||||
Qcow2,
|
||||
Raw,
|
||||
}
|
||||
|
||||
impl ImageFormat {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ImageFormat::Qcow2 => "qcow2",
|
||||
ImageFormat::Raw => "raw",
|
||||
}
|
||||
}
|
||||
|
||||
/// The format of the image at `path`, from its first bytes: qcow2's magic, else raw.
|
||||
pub fn detect(path: &Path) -> Result<ImageFormat> {
|
||||
use std::io::Read;
|
||||
let mut magic = [0u8; 4];
|
||||
let mut f =
|
||||
std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
|
||||
let n = f.read(&mut magic)?;
|
||||
Ok(if n == 4 && magic == *b"QFI\xfb" {
|
||||
ImageFormat::Qcow2
|
||||
} else {
|
||||
ImageFormat::Raw
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Display {
|
||||
/// The guest's display ports, 1 to 8, each with a window of its own.
|
||||
pub count: u32,
|
||||
/// The mode the guest runs first, `<width>x<height>`, or `host` for the host screen's own
|
||||
/// modes at its density.
|
||||
pub resolution: String,
|
||||
/// Whether the guest is told a density at which it runs a HiDPI desktop at the mode's pixels
|
||||
/// (3840x2160 then looks like 1920x1080).
|
||||
pub hidpi: bool,
|
||||
/// Borderless windows that fill their screens.
|
||||
pub borderless: bool,
|
||||
/// The refresh rate of the modes offered to the guest; the host screen's by default.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub refresh: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for Display {
|
||||
fn default() -> Display {
|
||||
Display {
|
||||
count: 1,
|
||||
resolution: "1920x1080".into(),
|
||||
hidpi: false,
|
||||
borderless: false,
|
||||
refresh: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display {
|
||||
/// The `resolution` property apple-gfx takes, checked as QEMU checks it.
|
||||
pub fn qemu_resolution(&self) -> Result<String> {
|
||||
let r = self.resolution.trim();
|
||||
if r == "host" {
|
||||
if self.hidpi {
|
||||
bail!("resolution host takes the host screen's own density: turn HiDPI off");
|
||||
}
|
||||
return Ok("host".into());
|
||||
}
|
||||
let (w, h) = parse_resolution(r)?;
|
||||
if !self.hidpi {
|
||||
return Ok(format!("{w}x{h}"));
|
||||
}
|
||||
match hidpi_ppi(w) {
|
||||
Some(ppi) => Ok(format!("{w}x{h}@{ppi}")),
|
||||
None => bail!(
|
||||
"a HiDPI desktop needs a mode at least 1920 pixels wide (it looks half that size), \
|
||||
not {w}x{h}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check(&self) -> Result<()> {
|
||||
if !(1..=8).contains(&self.count) {
|
||||
bail!("displays must be 1 to 8, not {}", self.count);
|
||||
}
|
||||
if let Some(r) = self.refresh
|
||||
&& !(1..=1000).contains(&r)
|
||||
{
|
||||
bail!("refresh must be 1 to 1000 Hz, not {r}");
|
||||
}
|
||||
self.qemu_resolution().map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_resolution(s: &str) -> Result<(u32, u32)> {
|
||||
let (w, h) = s
|
||||
.split_once(['x', 'X'])
|
||||
.with_context(|| format!("resolution must be <width>x<height> or host, not {s:?}"))?;
|
||||
let w: u32 = w
|
||||
.trim()
|
||||
.parse()
|
||||
.with_context(|| format!("bad width in {s:?}"))?;
|
||||
let h: u32 = h
|
||||
.trim()
|
||||
.parse()
|
||||
.with_context(|| format!("bad height in {s:?}"))?;
|
||||
if !(1..=65535).contains(&w) || !(1..=65535).contains(&h) {
|
||||
bail!("each side of a resolution is 1 to 65535 pixels, not {s:?}");
|
||||
}
|
||||
Ok((w, h))
|
||||
}
|
||||
|
||||
/// The millimetres a guest is told for `width` pixels at `ppi`, as apple-gfx computes them
|
||||
/// (`apple_gfx_guest_millimeters`): in single precision, rounded.
|
||||
fn guest_millimeters(width: u32, ppi: u32) -> u64 {
|
||||
let mm = width as f32 / (ppi as f64 / 25.46) as f32;
|
||||
(mm as f64 + 0.5) as u64
|
||||
}
|
||||
|
||||
/// The whole centimetres the guest reads them as, rounded up.
|
||||
fn guest_centimeters(width: u32, ppi: u32) -> u64 {
|
||||
guest_millimeters(width, ppi).div_ceil(10)
|
||||
}
|
||||
|
||||
/// apple-gfx's `apple_gfx_guest_scale_unknown`: whether the scale a macOS guest runs a mode at
|
||||
/// is not known from the density it is told, which QEMU refuses.
|
||||
fn guest_scale_unknown(width: u32, ppi: u32) -> bool {
|
||||
let cm = guest_centimeters(width, ppi);
|
||||
let w = width as u64;
|
||||
if cm == 0 || guest_millimeters(width, ppi) > u16::MAX as u64 {
|
||||
return true;
|
||||
}
|
||||
if w * 35 >= 2021 * cm {
|
||||
return width < 1920 || cm < 29;
|
||||
}
|
||||
width > 3811 || w * 66 > 3811 * cm
|
||||
}
|
||||
|
||||
/// A density at which the guest runs `width` HiDPI: about 29.5 cm across, so it reads 30 cm and
|
||||
/// at least 146.667 ppi, where apple-gfx knows the scale (widths of 1920 and more).
|
||||
pub fn hidpi_ppi(width: u32) -> Option<u32> {
|
||||
if width < 1920 {
|
||||
return None;
|
||||
}
|
||||
let ppi = (width as f64 * 25.46 / 295.0).round() as u32;
|
||||
let cm = guest_centimeters(width, ppi);
|
||||
let hidpi = width as u64 * 35 >= 2021 * cm;
|
||||
(hidpi && !guest_scale_unknown(width, ppi)).then_some(ppi)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Gpu {
|
||||
/// The Vulkan driver's manifest (ICD JSON) the loader is limited to: `VK_DRIVER_FILES`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub driver_file: Option<PathBuf>,
|
||||
/// The PCI device ID the loader keeps, where the driver drives several GPUs.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub device_id: Option<u32>,
|
||||
/// The GPU's name, for display.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Audio {
|
||||
pub enabled: bool,
|
||||
/// QEMU's audio backend (`coreaudio`, `pipewire`, `pa`, `alsa`, `none`); the host's best
|
||||
/// by default.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub backend: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Audio {
|
||||
fn default() -> Audio {
|
||||
Audio {
|
||||
enabled: true,
|
||||
backend: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Network {
|
||||
pub enabled: bool,
|
||||
pub mac: String,
|
||||
/// A host port on 127.0.0.1 forwarded to the guest's SSH port.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ssh_port: Option<u16>,
|
||||
}
|
||||
|
||||
impl Default for Network {
|
||||
fn default() -> Network {
|
||||
Network {
|
||||
enabled: true,
|
||||
mac: random_mac(),
|
||||
ssh_port: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Logs {
|
||||
/// The library's log, the guest's serial console and QEMU's timestamps, into `logs/`.
|
||||
/// QEMU's own errors are kept either way.
|
||||
pub enabled: bool,
|
||||
/// `REIMS_VGPU_LOG`'s filter: a level, and `target=level` pairs.
|
||||
pub level: String,
|
||||
}
|
||||
|
||||
impl Default for Logs {
|
||||
fn default() -> Logs {
|
||||
Logs {
|
||||
enabled: false,
|
||||
level: "info".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MediaKind {
|
||||
/// A CD drive (`.iso`, `.cdr`), whose disc can be changed while the VM runs.
|
||||
Cdrom,
|
||||
/// A read-only disk (a raw `BaseSystem.img`, as OSX-KVM's and ULTMOS's installers come):
|
||||
/// writes go to a temporary overlay.
|
||||
Disk,
|
||||
}
|
||||
|
||||
impl MediaKind {
|
||||
pub fn for_path(p: &Path) -> MediaKind {
|
||||
match p
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.as_deref()
|
||||
{
|
||||
Some("iso" | "cdr") => MediaKind::Cdrom,
|
||||
_ => MediaKind::Disk,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Q35 {
|
||||
/// The OpenCore image (its own copy in the VM's directory).
|
||||
pub opencore: PathBuf,
|
||||
#[serde(default)]
|
||||
pub opencore_format: ImageFormat,
|
||||
/// OVMF's code and variables (copies in the VM's directory).
|
||||
pub firmware_code: PathBuf,
|
||||
pub firmware_vars: PathBuf,
|
||||
/// The installer, used in place.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub installer: Option<PathBuf>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub installer_kind: Option<MediaKind>,
|
||||
#[serde(default = "default_cpu_model")]
|
||||
pub cpu_model: String,
|
||||
#[serde(default = "default_cpu_flags")]
|
||||
pub cpu_flags: String,
|
||||
/// The SMC key `isa-applesmc` gives the guest. Without one there is no `isa-applesmc`, and
|
||||
/// the OpenCore image must emulate the SMC (VirtualSMC).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub osk: Option<String>,
|
||||
/// The AHCI port of the system disk: 3, as OSX-KVM and ULTMOS attach it. OpenCore's saved
|
||||
/// boot entry names the port.
|
||||
#[serde(default = "default_disk_port")]
|
||||
pub disk_port: u32,
|
||||
}
|
||||
|
||||
pub fn default_cpu_model() -> String {
|
||||
"Haswell-noTSX".into()
|
||||
}
|
||||
|
||||
pub fn default_cpu_flags() -> String {
|
||||
"+ssse3,+sse4.2,+popcnt,+avx,+aes,+xsave,+xsaveopt,check".into()
|
||||
}
|
||||
|
||||
fn default_disk_port() -> u32 {
|
||||
3
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Vmapple {
|
||||
/// The auxiliary storage Virtualization.framework made, relative to the VM's directory. QEMU
|
||||
/// boots a copy without its first 16 KiB block (`aux.img.trimmed`).
|
||||
pub aux: PathBuf,
|
||||
/// The machine identifier's ECID, which `-M vmapple,uuid=` takes.
|
||||
pub ecid: u64,
|
||||
}
|
||||
|
||||
impl VmConfig {
|
||||
pub fn check(&self) -> Result<()> {
|
||||
check_name(&self.name)?;
|
||||
if self.cpus == 0 || self.cpus > 256 {
|
||||
bail!("cpus must be 1 to 256, not {}", self.cpus);
|
||||
}
|
||||
if self.memory_mib < 2048 {
|
||||
bail!("memory must be at least 2 GiB, not {} MiB", self.memory_mib);
|
||||
}
|
||||
self.display.check()?;
|
||||
match self.profile {
|
||||
Profile::Q35X86_64 if self.q35.is_none() => bail!("{}: no [q35] settings", self.name),
|
||||
Profile::VmappleArm64 if self.vmapple.is_none() => {
|
||||
bail!("{}: no [vmapple] settings", self.name)
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_name(name: &str) -> Result<()> {
|
||||
let ok = !name.is_empty()
|
||||
&& name.len() <= 64
|
||||
&& !name.starts_with(['-', '.'])
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
|
||||
if !ok {
|
||||
bail!(
|
||||
"a VM's name is 1 to 64 letters, digits, '-', '_' or '.', not starting with '-' or '.': {name:?}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A locally administered MAC in QEMU's 52:54:00 prefix.
|
||||
pub fn random_mac() -> String {
|
||||
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()
|
||||
{
|
||||
let t = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
let seed = t.as_nanos() ^ (std::process::id() as u128) << 64;
|
||||
for (i, x) in b.iter_mut().enumerate() {
|
||||
*x = (seed >> (i * 8)) as u8;
|
||||
}
|
||||
}
|
||||
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();
|
||||
let split = t
|
||||
.find(|c: char| !(c.is_ascii_digit() || c == '.'))
|
||||
.unwrap_or(t.len());
|
||||
let (num, unit) = t.split_at(split);
|
||||
let n: f64 = num
|
||||
.parse()
|
||||
.with_context(|| format!("not a size: {s:?} (try 8G or 512M)"))?;
|
||||
let mul = match unit.trim().to_ascii_lowercase().as_str() {
|
||||
"" | "g" | "gb" | "gib" => 1024.0,
|
||||
"m" | "mb" | "mib" => 1.0,
|
||||
"t" | "tb" | "tib" => 1024.0 * 1024.0,
|
||||
_ => bail!("not a size: {s:?} (try 8G or 512M)"),
|
||||
};
|
||||
let mib = (n * mul).round();
|
||||
if !(1.0..=1e12).contains(&mib) {
|
||||
bail!("not a size: {s:?}");
|
||||
}
|
||||
Ok(mib as u64)
|
||||
}
|
||||
|
||||
pub fn format_mib(mib: u64) -> String {
|
||||
if mib >= 1024 && mib.is_multiple_of(1024) {
|
||||
format!("{}G", mib / 1024)
|
||||
} else {
|
||||
format!("{mib}M")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Vm {
|
||||
pub dir: PathBuf,
|
||||
pub config: VmConfig,
|
||||
}
|
||||
|
||||
impl Vm {
|
||||
pub fn load(dir: &Path) -> Result<Vm> {
|
||||
let file = dir.join(CONFIG_FILE);
|
||||
let text =
|
||||
std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
|
||||
let config: VmConfig =
|
||||
toml::from_str(&text).with_context(|| format!("parse {}", file.display()))?;
|
||||
Ok(Vm {
|
||||
dir: dir.to_path_buf(),
|
||||
config,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Result<()> {
|
||||
self.config.check()?;
|
||||
let text = toml::to_string_pretty(&self.config)?;
|
||||
let file = self.dir.join(CONFIG_FILE);
|
||||
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 {
|
||||
&self.config.name
|
||||
}
|
||||
|
||||
/// `p` against the VM's directory, unless absolute.
|
||||
pub fn path(&self, p: &Path) -> PathBuf {
|
||||
if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
self.dir.join(p)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disk(&self) -> PathBuf {
|
||||
self.path(&self.config.disk)
|
||||
}
|
||||
|
||||
pub fn logs_dir(&self) -> PathBuf {
|
||||
self.dir.join("logs")
|
||||
}
|
||||
|
||||
pub fn qemu_log(&self) -> PathBuf {
|
||||
self.logs_dir().join("qemu.log")
|
||||
}
|
||||
|
||||
pub fn serial_log(&self) -> PathBuf {
|
||||
self.logs_dir().join("serial.log")
|
||||
}
|
||||
|
||||
pub fn pidfile(&self) -> PathBuf {
|
||||
self.dir.join("qemu.pid")
|
||||
}
|
||||
|
||||
/// The QMP socket: in the VM's directory where the path fits a Unix socket's 104 bytes
|
||||
/// (macOS's limit; Linux's is 108), else in the runtime directory.
|
||||
pub fn qmp_socket(&self) -> PathBuf {
|
||||
let own = self.dir.join("qmp.sock");
|
||||
if own.as_os_str().len() < 100 {
|
||||
own
|
||||
} else {
|
||||
paths::runtime_dir().join(format!("{}.qmp", self.config.name))
|
||||
}
|
||||
}
|
||||
|
||||
/// The trimmed auxiliary storage QEMU boots (vmapple).
|
||||
pub fn aux_trimmed(&self) -> Option<PathBuf> {
|
||||
let v = self.config.vmapple.as_ref()?;
|
||||
let aux = self.path(&v.aux);
|
||||
let mut name = aux.file_name()?.to_os_string();
|
||||
name.push(".trimmed");
|
||||
Some(aux.with_file_name(name))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the registry
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Registry {
|
||||
#[serde(default, rename = "vm")]
|
||||
pub vms: Vec<Entry>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Entry {
|
||||
pub name: String,
|
||||
pub dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
pub fn load() -> Result<Registry> {
|
||||
let file = paths::registry_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(Registry::default()),
|
||||
Err(e) => Err(e).with_context(|| format!("read {}", file.display())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let file = paths::registry_file();
|
||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
||||
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> {
|
||||
self.vms.iter().find(|e| e.name == name)
|
||||
}
|
||||
|
||||
pub fn add(&mut self, name: &str, dir: &Path) -> Result<()> {
|
||||
if self.find(name).is_some() {
|
||||
bail!("a VM named {name} already exists");
|
||||
}
|
||||
self.vms.push(Entry {
|
||||
name: name.into(),
|
||||
dir: dir.to_path_buf(),
|
||||
});
|
||||
self.vms.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, name: &str) -> Option<Entry> {
|
||||
let i = self.vms.iter().position(|e| e.name == name)?;
|
||||
Some(self.vms.remove(i))
|
||||
}
|
||||
|
||||
/// The VM named `name`.
|
||||
pub fn open(&self, name: &str) -> Result<Vm> {
|
||||
let e = self
|
||||
.find(name)
|
||||
.with_context(|| format!("no VM named {name} (reims-ctl list shows them)"))?;
|
||||
Vm::load(&e.dir)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hidpi_densities_are_ones_qemu_accepts() {
|
||||
for w in [1920, 2048, 2560, 2880, 3024, 3456, 3840, 5120, 6016] {
|
||||
let ppi = hidpi_ppi(w).unwrap_or_else(|| panic!("no density for {w}"));
|
||||
assert!(!guest_scale_unknown(w, ppi), "{w}@{ppi}");
|
||||
let cm = guest_centimeters(w, ppi);
|
||||
assert!(
|
||||
w as f64 / cm as f64 * 2.54 >= 146.667,
|
||||
"{w}@{ppi} is not HiDPI ({cm} cm)"
|
||||
);
|
||||
}
|
||||
assert_eq!(hidpi_ppi(1280), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn densities_match_apple_gfx_examples() {
|
||||
// docs/qemu.md: 2560x1600@200 runs HiDPI; @148 reads 44 cm, @146 45 cm.
|
||||
assert_eq!(guest_centimeters(2560, 148), 44);
|
||||
assert_eq!(guest_centimeters(2560, 146), 45);
|
||||
assert!(!guest_scale_unknown(2560, 200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_property() {
|
||||
let mut d = Display::default();
|
||||
assert_eq!(d.qemu_resolution().unwrap(), "1920x1080");
|
||||
d.hidpi = true;
|
||||
d.resolution = "3840x2160".into();
|
||||
assert!(d.qemu_resolution().unwrap().starts_with("3840x2160@"));
|
||||
d.resolution = "1280x800".into();
|
||||
assert!(d.qemu_resolution().is_err());
|
||||
d.resolution = "host".into();
|
||||
assert!(d.qemu_resolution().is_err());
|
||||
d.hidpi = false;
|
||||
assert_eq!(d.qemu_resolution().unwrap(), "host");
|
||||
d.resolution = "19x".into();
|
||||
assert!(d.qemu_resolution().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes() {
|
||||
assert_eq!(parse_size_mib("8G").unwrap(), 8192);
|
||||
assert_eq!(parse_size_mib("8").unwrap(), 8192);
|
||||
assert_eq!(parse_size_mib("512M").unwrap(), 512);
|
||||
assert_eq!(parse_size_mib("1.5GiB").unwrap(), 1536);
|
||||
assert_eq!(parse_size_mib("1T").unwrap(), 1024 * 1024);
|
||||
assert!(parse_size_mib("eight").is_err());
|
||||
assert!(parse_size_mib("8Q").is_err());
|
||||
assert_eq!(format_mib(8192), "8G");
|
||||
assert_eq!(format_mib(1536), "1536M");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names() {
|
||||
assert!(check_name("macos-26.1_b").is_ok());
|
||||
for bad in ["", "-a", ".a", "a b", "a/b", &"x".repeat(65)] {
|
||||
assert!(check_name(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_round_trips_through_toml() {
|
||||
let c = VmConfig {
|
||||
name: "t".into(),
|
||||
profile: Profile::Q35X86_64,
|
||||
cpus: 4,
|
||||
memory_mib: 8192,
|
||||
disk: "disk.qcow2".into(),
|
||||
disk_format: ImageFormat::Qcow2,
|
||||
stop_timeout_secs: 90,
|
||||
extra_args: vec!["-boot".into(), "menu=on".into()],
|
||||
display: Display::default(),
|
||||
gpu: Gpu {
|
||||
driver_file: Some("/usr/share/vulkan/icd.d/nvidia_icd.json".into()),
|
||||
device_id: Some(0x2204),
|
||||
name: None,
|
||||
},
|
||||
audio: Audio::default(),
|
||||
network: Network {
|
||||
enabled: true,
|
||||
mac: "52:54:00:01:02:03".into(),
|
||||
ssh_port: Some(2222),
|
||||
},
|
||||
logs: Logs::default(),
|
||||
q35: Some(Q35 {
|
||||
opencore: "opencore.qcow2".into(),
|
||||
opencore_format: ImageFormat::Qcow2,
|
||||
firmware_code: "OVMF_CODE.fd".into(),
|
||||
firmware_vars: "OVMF_VARS.fd".into(),
|
||||
installer: Some("/isos/BaseSystem.img".into()),
|
||||
installer_kind: Some(MediaKind::Disk),
|
||||
cpu_model: default_cpu_model(),
|
||||
cpu_flags: default_cpu_flags(),
|
||||
osk: None,
|
||||
disk_port: 3,
|
||||
}),
|
||||
vmapple: None,
|
||||
extra_env: BTreeMap::from([("A".into(), "b".into())]),
|
||||
};
|
||||
let text = toml::to_string_pretty(&c).unwrap();
|
||||
assert_eq!(toml::from_str::<VmConfig>(&text).unwrap(), c);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
//! Installing macOS from an IPSW into a new arm64 VM, through Virtualization.framework, the only
|
||||
//! thing that restores one. The result is what macosvm makes and QEMU's vmapple boots: a raw
|
||||
//! `disk.img`, the auxiliary storage `aux.img`, and a machine identifier, whose ECID
|
||||
//! `-M vmapple,uuid=` takes (the identifier's and the hardware model's data are kept beside them,
|
||||
//! in `machine-identifier.bin` and `hardware-model.bin`).
|
||||
//!
|
||||
//! The install runs in a child process (`reims-ctl __vz-install`): Virtualization.framework uses
|
||||
//! a virtual machine on its queue, the main one here, which the child's main thread serves by
|
||||
//! running the main run loop, whatever the parent's threads are doing (the interface runs
|
||||
//! installs on a thread of its own). The child prints `progress <fraction>` lines and, at the
|
||||
//! end, `ecid <n>`. It needs the `com.apple.security.virtualization` entitlement, which
|
||||
//! scripts/install-ctl.sh signs reims-ctl with.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::io::BufRead;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// Whether this binary carries the virtualization entitlement.
|
||||
pub fn entitled() -> bool {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return false;
|
||||
}
|
||||
let Ok(exe) = std::env::current_exe() else {
|
||||
return false;
|
||||
};
|
||||
Command::new("codesign")
|
||||
.args(["-d", "--entitlements", "-", "--xml"])
|
||||
.arg(&exe)
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).contains("com.apple.security.virtualization"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Installs `ipsw` (a path, or `latest`) into `dir`, making a disk of `disk_mib`; returns the
|
||||
/// machine identifier's ECID.
|
||||
pub fn install(
|
||||
ipsw: &str,
|
||||
dir: &Path,
|
||||
disk_mib: u64,
|
||||
cpus: u32,
|
||||
memory_mib: u64,
|
||||
progress: &mut dyn FnMut(&str),
|
||||
) -> Result<u64> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
bail!("an IPSW installs only on macOS");
|
||||
}
|
||||
if !entitled() {
|
||||
bail!(
|
||||
"installing from an IPSW needs reims-ctl signed with the com.apple.security.virtualization \
|
||||
entitlement: rerun scripts/install-ctl.sh (a plain cargo install leaves it out)"
|
||||
);
|
||||
}
|
||||
let exe = std::env::current_exe()?;
|
||||
let ipsw = if ipsw == "latest" {
|
||||
progress("asking Apple for the newest macOS this Mac supports");
|
||||
let out = Command::new(&exe).arg("__vz-latest").output()?;
|
||||
let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
if !out.status.success() || !url.starts_with("http") {
|
||||
bail!(
|
||||
"could not find the latest IPSW: {}",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
);
|
||||
}
|
||||
download(&url, progress)?
|
||||
} else {
|
||||
PathBuf::from(ipsw)
|
||||
};
|
||||
if !ipsw.is_file() {
|
||||
bail!("{} does not exist", ipsw.display());
|
||||
}
|
||||
progress("loading the IPSW");
|
||||
let mut child = Command::new(&exe)
|
||||
.arg("__vz-install")
|
||||
.arg("--ipsw")
|
||||
.arg(&ipsw)
|
||||
.arg("--dir")
|
||||
.arg(dir)
|
||||
.args([
|
||||
"--disk-mib",
|
||||
&disk_mib.to_string(),
|
||||
"--cpus",
|
||||
&cpus.to_string(),
|
||||
"--memory-mib",
|
||||
&memory_mib.to_string(),
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
let stderr = child.stderr.take().unwrap();
|
||||
let err_thread = std::thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
use std::io::Read;
|
||||
let _ = std::io::BufReader::new(stderr).read_to_string(&mut s);
|
||||
s
|
||||
});
|
||||
let mut ecid = None;
|
||||
let mut last = -1i64;
|
||||
for line in std::io::BufReader::new(child.stdout.take().unwrap()).lines() {
|
||||
let line = line?;
|
||||
if let Some(f) = line.strip_prefix("progress ") {
|
||||
let pct = (f.parse::<f64>().unwrap_or(0.0) * 100.0) as i64;
|
||||
if pct != last {
|
||||
last = pct;
|
||||
progress(&format!("installing macOS: {pct}%"));
|
||||
}
|
||||
} else if let Some(e) = line.strip_prefix("ecid ") {
|
||||
ecid = e.trim().parse().ok();
|
||||
} else if let Some(m) = line.strip_prefix("note ") {
|
||||
progress(m);
|
||||
}
|
||||
}
|
||||
let status = child.wait()?;
|
||||
let err = err_thread.join().unwrap_or_default();
|
||||
match (status.success(), ecid) {
|
||||
(true, Some(e)) => Ok(e),
|
||||
_ => bail!("the install failed: {}", err.trim()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads `url` into the data directory's `ipsw/`, resuming a partial download; returns the
|
||||
/// file.
|
||||
fn download(url: &str, progress: &mut dyn FnMut(&str)) -> Result<PathBuf> {
|
||||
let name = url
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.filter(|n| n.ends_with(".ipsw"))
|
||||
.unwrap_or("latest.ipsw");
|
||||
let dir = crate::paths::data_dir().join("ipsw");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let file = dir.join(name);
|
||||
if file.is_file() {
|
||||
progress(&format!(
|
||||
"using the IPSW downloaded before, {}",
|
||||
crate::paths::tilde(&file)
|
||||
));
|
||||
return Ok(file);
|
||||
}
|
||||
let part = dir.join(format!("{name}.part"));
|
||||
let total: u64 = Command::new("curl")
|
||||
.args(["-sIL", url])
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|o| {
|
||||
String::from_utf8_lossy(&o.stdout)
|
||||
.lines()
|
||||
.filter_map(|l| {
|
||||
l.to_ascii_lowercase()
|
||||
.strip_prefix("content-length:")
|
||||
.map(|v| v.trim().to_string())
|
||||
})
|
||||
.next_back()
|
||||
.and_then(|v| v.parse().ok())
|
||||
})
|
||||
.unwrap_or(0);
|
||||
let mut child = Command::new("curl")
|
||||
.args(["-fsSL", "--retry", "3", "-C", "-", "-o"])
|
||||
.arg(&part)
|
||||
.arg(url)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.context("run curl")?;
|
||||
loop {
|
||||
if let Some(st) = child.try_wait()? {
|
||||
if !st.success() {
|
||||
let mut e = String::new();
|
||||
use std::io::Read;
|
||||
let _ = child.stderr.take().map(|mut s| s.read_to_string(&mut e));
|
||||
bail!("the download failed: {}", e.trim());
|
||||
}
|
||||
break;
|
||||
}
|
||||
let have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if total > 0 {
|
||||
progress(&format!(
|
||||
"downloading {name}: {:.0}% of {:.1} GB",
|
||||
have as f64 * 100.0 / total as f64,
|
||||
total as f64 / 1e9
|
||||
));
|
||||
} else {
|
||||
progress(&format!("downloading {name}: {:.1} GB", have as f64 / 1e9));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
}
|
||||
std::fs::rename(&part, &file)?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod imp {
|
||||
use anyhow::{Context, Result, bail};
|
||||
use block2::RcBlock;
|
||||
use objc2::AllocAnyThread;
|
||||
use objc2::rc::Retained;
|
||||
use objc2_foundation::{NSArray, NSDate, NSError, NSRunLoop, NSString, NSURL};
|
||||
use objc2_virtualization::*;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn url(p: &Path) -> Retained<NSURL> {
|
||||
NSURL::fileURLWithPath(&NSString::from_str(&p.to_string_lossy()))
|
||||
}
|
||||
|
||||
fn describe(e: *mut NSError) -> String {
|
||||
if e.is_null() {
|
||||
return "unknown error".into();
|
||||
}
|
||||
// SAFETY: a non-null NSError the framework passed.
|
||||
unsafe { (*e).localizedDescription().to_string() }
|
||||
}
|
||||
|
||||
fn spin_until<T>(slot: &Arc<Mutex<Option<T>>>) -> T {
|
||||
loop {
|
||||
if let Some(v) = slot.lock().unwrap().take() {
|
||||
return v;
|
||||
}
|
||||
NSRunLoop::mainRunLoop().runUntilDate(&NSDate::dateWithTimeIntervalSinceNow(0.1));
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads a restore image (from a file, or Apple's newest), as a raw retained pointer.
|
||||
fn restore_image(file: Option<&Path>) -> Result<Retained<VZMacOSRestoreImage>> {
|
||||
let slot: Arc<Mutex<Option<Result<usize, String>>>> = Arc::new(Mutex::new(None));
|
||||
let s = slot.clone();
|
||||
let block = RcBlock::new(move |img: *mut VZMacOSRestoreImage, err: *mut NSError| {
|
||||
let r = if img.is_null() {
|
||||
Err(describe(err))
|
||||
} else {
|
||||
// SAFETY: a live image the framework passed; retained here, released by the
|
||||
// Retained made from it below.
|
||||
Ok(unsafe { Retained::into_raw(Retained::retain(img).unwrap()) } as usize)
|
||||
};
|
||||
*s.lock().unwrap() = Some(r);
|
||||
});
|
||||
// SAFETY: the block lives until the call returns, and the framework copies it.
|
||||
unsafe {
|
||||
match file {
|
||||
Some(f) => VZMacOSRestoreImage::loadFileURL_completionHandler(&url(f), &block),
|
||||
None => VZMacOSRestoreImage::fetchLatestSupportedWithCompletionHandler(&block),
|
||||
}
|
||||
}
|
||||
let ptr = spin_until(&slot).map_err(anyhow::Error::msg)?;
|
||||
// SAFETY: retained in the block above.
|
||||
Ok(unsafe { Retained::from_raw(ptr as *mut VZMacOSRestoreImage) }.unwrap())
|
||||
}
|
||||
|
||||
pub fn latest() -> Result<String> {
|
||||
let img = restore_image(None)?;
|
||||
// SAFETY: a loaded image.
|
||||
let u = unsafe { img.URL() };
|
||||
Ok(u.absoluteString()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
ipsw: &Path,
|
||||
dir: &Path,
|
||||
disk_mib: u64,
|
||||
cpus: u32,
|
||||
memory_mib: u64,
|
||||
) -> Result<u64> {
|
||||
let img = restore_image(Some(ipsw)).context("load the IPSW")?;
|
||||
// SAFETY: each call below is on the main thread, with live objects, in the order
|
||||
// Virtualization.framework's documentation gives.
|
||||
unsafe {
|
||||
let req = img.mostFeaturefulSupportedConfiguration().context(
|
||||
"this Mac cannot run the macOS in this IPSW (too old or too new for it)",
|
||||
)?;
|
||||
let hw = req.hardwareModel();
|
||||
if !hw.isSupported() {
|
||||
bail!("this Mac does not support the IPSW's hardware model");
|
||||
}
|
||||
let cpus = (cpus as usize).max(req.minimumSupportedCPUCount());
|
||||
let memory = (memory_mib * 1024 * 1024).max(req.minimumSupportedMemorySize());
|
||||
println!("note creating the auxiliary storage");
|
||||
let aux = VZMacAuxiliaryStorage::initCreatingStorageAtURL_hardwareModel_options_error(
|
||||
VZMacAuxiliaryStorage::alloc(),
|
||||
&url(&dir.join("aux.img")),
|
||||
&hw,
|
||||
VZMacAuxiliaryStorageInitializationOptions::AllowOverwrite,
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("create aux.img: {}", e.localizedDescription()))?;
|
||||
let ident = VZMacMachineIdentifier::new();
|
||||
let ident_data = ident.dataRepresentation().to_vec();
|
||||
std::fs::write(dir.join("machine-identifier.bin"), &ident_data)?;
|
||||
std::fs::write(
|
||||
dir.join("hardware-model.bin"),
|
||||
hw.dataRepresentation().to_vec(),
|
||||
)?;
|
||||
let ecid = crate::create::ecid_from_identifier(&ident_data)?;
|
||||
|
||||
let disk = dir.join("disk.img");
|
||||
std::fs::File::create(&disk)?.set_len(disk_mib * 1024 * 1024)?;
|
||||
|
||||
let platform = VZMacPlatformConfiguration::new();
|
||||
platform.setHardwareModel(&hw);
|
||||
platform.setMachineIdentifier(&ident);
|
||||
platform.setAuxiliaryStorage(Some(&aux));
|
||||
let config = VZVirtualMachineConfiguration::new();
|
||||
config.setPlatform(&platform);
|
||||
config.setBootLoader(Some(&VZMacOSBootLoader::new()));
|
||||
config.setCPUCount(cpus);
|
||||
config.setMemorySize(memory);
|
||||
let attachment = VZDiskImageStorageDeviceAttachment::initWithURL_readOnly_error(
|
||||
VZDiskImageStorageDeviceAttachment::alloc(),
|
||||
&url(&disk),
|
||||
false,
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("attach disk.img: {}", e.localizedDescription()))?;
|
||||
let blk = VZVirtioBlockDeviceConfiguration::initWithAttachment(
|
||||
VZVirtioBlockDeviceConfiguration::alloc(),
|
||||
&attachment,
|
||||
);
|
||||
config.setStorageDevices(&NSArray::from_retained_slice(&[Retained::into_super(blk)]));
|
||||
let display = VZMacGraphicsDisplayConfiguration::initWithWidthInPixels_heightInPixels_pixelsPerInch(
|
||||
VZMacGraphicsDisplayConfiguration::alloc(),
|
||||
1920,
|
||||
1200,
|
||||
80,
|
||||
);
|
||||
let gfx = VZMacGraphicsDeviceConfiguration::new();
|
||||
gfx.setDisplays(&NSArray::from_retained_slice(&[display]));
|
||||
config.setGraphicsDevices(&NSArray::from_retained_slice(&[Retained::into_super(gfx)]));
|
||||
config.validateWithError().map_err(|e| {
|
||||
anyhow::anyhow!("the VM's configuration: {}", e.localizedDescription())
|
||||
})?;
|
||||
|
||||
let vm = VZVirtualMachine::initWithConfiguration(VZVirtualMachine::alloc(), &config);
|
||||
let installer = VZMacOSInstaller::initWithVirtualMachine_restoreImageURL(
|
||||
VZMacOSInstaller::alloc(),
|
||||
&vm,
|
||||
&url(ipsw),
|
||||
);
|
||||
let done: Arc<Mutex<Option<Result<(), String>>>> = Arc::new(Mutex::new(None));
|
||||
let d = done.clone();
|
||||
let block = RcBlock::new(move |err: *mut NSError| {
|
||||
*d.lock().unwrap() = Some(if err.is_null() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(describe(err))
|
||||
});
|
||||
});
|
||||
println!("note installing macOS");
|
||||
installer.installWithCompletionHandler(&block);
|
||||
let progress = installer.progress();
|
||||
let mut last = -1.0;
|
||||
let result = loop {
|
||||
if let Some(r) = done.lock().unwrap().take() {
|
||||
break r;
|
||||
}
|
||||
let f = progress.fractionCompleted();
|
||||
if (f - last).abs() >= 0.001 {
|
||||
last = f;
|
||||
println!("progress {f:.4}");
|
||||
use std::io::Write;
|
||||
let _ = std::io::stdout().flush();
|
||||
}
|
||||
NSRunLoop::mainRunLoop().runUntilDate(&NSDate::dateWithTimeIntervalSinceNow(0.25));
|
||||
};
|
||||
result.map_err(anyhow::Error::msg)?;
|
||||
Ok(ecid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `reims-ctl __vz-install`.
|
||||
pub fn install_main(
|
||||
ipsw: &Path,
|
||||
dir: &Path,
|
||||
disk_mib: u64,
|
||||
cpus: u32,
|
||||
memory_mib: u64,
|
||||
) -> Result<i32> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let ecid = imp::install(ipsw, dir, disk_mib, cpus, memory_mib)?;
|
||||
println!("ecid {ecid}");
|
||||
Ok(0)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = (ipsw, dir, disk_mib, cpus, memory_mib);
|
||||
bail!("an IPSW installs only on macOS")
|
||||
}
|
||||
}
|
||||
|
||||
/// `reims-ctl __vz-latest`: the URL of the newest IPSW this Mac supports.
|
||||
pub fn latest_main() -> Result<i32> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
println!("{}", imp::latest()?);
|
||||
Ok(0)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
bail!("IPSWs are macOS's")
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
[package]
|
||||
name = "reims-vgpu-c"
|
||||
description = "The C API (rvg_*) over reims-vgpu; adds no behaviour"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
# cdylib: the dist tree's lib/libreims_vgpu.dylib (@rpath/libreims_vgpu.dylib), which the suite's
|
||||
# runner links; staticlib: lib/libreims_vgpu.a, which QEMU and the smoke link; rlib so Rust tests
|
||||
# link it.
|
||||
crate-type = ["cdylib", "staticlib", "rlib"]
|
||||
|
||||
[features]
|
||||
default = ["macos-sdl"]
|
||||
# SDL3's window on macOS (`reims-vgpu`'s `macos-sdl`), on by default: `--no-default-features`
|
||||
# builds the macOS library without SDL, its windows AppKit's alone.
|
||||
macos-sdl = ["reims-vgpu/macos-sdl"]
|
||||
# The Vulkan platform's proof of concept (architecture 11.1): every handle is made on
|
||||
# `VulkanPlatform` in place of `MetalPlatform`. Off by default: the Metal platform is the product.
|
||||
# `cargo xtask dist --platform vulkan` builds the dist tree with it.
|
||||
vulkan = ["reims-vgpu/vulkan"]
|
||||
|
||||
[dependencies]
|
||||
reims-vgpu.workspace = true
|
||||
# The platform trait's associated types (the unit tests' testkit platform stands where
|
||||
# MetalPlatform stands in the product), and the log hook.
|
||||
reims-vgpu-core.workspace = true
|
||||
log.workspace = true
|
||||
parking_lot.workspace = true
|
||||
# `fstat` and the host's page size, for the files behind a memory map's ranges.
|
||||
libc.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# `exception::catch` around every call of a host function (`ffi::host_call`, `ffi/catch/macos.rs`).
|
||||
objc2.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
reims-vgpu = { workspace = true, features = ["testkit"] }
|
||||
reims-vgpu-core = { workspace = true, features = ["testkit"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dev-dependencies]
|
||||
# The exceptions `ffi`'s tests throw as a host would (`ffi/tests/macos.rs`).
|
||||
objc2-foundation.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,68 @@
|
||||
# cbindgen configuration for include/reims_vgpu.h, the C API.
|
||||
# `cargo xtask header` regenerates the header; `--check` fails on drift.
|
||||
language = "C"
|
||||
include_guard = "REIMS_VGPU_H"
|
||||
autogen_warning = "/* Generated by cbindgen from crates/reims-vgpu-c (cbindgen.toml): `cargo xtask header`.\n * Committed and drift-checked by `cargo xtask header --check`. Do not edit by hand. */"
|
||||
usize_is_size_t = true
|
||||
style = "type"
|
||||
documentation = true
|
||||
documentation_style = "c99"
|
||||
cpp_compat = true
|
||||
sys_includes = ["stdbool.h", "stddef.h", "stdint.h"]
|
||||
no_includes = true
|
||||
header = """/*
|
||||
* reims_vgpu.h: the C API of reims-vgpu, the host side of a paravirtualized GPU driven by
|
||||
* macOS guests' drivers (the PCI device 106b:eeee, or vmapple's MMIO device).
|
||||
*
|
||||
* Handles. RvgDevice, RvgDisplay, RvgIOSurfaceDevice, RvgFrameTarget, RvgFrame and
|
||||
* RvgTraceRangeHandler are opaque. A create function makes one: it returns an RvgStatus and,
|
||||
* on RVG_OK only, writes the handle through its last argument. The caller owns that handle
|
||||
* and ends it with the matching release. RvgFrameTarget and RvgTraceRangeHandler also have a
|
||||
* retain, since hosts hand them between threads. A release of NULL does nothing. Every other
|
||||
* function needs a live handle: NULL is RVG_ERR_INVALID_ARGUMENT from a function that returns
|
||||
* an RvgStatus, and ends the process from any other.
|
||||
*
|
||||
* Lifetimes. A display keeps its device alive. A frame keeps its display and its target alive
|
||||
* until it completes or, uncommitted, is released. The device's teardown runs at the last
|
||||
* release of the device and of everything that keeps it alive, on the thread that makes that
|
||||
* release, and may block there. A frame target keeps only its Metal texture, and may outlive
|
||||
* the device it was made on.
|
||||
*
|
||||
* Configs. Every config struct, callback table and struct the library hands out starts with
|
||||
* `struct_size`: the size of the struct as the writer was compiled. For a struct the host
|
||||
* writes, a size below the first version's is RVG_ERR_INVALID_ARGUMENT; fields past
|
||||
* `struct_size` read as zero; a size above the library's is accepted when every byte past
|
||||
* the library's size is zero, and is RVG_ERR_UNSUPPORTED otherwise. Zero is each field's
|
||||
* default, except `display_port_count`, where 0 is refused. Configs and everything they point
|
||||
* to are borrowed for the call: the library copies what it keeps.
|
||||
*
|
||||
* Callbacks. A callback table carries one `ctx` for its functions and one optional
|
||||
* `destroy(ctx)`. A NULL function is a callback the host does not give; the library then does
|
||||
* what the function's comment says it does without it. `destroy` runs exactly once, on any
|
||||
* thread, when no function of the table will run again: at the end of the object the table was
|
||||
* given to (for a table with no function, at the host's release of the object), or before a
|
||||
* create that refuses returns. A create given no config, or a config or table it refuses for
|
||||
* its `struct_size`, has not read the table, and runs no destroy. Each callback type says the
|
||||
* thread it arrives on, what it is serialized with, and which functions of this header it may
|
||||
* call. The library never waits for the display thread. It does wait for its FIFO and worker
|
||||
* threads, where the device callbacks run, so a device callback must not wait for a host
|
||||
* thread that is inside a call on the same device.
|
||||
*
|
||||
* Deaths. Where the guest's input is invalid, or the host breaks a rule this header says ends
|
||||
* the process, the process ends at that operation: a line on stderr, then abort(). No function
|
||||
* unwinds into its caller: an exception a callback throws ends the process at that callback.
|
||||
*/"""
|
||||
|
||||
[parse]
|
||||
parse_deps = false
|
||||
|
||||
[export]
|
||||
prefix = ""
|
||||
item_types = ["constants", "globals", "enums", "structs", "unions", "typedefs", "opaque", "functions"]
|
||||
|
||||
[fn]
|
||||
args = "auto"
|
||||
sort_by = "None"
|
||||
|
||||
[struct]
|
||||
derive_eq = false
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,896 @@
|
||||
//! The device: [`RvgDeviceConfig`], [`RvgHostCallbacks`], and the `rvg_device_*` functions,
|
||||
//! suspend and resume among them.
|
||||
//!
|
||||
//! The host's functions become the Rust API's closures, each calling its function
|
||||
//! synchronously on the thread core calls it on, with the arguments core passes, so the order
|
||||
//! of VM-memory operations is core's (docs/api.md section 5). Each call into the host runs under
|
||||
//! `ffi::host_call`: a host function that raises ends the process at the call.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::num::NonZeroU64;
|
||||
use std::os::fd::{FromRawFd, OwnedFd};
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu::{
|
||||
AddTraceRange, CreateTask, DestroyTask, Device, DeviceConfig, Error, HostCallbacks, HostPtr,
|
||||
HostTask, HostTraceRange, MapMemory, MemoryFile, MemoryMap, PhysicalMemoryRange,
|
||||
RaiseInterrupt, ReadMemory, RemoveTraceRange, UnmapMemory,
|
||||
};
|
||||
|
||||
use crate::ffi;
|
||||
use crate::handle;
|
||||
use crate::sized::{self, HostStruct};
|
||||
use crate::status::{RVG_ERR_INVALID_ARGUMENT, RVG_OK, RvgStatus, status};
|
||||
use crate::table::{RvgDestroyFn, Table, WithTable};
|
||||
use crate::trace::RvgTraceRangeHandler;
|
||||
use crate::{Plat, null_handle};
|
||||
|
||||
/// Why a resume refused its state: one of RVG_RESUME_ERROR_*.
|
||||
pub type RvgResumeError = u32;
|
||||
|
||||
// The constants below are RvgResumeError values, typed `u32` so that cbindgen writes them with the
|
||||
// header's other constants, ahead of its types.
|
||||
|
||||
/// No reason stored.
|
||||
pub const RVG_RESUME_ERROR_NONE: u32 = 4294967295;
|
||||
|
||||
/// An internal fault.
|
||||
pub const RVG_RESUME_ERROR_INTERNAL_FAULT: u32 = 0;
|
||||
|
||||
/// The state's version is not one the device reads.
|
||||
pub const RVG_RESUME_ERROR_INVALID_SUSPEND_STATE_VERSION: u32 = 1;
|
||||
|
||||
/// The state is malformed, or absent.
|
||||
pub const RVG_RESUME_ERROR_INVALID_CONTENT: u32 = 2;
|
||||
|
||||
/// The guest's binary version in the state is not one the device supports.
|
||||
pub const RVG_RESUME_ERROR_INVALID_GUEST_VERSION: u32 = 3;
|
||||
|
||||
/// The state was taken on a device this one cannot stand in for.
|
||||
pub const RVG_RESUME_ERROR_INCOMPATIBLE_DEVICE: u32 = 4;
|
||||
|
||||
/// The state's display port count differs from the device's.
|
||||
pub const RVG_RESUME_ERROR_INVALID_DISPLAY_PORT_COUNT: u32 = 5;
|
||||
|
||||
const _: () = assert!(RVG_RESUME_ERROR_NONE == u32::MAX);
|
||||
|
||||
/// One range of guest physical memory.
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct RvgPhysicalMemoryRange {
|
||||
pub physical_address: u64,
|
||||
pub physical_length: u64,
|
||||
}
|
||||
|
||||
const _: () = assert!(size_of::<RvgPhysicalMemoryRange>() == size_of::<PhysicalMemoryRange>());
|
||||
const _: () = assert!(align_of::<RvgPhysicalMemoryRange>() == align_of::<PhysicalMemoryRange>());
|
||||
|
||||
impl From<PhysicalMemoryRange> for RvgPhysicalMemoryRange {
|
||||
fn from(r: PhysicalMemoryRange) -> Self {
|
||||
RvgPhysicalMemoryRange {
|
||||
physical_address: r.physical_address,
|
||||
physical_length: r.physical_length,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RvgPhysicalMemoryRange> for PhysicalMemoryRange {
|
||||
fn from(r: RvgPhysicalMemoryRange) -> Self {
|
||||
PhysicalMemoryRange {
|
||||
physical_address: r.physical_address,
|
||||
physical_length: r.physical_length,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `create_task(ctx, vm_size, &base_address)`: reserve `vm_size` bytes of host address space
|
||||
/// for a new GPU task. Returns the host's task, or NULL for a failure, and writes the base
|
||||
/// address of the reservation through `base_address`.
|
||||
///
|
||||
/// Thread: a library thread, or the host's thread inside a call marked "may call back".
|
||||
/// Calls for different tasks may run at once.
|
||||
/// May call: rvg_status_message only.
|
||||
pub type RvgCreateTaskFn = Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
ctx: *mut c_void,
|
||||
vm_size: u64,
|
||||
base_address: *mut *mut c_void,
|
||||
) -> *mut c_void,
|
||||
>;
|
||||
|
||||
/// `destroy_task(ctx, task)`: the task's last call. `task` is NULL after a failed root map.
|
||||
///
|
||||
/// Thread, and what it may call: as RvgCreateTaskFn. Every call for `task` has returned.
|
||||
pub type RvgDestroyTaskFn =
|
||||
Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, task: *mut c_void)>;
|
||||
|
||||
/// `map_memory(ctx, task, range_count, virtual_offset, read_only, ranges)`: map `range_count`
|
||||
/// guest ranges, one after another, at `virtual_offset` in the task's reservation. `ranges` is
|
||||
/// borrowed for the call. Returns false for a failure.
|
||||
///
|
||||
/// Thread, and what it may call: as RvgCreateTaskFn. One task's map and unmap calls come in the
|
||||
/// order the device makes them.
|
||||
pub type RvgMapMemoryFn = Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
ctx: *mut c_void,
|
||||
task: *mut c_void,
|
||||
range_count: u32,
|
||||
virtual_offset: u64,
|
||||
read_only: bool,
|
||||
ranges: *const RvgPhysicalMemoryRange,
|
||||
) -> bool,
|
||||
>;
|
||||
|
||||
/// `unmap_memory(ctx, task, virtual_offset, length)`. Returns false for a failure.
|
||||
///
|
||||
/// Thread, and what it may call: as RvgMapMemoryFn.
|
||||
pub type RvgUnmapMemoryFn = Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
ctx: *mut c_void,
|
||||
task: *mut c_void,
|
||||
virtual_offset: u64,
|
||||
length: u64,
|
||||
) -> bool,
|
||||
>;
|
||||
|
||||
/// `read_memory(ctx, physical_address, length, dst)`: copy guest memory into `dst`. Returns false
|
||||
/// for a failure. The device reads guest physical memory this way, at most one guest page (16 KiB
|
||||
/// on arm64, 4 KiB on x86-64) a call: a task's page tables, the task memory it copies through
|
||||
/// them, and each task's root node at a resume. With a memory map it reads through the map, and a
|
||||
/// config that gives read_memory is refused. Without a map and without read_memory, it maps the
|
||||
/// page into its root task (map_memory, then unmap_memory) and copies from there; while the guest
|
||||
/// has no root page, the device has no root task, and the read fails.
|
||||
///
|
||||
/// Thread, and what it may call: as RvgCreateTaskFn. It may wait for another host thread, unless
|
||||
/// that thread is itself waiting in a call on this device that may call back.
|
||||
pub type RvgReadMemoryFn = Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
ctx: *mut c_void,
|
||||
physical_address: u64,
|
||||
length: u64,
|
||||
dst: *mut c_void,
|
||||
) -> bool,
|
||||
>;
|
||||
|
||||
/// `raise_interrupt(ctx, vector)`: raise the guest interrupt `vector`.
|
||||
///
|
||||
/// Thread: a library thread (a FIFO's or the device's reporting thread), or the host's thread
|
||||
/// inside a call marked "may call back". The device's signal lock is held: one device's raises
|
||||
/// never run at once. It must not wait for a host thread that is in a call on this device.
|
||||
/// May call: rvg_status_message only. Without it, the device's first interrupt ends the
|
||||
/// process.
|
||||
pub type RvgRaiseInterruptFn = Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, vector: u32)>;
|
||||
|
||||
/// `add_trace_range(ctx, range, handler)`: watch guest writes to `range` (the EFI framebuffer)
|
||||
/// and call `handler` with the dirtied part. Returns the host's trace range, or NULL for none:
|
||||
/// the EFI display then presents every 100 ms instead of after each write. `handler` is borrowed
|
||||
/// for the call: keep it with rvg_trace_range_handler_retain. The handler must not be invoked
|
||||
/// from inside this call.
|
||||
///
|
||||
/// Thread: the host's thread inside a call marked "may call back", or a library thread.
|
||||
/// May call: rvg_trace_range_handler_retain, rvg_status_message.
|
||||
pub type RvgAddTraceRangeFn = Option<
|
||||
unsafe extern "C-unwind" fn(
|
||||
ctx: *mut c_void,
|
||||
range: RvgPhysicalMemoryRange,
|
||||
handler: *mut RvgTraceRangeHandler,
|
||||
) -> *mut c_void,
|
||||
>;
|
||||
|
||||
/// `remove_trace_range(ctx, trace_range)`: stop watching `trace_range`, a range add_trace_range
|
||||
/// returned. It comes once for each non-NULL range, when the EFI display stops presenting from
|
||||
/// it: at the guest's next write to an EFI framebuffer register, when EFI goes off, when port 0
|
||||
/// has no display to present to, or at the device's end. A NULL answer gets no call.
|
||||
///
|
||||
/// Thread: as RvgAddTraceRangeFn.
|
||||
/// May call: rvg_trace_range_handler_release, rvg_status_message.
|
||||
pub type RvgRemoveTraceRangeFn =
|
||||
Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, trace_range: *mut c_void)>;
|
||||
|
||||
/// The device's callbacks. Without a memory map, the device calls the task and memory
|
||||
/// callbacks; with one, it calls none of them and a config that gives any is refused. Without
|
||||
/// `add_trace_range` the device calls neither trace function.
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RvgHostCallbacks {
|
||||
/// sizeof(RvgHostCallbacks) as the host was compiled.
|
||||
pub struct_size: u32,
|
||||
pub ctx: *mut c_void,
|
||||
/// Runs once after the device's end, when no callback of the table runs again.
|
||||
pub destroy: RvgDestroyFn,
|
||||
pub create_task: RvgCreateTaskFn,
|
||||
pub destroy_task: RvgDestroyTaskFn,
|
||||
pub map_memory: RvgMapMemoryFn,
|
||||
pub unmap_memory: RvgUnmapMemoryFn,
|
||||
pub read_memory: RvgReadMemoryFn,
|
||||
pub raise_interrupt: RvgRaiseInterruptFn,
|
||||
pub add_trace_range: RvgAddTraceRangeFn,
|
||||
pub remove_trace_range: RvgRemoveTraceRangeFn,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; pointers and optional function pointers.
|
||||
unsafe impl HostStruct for RvgHostCallbacks {}
|
||||
|
||||
/// One range of guest physical memory and the host memory behind it.
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RvgMemoryRange {
|
||||
pub physical_address: u64,
|
||||
pub physical_length: u64,
|
||||
/// `physical_length` bytes, mapped (`mach_vm_allocate`d or equivalent) for as long as any
|
||||
/// device or IOSurface device made over the map lives.
|
||||
pub host_address: *mut c_void,
|
||||
}
|
||||
|
||||
/// The guest's RAM, as the host maps it. The ranges are copied at the create call, in order.
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RvgMemoryMap {
|
||||
pub ranges: *const RvgMemoryRange,
|
||||
pub range_count: usize,
|
||||
}
|
||||
|
||||
/// The file behind one range of a memory map: the range's host memory is a shared mapping
|
||||
/// (MAP_SHARED) of `fd` from byte `offset`. Plain data.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RvgMemoryRangeFile {
|
||||
/// An open file descriptor, which the library duplicates during the create (the host may
|
||||
/// close its own afterwards), or -1 for a range with no file.
|
||||
pub fd: i32,
|
||||
/// 0; other values are refused.
|
||||
pub flags: u32,
|
||||
/// The file offset of the range's first byte, a multiple of the host's page size.
|
||||
pub offset: u64,
|
||||
}
|
||||
|
||||
const _: () = assert!(size_of::<RvgMemoryRangeFile>() == 16);
|
||||
|
||||
/// The device's config.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RvgDeviceConfig {
|
||||
/// sizeof(RvgDeviceConfig) as the host was compiled.
|
||||
pub struct_size: u32,
|
||||
/// 1 to RVG_MAX_DISPLAY_PORTS; 0 is refused.
|
||||
pub display_port_count: u32,
|
||||
/// The Metal device's registry ID; 0 is the system's default Metal device.
|
||||
pub metal_registry_id: u64,
|
||||
/// The feature level: 0 and 4 offer every feature; 1, 2 and 3 cap the binary version the
|
||||
/// guest may choose at 62, 113 and 209, and trim the device info it reads. A level above 4 is
|
||||
/// accepted here; the guest's first binary version write then ends the process, as do
|
||||
/// rvg_device_reset and rvg_device_will_resume once it applies the state's version.
|
||||
pub feature_level: u64,
|
||||
/// The display port connection types the guest reads (0: none set); below binary version 245
|
||||
/// it reads their low 2 bits. A resume of a state from binary version 238 or later refuses one
|
||||
/// taken with other types (RVG_RESUME_ERROR_INTERNAL_FAULT).
|
||||
pub display_port_connection_types: u32,
|
||||
/// Map guest IOSurfaces through the process's latest RvgIOSurfaceDevice (vmapple).
|
||||
pub use_iosurface_mapper: bool,
|
||||
/// Run each isolated guest task with the task service's semantics (needs a memory map).
|
||||
pub process_isolation: bool,
|
||||
/// Withhold argument buffers from the guest. They are offered only with process isolation, on
|
||||
/// a Metal device that can detach backing and is not itself paravirtual.
|
||||
pub disable_argument_buffers: bool,
|
||||
/// The guest's RAM, or NULL to reach it through the host callbacks.
|
||||
pub memory_map: *const RvgMemoryMap,
|
||||
/// NULL is a table with every callback absent.
|
||||
pub callbacks: *const RvgHostCallbacks,
|
||||
/// With `memory_map`: `memory_map->range_count` entries, the i-th naming the file behind
|
||||
/// the map's i-th range in the order the host listed them; NULL for none. On Linux the
|
||||
/// library builds its views of guest pages from these files (a range without one gets no
|
||||
/// view, and a guest use that needs one fails as a failed remap does, as does one over a
|
||||
/// file of huge pages, hugetlbfs, which the checks below accept and no view of a page of the
|
||||
/// host's size can map: give such a range fd -1); on macOS they are checked and not used. Files without a map are refused, and so is an entry whose `fd` is
|
||||
/// below -1, whose `flags` are not 0, or, for an `fd` of 0 or more, whose file `fstat`
|
||||
/// cannot read, holds fewer than `offset` + the range's length bytes, or whose `offset` is
|
||||
/// not a multiple of the host's page size: RVG_ERR_INVALID_ARGUMENT, in that order, before
|
||||
/// any file is duplicated.
|
||||
pub memory_files: *const RvgMemoryRangeFile,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; integers, bools and pointers.
|
||||
unsafe impl HostStruct for RvgDeviceConfig {
|
||||
/// The first version ends at `callbacks`: a host built against it passes 48, and has no
|
||||
/// `memory_files`.
|
||||
const V1_SIZE: usize = 48;
|
||||
}
|
||||
|
||||
const _: () =
|
||||
assert!(std::mem::offset_of!(RvgDeviceConfig, memory_files) == RvgDeviceConfig::V1_SIZE);
|
||||
|
||||
/// The device: one paravirtualized GPU and its display ports.
|
||||
pub struct RvgDevice {
|
||||
pub(crate) device: WithTable<Device<Plat>>,
|
||||
}
|
||||
|
||||
/// Bytes the library allocated; free them with rvg_bytes_free.
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct RvgBytes {
|
||||
pub data: *mut u8,
|
||||
pub length: usize,
|
||||
}
|
||||
|
||||
/// The Rust API's map of a host's `RvgMemoryMap`, with the files behind its ranges
|
||||
/// (`RvgDeviceConfig.memory_files`, NULL for none). `Err(RVG_ERR_INVALID_ARGUMENT)`, in this
|
||||
/// order: ranges that are NULL but counted; files without a map; a file entry
|
||||
/// [`file_refusal`] refuses, the first range's first; a file that cannot be duplicated. Each
|
||||
/// file is duplicated only once every entry has passed, so a refusal before then touches no
|
||||
/// file. A refusal of the files logs a line saying which.
|
||||
///
|
||||
/// # Safety
|
||||
/// `map` is NULL or a live map whose `ranges` hold `range_count` ranges; `files` is NULL or
|
||||
/// holds `range_count` entries.
|
||||
pub(crate) unsafe fn memory_map(
|
||||
map: *const RvgMemoryMap,
|
||||
files: *const RvgMemoryRangeFile,
|
||||
) -> Result<Option<MemoryMap>, RvgStatus> {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(map) = (unsafe { map.as_ref() }) else {
|
||||
if !files.is_null() {
|
||||
log::warn!("device not created: memory files without a memory map");
|
||||
return Err(RVG_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
return Ok(None);
|
||||
};
|
||||
let ranges: &[RvgMemoryRange] = if map.range_count == 0 {
|
||||
&[]
|
||||
} else if map.ranges.is_null() {
|
||||
return Err(RVG_ERR_INVALID_ARGUMENT);
|
||||
} else {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { std::slice::from_raw_parts(map.ranges, map.range_count) }
|
||||
};
|
||||
let files: &[RvgMemoryRangeFile] = if files.is_null() || ranges.is_empty() {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { std::slice::from_raw_parts(files, ranges.len()) }
|
||||
};
|
||||
let page = host_page_size();
|
||||
for (i, (r, f)) in ranges.iter().zip(files).enumerate() {
|
||||
if let Some(why) = file_refusal(r, f, page) {
|
||||
log::warn!("device not created: the file of memory range {i} {why}");
|
||||
return Err(RVG_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
}
|
||||
let mut m = MemoryMap::new();
|
||||
for (i, r) in ranges.iter().enumerate() {
|
||||
let file = match files.get(i) {
|
||||
Some(f) if f.fd >= 0 => match duplicate(f.fd) {
|
||||
Ok(fd) => Some(MemoryFile {
|
||||
fd: Arc::new(fd),
|
||||
offset: f.offset,
|
||||
}),
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"device not created: the file of memory range {i}, fd {}, was not \
|
||||
duplicated: {e}",
|
||||
f.fd
|
||||
);
|
||||
return Err(RVG_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
// SAFETY: the header's contract on `host_address`: mapped while any device made over
|
||||
// the map lives, and, with a file, a shared mapping of it from `offset`.
|
||||
unsafe {
|
||||
m.push_with_file(
|
||||
r.physical_address,
|
||||
r.physical_length,
|
||||
r.host_address.cast(),
|
||||
file,
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(Some(m))
|
||||
}
|
||||
|
||||
/// Why the file entry `f` of range `r` is refused, as the end of a log line, or `None`: an `fd`
|
||||
/// below -1, `flags` other than 0, and for an `fd` of 0 or more, a file `fstat` cannot read, one
|
||||
/// holding fewer than `offset + physical_length` bytes, or an `offset` that is not a multiple of
|
||||
/// `page`, in that order.
|
||||
fn file_refusal(r: &RvgMemoryRange, f: &RvgMemoryRangeFile, page: NonZeroU64) -> Option<String> {
|
||||
if f.fd < -1 {
|
||||
return Some(format!("has fd {}, below -1", f.fd));
|
||||
}
|
||||
if f.flags != 0 {
|
||||
return Some(format!("has flags {:#x}, not 0", f.flags));
|
||||
}
|
||||
if f.fd == -1 {
|
||||
return None;
|
||||
}
|
||||
let size = match file_size(f.fd) {
|
||||
Ok(size) => size,
|
||||
Err(e) => return Some(format!("has fd {}, which fstat cannot read: {e}", f.fd)),
|
||||
};
|
||||
if f.offset
|
||||
.checked_add(r.physical_length)
|
||||
.is_none_or(|end| size < end)
|
||||
{
|
||||
return Some(format!(
|
||||
"holds {size:#x} bytes, fewer than its offset {:#x} and the range's {:#x}",
|
||||
f.offset, r.physical_length
|
||||
));
|
||||
}
|
||||
if f.offset % page != 0 {
|
||||
return Some(format!(
|
||||
"has offset {:#x}, not a multiple of the page size {page:#x}",
|
||||
f.offset
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The host's page size (`sysconf(_SC_PAGESIZE)`, which does not fail): 16 KiB on arm64 macOS,
|
||||
/// 4 KiB on x86-64.
|
||||
fn host_page_size() -> NonZeroU64 {
|
||||
// SAFETY: a query of a constant; it reads and writes no memory of the caller's.
|
||||
let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
|
||||
u64::try_from(page)
|
||||
.ok()
|
||||
.and_then(NonZeroU64::new)
|
||||
.unwrap_or(NonZeroU64::MIN)
|
||||
}
|
||||
|
||||
/// The size of the file `fd` names (`fstat`).
|
||||
fn file_size(fd: i32) -> std::io::Result<u64> {
|
||||
let mut st = MaybeUninit::<libc::stat>::zeroed();
|
||||
// SAFETY: `st` is a writable `struct stat`; an `fd` that names no open file is an error the
|
||||
// call returns.
|
||||
if unsafe { libc::fstat(fd, st.as_mut_ptr()) } != 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: `fstat` succeeded, so it filled `st`; it was zeroed before.
|
||||
let st = unsafe { st.assume_init() };
|
||||
Ok(u64::try_from(st.st_size).unwrap_or(0))
|
||||
}
|
||||
|
||||
/// A duplicate of `fd`, close-on-exec (`fcntl(F_DUPFD_CLOEXEC)`), which the map holds.
|
||||
fn duplicate(fd: i32) -> std::io::Result<OwnedFd> {
|
||||
// SAFETY: `fcntl` reads and writes no memory of the caller's; an `fd` that names no open
|
||||
// file is an error the call returns.
|
||||
let new = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) };
|
||||
if new < 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: `new` is a descriptor this call opened, owned by nothing else.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(new) })
|
||||
}
|
||||
|
||||
/// The host's task pointer as the Rust API's value, and back.
|
||||
fn task_ptr(t: HostTask) -> *mut c_void {
|
||||
std::ptr::with_exposed_provenance_mut(t.addr())
|
||||
}
|
||||
|
||||
// `HostPtr` is one pointer-sized word, so `create_task` can write the caller's own.
|
||||
const _: () = assert!(
|
||||
size_of::<HostPtr>() == size_of::<*mut c_void>()
|
||||
&& align_of::<HostPtr>() == align_of::<*mut c_void>()
|
||||
);
|
||||
|
||||
/// The Rust API's closures over a host table: each holds the table, and calls its function
|
||||
/// with the table's `ctx`.
|
||||
pub(crate) fn host_callbacks(t: &Arc<Table>, c: &RvgHostCallbacks) -> HostCallbacks {
|
||||
HostCallbacks {
|
||||
create_task: c.create_task.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: CreateTask = Arc::new(move |vm_size, base: &mut HostPtr| {
|
||||
let out = std::ptr::from_mut(base).cast::<*mut c_void>();
|
||||
// SAFETY: the host's function over its ctx; `out` is the caller's `HostPtr`, a
|
||||
// pointer-sized word (the assert above), live and untouched for the call.
|
||||
let task = ffi::host_call("create_task", || unsafe { f(t.ctx(), vm_size, out) });
|
||||
HostTask::from_addr(task.expose_provenance())
|
||||
});
|
||||
c
|
||||
}),
|
||||
destroy_task: c.destroy_task.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: DestroyTask = Arc::new(move |task| {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("destroy_task", || unsafe { f(t.ctx(), task_ptr(task)) });
|
||||
});
|
||||
c
|
||||
}),
|
||||
map_memory: c.map_memory.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: MapMemory = Arc::new(
|
||||
move |task, count, offset, read_only, ranges: &[PhysicalMemoryRange]| {
|
||||
let ranges = ranges.as_ptr().cast::<RvgPhysicalMemoryRange>();
|
||||
// SAFETY: the host's function over its ctx; `ranges` is live for the call
|
||||
// and has RvgPhysicalMemoryRange's layout (the asserts above).
|
||||
ffi::host_call("map_memory", || unsafe {
|
||||
f(t.ctx(), task_ptr(task), count, offset, read_only, ranges)
|
||||
})
|
||||
},
|
||||
);
|
||||
c
|
||||
}),
|
||||
unmap_memory: c.unmap_memory.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: UnmapMemory = Arc::new(move |task, offset, length| {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("unmap_memory", || unsafe {
|
||||
f(t.ctx(), task_ptr(task), offset, length)
|
||||
})
|
||||
});
|
||||
c
|
||||
}),
|
||||
read_memory: c.read_memory.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: ReadMemory = Arc::new(move |address, length, dst: HostPtr| {
|
||||
// SAFETY: the host's function over its ctx; `dst` holds `length` bytes.
|
||||
ffi::host_call("read_memory", || unsafe {
|
||||
f(t.ctx(), address, length, dst.as_ptr())
|
||||
})
|
||||
});
|
||||
c
|
||||
}),
|
||||
raise_interrupt: c.raise_interrupt.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: RaiseInterrupt = Arc::new(move |vector| {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("raise_interrupt", || unsafe { f(t.ctx(), vector) });
|
||||
});
|
||||
c
|
||||
}),
|
||||
add_trace_range: c.add_trace_range.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: AddTraceRange = Arc::new(move |range, handler| {
|
||||
// A host that keeps the handler retains it; otherwise it goes with this frame.
|
||||
let h = handle::Lent::new(RvgTraceRangeHandler::new(handler));
|
||||
let p = h.as_ptr();
|
||||
// SAFETY: the host's function over its ctx; `p` is live for the call.
|
||||
let r =
|
||||
ffi::host_call("add_trace_range", || unsafe { f(t.ctx(), range.into(), p) });
|
||||
HostTraceRange::from_addr(r.expose_provenance())
|
||||
});
|
||||
c
|
||||
}),
|
||||
remove_trace_range: c.remove_trace_range.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: RemoveTraceRange = Arc::new(move |r: HostTraceRange| {
|
||||
let r = std::ptr::with_exposed_provenance_mut(r.addr());
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("remove_trace_range", || unsafe { f(t.ctx(), r) });
|
||||
});
|
||||
c
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The device behind a handle, or the process's end for NULL.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live device handle.
|
||||
unsafe fn live<'a>(device: *const RvgDevice, call: &'static str) -> &'a RvgDevice {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::get(device) }.unwrap_or_else(|| null_handle(call))
|
||||
}
|
||||
|
||||
/// A new device. Refusals, checked in this order: RVG_ERR_INVALID_ARGUMENT for the config
|
||||
/// itself (the files behind its memory map's ranges among it), RVG_ERR_UNSUPPORTED,
|
||||
/// RVG_ERR_DISPLAY_PORT_COUNT, RVG_ERR_NO_METAL_DEVICE, RVG_ERR_MEMORY_CONFLICT,
|
||||
/// RVG_ERR_MEMORY_MAP, RVG_ERR_INVALID_ARGUMENT (`add_trace_range` without
|
||||
/// `remove_trace_range`), RVG_ERR_METAL, RVG_ERR_ISOLATION_WITHOUT_MAP. The first call
|
||||
/// given a Metal device makes the process's frame queue for it, before the device is built, even
|
||||
/// when the device is then refused. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `config` is NULL or a live config (header preamble); `device` is NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_create(
|
||||
config: *const RvgDeviceConfig,
|
||||
device: *mut *mut RvgDevice,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let c = match unsafe { sized::read(config) } {
|
||||
Ok(Some(c)) => c,
|
||||
Ok(None) => return RVG_ERR_INVALID_ARGUMENT,
|
||||
Err(s) => return s,
|
||||
};
|
||||
// SAFETY: the config's contract: NULL or a live table.
|
||||
let callbacks = match unsafe { sized::read_or_zero(c.callbacks) } {
|
||||
Ok(t) => t,
|
||||
Err(s) => return s,
|
||||
};
|
||||
// From here the table is the library's: a refusal ends it before it returns.
|
||||
let table = Table::new(callbacks.ctx, callbacks.destroy);
|
||||
let refuse = |s: RvgStatus| {
|
||||
table.end();
|
||||
s
|
||||
};
|
||||
if device.is_null() {
|
||||
return refuse(RVG_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
// 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,
|
||||
Err(s) => return refuse(s),
|
||||
};
|
||||
let config = DeviceConfig {
|
||||
metal_registry_id: (c.metal_registry_id != 0).then_some(c.metal_registry_id),
|
||||
display_port_count: c.display_port_count,
|
||||
feature_level: c.feature_level,
|
||||
display_port_connection_types: c.display_port_connection_types,
|
||||
memory_map,
|
||||
use_iosurface_mapper: c.use_iosurface_mapper,
|
||||
process_isolation: c.process_isolation,
|
||||
argument_buffers: !c.disable_argument_buffers,
|
||||
callbacks: host_callbacks(&table, &callbacks),
|
||||
};
|
||||
match Device::with_platform(<Plat as reims_vgpu::ApiPlatform>::process(), config) {
|
||||
Ok(d) => {
|
||||
let h = handle::new(RvgDevice {
|
||||
device: WithTable::new(d, table),
|
||||
});
|
||||
// SAFETY: checked non-NULL; the caller's contract.
|
||||
unsafe { device.write(h) };
|
||||
RVG_OK
|
||||
}
|
||||
Err(e) => refuse(status(e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Drops the host's reference; the last reference (see the preamble) is the device's teardown,
|
||||
/// which stops the device and may block. May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live device handle, not used again.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_release(device: *mut RvgDevice) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::release(device) }
|
||||
})
|
||||
}
|
||||
|
||||
/// A 32-bit read at `offset` in the device's MMIO region. May block and may call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_mmio_read(device: *mut RvgDevice, offset: u64) -> u32 {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_device_mmio_read") }
|
||||
.device
|
||||
.mmio_read(offset)
|
||||
})
|
||||
}
|
||||
|
||||
/// A 32-bit write at `offset` in the device's MMIO region. May block: a root FIFO write waits
|
||||
/// for the FIFO's thread. May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_mmio_write(device: *mut RvgDevice, offset: u64, value: u32) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_device_mmio_write") }
|
||||
.device
|
||||
.mmio_write(offset, value);
|
||||
})
|
||||
}
|
||||
|
||||
/// Resets the device as the guest's bus reset does: stops it as rvg_device_stop does, sets the
|
||||
/// guest's binary version back to 0 and turns EFI off, and returns once it is quiesced. May
|
||||
/// block: it waits as rvg_device_stop does, and for the EFI display's present thread. At a
|
||||
/// `feature_level` above 4 it ends the process. May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_reset(device: *mut RvgDevice) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_device_reset") }.device.reset();
|
||||
})
|
||||
}
|
||||
|
||||
/// Pauses the device: each FIFO finishes the commands it started and stops, then the guest's
|
||||
/// displays pause. May block: it waits for each FIFO's thread to stop and for those commands to
|
||||
/// complete, and hangs while one never does. Where the guest has given a port a display page, a
|
||||
/// second pause before rvg_device_unpause ends the process. May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_pause(device: *mut RvgDevice) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_device_pause") }.device.pause();
|
||||
})
|
||||
}
|
||||
|
||||
/// Resumes the device after rvg_device_pause: unpauses the guest's displays, starts every FIFO
|
||||
/// and raises one interrupt. May block: it waits while the FIFOs start on the library's FIFO
|
||||
/// control thread. Where the guest has given a port a display page, an unpause while the guest's
|
||||
/// displays are not paused ends the process: rvg_device_pause and rvg_device_finish_suspend
|
||||
/// pause them, and rvg_device_will_suspend does not. May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_unpause(device: *mut RvgDevice) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_device_unpause") }
|
||||
.device
|
||||
.unpause();
|
||||
})
|
||||
}
|
||||
|
||||
/// Stops the device as a root page of 0 does: its FIFOs, the guest's tasks and the guest's
|
||||
/// display pages are torn down. May block: it waits for each FIFO's thread to stop and for the
|
||||
/// commands it started to complete. May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_stop(device: *mut RvgDevice) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_device_stop") }.device.stop();
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts a suspend: from here the device raises no interrupt, and drops those not yet raised.
|
||||
/// It quiesces the FIFOs without waiting for them, and pauses none of the guest's displays. May
|
||||
/// call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_will_suspend(device: *mut RvgDevice) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_device_will_suspend") }
|
||||
.device
|
||||
.will_suspend();
|
||||
})
|
||||
}
|
||||
|
||||
/// Ends a suspend: on RVG_OK, writes the device's state through `state`; free it with
|
||||
/// rvg_bytes_free. The device always has a state to give, so RVG_ERR_SUSPEND never comes.
|
||||
/// Without rvg_device_will_suspend before it, it ends the process. May block: it waits for each
|
||||
/// FIFO's thread to stop and for the commands it started to complete, then flushes and ends the
|
||||
/// guest's tasks and pauses the guest's displays. May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live device handle; `state` is NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_finish_suspend(
|
||||
device: *mut RvgDevice,
|
||||
state: *mut RvgBytes,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(d) = (unsafe { handle::get(device) }) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
if state.is_null() {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
match d.device.finish_suspend() {
|
||||
Ok(bytes) => {
|
||||
let bytes = Box::into_raw(bytes.into_boxed_slice());
|
||||
let out = RvgBytes {
|
||||
data: bytes.cast::<u8>(),
|
||||
length: bytes.len(),
|
||||
};
|
||||
// SAFETY: checked non-NULL; the caller's contract.
|
||||
unsafe { state.write(out) };
|
||||
RVG_OK
|
||||
}
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Frees what rvg_device_finish_suspend wrote. `{NULL, 0}` does nothing.
|
||||
///
|
||||
/// # Safety
|
||||
/// `bytes` is `{NULL, 0}` or what rvg_device_finish_suspend wrote, not freed before.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_bytes_free(bytes: RvgBytes) {
|
||||
ffi::export(|| {
|
||||
if bytes.data.is_null() {
|
||||
return;
|
||||
}
|
||||
let slice = std::ptr::slice_from_raw_parts_mut(bytes.data, bytes.length);
|
||||
// SAFETY: the caller's contract: the boxed slice rvg_device_finish_suspend made.
|
||||
drop(unsafe { Box::from_raw(slice) });
|
||||
})
|
||||
}
|
||||
|
||||
/// Offers the device a state rvg_device_finish_suspend gave, before the guest runs again.
|
||||
/// `state` NULL is no state (the device refuses it with RVG_RESUME_ERROR_INVALID_CONTENT); a
|
||||
/// non-NULL `state` with `state_length` 0 is an empty state. RVG_OK, or RVG_ERR_RESUME. When
|
||||
/// `error` is not NULL, the device's reason is written there, or RVG_RESUME_ERROR_NONE where it
|
||||
/// stored none (a refusal may store none, and RVG_OK stores none). From this call until
|
||||
/// rvg_device_did_resume, whether or not it accepted the state, a new mapping of guest memory
|
||||
/// (the guest's root page write, for one) ends the process. May block: a state whose binary
|
||||
/// version has no EFI display turns EFI off, which waits for the EFI display's present thread.
|
||||
/// May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live device handle; `state` is NULL or holds `state_length` bytes;
|
||||
/// `error` is NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_will_resume(
|
||||
device: *mut RvgDevice,
|
||||
state: *const u8,
|
||||
state_length: usize,
|
||||
error: *mut RvgResumeError,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(d) = (unsafe { handle::get(device) }) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
let state = if state.is_null() {
|
||||
None
|
||||
} else {
|
||||
// SAFETY: the caller's contract.
|
||||
Some(unsafe { std::slice::from_raw_parts(state, state_length) })
|
||||
};
|
||||
let (s, reason) = match d.device.will_resume(state) {
|
||||
Ok(()) => (RVG_OK, RVG_RESUME_ERROR_NONE),
|
||||
Err(Error::Resume(reason)) => (
|
||||
status(Error::Resume(reason)),
|
||||
reason.map_or(RVG_RESUME_ERROR_NONE, |r| r.code()),
|
||||
),
|
||||
Err(e) => (status(e), RVG_RESUME_ERROR_NONE),
|
||||
};
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::write_out(error, reason) };
|
||||
s
|
||||
})
|
||||
}
|
||||
|
||||
/// Ends a resume that rvg_device_will_resume accepted: rebuilds the device from the state, starts
|
||||
/// its FIFOs and raises one interrupt. May block: rebuilding the EFI display waits for its
|
||||
/// present thread, and a root the device still has is torn down as rvg_device_stop does. May
|
||||
/// call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_device_did_resume(device: *mut RvgDevice) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_device_did_resume") }
|
||||
.device
|
||||
.did_resume();
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,556 @@
|
||||
use reims_vgpu_core::guest::records::APV_PAGE_SHIFT;
|
||||
use reims_vgpu_core::testkit::GuestRam;
|
||||
use reims_vgpu_core::testkit::host::FakeHost;
|
||||
|
||||
use super::*;
|
||||
use crate::status::*;
|
||||
use crate::testkit::{HostCtx, Rec, Rig, config, host_table, t_destroy, test_platform};
|
||||
|
||||
/// A table with only a destroy, over `rec`.
|
||||
fn only_destroy(rec: &Arc<Rec>) -> RvgHostCallbacks {
|
||||
RvgHostCallbacks {
|
||||
struct_size: crate::sized::size_u32::<RvgHostCallbacks>(),
|
||||
ctx: rec.ctx(),
|
||||
destroy: Some(t_destroy),
|
||||
create_task: None,
|
||||
destroy_task: None,
|
||||
map_memory: None,
|
||||
unmap_memory: None,
|
||||
read_memory: None,
|
||||
raise_interrupt: None,
|
||||
add_trace_range: None,
|
||||
remove_trace_range: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn create(c: &RvgDeviceConfig) -> (RvgStatus, *mut RvgDevice) {
|
||||
let mut d = std::ptr::null_mut();
|
||||
// SAFETY: a live config; `d` is writable.
|
||||
let s = unsafe { rvg_device_create(c, &mut d) };
|
||||
(s, d)
|
||||
}
|
||||
|
||||
/// Each refusal in the header's order, with the table's one destroy before the create returns
|
||||
/// on the caller's thread; a config or table the create cannot read runs none
|
||||
#[test]
|
||||
fn refusals_end_the_table() {
|
||||
let p = test_platform();
|
||||
let rec = Rec::new();
|
||||
let table = only_destroy(&rec);
|
||||
let mut c = config(1, &table);
|
||||
// SAFETY: NULL config.
|
||||
let s = unsafe { rvg_device_create(std::ptr::null(), &mut std::ptr::null_mut()) };
|
||||
assert_eq!(s, RVG_ERR_INVALID_ARGUMENT);
|
||||
c.struct_size = 8;
|
||||
assert_eq!(create(&c).0, RVG_ERR_INVALID_ARGUMENT);
|
||||
c.struct_size = crate::sized::size_u32::<RvgDeviceConfig>();
|
||||
let mut small = table;
|
||||
small.struct_size = 8;
|
||||
c.callbacks = &small;
|
||||
assert_eq!(create(&c).0, RVG_ERR_INVALID_ARGUMENT);
|
||||
c.callbacks = &table;
|
||||
assert!(rec.destroys().is_empty());
|
||||
|
||||
// SAFETY: a live config; NULL out-pointer.
|
||||
let s = unsafe { rvg_device_create(&c, std::ptr::null_mut()) };
|
||||
assert_eq!(s, RVG_ERR_INVALID_ARGUMENT);
|
||||
c.display_port_count = 0;
|
||||
assert_eq!(create(&c).0, RVG_ERR_DISPLAY_PORT_COUNT);
|
||||
c.display_port_count = 1;
|
||||
c.metal_registry_id = 1;
|
||||
assert_eq!(create(&c).0, RVG_ERR_NO_METAL_DEVICE);
|
||||
c.metal_registry_id = reims_vgpu_core::testkit::platform::FAKE_REGISTRY_ID;
|
||||
c.process_isolation = true;
|
||||
assert_eq!(create(&c).0, RVG_ERR_ISOLATION_WITHOUT_MAP);
|
||||
c.process_isolation = false;
|
||||
let mut with_add = table;
|
||||
with_add.add_trace_range = Some(crate::testkit::t_add_trace);
|
||||
c.callbacks = &with_add;
|
||||
assert_eq!(create(&c).0, RVG_ERR_INVALID_ARGUMENT);
|
||||
let null_ranges = RvgMemoryMap {
|
||||
ranges: std::ptr::null(),
|
||||
range_count: 1,
|
||||
};
|
||||
c.callbacks = &table;
|
||||
c.memory_map = &null_ranges;
|
||||
assert_eq!(create(&c).0, RVG_ERR_INVALID_ARGUMENT);
|
||||
let me = std::thread::current().id();
|
||||
assert_eq!(rec.destroys(), vec![me; 6]);
|
||||
drop(p);
|
||||
}
|
||||
|
||||
/// A task or memory callback beside a memory map is a conflict
|
||||
#[test]
|
||||
fn memory_conflict() {
|
||||
let p = test_platform();
|
||||
let host = FakeHost::new(&p, GuestRam::new());
|
||||
let ctx = Arc::new(HostCtx {
|
||||
rec: Rec::new(),
|
||||
blocks: host.blocks(),
|
||||
});
|
||||
let table = host_table(&ctx);
|
||||
let map = RvgMemoryMap {
|
||||
ranges: std::ptr::null(),
|
||||
range_count: 0,
|
||||
};
|
||||
let mut c = config(1, &table);
|
||||
c.memory_map = ↦
|
||||
assert_eq!(create(&c).0, RVG_ERR_MEMORY_CONFLICT);
|
||||
assert_eq!(ctx.rec.destroys().len(), 1);
|
||||
}
|
||||
|
||||
/// The table's destroy runs once, after the device's end, on the releasing thread; a longer
|
||||
/// config with zero past the library's size is accepted
|
||||
#[test]
|
||||
fn destroy_after_the_end() {
|
||||
let mut rig = Rig::new(1);
|
||||
assert!(rig.ctx.rec.destroys().is_empty());
|
||||
// SAFETY: the rig's live device.
|
||||
let d = unsafe { &*rig.device };
|
||||
for off in (0x1000..0x1240).step_by(4) {
|
||||
// SAFETY: as above.
|
||||
let v = unsafe { rvg_device_mmio_read(rig.device, off) };
|
||||
assert_eq!(v, d.device.core().mmio_read(off), "{off:#x}");
|
||||
}
|
||||
rig.release();
|
||||
assert_eq!(rig.ctx.rec.destroys(), vec![std::thread::current().id()]);
|
||||
|
||||
#[repr(C)]
|
||||
struct Longer {
|
||||
c: RvgDeviceConfig,
|
||||
later: u64,
|
||||
}
|
||||
let rec = Rec::new();
|
||||
let table = only_destroy(&rec);
|
||||
let mut l = Longer {
|
||||
c: config(1, &table),
|
||||
later: 0,
|
||||
};
|
||||
l.c.struct_size = crate::sized::size_u32::<Longer>();
|
||||
let (s, d) = create(&l.c);
|
||||
assert_eq!(s, RVG_OK);
|
||||
assert!(rec.destroys().is_empty());
|
||||
// SAFETY: the device made above.
|
||||
unsafe { rvg_device_release(d) };
|
||||
assert_eq!(rec.destroys().len(), 1);
|
||||
l.later = 1;
|
||||
assert_eq!(create(&l.c).0, RVG_ERR_UNSUPPORTED);
|
||||
assert_eq!(rec.destroys().len(), 1);
|
||||
}
|
||||
|
||||
/// Suspend gives bytes the device takes back; no state is refused with its reason; the
|
||||
/// status functions refuse NULL
|
||||
#[test]
|
||||
fn suspend_and_resume() {
|
||||
let rig = Rig::new(1);
|
||||
let mut e = 99;
|
||||
// SAFETY: the rig's live device; `e` is writable.
|
||||
unsafe {
|
||||
assert_eq!(
|
||||
rvg_device_will_resume(rig.device, std::ptr::null(), 0, &mut e),
|
||||
RVG_ERR_RESUME
|
||||
);
|
||||
assert_eq!(e, RVG_RESUME_ERROR_INVALID_CONTENT);
|
||||
rvg_device_will_suspend(rig.device);
|
||||
let mut state = RvgBytes {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
assert_eq!(rvg_device_finish_suspend(rig.device, &mut state), RVG_OK);
|
||||
assert!(!state.data.is_null() && state.length > 0);
|
||||
assert_eq!(
|
||||
rvg_device_will_resume(rig.device, state.data, state.length, &mut e),
|
||||
RVG_OK
|
||||
);
|
||||
assert_eq!(e, RVG_RESUME_ERROR_NONE);
|
||||
assert_eq!(
|
||||
rvg_device_will_resume(rig.device, state.data, state.length, std::ptr::null_mut()),
|
||||
RVG_OK
|
||||
);
|
||||
rvg_bytes_free(state);
|
||||
rvg_bytes_free(RvgBytes {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
});
|
||||
rvg_device_did_resume(rig.device);
|
||||
rvg_device_pause(rig.device);
|
||||
rvg_device_unpause(rig.device);
|
||||
rvg_device_reset(rig.device);
|
||||
rvg_device_stop(rig.device);
|
||||
let mut again = RvgBytes {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
rvg_device_finish_suspend(std::ptr::null_mut(), &mut again),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_device_finish_suspend(rig.device, std::ptr::null_mut()),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
e = 7;
|
||||
assert_eq!(
|
||||
rvg_device_will_resume(std::ptr::null_mut(), std::ptr::null(), 0, &mut e),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(e, 7);
|
||||
rvg_device_release(std::ptr::null_mut());
|
||||
}
|
||||
}
|
||||
|
||||
/// The fake host's callbacks reach the host through the table: the device's order of calls
|
||||
/// is its twin's, made on the Rust API over the same blocks
|
||||
#[test]
|
||||
fn host_calls_are_the_twins() {
|
||||
let rig = Rig::new(1);
|
||||
// SAFETY: the rig's live device: a reset, which stops and restarts the FIFOs.
|
||||
unsafe {
|
||||
rvg_device_mmio_write(rig.device, 0x1000, 0);
|
||||
rvg_device_reset(rig.device);
|
||||
}
|
||||
let ours = host_calls(&rig.p);
|
||||
let twin_p = std::sync::Arc::new(reims_vgpu_core::testkit::FakePlatform::new());
|
||||
let twin_host = FakeHost::new(&twin_p, GuestRam::with_range(0, 0x40_0000).unwrap());
|
||||
let b = twin_host.blocks();
|
||||
let c = reims_vgpu::DeviceConfig {
|
||||
callbacks: reims_vgpu::HostCallbacks {
|
||||
create_task: b.create_task,
|
||||
destroy_task: b.destroy_task,
|
||||
map_memory: b.map_memory,
|
||||
unmap_memory: b.unmap_memory,
|
||||
read_memory: b.read_memory,
|
||||
raise_interrupt: b.raise_interrupt,
|
||||
add_trace_range: b.add_trace_range,
|
||||
remove_trace_range: b.remove_trace_range,
|
||||
},
|
||||
..reims_vgpu::DeviceConfig::default()
|
||||
};
|
||||
let twin = Device::with_platform(twin_p.clone(), c).unwrap();
|
||||
twin.mmio_write(0x1000, 0);
|
||||
twin.reset();
|
||||
assert_eq!(ours, host_calls(&twin_p));
|
||||
}
|
||||
|
||||
/// The host-block calls `p`'s fake host saw, in order.
|
||||
fn host_calls(p: &reims_vgpu_core::testkit::FakePlatform) -> Vec<&'static str> {
|
||||
p.call_log()
|
||||
.calls()
|
||||
.into_iter()
|
||||
.filter(|c| c.class == "HostBlocks")
|
||||
.map(|c| c.sel)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The device info pairs the guest reads in page `page`, where it asked for them, up to their
|
||||
/// terminator: 8 bytes each, the key low and the value high.
|
||||
fn device_info_pairs(rig: &Rig, page: u32) -> Vec<(u32, u32)> {
|
||||
// What the device wrote through its mapping of the page, in the guest's RAM.
|
||||
rig.p.fake_vm().sync();
|
||||
let at = u64::from(page) << APV_PAGE_SHIFT;
|
||||
let mut pairs = Vec::new();
|
||||
for i in 0..64 {
|
||||
let w = rig._host.ram().read_u64(at + 8 * i).unwrap();
|
||||
let pair = (
|
||||
u32::try_from(w & 0xffff_ffff).unwrap(),
|
||||
u32::try_from(w >> 32).unwrap(),
|
||||
);
|
||||
pairs.push(pair);
|
||||
if pair.0 == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
pairs
|
||||
}
|
||||
|
||||
/// The feature level reaches the guest: the binary version it reads back after asking for
|
||||
/// 0xf5, capped by levels 1 to 3; and the device info it reads, which those levels trim (key
|
||||
/// 18's value, the highest key below 40, and keys 42 and 44); levels 0 and 4 read the same
|
||||
#[test]
|
||||
fn the_feature_level_reaches_the_guest() {
|
||||
let mut seen = Vec::new();
|
||||
let mut infos = Vec::new();
|
||||
for level in 0..=4 {
|
||||
let rig = Rig::with(1, |c| c.feature_level = level);
|
||||
// SAFETY: the rig's live device: the version, then a root node for the mapping.
|
||||
let version = unsafe {
|
||||
rvg_device_mmio_write(rig.device, 0x1034, 0xf5);
|
||||
let v = rvg_device_mmio_read(rig.device, 0x1034);
|
||||
rvg_device_mmio_write(rig.device, 0x101c, 1);
|
||||
v
|
||||
};
|
||||
// The guest's device info request (opcode 58) for every key, into guest page 0x20.
|
||||
// SAFETY: as above.
|
||||
let core = unsafe { &*rig.device }.device.core();
|
||||
core.get_device_info(45, 46, 0x20).unwrap();
|
||||
let pairs = device_info_pairs(&rig, 0x20);
|
||||
let value = |key| pairs.iter().find(|p| p.0 == key).map(|p| p.1);
|
||||
let below_40 = pairs.iter().map(|p| p.0).filter(|&k| k < 40).max();
|
||||
seen.push((
|
||||
version,
|
||||
value(18),
|
||||
below_40,
|
||||
value(42).is_some() && value(44).is_some(),
|
||||
));
|
||||
infos.push(pairs);
|
||||
}
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(0xf5, Some(0x20007), Some(37), true),
|
||||
(0x3e, Some(0x20002), Some(18), false),
|
||||
(0x71, Some(0x20006), Some(28), false),
|
||||
(0xd1, Some(0x20007), Some(37), false),
|
||||
(0xf5, Some(0x20007), Some(37), true),
|
||||
]
|
||||
);
|
||||
assert_eq!(infos[0], infos[4]);
|
||||
}
|
||||
|
||||
/// The config's first version ends at `callbacks`, 48 bytes; `memory_files` makes it 56
|
||||
#[test]
|
||||
fn a_first_version_device_config_is_48_bytes() {
|
||||
assert_eq!(<RvgDeviceConfig as HostStruct>::V1_SIZE, 48);
|
||||
assert_eq!(std::mem::offset_of!(RvgDeviceConfig, memory_files), 48);
|
||||
assert_eq!(size_of::<RvgDeviceConfig>(), 56);
|
||||
assert_eq!(size_of::<RvgMemoryRangeFile>(), 16);
|
||||
assert_eq!(std::mem::offset_of!(RvgMemoryRangeFile, flags), 4);
|
||||
assert_eq!(std::mem::offset_of!(RvgMemoryRangeFile, offset), 8);
|
||||
}
|
||||
|
||||
/// `len` bytes of the fake VM's memory, as one range at guest physical 0.
|
||||
fn fake_range(p: &reims_vgpu_core::testkit::FakePlatform, len: u64) -> RvgMemoryRange {
|
||||
let host = reims_vgpu_core::platform::Platform::vm(p)
|
||||
.allocate_anywhere(len)
|
||||
.unwrap();
|
||||
RvgMemoryRange {
|
||||
physical_address: 0,
|
||||
physical_length: len,
|
||||
host_address: host.as_ptr(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A file of `len` bytes in the temporary directory, removed at its drop.
|
||||
struct TempFile {
|
||||
path: std::path::PathBuf,
|
||||
file: std::fs::File,
|
||||
}
|
||||
|
||||
impl TempFile {
|
||||
fn new(name: &str, len: u64) -> TempFile {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("rvg-memory-file-{name}-{}", std::process::id()));
|
||||
let file = std::fs::File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
file.set_len(len).unwrap();
|
||||
TempFile { path, file }
|
||||
}
|
||||
|
||||
fn fd(&self) -> i32 {
|
||||
std::os::fd::AsRawFd::as_raw_fd(&self.file)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The descriptors open in this process (nextest runs each test in a process of its own).
|
||||
fn open_fds() -> usize {
|
||||
std::fs::read_dir("/dev/fd").unwrap().count()
|
||||
}
|
||||
|
||||
/// A host built before `memory_files` passes 48: its config is read without files, whatever
|
||||
/// follows it in memory; read at its full size, the same bytes are refused, with the table's
|
||||
/// one destroy
|
||||
#[test]
|
||||
fn a_48_byte_device_config_is_accepted() {
|
||||
let p = test_platform();
|
||||
let rec = Rec::new();
|
||||
let table = only_destroy(&rec);
|
||||
let range = fake_range(&p, 0x1_0000);
|
||||
let map = RvgMemoryMap {
|
||||
ranges: &range,
|
||||
range_count: 1,
|
||||
};
|
||||
let bad = RvgMemoryRangeFile {
|
||||
fd: -5,
|
||||
flags: 1,
|
||||
offset: 1,
|
||||
};
|
||||
let mut c = config(1, &table);
|
||||
c.memory_map = ↦
|
||||
c.memory_files = &bad;
|
||||
assert_eq!(create(&c).0, RVG_ERR_INVALID_ARGUMENT);
|
||||
assert_eq!(rec.destroys().len(), 1);
|
||||
c.struct_size = 48;
|
||||
let (s, d) = create(&c);
|
||||
assert_eq!(s, RVG_OK);
|
||||
// SAFETY: the device made above.
|
||||
unsafe { rvg_device_release(d) };
|
||||
assert_eq!(rec.destroys().len(), 2);
|
||||
}
|
||||
|
||||
/// Each file refusal in the header's order, the first range's first, each with its line and no
|
||||
/// descriptor duplicated
|
||||
#[test]
|
||||
fn memory_file_refusals() {
|
||||
let p = test_platform();
|
||||
let page = host_page_size().get();
|
||||
let file = TempFile::new("refusals", 0x1_0000);
|
||||
let range = fake_range(&p, 0x8000);
|
||||
let ranges = [range, range];
|
||||
let map = RvgMemoryMap {
|
||||
ranges: ranges.as_ptr(),
|
||||
range_count: 2,
|
||||
};
|
||||
let ok = RvgMemoryRangeFile {
|
||||
fd: file.fd(),
|
||||
flags: 0,
|
||||
offset: 0x8000,
|
||||
};
|
||||
let none = RvgMemoryRangeFile {
|
||||
fd: -1,
|
||||
flags: 0,
|
||||
offset: 1,
|
||||
};
|
||||
let entry = |fd: i32, flags: u32, offset: u64| RvgMemoryRangeFile { fd, flags, offset };
|
||||
let logs = reims_vgpu_core::testkit::logs::capture();
|
||||
let fds = open_fds();
|
||||
let refused = |files: [RvgMemoryRangeFile; 2]| -> String {
|
||||
// SAFETY: a live map of two ranges, and two entries.
|
||||
let r = unsafe { memory_map(&map, files.as_ptr()) };
|
||||
assert_eq!(r.err(), Some(RVG_ERR_INVALID_ARGUMENT));
|
||||
let lines = logs.take();
|
||||
assert_eq!(lines.len(), 1, "{lines:?}");
|
||||
lines[0].2.clone()
|
||||
};
|
||||
// Files without a map.
|
||||
// SAFETY: no map; the entry is live.
|
||||
let r = unsafe { memory_map(std::ptr::null(), &ok) };
|
||||
assert_eq!(r.err(), Some(RVG_ERR_INVALID_ARGUMENT));
|
||||
assert_eq!(
|
||||
logs.take()[0].2,
|
||||
"device not created: memory files without a memory map"
|
||||
);
|
||||
// Each check, on range 1 after a range 0 that passes.
|
||||
assert_eq!(
|
||||
refused([ok, entry(-2, 1, 0x10)]),
|
||||
"device not created: the file of memory range 1 has fd -2, below -1"
|
||||
);
|
||||
assert_eq!(
|
||||
refused([ok, entry(i32::MAX, 1, 0x10)]),
|
||||
"device not created: the file of memory range 1 has flags 0x1, not 0"
|
||||
);
|
||||
assert_eq!(
|
||||
refused([ok, entry(-1, 2, 0)]),
|
||||
"device not created: the file of memory range 1 has flags 0x2, not 0"
|
||||
);
|
||||
let unreadable = refused([ok, entry(i32::MAX, 0, 0x10)]);
|
||||
assert!(
|
||||
unreadable.starts_with(
|
||||
"device not created: the file of memory range 1 has fd 2147483647, which fstat \
|
||||
cannot read: "
|
||||
),
|
||||
"{unreadable}"
|
||||
);
|
||||
assert_eq!(
|
||||
refused([ok, entry(file.fd(), 0, 0x8010)]),
|
||||
"device not created: the file of memory range 1 holds 0x10000 bytes, fewer than its \
|
||||
offset 0x8010 and the range's 0x8000"
|
||||
);
|
||||
assert_eq!(
|
||||
refused([ok, entry(file.fd(), 0, u64::MAX - 1)]),
|
||||
"device not created: the file of memory range 1 holds 0x10000 bytes, fewer than its \
|
||||
offset 0xfffffffffffffffe and the range's 0x8000"
|
||||
);
|
||||
assert_eq!(
|
||||
refused([ok, entry(file.fd(), 0, 0x10)]),
|
||||
format!(
|
||||
"device not created: the file of memory range 1 has offset 0x10, not a multiple of \
|
||||
the page size {page:#x}"
|
||||
)
|
||||
);
|
||||
// The first range's refusal comes first.
|
||||
assert_eq!(
|
||||
refused([entry(file.fd(), 0, 0x10), entry(-2, 0, 0)]),
|
||||
format!(
|
||||
"device not created: the file of memory range 0 has offset 0x10, not a multiple of \
|
||||
the page size {page:#x}"
|
||||
)
|
||||
);
|
||||
// No refusal duplicated a descriptor; a range without a file takes no offset check.
|
||||
assert_eq!(open_fds(), fds);
|
||||
// SAFETY: a live map of two ranges, and two entries.
|
||||
let m = unsafe { memory_map(&map, [none, none].as_ptr()) }.unwrap();
|
||||
assert!(m.unwrap().files().iter().all(Option::is_none));
|
||||
assert!(logs.take().is_empty());
|
||||
}
|
||||
|
||||
/// The files the map takes: each a duplicate of the host's descriptor, close-on-exec, of the
|
||||
/// same file, at the host's offset, in the ranges' order; none for -1 or NULL; the duplicates
|
||||
/// close with the last map that holds them
|
||||
#[test]
|
||||
fn memory_files_are_duplicated() {
|
||||
let p = test_platform();
|
||||
let file = TempFile::new("duplicated", 0x2_0000);
|
||||
let range = fake_range(&p, 0x8000);
|
||||
let ranges = [range, range];
|
||||
let map = RvgMemoryMap {
|
||||
ranges: ranges.as_ptr(),
|
||||
range_count: 2,
|
||||
};
|
||||
let files = [
|
||||
RvgMemoryRangeFile {
|
||||
fd: -1,
|
||||
flags: 0,
|
||||
offset: 0,
|
||||
},
|
||||
RvgMemoryRangeFile {
|
||||
fd: file.fd(),
|
||||
flags: 0,
|
||||
offset: 0x1_0000,
|
||||
},
|
||||
];
|
||||
let fds = open_fds();
|
||||
// SAFETY: a live map of two ranges, and two entries.
|
||||
let m = unsafe { memory_map(&map, files.as_ptr()) }
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(open_fds(), fds + 1);
|
||||
assert!(m.files()[0].is_none());
|
||||
let f = m.files()[1].as_ref().unwrap();
|
||||
assert_eq!(f.offset, 0x1_0000);
|
||||
let dup = std::os::fd::AsRawFd::as_raw_fd(&*f.fd);
|
||||
assert_ne!(dup, file.fd());
|
||||
// SAFETY: a query of a descriptor the map holds open.
|
||||
let flags = unsafe { libc::fcntl(dup, libc::F_GETFD) };
|
||||
assert_eq!(flags & libc::FD_CLOEXEC, libc::FD_CLOEXEC);
|
||||
let ino = |fd: i32| {
|
||||
let mut st = MaybeUninit::<libc::stat>::zeroed();
|
||||
// SAFETY: `st` is a writable `struct stat`, and `fd` is open.
|
||||
assert_eq!(unsafe { libc::fstat(fd, st.as_mut_ptr()) }, 0);
|
||||
// SAFETY: filled by the call above.
|
||||
let st = unsafe { st.assume_init() };
|
||||
(st.st_dev, st.st_ino)
|
||||
};
|
||||
assert_eq!(ino(dup), ino(file.fd()));
|
||||
// NULL files: none.
|
||||
// SAFETY: a live map of two ranges.
|
||||
let bare = unsafe { memory_map(&map, std::ptr::null()) }
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(bare.files().iter().all(Option::is_none));
|
||||
let copy = m.clone();
|
||||
drop(m);
|
||||
assert_eq!(open_fds(), fds + 1);
|
||||
drop(copy);
|
||||
assert_eq!(open_fds(), fds);
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
//! Displays: [`RvgDisplayConfig`], [`RvgDisplayCallbacks`], and the `rvg_display_*` functions
|
||||
//! other than the frame encode ([`crate::frame`]).
|
||||
//!
|
||||
//! A display's callbacks run on the process's display thread, one at a time across every
|
||||
//! display, in the order core queued them (docs/api.md section 5). Each calls the host's
|
||||
//! function under `ffi::host_call`. A display with a window has a second table, the window's
|
||||
//! ([`crate::window`]), which its handle holds beside the display's.
|
||||
|
||||
use std::ffi::{c_char, c_void};
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu::{
|
||||
CursorGlyph, CursorGlyphFn, CursorMoveFn, CursorShowFn, Display, DisplayCallbacks,
|
||||
DisplayConfig, DisplayMode, ModeChangeFn, NewFrameFn,
|
||||
};
|
||||
|
||||
use crate::device::RvgDevice;
|
||||
use crate::ffi;
|
||||
use crate::handle;
|
||||
use crate::sized::{self, HostStruct};
|
||||
use crate::status::{RVG_ERR_INVALID_ARGUMENT, RVG_OK, RvgStatus, status};
|
||||
use crate::table::{RvgDestroyFn, Table, WithTable};
|
||||
use crate::window::{RvgWindowConfig, window_callbacks};
|
||||
use crate::{Plat, null_handle};
|
||||
|
||||
/// The mode supports EDR: the guest reads the flag in the mode's entry.
|
||||
pub const RVG_DISPLAY_MODE_EDR: u32 = 1;
|
||||
|
||||
/// The mode supports 10 bits per channel: the guest reads the flag in the mode's entry.
|
||||
pub const RVG_DISPLAY_MODE_10BPC: u32 = 2;
|
||||
|
||||
/// A display mode offered to the guest.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
pub struct RvgDisplayMode {
|
||||
pub width: u16,
|
||||
pub height: u16,
|
||||
/// RVG_DISPLAY_MODE_* bits; 0 for a plain mode.
|
||||
pub flags: u32,
|
||||
pub refresh_rate_hz: f64,
|
||||
}
|
||||
|
||||
impl RvgDisplayMode {
|
||||
/// The Rust API's mode; bits the library does not define are ignored.
|
||||
fn to_mode(self) -> DisplayMode {
|
||||
DisplayMode {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
refresh_rate_hz: self.refresh_rate_hz,
|
||||
supports_edr: self.flags & RVG_DISPLAY_MODE_EDR != 0,
|
||||
supports_10bpc: self.flags & RVG_DISPLAY_MODE_10BPC != 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A position or size in pixels.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
pub struct RvgDisplayCoord {
|
||||
pub x: u16,
|
||||
pub y: u16,
|
||||
}
|
||||
|
||||
/// `mode_change(ctx, width, height, pixel_format)`: the guest set a mode. `pixel_format` is the
|
||||
/// guest's IOSurface pixel format code.
|
||||
///
|
||||
/// Thread: the library's display thread, a serial worker that runs every display callback of
|
||||
/// the process one at a time, in the order the library queued them, and never inside a call of
|
||||
/// the host's. After 5 s idle it exits, and the next callback starts a new one.
|
||||
/// May call: every function of this header. A display callback may block (the host's big lock,
|
||||
/// for example): the library never waits for this thread, and the next display callback waits
|
||||
/// until it returns.
|
||||
/// Without it, the guest's mode changes are not reported.
|
||||
pub type RvgModeChangeFn = Option<
|
||||
unsafe extern "C-unwind" fn(ctx: *mut c_void, width: u16, height: u16, pixel_format: u32),
|
||||
>;
|
||||
|
||||
/// `new_frame(ctx)`: the guest presented a frame since the last call (calls coalesce).
|
||||
///
|
||||
/// Thread, and what it may call: as RvgModeChangeFn. Without it, the EFI display's first present
|
||||
/// to this display ends the process, and a guest's present to it completes with no call.
|
||||
pub type RvgNewFrameFn = Option<unsafe extern "C-unwind" fn(ctx: *mut c_void)>;
|
||||
|
||||
/// The cursor glyph, borrowed for the call.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
pub struct RvgCursorGlyph {
|
||||
/// sizeof(RvgCursorGlyph) as the library was compiled.
|
||||
pub struct_size: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// The hot spot, in pixels from the top left.
|
||||
pub hot_spot: RvgDisplayCoord,
|
||||
/// `width * 4` bytes a row, `height` rows: the guest's BGRA pixels with red and blue swapped.
|
||||
pub rgba: *const u8,
|
||||
pub rgba_length: usize,
|
||||
}
|
||||
|
||||
/// `cursor_glyph(ctx, glyph)`: the guest set a cursor glyph.
|
||||
///
|
||||
/// Thread, and what it may call: as RvgModeChangeFn. Without it, the guest reads a cursor glyph
|
||||
/// size limit of 0, and 256 with it.
|
||||
pub type RvgCursorGlyphFn =
|
||||
Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, glyph: *const RvgCursorGlyph)>;
|
||||
|
||||
/// `cursor_show(ctx, show)`: the guest showed or hid the cursor. `show` is the guest's byte as
|
||||
/// written: 0 hides, any other value shows.
|
||||
///
|
||||
/// Thread, and what it may call: as RvgModeChangeFn. The guest reads whether the display has it.
|
||||
pub type RvgCursorShowFn = Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, show: u8)>;
|
||||
|
||||
/// `cursor_move(ctx)`: the guest moved the cursor; rvg_display_cursor_position reads where.
|
||||
///
|
||||
/// Thread, and what it may call: as RvgModeChangeFn. The guest reads whether the display has it.
|
||||
pub type RvgCursorMoveFn = Option<unsafe extern "C-unwind" fn(ctx: *mut c_void)>;
|
||||
|
||||
/// A display's callbacks.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
pub struct RvgDisplayCallbacks {
|
||||
/// sizeof(RvgDisplayCallbacks) as the host was compiled.
|
||||
pub struct_size: u32,
|
||||
pub ctx: *mut c_void,
|
||||
/// Runs once after the display's end, when no callback of the table runs again.
|
||||
pub destroy: RvgDestroyFn,
|
||||
pub mode_change: RvgModeChangeFn,
|
||||
pub new_frame: RvgNewFrameFn,
|
||||
pub cursor_glyph: RvgCursorGlyphFn,
|
||||
pub cursor_show: RvgCursorShowFn,
|
||||
pub cursor_move: RvgCursorMoveFn,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; a pointer and optional function pointers.
|
||||
unsafe impl HostStruct for RvgDisplayCallbacks {}
|
||||
|
||||
/// A display's config.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
pub struct RvgDisplayConfig {
|
||||
/// sizeof(RvgDisplayConfig) as the host was compiled.
|
||||
pub struct_size: u32,
|
||||
/// The guest's serial number for the display, unique in the process.
|
||||
pub serial_number: u32,
|
||||
/// The port, below the device's `display_port_count`.
|
||||
pub port: u64,
|
||||
/// UTF-8, `name_length` bytes, not NUL-terminated; invalid sequences become U+FFFD. NULL is
|
||||
/// "Apple Virtual".
|
||||
pub name: *const c_char,
|
||||
pub name_length: usize,
|
||||
pub width_millimeters: f64,
|
||||
pub height_millimeters: f64,
|
||||
/// NULL is a table with every callback absent.
|
||||
pub callbacks: *const RvgDisplayCallbacks,
|
||||
/// NULL is no window. Otherwise the library opens a window for the display (RvgWindowConfig
|
||||
/// says what the display and the host then see).
|
||||
pub window: *const RvgWindowConfig,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; integers, floats and pointers.
|
||||
unsafe impl HostStruct for RvgDisplayConfig {
|
||||
/// The first version ends at `callbacks`.
|
||||
const V1_SIZE: usize = 56;
|
||||
}
|
||||
|
||||
const _: () = assert!(std::mem::offset_of!(RvgDisplayConfig, window) == RvgDisplayConfig::V1_SIZE);
|
||||
|
||||
/// A display on one of the device's ports.
|
||||
pub struct RvgDisplay {
|
||||
/// The window's table, for a display with a window: held here so that a table with no
|
||||
/// function still has its destroy at the release. It goes before the display, whose window
|
||||
/// holds the table's other references until it closes.
|
||||
window_table: Option<Arc<Table>>,
|
||||
pub(crate) display: WithTable<Display<Plat>>,
|
||||
}
|
||||
|
||||
impl Drop for RvgDisplay {
|
||||
/// The window's table first, then the display: with functions, the window's closures, which
|
||||
/// the display's last reference lets go of when it closes the window, hold its last
|
||||
/// references.
|
||||
fn drop(&mut self) {
|
||||
drop(self.window_table.take());
|
||||
}
|
||||
}
|
||||
|
||||
/// The Rust API's closures over a display table: each holds the table, and calls its function
|
||||
/// with the table's `ctx`.
|
||||
fn display_callbacks(t: &Arc<Table>, c: &RvgDisplayCallbacks) -> DisplayCallbacks {
|
||||
DisplayCallbacks {
|
||||
mode_change: c.mode_change.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: ModeChangeFn = Arc::new(move |width, height, format| {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("mode_change", || unsafe {
|
||||
f(t.ctx(), width, height, format)
|
||||
});
|
||||
});
|
||||
c
|
||||
}),
|
||||
new_frame: c.new_frame.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: NewFrameFn = Arc::new(move || {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("new_frame", || unsafe { f(t.ctx()) });
|
||||
});
|
||||
c
|
||||
}),
|
||||
cursor_glyph: c.cursor_glyph.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: CursorGlyphFn = Arc::new(move |g: &CursorGlyph<'_>| {
|
||||
let glyph = RvgCursorGlyph {
|
||||
struct_size: sized::size_u32::<RvgCursorGlyph>(),
|
||||
width: g.width,
|
||||
height: g.height,
|
||||
hot_spot: RvgDisplayCoord {
|
||||
x: g.hot_spot.0,
|
||||
y: g.hot_spot.1,
|
||||
},
|
||||
rgba: g.rgba.as_ptr(),
|
||||
rgba_length: g.rgba.len(),
|
||||
};
|
||||
let glyph = &raw const glyph;
|
||||
// SAFETY: the host's function over its ctx; the glyph and its pixels are live
|
||||
// for the call.
|
||||
ffi::host_call("cursor_glyph", || unsafe { f(t.ctx(), glyph) });
|
||||
});
|
||||
c
|
||||
}),
|
||||
cursor_show: c.cursor_show.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: CursorShowFn = Arc::new(move |show| {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("cursor_show", || unsafe { f(t.ctx(), show) });
|
||||
});
|
||||
c
|
||||
}),
|
||||
cursor_move: c.cursor_move.map(|f| {
|
||||
let t = t.clone();
|
||||
let c: CursorMoveFn = Arc::new(move || {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("cursor_move", || unsafe { f(t.ctx()) });
|
||||
});
|
||||
c
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The display behind a handle, or the process's end for NULL.
|
||||
///
|
||||
/// # Safety
|
||||
/// `display` is NULL or a live display handle.
|
||||
unsafe fn live<'a>(display: *const RvgDisplay, call: &'static str) -> &'a RvgDisplay {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::get(display) }.unwrap_or_else(|| null_handle(call))
|
||||
}
|
||||
|
||||
/// A new display on `device`. Refusals, checked in this order: RVG_ERR_INVALID_ARGUMENT,
|
||||
/// RVG_ERR_UNSUPPORTED, RVG_ERR_PORT_OUT_OF_RANGE, RVG_ERR_METAL, RVG_ERR_SERIAL_IN_USE,
|
||||
/// RVG_ERR_PORT_IN_USE. The display keeps the device alive. May call back.
|
||||
///
|
||||
/// The config's `window`, and its callbacks, are read with the config, before either table is
|
||||
/// the library's: a `struct_size` refusal of any of the four structs runs no destroy, and every
|
||||
/// later refusal runs both tables' destroys before it returns, the window's first. With a
|
||||
/// window, the display has all five display callbacks as the guest reads them (a cursor glyph
|
||||
/// size limit of 256, and each cursor callback), whichever of `callbacks` the host gives, and
|
||||
/// calls those it gives. With RVG_WINDOW_MATCH_HOST_SCREEN, the display's size in millimetres,
|
||||
/// its scale factor and its first modes are those of the window's host screen, where there is
|
||||
/// one, or, with the window config's mode, that mode's at a 1× density or the config's
|
||||
/// `mode_pixels_per_inch`, and the screen's refresh rate; a later rvg_display_set_modes
|
||||
/// replaces the modes.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live device handle; `config` is NULL or a live config; `display` is
|
||||
/// NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_display_create(
|
||||
device: *mut RvgDevice,
|
||||
config: *const RvgDisplayConfig,
|
||||
display: *mut *mut RvgDisplay,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let c = match unsafe { sized::read(config) } {
|
||||
Ok(Some(c)) => c,
|
||||
Ok(None) => return RVG_ERR_INVALID_ARGUMENT,
|
||||
Err(s) => return s,
|
||||
};
|
||||
// SAFETY: the config's contract: NULL or a live table.
|
||||
let callbacks = match unsafe { sized::read_or_zero(c.callbacks) } {
|
||||
Ok(t) => t,
|
||||
Err(s) => return s,
|
||||
};
|
||||
// SAFETY: the config's contract: NULL or a live window config.
|
||||
let window = match unsafe { sized::read(c.window) } {
|
||||
Ok(w) => w,
|
||||
Err(s) => return s,
|
||||
};
|
||||
let window = match window {
|
||||
None => None,
|
||||
// SAFETY: the window config's contract: NULL or a live table.
|
||||
Some(w) => match unsafe { sized::read_or_zero(w.callbacks) } {
|
||||
Ok(t) => Some((w, t)),
|
||||
Err(s) => return s,
|
||||
},
|
||||
};
|
||||
// From here the tables are the library's: a refusal ends them before it returns, the
|
||||
// window's first, as a release does.
|
||||
let table = Table::new(callbacks.ctx, callbacks.destroy);
|
||||
let window_table = window.as_ref().map(|(_, t)| Table::new(t.ctx, t.destroy));
|
||||
let refuse = |s: RvgStatus| {
|
||||
if let Some(t) = &window_table {
|
||||
t.end();
|
||||
}
|
||||
table.end();
|
||||
s
|
||||
};
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(device) = (unsafe { handle::get(device) }) else {
|
||||
return refuse(RVG_ERR_INVALID_ARGUMENT);
|
||||
};
|
||||
if display.is_null() {
|
||||
return refuse(RVG_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
let name = (!c.name.is_null()).then(|| {
|
||||
// SAFETY: the config's contract: `name_length` bytes at `name`.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(c.name.cast::<u8>(), c.name_length) };
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
});
|
||||
let mut config = DisplayConfig::new(c.port, c.serial_number);
|
||||
config.name = name;
|
||||
config.size_in_millimeters = (c.width_millimeters, c.height_millimeters);
|
||||
config.callbacks = display_callbacks(&table, &callbacks);
|
||||
if let (Some((w, wc)), Some(t)) = (&window, &window_table) {
|
||||
config.window = Some(w.to_config(window_callbacks(t, wc)));
|
||||
}
|
||||
match device.device.new_display(config) {
|
||||
Ok(d) => {
|
||||
let h = handle::new(RvgDisplay {
|
||||
window_table,
|
||||
display: WithTable::new(d, table),
|
||||
});
|
||||
// SAFETY: checked non-NULL; the caller's contract.
|
||||
unsafe { display.write(h) };
|
||||
RVG_OK
|
||||
}
|
||||
Err(e) => refuse(status(e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Drops the host's reference; the last one unplugs the display from the guest, and may be the
|
||||
/// device's last reference. May block, and may call back. A display with a window closes it
|
||||
/// first, waiting neither for the main thread nor for the window's frames: the window table's
|
||||
/// destroy runs here, or once a window callback running on the main thread returns, and a
|
||||
/// frame the window has in flight keeps the display until it completes, as an RvgFrame does.
|
||||
///
|
||||
/// # Safety
|
||||
/// `display` is NULL or a live display handle, not used again.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_display_release(display: *mut RvgDisplay) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::release(display) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Offers the guest `count` modes, in order (copied). `count` 0 changes nothing, and `modes`
|
||||
/// may then be NULL; a NULL `modes` with a `count` above 0 ends the process. The guest's display
|
||||
/// page for the port takes the first 128: the first list it takes connects the display to the
|
||||
/// guest, and a later one that differs updates it. Until the guest gives the port a page, the
|
||||
/// list waits for it. The EFI mode registers read port 0's list. May call back.
|
||||
///
|
||||
/// # Safety
|
||||
/// `display` is a live display handle; `modes` holds `count` modes (it may be NULL when `count`
|
||||
/// is 0).
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_display_set_modes(
|
||||
display: *mut RvgDisplay,
|
||||
modes: *const RvgDisplayMode,
|
||||
count: usize,
|
||||
) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(display, "rvg_display_set_modes") };
|
||||
// Core is given the empty list too: it changes nothing there.
|
||||
let modes: &[RvgDisplayMode] = if count == 0 {
|
||||
&[]
|
||||
} else if modes.is_null() {
|
||||
null_handle("rvg_display_set_modes")
|
||||
} else {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { std::slice::from_raw_parts(modes, count) }
|
||||
};
|
||||
let modes: Vec<DisplayMode> = modes.iter().map(|m| m.to_mode()).collect();
|
||||
d.display.set_modes(&modes);
|
||||
})
|
||||
}
|
||||
|
||||
/// The cursor's position; {65535, 65535} before the guest has linked the display. While the
|
||||
/// device is paused (rvg_device_pause, or a finished suspend), a display the guest has linked
|
||||
/// ends the process here. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `display` is a live display handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_display_cursor_position(
|
||||
display: *const RvgDisplay,
|
||||
) -> RvgDisplayCoord {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let (x, y) = unsafe { live(display, "rvg_display_cursor_position") }
|
||||
.display
|
||||
.cursor_position();
|
||||
RvgDisplayCoord { x, y }
|
||||
})
|
||||
}
|
||||
|
||||
/// The guest's presents, and the host's encodes of a new frame, counted so far. Either pointer
|
||||
/// may be NULL. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `display` is a live display handle; `guest` and `host` are each NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_display_present_counts(
|
||||
display: *const RvgDisplay,
|
||||
guest: *mut u64,
|
||||
host: *mut u64,
|
||||
) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let d = unsafe { live(display, "rvg_display_present_counts") };
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe {
|
||||
handle::write_out(guest, d.display.guest_present_count());
|
||||
handle::write_out(host, d.display.host_present_count());
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,353 @@
|
||||
use reims_vgpu_core::guest::records::APV_PAGE_SHIFT;
|
||||
|
||||
use super::*;
|
||||
use crate::status::*;
|
||||
use crate::testkit::{Rec, Rig, t_destroy};
|
||||
|
||||
unsafe extern "C-unwind" fn t_mode_change(ctx: *mut c_void, w: u16, h: u16, format: u32) {
|
||||
Rec::push(ctx, format!("mode_change {w}x{h} {format:#x}"));
|
||||
}
|
||||
unsafe extern "C-unwind" fn t_new_frame(ctx: *mut c_void) {
|
||||
Rec::push(ctx, "new_frame".to_owned());
|
||||
}
|
||||
unsafe extern "C-unwind" fn t_glyph(ctx: *mut c_void, g: *const RvgCursorGlyph) {
|
||||
// SAFETY: the glyph is live for the call.
|
||||
let g = unsafe { &*g };
|
||||
// SAFETY: its pixels, as above.
|
||||
let px = unsafe { std::slice::from_raw_parts(g.rgba, g.rgba_length) };
|
||||
Rec::push(
|
||||
ctx,
|
||||
format!(
|
||||
"glyph {} {}x{} at {},{} {px:?}",
|
||||
g.struct_size, g.width, g.height, g.hot_spot.x, g.hot_spot.y
|
||||
),
|
||||
);
|
||||
}
|
||||
unsafe extern "C-unwind" fn t_show(ctx: *mut c_void, show: u8) {
|
||||
Rec::push(ctx, format!("show {show}"));
|
||||
}
|
||||
unsafe extern "C-unwind" fn t_move(ctx: *mut c_void) {
|
||||
Rec::push(ctx, "move".to_owned());
|
||||
}
|
||||
|
||||
fn table(rec: &Arc<Rec>) -> RvgDisplayCallbacks {
|
||||
RvgDisplayCallbacks {
|
||||
struct_size: sized::size_u32::<RvgDisplayCallbacks>(),
|
||||
ctx: rec.ctx(),
|
||||
destroy: Some(t_destroy),
|
||||
mode_change: Some(t_mode_change),
|
||||
new_frame: Some(t_new_frame),
|
||||
cursor_glyph: Some(t_glyph),
|
||||
cursor_show: Some(t_show),
|
||||
cursor_move: Some(t_move),
|
||||
}
|
||||
}
|
||||
|
||||
fn config(port: u64, serial: u32, cb: &RvgDisplayCallbacks) -> RvgDisplayConfig {
|
||||
RvgDisplayConfig {
|
||||
struct_size: sized::size_u32::<RvgDisplayConfig>(),
|
||||
serial_number: serial,
|
||||
port,
|
||||
name: std::ptr::null(),
|
||||
name_length: 0,
|
||||
width_millimeters: 0.0,
|
||||
height_millimeters: 0.0,
|
||||
callbacks: cb,
|
||||
window: std::ptr::null(),
|
||||
}
|
||||
}
|
||||
|
||||
fn create(device: *mut RvgDevice, c: &RvgDisplayConfig) -> (RvgStatus, *mut RvgDisplay) {
|
||||
let mut d = std::ptr::null_mut();
|
||||
// SAFETY: a live device or NULL, a live config; `d` is writable.
|
||||
let s = unsafe { rvg_display_create(device, c, &mut d) };
|
||||
(s, d)
|
||||
}
|
||||
|
||||
/// Each closure calls its C function with the table's ctx and the arguments core passes; the
|
||||
/// glyph crosses with its struct size, hot spot and pixels
|
||||
#[test]
|
||||
fn callbacks_forward() {
|
||||
let rec = Rec::new();
|
||||
let t = Table::new(rec.ctx(), None);
|
||||
let cb = display_callbacks(&t, &table(&rec));
|
||||
(cb.mode_change.unwrap())(640, 480, 0x4247_5241);
|
||||
(cb.new_frame.unwrap())();
|
||||
(cb.cursor_glyph.unwrap())(&CursorGlyph {
|
||||
width: 1,
|
||||
height: 1,
|
||||
hot_spot: (3, 4),
|
||||
rgba: &[1, 2, 3, 4],
|
||||
});
|
||||
(cb.cursor_show.unwrap())(2);
|
||||
(cb.cursor_move.unwrap())();
|
||||
assert_eq!(
|
||||
rec.lines(),
|
||||
vec![
|
||||
"mode_change 640x480 0x42475241".to_owned(),
|
||||
"new_frame".to_owned(),
|
||||
format!(
|
||||
"glyph {} 1x1 at 3,4 [1, 2, 3, 4]",
|
||||
size_of::<RvgCursorGlyph>()
|
||||
),
|
||||
"show 2".to_owned(),
|
||||
"move".to_owned(),
|
||||
]
|
||||
);
|
||||
let none = RvgDisplayCallbacks {
|
||||
mode_change: None,
|
||||
new_frame: None,
|
||||
cursor_glyph: None,
|
||||
cursor_show: None,
|
||||
cursor_move: None,
|
||||
..table(&rec)
|
||||
};
|
||||
let cb = display_callbacks(&t, &none);
|
||||
assert!(cb.mode_change.is_none() && cb.new_frame.is_none() && cb.cursor_glyph.is_none());
|
||||
assert!(cb.cursor_show.is_none() && cb.cursor_move.is_none());
|
||||
}
|
||||
|
||||
/// The config reaches core: port, serial number, name (lossy UTF-8; NULL is core's default),
|
||||
/// size; the modes keep their flags; the queries answer core's values
|
||||
#[test]
|
||||
fn config_and_queries() {
|
||||
let rig = Rig::new(2);
|
||||
let rec = Rec::new();
|
||||
let cb = table(&rec);
|
||||
let mut c = config(1, 0x5eed_c001, &cb);
|
||||
let name = b"Caf\xc3\xa9 \xff";
|
||||
c.name = name.as_ptr().cast();
|
||||
c.name_length = name.len();
|
||||
c.width_millimeters = 400.0;
|
||||
c.height_millimeters = 300.0;
|
||||
let (s, d) = create(rig.device, &c);
|
||||
assert_eq!(s, RVG_OK);
|
||||
// SAFETY: the display made above.
|
||||
let core = unsafe { &*d }.display.core();
|
||||
assert_eq!((core.port(), core.serial_num()), (1, 0x5eed_c001));
|
||||
assert_eq!(core.name().map(|n| n.as_str()), Some("Café \u{fffd}"));
|
||||
assert_eq!(core.size_in_millimeters(), (400.0, 300.0));
|
||||
let modes = [
|
||||
RvgDisplayMode {
|
||||
width: 1280,
|
||||
height: 720,
|
||||
flags: 0,
|
||||
refresh_rate_hz: 60.0,
|
||||
},
|
||||
RvgDisplayMode {
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
flags: RVG_DISPLAY_MODE_EDR | RVG_DISPLAY_MODE_10BPC | 0x100,
|
||||
refresh_rate_hz: 120.0,
|
||||
},
|
||||
];
|
||||
// SAFETY: the live display; two modes.
|
||||
unsafe { rvg_display_set_modes(d, modes.as_ptr(), 2) };
|
||||
let got = core.mode_list();
|
||||
assert_eq!(got.len(), 2);
|
||||
assert!(!got[0].supports_edr && !got[0].supports_10bpc);
|
||||
assert!(got[1].supports_edr && got[1].supports_10bpc);
|
||||
assert_eq!(got[1].refresh_rate_in_hz, 120.0);
|
||||
// SAFETY: as above: no modes changes nothing.
|
||||
unsafe { rvg_display_set_modes(d, std::ptr::null(), 0) };
|
||||
assert_eq!(core.mode_list().len(), 2);
|
||||
// SAFETY: as above.
|
||||
let pos = unsafe { rvg_display_cursor_position(d) };
|
||||
assert_eq!((pos.x, pos.y), (0xffff, 0xffff));
|
||||
let (mut g, mut h) = (9, 9);
|
||||
// SAFETY: as above.
|
||||
unsafe {
|
||||
rvg_display_present_counts(d, &mut g, &mut h);
|
||||
rvg_display_present_counts(d, std::ptr::null_mut(), std::ptr::null_mut());
|
||||
}
|
||||
assert_eq!((g, h), (0, 0));
|
||||
assert!(rec.destroys().is_empty());
|
||||
// SAFETY: the display's reference.
|
||||
unsafe { rvg_display_release(d) };
|
||||
let c = config(0, 0x5eed_c002, &cb);
|
||||
let (s, d) = create(rig.device, &c);
|
||||
assert_eq!(s, RVG_OK);
|
||||
// SAFETY: the display made above.
|
||||
let name = unsafe { &*d }
|
||||
.display
|
||||
.core()
|
||||
.name()
|
||||
.map(|n| n.as_str().to_owned());
|
||||
assert_eq!(name.as_deref(), Some("Apple Virtual"));
|
||||
// SAFETY: as above.
|
||||
unsafe {
|
||||
rvg_display_release(d);
|
||||
rvg_display_release(std::ptr::null_mut());
|
||||
}
|
||||
// Each display's table ends once, maybe on the display thread after its release returned.
|
||||
assert_eq!(rec.wait_destroys(2).len(), 2);
|
||||
}
|
||||
|
||||
/// Each mode's flags reach the guest's display page for the port: RVG_DISPLAY_MODE_EDR is bit 0
|
||||
/// and RVG_DISPLAY_MODE_10BPC bit 1 of the flags byte of the mode's entry, and a bit the library
|
||||
/// does not define is neither
|
||||
#[test]
|
||||
fn mode_flags_reach_the_guest_s_display_page() {
|
||||
use reims_vgpu_core::display::page as sp;
|
||||
let rig = Rig::new(1);
|
||||
// The guest's root node, then its display page for port 0 at guest page 0x10.
|
||||
// SAFETY: the rig's live device.
|
||||
unsafe { crate::device::rvg_device_mmio_write(rig.device, 0x101c, 1) };
|
||||
// SAFETY: as above.
|
||||
let core = unsafe { &*rig.device }.device.core();
|
||||
core.set_shared_display_state_page(0x10, 0, false).unwrap();
|
||||
let rec = Rec::new();
|
||||
let cb = table(&rec);
|
||||
let (s, d) = create(rig.device, &config(0, 0x5eed_c301, &cb));
|
||||
assert_eq!(s, RVG_OK);
|
||||
let mode = |flags| RvgDisplayMode {
|
||||
width: 640,
|
||||
height: 480,
|
||||
flags,
|
||||
refresh_rate_hz: 60.0,
|
||||
};
|
||||
let modes = [
|
||||
mode(0),
|
||||
mode(RVG_DISPLAY_MODE_EDR),
|
||||
mode(RVG_DISPLAY_MODE_10BPC),
|
||||
mode(RVG_DISPLAY_MODE_EDR | RVG_DISPLAY_MODE_10BPC),
|
||||
mode(0x100),
|
||||
];
|
||||
// SAFETY: the display made above; five modes.
|
||||
unsafe { rvg_display_set_modes(d, modes.as_ptr(), modes.len()) };
|
||||
// What the device wrote through its mapping of the page, in the guest's RAM.
|
||||
rig.p.fake_vm().sync();
|
||||
let page = 0x10u64 << APV_PAGE_SHIFT;
|
||||
let ram = rig._host.ram();
|
||||
let count = ram.read_vec(page + sp::MODE_LIST_COUNT, 2).unwrap();
|
||||
assert_eq!(u16::from_le_bytes([count[0], count[1]]), 5);
|
||||
let flags: Vec<u8> = (0..5)
|
||||
.map(|i| {
|
||||
ram.read_vec(page + sp::mode_entry(i) + sp::MODE_FLAGS, 1)
|
||||
.unwrap()[0]
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(flags, [0, 1, 2, 3, 0]);
|
||||
// SAFETY: the display's reference.
|
||||
unsafe { rvg_display_release(d) };
|
||||
assert_eq!(rec.wait_destroys(1).len(), 1);
|
||||
}
|
||||
|
||||
/// Each refusal in the header's order ends the table before the create returns; a config the
|
||||
/// create cannot read runs no destroy
|
||||
#[test]
|
||||
fn refusals_end_the_table() {
|
||||
let rig = Rig::new(1);
|
||||
let rec = Rec::new();
|
||||
let cb = table(&rec);
|
||||
let (s, d) = create(rig.device, &config(0, 0x5eed_c101, &cb));
|
||||
assert_eq!(s, RVG_OK);
|
||||
let other = Rec::new();
|
||||
let ocb = table(&other);
|
||||
let mut c = config(0, 0x5eed_c102, &ocb);
|
||||
c.struct_size = 4;
|
||||
assert_eq!(create(rig.device, &c).0, RVG_ERR_INVALID_ARGUMENT);
|
||||
c.struct_size = sized::size_u32::<RvgDisplayConfig>();
|
||||
assert!(other.destroys().is_empty());
|
||||
assert_eq!(create(std::ptr::null_mut(), &c).0, RVG_ERR_INVALID_ARGUMENT);
|
||||
c.port = 1;
|
||||
assert_eq!(create(rig.device, &c).0, RVG_ERR_PORT_OUT_OF_RANGE);
|
||||
c.port = 0;
|
||||
c.serial_number = 0x5eed_c101;
|
||||
assert_eq!(create(rig.device, &c).0, RVG_ERR_SERIAL_IN_USE);
|
||||
c.serial_number = 0x5eed_c102;
|
||||
assert_eq!(create(rig.device, &c).0, RVG_ERR_PORT_IN_USE);
|
||||
let me = std::thread::current().id();
|
||||
assert_eq!(other.destroys(), vec![me; 4]);
|
||||
// SAFETY: the display made above.
|
||||
unsafe { rvg_display_release(d) };
|
||||
// The display's table ends once, maybe on the display thread after the release returned.
|
||||
assert_eq!(rec.wait_destroys(1).len(), 1);
|
||||
}
|
||||
|
||||
/// Display A's cursor move holds the display thread until the child says go.
|
||||
static MOVE_STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
static MOVE_GO: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
unsafe extern "C-unwind" fn t_blocking_move(_ctx: *mut c_void) {
|
||||
use std::sync::atomic::Ordering::SeqCst;
|
||||
MOVE_STARTED.store(true, SeqCst);
|
||||
for _ in 0..1000 {
|
||||
if MOVE_GO.load(SeqCst) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits up to 10 s for `flag`.
|
||||
fn wait_for(flag: &std::sync::atomic::AtomicBool) -> bool {
|
||||
for _ in 0..1000 {
|
||||
if flag.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The child of [`a_display_released_with_a_job_queued_dies`]: display A's cursor move holds
|
||||
/// the display thread; the guest rings display B's doorbell, whose cursor move is queued behind
|
||||
/// it; the host releases B; the job then finds B's handler gone.
|
||||
#[test]
|
||||
#[ignore = "run by a_display_released_with_a_job_queued_dies in a child process"]
|
||||
fn child_a_display_released_with_a_job_queued() {
|
||||
reims_vgpu_core::testkit::capture::set_capture_enabled(false);
|
||||
let rig = Rig::new(2);
|
||||
// The guest's root node, then a guest display on each port over its own page.
|
||||
// SAFETY: the rig's live device.
|
||||
unsafe { crate::device::rvg_device_mmio_write(rig.device, 0x101c, 1) };
|
||||
// SAFETY: as above.
|
||||
let core = unsafe { &*rig.device }.device.core();
|
||||
core.set_shared_display_state_page(0x10, 0, false).unwrap();
|
||||
core.set_shared_display_state_page(0x11, 1, false).unwrap();
|
||||
let rec = Rec::new();
|
||||
let mut a_cb = table(&rec);
|
||||
a_cb.cursor_move = Some(t_blocking_move);
|
||||
let (s, _a) = create(rig.device, &config(0, 0x5eed_c201, &a_cb));
|
||||
assert_eq!(s, RVG_OK);
|
||||
let b_cb = table(&rec);
|
||||
let (s, b) = create(rig.device, &config(1, 0x5eed_c202, &b_cb));
|
||||
assert_eq!(s, RVG_OK);
|
||||
// SAFETY: the rig's live device; the displays made above.
|
||||
unsafe {
|
||||
crate::device::rvg_device_mmio_write(rig.device, 0x1220, 0);
|
||||
assert!(wait_for(&MOVE_STARTED));
|
||||
crate::device::rvg_device_mmio_write(rig.device, 0x1220, 1);
|
||||
rvg_display_release(b);
|
||||
}
|
||||
eprintln!("RELEASED");
|
||||
MOVE_GO.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
std::thread::sleep(std::time::Duration::from_secs(5));
|
||||
eprintln!("SURVIVED");
|
||||
}
|
||||
|
||||
/// A display released with one of its callback jobs queued on the display thread dies at that
|
||||
/// job, as it did on the host's queue: the job reads the handler when it runs
|
||||
#[test]
|
||||
fn a_display_released_with_a_job_queued_dies() {
|
||||
use std::os::unix::process::ExitStatusExt as _;
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--ignored",
|
||||
"--exact",
|
||||
"display::tests::child_a_display_released_with_a_job_queued",
|
||||
"--nocapture",
|
||||
"--test-threads=1",
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.signal(), Some(6), "{out:?}");
|
||||
assert!(err.contains("RELEASED"), "{err}");
|
||||
assert!(
|
||||
err.contains("guest_display.cursor.move_handler_gone"),
|
||||
"{err}"
|
||||
);
|
||||
assert!(!err.contains("SURVIVED"), "{err}");
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! The boundary with the host, both ways: [`export`] around the body of every `rvg_` function,
|
||||
//! 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 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
|
||||
//! them. `tests/exports.rs` checks that every export has this shape.
|
||||
//!
|
||||
//! **Out to the host.** Every call of a host function runs inside [`host_call`], the innermost
|
||||
//! frame around the function pointer: whatever the host throws ends the process at the call. The
|
||||
//! catch is the OS's ([`catch`]): objc2's `exception::catch` on macOS, std's `catch_unwind` on
|
||||
//! Linux. The host's function-pointer types stay `extern "C-unwind"`, since both are sound only
|
||||
//! around an ABI that unwinds.
|
||||
|
||||
use reims_vgpu_core::raise::death::{DeathId, fatal};
|
||||
use reims_vgpu_core::rt::enter_ours;
|
||||
|
||||
mod catch;
|
||||
|
||||
/// Runs the body of one export: the panic hook installed (once per process), then `body` with the
|
||||
/// thread marked as the library's until it returns (module doc). An export reached inside another
|
||||
/// (a host callback that calls back in) nests, and restores the mark it found.
|
||||
pub(crate) fn export<R>(body: impl FnOnce() -> R) -> R {
|
||||
// A thread already unwinding (a Rust host's drop during its own panic) cannot install a hook,
|
||||
// and a panic of ours there is a double panic, which aborts anyway.
|
||||
if !std::thread::panicking() {
|
||||
reims_vgpu::singleton::install_panic_hook();
|
||||
}
|
||||
let _ours = enter_ours();
|
||||
body()
|
||||
}
|
||||
|
||||
/// Calls the host's code through `f`, and answers what it returns. Anything the host throws ends
|
||||
/// the process here, at `call`, whatever handlers of the library's are live: the call runs inside
|
||||
/// the OS's [`catch`], so the throw stops at this frame and no frame of the library unwinds. What
|
||||
/// the catch stops is `DeathId::HostRaised`. QEMU and the suite never raise from a callback.
|
||||
///
|
||||
/// `f` must own no value with a `Drop`: a foreign unwind runs its frame's landing pads.
|
||||
pub(crate) fn host_call<R>(call: &'static str, f: impl FnOnce() -> R) -> R {
|
||||
match catch::catch(f) {
|
||||
Ok(r) => r,
|
||||
Err(()) => fatal(DeathId::HostRaised { call }),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,12 @@
|
||||
//! The catch around a call of a host function ([`super::host_call`]), in one file per OS with the
|
||||
//! same function: `catch(f)` runs `f` and answers its value, or `Err(())` for what the host threw.
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) use linux::catch;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) use macos::catch;
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Linux: std's `catch_unwind`. A Rust panic that unwinds this far (one the library's panic hook
|
||||
//! did not end first, as `resume_unwind` does not call it) stops at this frame. A foreign
|
||||
//! exception, a C++ throw through the host's `extern "C-unwind"` function, cannot be caught by
|
||||
//! Rust: std ends the process where it reaches this frame. Either way the process ends at the
|
||||
//! call.
|
||||
|
||||
use std::panic::AssertUnwindSafe;
|
||||
|
||||
/// Runs `f` inside `catch_unwind`: its value, or `Err(())` for a Rust unwind out of it.
|
||||
#[expect(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the C API's catch around a host call on Linux, which ends the process (6.7)"
|
||||
)]
|
||||
pub(crate) fn catch<R>(f: impl FnOnce() -> R) -> Result<R, ()> {
|
||||
std::panic::catch_unwind(AssertUnwindSafe(f)).map_err(drop)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! macOS: objc2's `exception::catch`. An Objective-C exception the host throws, `@throw nil`
|
||||
//! among them, stops at this frame. A Rust panic in `f` passes through unchanged, to the panic
|
||||
//! hook.
|
||||
|
||||
use std::panic::AssertUnwindSafe;
|
||||
|
||||
/// Runs `f` inside `@try`: its value, or `Err(())` for an exception it threw.
|
||||
///
|
||||
/// The exception is never released: the caller ends the process at the call
|
||||
/// (`DeathId::HostRaised`), and a release first would run the host's object's `dealloc`, host code,
|
||||
/// before the death, which the library has never done.
|
||||
pub(crate) fn catch<R>(f: impl FnOnce() -> R) -> Result<R, ()> {
|
||||
objc2::exception::catch(AssertUnwindSafe(f)).map_err(std::mem::forget)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! The boundary's tests on every OS; each OS's own catch has its tests beside them.
|
||||
|
||||
use std::os::unix::process::ExitStatusExt as _;
|
||||
use std::process::Command;
|
||||
|
||||
use reims_vgpu_core::raise::death::{DeathKind, DeathSite};
|
||||
use reims_vgpu_core::rt::is_our_thread;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
|
||||
/// The death of a host raise at `call`.
|
||||
fn host_raised(call: &'static str) -> DeathSite {
|
||||
DeathSite {
|
||||
kind: DeathKind::HostRaised,
|
||||
file: call,
|
||||
line: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A call that returns answers its value
|
||||
#[test]
|
||||
fn a_host_call_answers_its_value() {
|
||||
assert_eq!(host_call("count", || 3u64), 3);
|
||||
}
|
||||
|
||||
/// An export's body runs marked as the library's; the mark nests, and the one found is back
|
||||
/// when the export returns
|
||||
#[test]
|
||||
fn an_export_marks_its_thread_for_the_call() {
|
||||
assert!(!is_our_thread());
|
||||
let got = export(|| {
|
||||
assert!(is_our_thread());
|
||||
export(|| assert!(is_our_thread()));
|
||||
assert!(is_our_thread());
|
||||
7
|
||||
});
|
||||
assert_eq!(got, 7);
|
||||
assert!(!is_our_thread());
|
||||
}
|
||||
|
||||
/// Re-runs this test binary on one test with `var` set.
|
||||
fn child(test: &str, var: &str) -> std::process::Output {
|
||||
Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", test, "--nocapture", "--test-threads=1"])
|
||||
.env(var, "1")
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Prints when dropped.
|
||||
struct Loud;
|
||||
|
||||
impl Drop for Loud {
|
||||
fn drop(&mut self) {
|
||||
println!("DROPPED");
|
||||
}
|
||||
}
|
||||
|
||||
/// A panic under an export ends the process in the library's hook before anything unwinds,
|
||||
/// though nothing made the platform first: the export installs the hook itself. In a child,
|
||||
/// since the hook is the process's.
|
||||
#[test]
|
||||
fn a_panic_under_an_export_aborts_before_unwinding() {
|
||||
if std::env::var_os("RVG_FFI_PANIC_CHILD").is_some() {
|
||||
export(|| {
|
||||
let _l = Loud;
|
||||
panic!("under an export");
|
||||
});
|
||||
return;
|
||||
}
|
||||
let out = child(
|
||||
"ffi::tests::a_panic_under_an_export_aborts_before_unwinding",
|
||||
"RVG_FFI_PANIC_CHILD",
|
||||
);
|
||||
assert_eq!(out.status.signal(), Some(6), "{out:?}");
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!stdout.contains("DROPPED"), "{stdout}");
|
||||
assert!(
|
||||
stderr.contains("reims-vgpu: panic: ") && stderr.contains("under an export"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A destroy that panics.
|
||||
unsafe extern "C-unwind" fn panicking_destroy(_ctx: *mut std::ffi::c_void) {
|
||||
panic!("in the host's destroy");
|
||||
}
|
||||
|
||||
/// A panic in a host callback that the first export of the process runs (a refused create's
|
||||
/// destroy, before any platform exists) ends in the library's hook: the export installed it
|
||||
/// and marked the thread. In a child, since the hook is the process's.
|
||||
#[test]
|
||||
fn a_panic_in_a_callback_of_the_first_export_ends_in_the_hook() {
|
||||
if std::env::var_os("RVG_FFI_CALLBACK_CHILD").is_some() {
|
||||
let callbacks = crate::device::RvgHostCallbacks {
|
||||
struct_size: crate::sized::size_u32::<crate::device::RvgHostCallbacks>(),
|
||||
ctx: std::ptr::null_mut(),
|
||||
destroy: Some(panicking_destroy),
|
||||
create_task: None,
|
||||
destroy_task: None,
|
||||
map_memory: None,
|
||||
unmap_memory: None,
|
||||
read_memory: None,
|
||||
raise_interrupt: None,
|
||||
add_trace_range: None,
|
||||
remove_trace_range: None,
|
||||
};
|
||||
let config = crate::testkit::config(1, &callbacks);
|
||||
// SAFETY: a live config; a NULL out-pointer, which the create refuses.
|
||||
let _ = unsafe { crate::device::rvg_device_create(&config, std::ptr::null_mut()) };
|
||||
return;
|
||||
}
|
||||
let out = child(
|
||||
"ffi::tests::a_panic_in_a_callback_of_the_first_export_ends_in_the_hook",
|
||||
"RVG_FFI_CALLBACK_CHILD",
|
||||
);
|
||||
assert_eq!(out.status.signal(), Some(6), "{out:?}");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(
|
||||
stderr.contains("reims-vgpu: panic: ") && stderr.contains("in the host's destroy"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! The catch on Linux: a Rust unwind out of the host's code that no panic hook ended first ends
|
||||
//! the process at the call.
|
||||
|
||||
use reims_vgpu_core::testkit::capture::catch_death;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// An unwind the panic hook never saw (`resume_unwind`) is fatal at the call
|
||||
#[test]
|
||||
fn a_rust_unwind_from_the_host_is_fatal_at_the_call() {
|
||||
let d = catch_death(|| host_call("map_memory", || std::panic::resume_unwind(Box::new(7))));
|
||||
assert_eq!(d.unwrap_err(), host_raised("map_memory"));
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! The catch on macOS: whatever Objective-C object the host throws, and `@throw nil`, ends the
|
||||
//! process at the call.
|
||||
|
||||
use objc2::exception::{self, Exception};
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::{AnyObject, NSObject};
|
||||
use objc2_foundation::{NSException, NSString};
|
||||
use reims_vgpu_core::testkit::capture::catch_death;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `@throw object` from the host's code.
|
||||
fn throw(object: Retained<AnyObject>) -> ! {
|
||||
// SAFETY: any Objective-C object may be thrown; `Exception` wraps one.
|
||||
exception::throw(unsafe { Retained::cast_unchecked::<Exception>(object) })
|
||||
}
|
||||
|
||||
fn ns_exception() -> Retained<AnyObject> {
|
||||
let name = NSString::from_str("HostRefusal");
|
||||
let reason = NSString::from_str("the host's reason");
|
||||
// SAFETY: a name and a reason, no userInfo.
|
||||
let e = unsafe { NSException::exceptionWithName_reason_userInfo(&name, Some(&reason), None) };
|
||||
Retained::into_super(Retained::into_super(e))
|
||||
}
|
||||
|
||||
/// Whatever the host throws ends the process at the call
|
||||
#[test]
|
||||
fn a_host_raise_is_fatal_at_the_call() {
|
||||
let d = catch_death(|| host_call("map_memory", || throw(ns_exception())));
|
||||
assert_eq!(d.unwrap_err(), host_raised("map_memory"));
|
||||
let d = catch_death(|| host_call("unmap_memory", || throw(ns_exception())));
|
||||
assert_eq!(d.unwrap_err(), host_raised("unmap_memory"));
|
||||
let d = catch_death(|| host_call("read_memory", || throw(NSObject::new().into_super())));
|
||||
assert_eq!(d.unwrap_err(), host_raised("read_memory"));
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" {
|
||||
/// `@throw nil` (objc2's `throw` takes an object).
|
||||
fn objc_exception_throw(exception: *mut AnyObject) -> !;
|
||||
}
|
||||
|
||||
/// `@throw nil` is fatal too
|
||||
#[test]
|
||||
fn a_nil_throw_is_fatal() {
|
||||
// SAFETY: objc_exception_throw(nil).
|
||||
let d = catch_death(|| {
|
||||
host_call("create_task", || unsafe {
|
||||
objc_exception_throw(std::ptr::null_mut())
|
||||
})
|
||||
});
|
||||
assert_eq!(d.unwrap_err(), host_raised("create_task"));
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Frames copied into host memory: [`RvgFrameTarget`], the encode into it, and [`RvgFrame`].
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use parking_lot::RwLock;
|
||||
use reims_vgpu::{Frame, FrameTarget, PixelFormat, Region};
|
||||
|
||||
use crate::Plat;
|
||||
use crate::device::RvgDevice;
|
||||
use crate::display::RvgDisplay;
|
||||
use crate::ffi;
|
||||
use crate::handle;
|
||||
use crate::sized::{self, HostStruct};
|
||||
use crate::status::{RVG_ERR_INVALID_ARGUMENT, RVG_OK, RvgStatus, status};
|
||||
|
||||
/// A frame target's pixel format: one of RVG_PIXEL_FORMAT_*.
|
||||
pub type RvgPixelFormat = u32;
|
||||
|
||||
// The constants below are RvgPixelFormat values, typed `u32` so that cbindgen writes them with the
|
||||
// header's other constants, ahead of its types.
|
||||
|
||||
/// 8-bit RGBA, normalized (Metal's MTLPixelFormatRGBA8Unorm, 70).
|
||||
pub const RVG_PIXEL_FORMAT_RGBA8_UNORM: u32 = 70;
|
||||
|
||||
/// 8-bit RGBA, sRGB (71).
|
||||
pub const RVG_PIXEL_FORMAT_RGBA8_UNORM_SRGB: u32 = 71;
|
||||
|
||||
/// 8-bit BGRA, normalized (80): the byte order of a pixman x8r8g8b8 surface.
|
||||
pub const RVG_PIXEL_FORMAT_BGRA8_UNORM: u32 = 80;
|
||||
|
||||
/// 8-bit BGRA, sRGB (81).
|
||||
pub const RVG_PIXEL_FORMAT_BGRA8_UNORM_SRGB: u32 = 81;
|
||||
|
||||
/// Where a frame is drawn in its target, in pixels. The whole target is cleared first.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
pub struct RvgRegion {
|
||||
pub x: u64,
|
||||
pub y: u64,
|
||||
pub width: u64,
|
||||
pub height: u64,
|
||||
}
|
||||
|
||||
/// A frame target's config.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RvgFrameTargetConfig {
|
||||
/// sizeof(RvgFrameTargetConfig) as the host was compiled.
|
||||
pub struct_size: u32,
|
||||
/// 1 to 16384.
|
||||
pub width: u32,
|
||||
/// 1 to 16384.
|
||||
pub height: u32,
|
||||
/// One of RVG_PIXEL_FORMAT_*.
|
||||
pub format: RvgPixelFormat,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; integers only.
|
||||
unsafe impl HostStruct for RvgFrameTargetConfig {}
|
||||
|
||||
/// A 2D texture the library draws frames into and reads pixels back from.
|
||||
pub struct RvgFrameTarget {
|
||||
target: FrameTarget<Plat>,
|
||||
}
|
||||
|
||||
/// One encode of a display's current frame into a frame target: uncommitted, committed, or
|
||||
/// complete.
|
||||
pub struct RvgFrame {
|
||||
/// Committed under the write lock; waited on under the read lock, so waits may overlap.
|
||||
frame: RwLock<Frame<Plat>>,
|
||||
}
|
||||
|
||||
/// A frame target on `device`'s Metal device: a 2D texture of `config`'s size and format that
|
||||
/// the library can draw into and the CPU can read. RVG_ERR_INVALID_ARGUMENT for a size or format
|
||||
/// out of range, RVG_ERR_METAL where Metal refuses the texture. The target holds no reference to
|
||||
/// the device. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live device handle; `config` is NULL or a live config; `target` is
|
||||
/// NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_frame_target_create(
|
||||
device: *mut RvgDevice,
|
||||
config: *const RvgFrameTargetConfig,
|
||||
target: *mut *mut RvgFrameTarget,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let c = match unsafe { sized::read(config) } {
|
||||
Ok(Some(c)) => c,
|
||||
Ok(None) => return RVG_ERR_INVALID_ARGUMENT,
|
||||
Err(s) => return s,
|
||||
};
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(device) = (unsafe { handle::get(device) }) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
if target.is_null() {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
let Some(format) = PixelFormat::from_metal(c.format) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
match device.device.new_frame_target(c.width, c.height, format) {
|
||||
Ok(t) => {
|
||||
let h = handle::new(RvgFrameTarget { target: t });
|
||||
// SAFETY: checked non-NULL; the caller's contract.
|
||||
unsafe { target.write(h) };
|
||||
RVG_OK
|
||||
}
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// One more reference to `target`; returns it.
|
||||
///
|
||||
/// # Safety
|
||||
/// `target` is NULL or a live frame target.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_frame_target_retain(
|
||||
target: *mut RvgFrameTarget,
|
||||
) -> *mut RvgFrameTarget {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::retain(target) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Drops one reference to `target`; frames still drawing into it keep their own.
|
||||
///
|
||||
/// # Safety
|
||||
/// `target` is NULL or a live frame target whose reference the caller owns.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_frame_target_release(target: *mut RvgFrameTarget) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::release(target) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Copies the whole target into `dst`: `height` rows of `width * 4` bytes, each row
|
||||
/// `bytes_per_row` bytes after the last, in the target's format. It reads what the GPU has
|
||||
/// written so far: wait for the frames that draw into it first. RVG_ERR_INVALID_ARGUMENT when
|
||||
/// `bytes_per_row` is below `width * 4` or `dst_length` is below the copy's extent. Calls
|
||||
/// back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `target` is NULL or a live frame target; `dst` is NULL or holds `dst_length` writable bytes.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_frame_target_read_pixels(
|
||||
target: *const RvgFrameTarget,
|
||||
dst: *mut c_void,
|
||||
bytes_per_row: usize,
|
||||
dst_length: usize,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(t) = (unsafe { handle::get(target) }) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
if dst.is_null() {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// SAFETY: the caller's contract.
|
||||
let dst = unsafe { std::slice::from_raw_parts_mut(dst.cast::<u8>(), dst_length) };
|
||||
match t.target.read_pixels(dst, bytes_per_row) {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Encodes the display's current frame into `target` over `region` (NULL: the whole target),
|
||||
/// on the process's frame queue, and writes the uncommitted frame through `frame`. The display
|
||||
/// counts the frame in flight until it completes; its presents wait for frames in flight. The
|
||||
/// first encode after each new guest frame counts one host present. RVG_ERR_INVALID_ARGUMENT
|
||||
/// for a target on another Metal device, RVG_ERR_METAL where Metal gives no command buffer.
|
||||
/// Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `display` is NULL or a live display handle; `target` is NULL or a live frame target;
|
||||
/// `region` is NULL or a live region; `frame` is NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_display_encode_frame(
|
||||
display: *mut RvgDisplay,
|
||||
target: *mut RvgFrameTarget,
|
||||
region: *const RvgRegion,
|
||||
frame: *mut *mut RvgFrame,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let (Some(d), Some(t)) = (unsafe { handle::get(display) }, unsafe {
|
||||
handle::get(target)
|
||||
}) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
if frame.is_null() {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
// SAFETY: the caller's contract.
|
||||
let region = unsafe { region.as_ref() }.map(|r| Region {
|
||||
x: r.x,
|
||||
y: r.y,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
});
|
||||
match d.display.encode_frame(&t.target, region) {
|
||||
Ok(f) => {
|
||||
let h = handle::new(RvgFrame {
|
||||
frame: RwLock::new(f),
|
||||
});
|
||||
// SAFETY: checked non-NULL; the caller's contract.
|
||||
unsafe { frame.write(h) };
|
||||
RVG_OK
|
||||
}
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Submits the frame to the GPU. RVG_ERR_FRAME_STATE if it was committed already. Calls
|
||||
/// back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `frame` is NULL or a live frame.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_frame_commit(frame: *mut RvgFrame) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(f) = (unsafe { handle::get(frame) }) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
match f.frame.write().commit() {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Waits until the committed frame completes: RVG_OK, or RVG_ERR_GPU when the GPU work ended
|
||||
/// with an error. RVG_ERR_FRAME_STATE before rvg_frame_commit. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `frame` is NULL or a live frame.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_frame_wait(frame: *mut RvgFrame) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let Some(f) = (unsafe { handle::get(frame) }) else {
|
||||
return RVG_ERR_INVALID_ARGUMENT;
|
||||
};
|
||||
match f.frame.read().wait() {
|
||||
Ok(()) => RVG_OK,
|
||||
Err(e) => status(e),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Drops the frame. A committed frame completes on its own. An uncommitted one is never drawn,
|
||||
/// and stays counted in flight for the display's life. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `frame` is NULL or a live frame, not used again.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_frame_release(frame: *mut RvgFrame) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::release(frame) }
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,196 @@
|
||||
use reims_vgpu_core::testkit::CompleteOn;
|
||||
|
||||
use super::*;
|
||||
use crate::display::{RvgDisplayConfig, rvg_display_create, rvg_display_release};
|
||||
use crate::status::*;
|
||||
use crate::testkit::Rig;
|
||||
|
||||
fn target(device: *mut RvgDevice, w: u32, h: u32, format: u32) -> (RvgStatus, *mut RvgFrameTarget) {
|
||||
let c = RvgFrameTargetConfig {
|
||||
struct_size: sized::size_u32::<RvgFrameTargetConfig>(),
|
||||
width: w,
|
||||
height: h,
|
||||
format,
|
||||
};
|
||||
let mut t = std::ptr::null_mut();
|
||||
// SAFETY: a live device or NULL, a live config; `t` is writable.
|
||||
let s = unsafe { rvg_frame_target_create(device, &c, &mut t) };
|
||||
(s, t)
|
||||
}
|
||||
|
||||
fn display(device: *mut RvgDevice) -> *mut RvgDisplay {
|
||||
let c = RvgDisplayConfig {
|
||||
struct_size: sized::size_u32::<RvgDisplayConfig>(),
|
||||
serial_number: 0x5eed_f001,
|
||||
port: 0,
|
||||
name: std::ptr::null(),
|
||||
name_length: 0,
|
||||
width_millimeters: 0.0,
|
||||
height_millimeters: 0.0,
|
||||
callbacks: std::ptr::null(),
|
||||
window: std::ptr::null(),
|
||||
};
|
||||
let mut d = std::ptr::null_mut();
|
||||
// SAFETY: a live device and config; `d` is writable.
|
||||
assert_eq!(unsafe { rvg_display_create(device, &c, &mut d) }, RVG_OK);
|
||||
d
|
||||
}
|
||||
|
||||
/// Sizes 1 to 16384 and the four formats; anything else is an invalid argument
|
||||
#[test]
|
||||
fn target_refusals() {
|
||||
let rig = Rig::new(1);
|
||||
for (w, h, f) in [
|
||||
(0, 1, RVG_PIXEL_FORMAT_BGRA8_UNORM),
|
||||
(1, 16385, RVG_PIXEL_FORMAT_BGRA8_UNORM),
|
||||
(1, 1, 73),
|
||||
(1, 1, 0),
|
||||
] {
|
||||
assert_eq!(
|
||||
target(rig.device, w, h, f).0,
|
||||
RVG_ERR_INVALID_ARGUMENT,
|
||||
"{w} {h} {f}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
target(std::ptr::null_mut(), 1, 1, 80).0,
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
for f in [70, 71, 80, 81] {
|
||||
let (s, t) = target(rig.device, 16384, 1, f);
|
||||
assert_eq!(s, RVG_OK);
|
||||
// SAFETY: the target made above.
|
||||
unsafe {
|
||||
assert_eq!(rvg_frame_target_retain(t), t);
|
||||
rvg_frame_target_release(t);
|
||||
rvg_frame_target_release(t);
|
||||
}
|
||||
}
|
||||
// SAFETY: NULL is nothing.
|
||||
unsafe {
|
||||
assert!(rvg_frame_target_retain(std::ptr::null_mut()).is_null());
|
||||
rvg_frame_target_release(std::ptr::null_mut());
|
||||
}
|
||||
}
|
||||
|
||||
/// A retain is one more reference to the same target: after the first of its two releases the
|
||||
/// target is still usable, and its texture goes at the second, not before
|
||||
#[test]
|
||||
fn a_retained_target_lives_until_its_last_release() {
|
||||
let rig = Rig::new(1);
|
||||
let textures = || rig.p.world().live("MTLTexture");
|
||||
let before = textures();
|
||||
let (s, t) = target(rig.device, 4, 3, RVG_PIXEL_FORMAT_BGRA8_UNORM);
|
||||
assert_eq!(s, RVG_OK);
|
||||
let made: Vec<_> = textures()
|
||||
.into_iter()
|
||||
.filter(|id| !before.contains(id))
|
||||
.collect();
|
||||
assert_eq!(made.len(), 1, "{made:?}");
|
||||
let mut buf = [0xa5u8; 48];
|
||||
// SAFETY: the target made above, whose two references are given back once each; `buf` holds
|
||||
// 48 bytes.
|
||||
unsafe {
|
||||
assert_eq!(rvg_frame_target_retain(t), t);
|
||||
rvg_frame_target_release(t);
|
||||
assert!(textures().contains(&made[0]));
|
||||
assert_eq!(
|
||||
rvg_frame_target_read_pixels(t, buf.as_mut_ptr().cast(), 16, 48),
|
||||
RVG_OK
|
||||
);
|
||||
rvg_frame_target_release(t);
|
||||
}
|
||||
assert!(buf.iter().all(|&b| b == 0));
|
||||
assert!(!textures().contains(&made[0]));
|
||||
}
|
||||
|
||||
/// The copy's extent is checked before anything is read
|
||||
#[test]
|
||||
fn read_pixels_checks_the_extent() {
|
||||
let rig = Rig::new(1);
|
||||
let (_, t) = target(rig.device, 4, 3, RVG_PIXEL_FORMAT_RGBA8_UNORM);
|
||||
// Rows of 16 bytes, 20 apart: the extent is 56.
|
||||
let mut buf = vec![0xa5u8; 64];
|
||||
let p = buf.as_mut_ptr().cast::<c_void>();
|
||||
// SAFETY: the target is live; `buf` holds 64 bytes.
|
||||
unsafe {
|
||||
assert_eq!(
|
||||
rvg_frame_target_read_pixels(t, p, 15, 64),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_frame_target_read_pixels(t, p, 20, 55),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_frame_target_read_pixels(t, std::ptr::null_mut(), 20, 64),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_frame_target_read_pixels(std::ptr::null(), p, 20, 64),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(rvg_frame_target_read_pixels(t, p, 20, 56), RVG_OK);
|
||||
rvg_frame_target_release(t);
|
||||
}
|
||||
// The fake platform's pixels read as zero, over the extent only.
|
||||
assert!(buf[..56].iter().all(|&b| b == 0));
|
||||
assert!(buf[56..].iter().all(|&b| b == 0xa5));
|
||||
}
|
||||
|
||||
/// A frame is encoded uncommitted, committed once, and waited on after its commit; it keeps
|
||||
/// the display alive until it completes, and the target keeps nothing of the device
|
||||
#[test]
|
||||
fn frame_states() {
|
||||
let mut rig = Rig::new(1);
|
||||
let d = display(rig.device);
|
||||
let (_, t) = target(rig.device, 8, 8, RVG_PIXEL_FORMAT_BGRA8_UNORM);
|
||||
let mut f = std::ptr::null_mut();
|
||||
let r = RvgRegion {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 4,
|
||||
height: 4,
|
||||
};
|
||||
// SAFETY: live display and target; `f` is writable.
|
||||
unsafe {
|
||||
assert_eq!(
|
||||
rvg_display_encode_frame(d, std::ptr::null_mut(), &r, &mut f),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_display_encode_frame(d, t, &r, std::ptr::null_mut()),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(rvg_display_encode_frame(d, t, &r, &mut f), RVG_OK);
|
||||
assert_eq!(rvg_frame_wait(f), RVG_ERR_FRAME_STATE);
|
||||
assert_eq!(rvg_frame_commit(f), RVG_OK);
|
||||
assert_eq!(rvg_frame_commit(f), RVG_ERR_FRAME_STATE);
|
||||
// The fake GPU completes what was committed when told.
|
||||
assert_eq!(rig.p.world().complete_all(CompleteOn::Caller), 1);
|
||||
assert_eq!(rvg_frame_wait(f), RVG_OK);
|
||||
assert_eq!(
|
||||
rvg_frame_commit(std::ptr::null_mut()),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
rvg_frame_wait(std::ptr::null_mut()),
|
||||
RVG_ERR_INVALID_ARGUMENT
|
||||
);
|
||||
rvg_frame_release(f);
|
||||
rvg_frame_release(std::ptr::null_mut());
|
||||
assert_eq!(
|
||||
rvg_display_encode_frame(d, t, std::ptr::null(), &mut f),
|
||||
RVG_OK
|
||||
);
|
||||
rvg_display_release(d);
|
||||
}
|
||||
rig.release();
|
||||
// The target outlives the device, and the uncommitted frame the display.
|
||||
// SAFETY: the frame and target made above.
|
||||
unsafe {
|
||||
rvg_frame_release(f);
|
||||
rvg_frame_target_release(t);
|
||||
}
|
||||
assert_eq!(rig.ctx.rec.destroys().len(), 1);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Opaque handles.
|
||||
//!
|
||||
//! Every `Rvg<Name> *` the API hands out is `Arc::into_raw` of an `Arc<Rvg<Name>>`: one
|
||||
//! reference per pointer a create or a `_retain` returns. A release drops one, and the release
|
||||
//! that drops the last one ends the object, which may block. Releasing NULL does nothing.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A new handle holding one reference.
|
||||
pub(crate) fn new<T>(value: T) -> *mut T {
|
||||
Arc::into_raw(Arc::new(value)).cast_mut()
|
||||
}
|
||||
|
||||
/// A new handle lent to a host's callback for one call: this frame owns its one reference and
|
||||
/// gives it back when the frame ends. A host that keeps the handle retains its own.
|
||||
pub(crate) struct Lent<T>(*mut T);
|
||||
|
||||
impl<T> Lent<T> {
|
||||
/// Lends a new handle over `value`.
|
||||
pub(crate) fn new(value: T) -> Lent<T> {
|
||||
Lent(new(value))
|
||||
}
|
||||
|
||||
/// The handle, live until `self` drops.
|
||||
pub(crate) fn as_ptr(&self) -> *mut T {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for Lent<T> {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the one reference `new` made, given back once.
|
||||
unsafe { release(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
/// One more reference; returns `p` (NULL stays NULL).
|
||||
///
|
||||
/// # Safety
|
||||
/// `p` is NULL or a live handle of type `T` from this crate.
|
||||
pub(crate) unsafe fn retain<T>(p: *mut T) -> *mut T {
|
||||
if !p.is_null() {
|
||||
// SAFETY: the caller's contract: `p` came from `Arc::into_raw` and is live.
|
||||
unsafe { Arc::increment_strong_count(p.cast_const()) };
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// One reference less; the last runs the value's drop (NULL does nothing).
|
||||
///
|
||||
/// # Safety
|
||||
/// `p` is NULL or a live handle of type `T` from this crate, whose reference the caller owns.
|
||||
pub(crate) unsafe fn release<T>(p: *mut T) {
|
||||
if !p.is_null() {
|
||||
// SAFETY: the caller's contract: this gives back one reference `Arc::into_raw` made.
|
||||
drop(unsafe { Arc::from_raw(p.cast_const()) });
|
||||
}
|
||||
}
|
||||
|
||||
/// The value behind a borrowed handle; `None` for NULL.
|
||||
///
|
||||
/// # Safety
|
||||
/// `p` is NULL or a live handle of type `T` from this crate, live for `'a`.
|
||||
pub(crate) unsafe fn get<'a, T>(p: *const T) -> Option<&'a T> {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { p.as_ref() }
|
||||
}
|
||||
|
||||
/// Writes `value` through `out` when `out` is not NULL (an optional out-parameter).
|
||||
///
|
||||
/// # Safety
|
||||
/// `out` is NULL or valid for a write of `T`.
|
||||
pub(crate) unsafe fn write_out<T>(out: *mut T, value: T) {
|
||||
if !out.is_null() {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { out.write(value) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
static DROPS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct Counted(u32);
|
||||
impl Drop for Counted {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// One reference per pointer, the last release drops, NULL does nothing
|
||||
#[test]
|
||||
fn refcount() {
|
||||
let before = DROPS.load(Ordering::SeqCst);
|
||||
let p = new(Counted(7));
|
||||
// SAFETY: `p` is live throughout; each release gives back one reference.
|
||||
unsafe {
|
||||
assert_eq!(get(p).unwrap().0, 7);
|
||||
assert_eq!(retain(p), p);
|
||||
release(p);
|
||||
assert_eq!(DROPS.load(Ordering::SeqCst), before);
|
||||
release(p);
|
||||
}
|
||||
assert_eq!(DROPS.load(Ordering::SeqCst), before + 1);
|
||||
let null: *mut Counted = std::ptr::null_mut();
|
||||
// SAFETY: NULL is accepted by each.
|
||||
unsafe {
|
||||
assert!(retain(null).is_null());
|
||||
release(null);
|
||||
assert!(get(null).is_none());
|
||||
}
|
||||
{
|
||||
let lent = Lent::new(Counted(1));
|
||||
// SAFETY: the lent handle is live in this block.
|
||||
assert_eq!(unsafe { get(lent.as_ptr()) }.unwrap().0, 1);
|
||||
}
|
||||
assert_eq!(DROPS.load(Ordering::SeqCst), before + 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! The IOSurface device: vmapple's second MMIO region, [`RvgIOSurfaceDeviceConfig`], and the
|
||||
//! `rvg_iosurface_device_*` functions.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu::{IoSurfaceDevice, IoSurfaceDeviceConfig, RaiseInterrupt};
|
||||
|
||||
use crate::device::{RvgMemoryMap, memory_map};
|
||||
use crate::ffi;
|
||||
use crate::handle;
|
||||
use crate::sized::{self, HostStruct};
|
||||
use crate::status::{RVG_ERR_INVALID_ARGUMENT, RVG_OK, RvgStatus, status};
|
||||
use crate::table::{RvgDestroyFn, Table, WithTable};
|
||||
use crate::{Plat, null_handle};
|
||||
|
||||
/// `raise_interrupt(ctx, vector)` of the IOSurface device.
|
||||
///
|
||||
/// Thread: the IOSurface device's own serial worker, one call at a time.
|
||||
/// May call: every function of this header except rvg_iosurface_device_release on its own
|
||||
/// device, which ends the process. Without it, the IOSurface device's first interrupt ends
|
||||
/// the process.
|
||||
pub type RvgIOSurfaceRaiseInterruptFn =
|
||||
Option<unsafe extern "C-unwind" fn(ctx: *mut c_void, vector: u32)>;
|
||||
|
||||
/// The IOSurface device's callbacks.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
#[expect(
|
||||
missing_docs,
|
||||
reason = "the fields' names say what they hold, as the header shows them"
|
||||
)]
|
||||
pub struct RvgIOSurfaceCallbacks {
|
||||
/// sizeof(RvgIOSurfaceCallbacks) as the host was compiled.
|
||||
pub struct_size: u32,
|
||||
pub ctx: *mut c_void,
|
||||
/// Runs once after the IOSurface device's end, when its raise runs no more.
|
||||
pub destroy: RvgDestroyFn,
|
||||
pub raise_interrupt: RvgIOSurfaceRaiseInterruptFn,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; a pointer and optional function pointers.
|
||||
unsafe impl HostStruct for RvgIOSurfaceCallbacks {}
|
||||
|
||||
/// The IOSurface device's config.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RvgIOSurfaceDeviceConfig {
|
||||
/// sizeof(RvgIOSurfaceDeviceConfig) as the host was compiled.
|
||||
pub struct_size: u32,
|
||||
/// Required.
|
||||
pub memory_map: *const RvgMemoryMap,
|
||||
/// NULL is a table with every callback absent.
|
||||
pub callbacks: *const RvgIOSurfaceCallbacks,
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), a u32 first; pointers.
|
||||
unsafe impl HostStruct for RvgIOSurfaceDeviceConfig {}
|
||||
|
||||
/// The IOSurface device: vmapple's second MMIO region.
|
||||
pub struct RvgIOSurfaceDevice {
|
||||
pub(crate) device: WithTable<IoSurfaceDevice<Plat>>,
|
||||
}
|
||||
|
||||
/// The IOSurface device behind a handle, or the process's end for NULL.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live IOSurface device handle.
|
||||
unsafe fn live<'a>(
|
||||
device: *const RvgIOSurfaceDevice,
|
||||
call: &'static str,
|
||||
) -> &'a RvgIOSurfaceDevice {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::get(device) }.unwrap_or_else(|| null_handle(call))
|
||||
}
|
||||
|
||||
/// A new IOSurface device, the process's latest (a device with `use_iosurface_mapper` finds
|
||||
/// it at its first use). Refusals, checked in this order: RVG_ERR_INVALID_ARGUMENT,
|
||||
/// RVG_ERR_UNSUPPORTED, RVG_ERR_NO_MEMORY_MAP, RVG_ERR_MEMORY_MAP. Calls back: never.
|
||||
///
|
||||
/// # Safety
|
||||
/// `config` is NULL or a live config; `device` is NULL or writable.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_iosurface_device_create(
|
||||
config: *const RvgIOSurfaceDeviceConfig,
|
||||
device: *mut *mut RvgIOSurfaceDevice,
|
||||
) -> RvgStatus {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
let c = match unsafe { sized::read(config) } {
|
||||
Ok(Some(c)) => c,
|
||||
Ok(None) => return RVG_ERR_INVALID_ARGUMENT,
|
||||
Err(s) => return s,
|
||||
};
|
||||
// SAFETY: the config's contract: NULL or a live table.
|
||||
let callbacks = match unsafe { sized::read_or_zero(c.callbacks) } {
|
||||
Ok(t) => t,
|
||||
Err(s) => return s,
|
||||
};
|
||||
// From here the table is the library's: a refusal ends it before it returns.
|
||||
let table = Table::new(callbacks.ctx, callbacks.destroy);
|
||||
let refuse = |s: RvgStatus| {
|
||||
table.end();
|
||||
s
|
||||
};
|
||||
if device.is_null() {
|
||||
return refuse(RVG_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
// SAFETY: the config's contract: NULL or a live map.
|
||||
let memory_map = match unsafe { memory_map(c.memory_map, std::ptr::null()) } {
|
||||
Ok(m) => m,
|
||||
Err(s) => return refuse(s),
|
||||
};
|
||||
let raise_interrupt = callbacks.raise_interrupt.map(|f| {
|
||||
let t = table.clone();
|
||||
let r: RaiseInterrupt = Arc::new(move |vector| {
|
||||
// SAFETY: the host's function over its ctx.
|
||||
ffi::host_call("raise_interrupt", || unsafe { f(t.ctx(), vector) });
|
||||
});
|
||||
r
|
||||
});
|
||||
let config = IoSurfaceDeviceConfig {
|
||||
memory_map,
|
||||
raise_interrupt,
|
||||
};
|
||||
match IoSurfaceDevice::with_platform(<Plat as reims_vgpu::ApiPlatform>::process(), config) {
|
||||
Ok(d) => {
|
||||
let h = handle::new(RvgIOSurfaceDevice {
|
||||
device: WithTable::new(d, table),
|
||||
});
|
||||
// SAFETY: checked non-NULL; the caller's contract.
|
||||
unsafe { device.write(h) };
|
||||
RVG_OK
|
||||
}
|
||||
Err(e) => refuse(status(e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Drops the host's reference; the last one is the IOSurface device's teardown, which waits for
|
||||
/// its thread. Inside its own raise_interrupt it ends the process.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is NULL or a live IOSurface device handle, not used again.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_iosurface_device_release(device: *mut RvgIOSurfaceDevice) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { handle::release(device) }
|
||||
})
|
||||
}
|
||||
|
||||
/// A 64-bit read at `offset` in the IOSurface device's registers (0x1000 to 0x1030); an offset
|
||||
/// that names no register reads all ones.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live IOSurface device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_iosurface_device_mmio_read(
|
||||
device: *mut RvgIOSurfaceDevice,
|
||||
offset: u64,
|
||||
) -> u64 {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_iosurface_device_mmio_read") }
|
||||
.device
|
||||
.mmio_read(offset)
|
||||
})
|
||||
}
|
||||
|
||||
/// A 64-bit write at `offset` in the IOSurface device's registers; other offsets are ignored.
|
||||
/// May block on the IOSurface device's thread.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` is a live IOSurface device handle.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn rvg_iosurface_device_mmio_write(
|
||||
device: *mut RvgIOSurfaceDevice,
|
||||
offset: u64,
|
||||
value: u64,
|
||||
) {
|
||||
ffi::export(|| {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { live(device, "rvg_iosurface_device_mmio_write") }
|
||||
.device
|
||||
.mmio_write(offset, value);
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
Loaded 100 of 7821 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user