The renderer makes a tessellated draw's vertex and control shaders one kernel that takes the draw's vertices as a patch control point input, and makes its compute pipeline under a stage input descriptor. Metal compiles that input in no kernel (m3-max-30197): its own devices define the input's control point function from the descriptor. The device's pipeline of the kernel was refused, and the renderer drew the draw's vertex and control stages in software. A kernel variant with the input now keeps its module's text, and its compute pipeline is made of the kernel made one without the input under the pipeline's descriptor, once per descriptor: a wrapper kernel of the same name takes the buffers the fields read and the stage input region's origin, and the control point function, defined in place of its declaration, fetches each field as Metal's [[stage_in]] fetch does. The pipeline answers the variant's reflection. GL tessellated draws run on the GPU where the renderer drew them in software. The fetch matches the M3 Max's own [[stage_in]] kernels bit for bit, for every attribute format and step function (gl_tests' stage input oracle, m3-max-30314), which measured two of its conversions: Int1010102Normalized's 10-bit components are c times the float nearest 1/511, and RG11B10Float's NaNs are 0x7fc00000.
4858 lines
335 KiB
Markdown
4858 lines
335 KiB
Markdown
# reims-graphics: design
|
||
|
||
Status: stage 1 done. "Decided" holds what the owner and the research
|
||
settled, "Stage 2 wire protocol" is what stage 2 builds, and "Open" holds what
|
||
waits on the owner or on a later stage. The research's notes, with sources and
|
||
measured, read or inferred tags, are kept outside the repository.
|
||
|
||
## Goal
|
||
|
||
Our own GPU device for macOS guests, with our own guest kext and Metal GPU
|
||
bundle, our own protocol, and our own QEMU device and host side. It has its
|
||
own PCI vendor:device ID, so Apple's paravirt kext never matches it, and it
|
||
serves x86-64 guests through OpenCore and arm64 guests from macOS 14 on
|
||
Ambrosia (Decided 13). Resources are stored and rendered in host GPU memory.
|
||
The guest names them by handle, and the guest CPU reaches GPU memory only
|
||
where Metal gives it a pointer.
|
||
|
||
It is engineered for maximum performance from the first version, without
|
||
cheating: every result a guest observes is Metal's, and no fast path trades
|
||
correctness.
|
||
|
||
Stages:
|
||
1. Research and probes, ending in this document.
|
||
2. The kext, unaccelerated: the device, the transport and the display.
|
||
3. Acceleration through the library's platforms (Metal on a Mac,
|
||
metal2vulkan on Vulkan).
|
||
|
||
## Decided
|
||
|
||
1. **Device identity.** The device has its own PCI vendor:device ID, so
|
||
Apple's paravirt kext never matches it and nothing of the guest OS is
|
||
patched. The two lanes live side by side, and QEMU picks one by the device
|
||
a VM is given. The lane serves x86-64 guests: Apple says third-party kexts
|
||
are not supported in macOS VMs on Apple silicon, and vmapple guests boot
|
||
the same way, so arm64 guests stay on the Apple lane.
|
||
Superseded 2026-11-08: one lane. Apple's paravirt lane is deleted
|
||
(2026-11-07), and arm64 guests from macOS 14 take this device's arm64e set
|
||
on Ambrosia (Decided 13).
|
||
2. **The cut: Metal-level calls.** The guest bundle streams Metal's calls,
|
||
and the host decodes them into the library's `Platform`, which has a Metal
|
||
and a metal2vulkan implementation, so both arms come with it. A
|
||
Vulkan-level cut would put the Metal-to-Vulkan runtime, its shader
|
||
translator and its caches in every guest process, translate on the
|
||
guest's vCPUs, and translate twice on a Mac host.
|
||
- Measured on one AMD host (XDC 2023): API forwarding (virgl, Venus,
|
||
gfxstream) runs at 37-73% of bare metal, and DRM native context at
|
||
64-98.5%. Native context wins by its mechanics, which this protocol
|
||
keeps: the guest picks GPU addresses and sequence numbers itself,
|
||
replies sit in shared memory, and mappings are made once.
|
||
- In the Apple lane, copies are the cost and decoding is not: a 4K Finder
|
||
drag moves 182-938 MB a frame to the GPU, while the decode threads use
|
||
about 4% of a CPU.
|
||
3. **Queues and rings.** Each `MTLCommandQueue` gets one submission ring and
|
||
one completion ring, created when the guest makes the queue. Thousands are
|
||
allowed.
|
||
- Encoders stream as they end, and at a size threshold inside a long
|
||
encoder, so the host lowers encoder N while the guest encodes N+1.
|
||
Commit is a small message.
|
||
- No VM exit per submit. The host polls a busy ring, and the guest rings
|
||
the doorbell (an `ioeventfd`) only after the host has marked the ring
|
||
idle.
|
||
- Each ring is decoded on its own host worker, so one queue's work never
|
||
blocks another's. Single consumers are what limited the measured cases:
|
||
virgl decodes every GL context on one host thread, and a global lock left
|
||
gfxstream's GPU 8% busy (143 fps against 800 on Venus).
|
||
- Native GPUs have one graphics engine, a few compute and copy engines,
|
||
and far more queues than engines. RADV and ANV expose one graphics
|
||
queue and NVIDIA 16, so on AMD and Intel the graphics work of every guest
|
||
queue meets on one host queue, as native apps' work does.
|
||
- WindowServer's queue runs at high priority where the host driver offers
|
||
queue priorities.
|
||
- Completion records (seqno, status, Metal's error and the failing
|
||
encoders' info, GPU times) go in the queue's completion ring.
|
||
- An interrupt fires only when the guest armed one, on several MSI-X
|
||
vectors spread over the guest's CPUs.
|
||
- Presents are never batched. Every command buffer completes exactly, with
|
||
no grouping.
|
||
4. **Memory model.** VRAM is the primary allocation. `hasUnifiedMemory`
|
||
follows the host GPU.
|
||
- On a discrete GPU it is false:
|
||
- Private buffers and all textures live in VRAM and are never mapped
|
||
into the guest.
|
||
- Managed resources are two copies: the VRAM copy, which is primary, and
|
||
a host-cached CPU copy the guest maps.
|
||
- `didModifyRange:` copies exactly the named range to VRAM, before any
|
||
command of the next submission.
|
||
- `synchronizeResource:` copies VRAM back to the CPU copy inside the
|
||
blit encoder.
|
||
- A range message is ordered before every later commit of its
|
||
context, on any queue, as Metal promises.
|
||
- Managed textures get two copies too: a linear CPU copy the guest
|
||
maps, beside the VRAM image. `replaceRegion:` and `getBytes:` are
|
||
then guest memcpys plus a region message, with no round trip.
|
||
- Shared buffers are host-cached system memory mapped into the guest,
|
||
which the GPU reads over PCIe (measured on a 3090: CPU reads 45 GB/s
|
||
there, against 0.01 GB/s from resizable-BAR VRAM), whatever their
|
||
CPU cache mode.
|
||
- A texture made over a Shared buffer shares the buffer's system memory,
|
||
and the GPU samples it there, as Apple documents for discrete GPUs:
|
||
no VRAM copy and no dirty log (owner, 2026-10-30).
|
||
- On an integrated GPU (Apple silicon, AMD and Intel iGPUs) it is true,
|
||
with one copy of each resource.
|
||
- The host allocates every block, and the guest sub-allocates buffers
|
||
inside blocks, so creating a block is the only memory call that waits
|
||
for the host. A block mapped into the guest is a dedicated, page-aligned
|
||
host allocation.
|
||
5. **The guest maps host memory only.** VRAM is reached by the host alone.
|
||
- What crosses the API (draws, uploads, `didModifyRange:` ranges and
|
||
readbacks) reaches VRAM by the host's own GPU copies.
|
||
- The guest maps memory only where Metal gives the app a pointer:
|
||
`contents` of Shared and Managed buffers, and IOSurfaces the CPU locks.
|
||
That memory is plain anonymous host memory, zeroed with stores, imported
|
||
into Vulkan by pointer and mapped into the BAR. KVM maps it like guest
|
||
RAM on any kernel, and the host GPU reads it in place. The staging rings
|
||
live there too.
|
||
- Real discrete Macs keep Shared in system memory, so this is Metal's
|
||
discrete model.
|
||
- IOSurfaces are the one place the host reaches guest RAM: where the
|
||
device has `RGFX_FEATURE_SURFACE_PAGES`, the host maps a surface's own
|
||
guest pages for its GPU in place (Decided 14, "Today"), from the guest
|
||
RAM's map QEMU gives it.
|
||
- VRAM mapped into the guest was considered and dropped. It needed kernel
|
||
6.13 or later and resizable BAR, and was good for guest writes only:
|
||
measured on amdgpu, CPU reads from VRAM run at 15 MiB/s with memcpy,
|
||
against about 10 GiB/s for writes. It returns only if a measured frame
|
||
shows the GPU's reads of Shared memory across PCIe costing.
|
||
- The BAR is one host memory region that the device reserves at start and
|
||
registers with KVM once. Blocks are ranges inside it, so making or
|
||
freeing a block never changes the VM's memory map. It is ordinary
|
||
cached memory on the host, but the guest's kernel maps it uncached
|
||
wherever the kext asks for write-back: xnu's pmap sets PCD on every page
|
||
it does not manage (its PAT's UC-), and the region is no RAM of the
|
||
guest's. A write-combined ask takes, since the region's descriptor is
|
||
physically contiguous and xnu's fault path maps such an object's pages
|
||
in its own mode (read from the public xnu source: vm_fault's
|
||
`pmap_map_block_addr`). An AMD
|
||
host applies the guest's memory type, where an Intel host's EPT ignores
|
||
it: measured on the Radeon 780M host, the guest's stores there ran at
|
||
13 MB/s and its loads at 8 to 180 MB/s, against 5.6 to 123 GB/s in its
|
||
own RAM. Uncached loads cost 79-138 ns against 2-4 ns cached. So what
|
||
the CPU touches most lies in the process's own pages instead (its Shared
|
||
and Managed buffers' slabs and its upload chunks, "Managed storage", and
|
||
its indirect command buffers' slots, `ICB_SLOTS_IN_PAGES`),
|
||
and what the process only writes takes a write-combined part of its
|
||
block, which the kext maps so (a submission ring's data, command
|
||
buffers' bodies and a library's staging chunks; the bundle's
|
||
`RgfxRegion.hpp`): measured on the 780M host, draws.10k's encode took
|
||
9.2-9.5 ms with everything in the region, 7.7 ms with the slabs and
|
||
chunks in the process's pages, and 1.05-1.3 ms with those parts
|
||
write-combined as well. The kext maps those parts from a descriptor of
|
||
the region of their own: a mapping's cache mode is set on its
|
||
descriptor's one VM object, for every page of it, so asked of the
|
||
region's own descriptor it would hold for every region page faulted
|
||
after it, and each later write-back ask would walk the object's pages
|
||
to take it back (`RgfxAccelerator::copyWriteCombinedRegion`).
|
||
The kext writes ring 0's submit data the same way on x86-64: the
|
||
data's whole 4 KiB pages past its header's, through a write-combined
|
||
map of a descriptor of their own, the header's page uncached
|
||
(`RgfxControlRing.hpp`). A write-combined store is ordered with no
|
||
later store, so the kext fences its stores (SFENCE) before it stores
|
||
the producer: the host never sees the producer before the data it
|
||
covers. arm64 maps no write-combined part, and its release store of the
|
||
producer orders the data's stores before it. `control_ring_test` holds
|
||
both orders, under each architecture's rules. Measured in Geekbench's
|
||
Metal Super Resolution on the 780M host, a SubmitBatch call, the
|
||
creates and destroys a commit posts there, took 33.6 us p50 (59.4 p90)
|
||
with the data uncached and 31.3 us (58.2) write-combined, so the data's
|
||
stores are a small part of it (15.2 us p50 on the Iris Xe host, whose
|
||
EPT ignores the guest's memory type). The kext's kdebug stamps split the
|
||
call (33.3 us p50 in the same benchmark): 16.1 us went to the look-up of
|
||
the framebuffer, which every post made, 5.5 us to ring 0's doorbell
|
||
write, an exit to the host, 4.7 us to the system call's entry and 3.4 us
|
||
to its return, and 1.0 us to the data's stores. The look-up is the
|
||
guest kernel's own code, 1.6-1.8 times slower on the 780M host than on
|
||
the Iris Xe; the exits, entry and return cost the same on both hosts
|
||
when warm, and grow after an idle. The kext now keeps the framebuffer
|
||
it found started, and a commit behind held messages publishes its
|
||
buffer in the same call ("A commit behind held messages is one call"),
|
||
so the call now goes to the exits: 18.9 us p50 in the same benchmark
|
||
(entry 4.6, ring 0's doorbell 5.4, the queue's doorbell 4.1 where the
|
||
host's queue thread sleeps, return 3.3, the kext's own work about 3),
|
||
and the benchmark's own doorbell calls fell from 763 to 166. A commit
|
||
behind held messages, timed in the guest, took 17.4-18.0 us p50 before
|
||
and 8.7-9.6 us after on the 780M host, and 15.1-15.2 us before and
|
||
8.8-9.0 us after on the Iris Xe (11-14).
|
||
- The region is memory of QEMU's process, and the host side runs in that
|
||
process. On Linux it is a shared mapping of a memfd of the library's
|
||
(`reims-vgpu-vulkan`'s `RegionMemory`): RADV refuses a pointer to a
|
||
memfd's or any shared mapping (measured on the 780M and the RX 7900 XTX),
|
||
and imports dma-bufs of each block's pages instead, which cost a
|
||
submission the same at any size, where amdgpu walks every page of every
|
||
pointer import in each submission; NVIDIA imports it by pointer. On macOS
|
||
it is private anonymous memory.
|
||
- Blocks are few and large, each imported into Vulkan once, and the guest
|
||
sub-allocates buffers inside them. RADV lists every import in every
|
||
submission, and an import costs 17-43 us plus about 16 us per MiB of
|
||
fresh pages.
|
||
6. **Addresses and IDs.** The guest bundle picks every `gpuAddress` and
|
||
`gpuResourceID`, and the host pins them in metal2vulkan's own Metal
|
||
address space. Creating a buffer then needs no round trip, and argument
|
||
buffers need no patching. Host device addresses never reach the guest.
|
||
7. **Contexts.** Every guest process that opens the device is a context, with
|
||
its own resources, queues, and slices of the address and ID spaces.
|
||
Sharing across contexts (IOSurfaces, shared events, shared textures) is
|
||
explicit, by a global name.
|
||
8. **Shaders.** AIR crosses once, named by its SHA-256, with each pipeline's
|
||
descriptor and function constants. The host takes no keys or reflection
|
||
from the guest, and answers once translation finishes, without waiting
|
||
for the driver's compile.
|
||
- The bundle resolves a function's constant values as Metal does, against
|
||
the constants the library's own bytes declare (each function's `CNST`
|
||
table): a value set at a constant's index (by index or by range) wins,
|
||
else the one set under its name; values for constants the function does
|
||
not declare are ignored; a value of another type than its constant's
|
||
fails the function with Metal's error; a required constant with no value
|
||
reads 0, and an optional one stays undefined. Each pipeline create
|
||
carries one record per constant given a value, by index, with up to 32
|
||
bytes (a `long4`). A function made with no values builds no pipeline:
|
||
Metal asserts there, and the bundle refuses it.
|
||
9. **Synchronization.** The bundle sends Metal's own semantics exactly:
|
||
tracking modes, resource usage, `useResource`/`useHeap`, memory barriers,
|
||
fences and events. The host derives the Vulkan barriers. Shared-event
|
||
values sit on a page the guest reads, so `signaledValue` needs no round
|
||
trip.
|
||
10. **Device answers.** One versioned blob at device open holds every answer,
|
||
taken from the host GPU, and the bundle caches it.
|
||
- The device shows the host GPU's real name, and claims the Apple GPU
|
||
families the host platform claims, with every family and feature set
|
||
those contain, as an Apple-silicon Mac of that generation answers. It
|
||
invents no family of its own (owner, 2026-10-31).
|
||
- An Apple family is claimed only up to the highest one whose rows in
|
||
Apple's Metal Feature Set Tables the lane fully carries, and only where
|
||
the platform claims it too; the iOS feature sets of a family not
|
||
claimed answer no with it (2026-10-31). Apple1 answers as Apple2, as
|
||
Metal does: the tables' first Apple column is Apple2.
|
||
- No Apple family is claimed until the lane carries every piece of
|
||
Apple7's rows and of the families' before it (2026-11-01). A Mac's GPU
|
||
answers no Apple family (Intel, AMD) or Apple1 to Apple7 at least
|
||
(Apple silicon), and the guest's frameworks choose their paths from
|
||
those answers together. With Apple1 and Apple2 answered yes and Apple3
|
||
no, RenderBox made its passes' extra attachments memoryless and used
|
||
them in a way Metal fails: every command buffer it drew an app icon in
|
||
failed with `MTLCommandBufferErrorInvalidResource`, and the Dock's icons
|
||
were blank (an x86-64 macOS 26 guest). With no Apple family, as an
|
||
Intel or AMD Mac answers, they draw.
|
||
- Today the lane carries Apple1's and Apple2's pieces (argument encoders,
|
||
placement in `Automatic` heaps with the heap texture size, programmable
|
||
sample positions, texture views and Metal IO queues; the IO queues are
|
||
Metal's own over the bundle's device, with nothing on the wire) and
|
||
binary archives, so it claims no Apple family. Apple3 waits on indirect
|
||
command buffers. Each family's pieces are listed in `device_info.rs`
|
||
(`APPLE_PIECES`), and the claim rises to Apple7 when the last of its
|
||
pieces lands, then family by family.
|
||
- Mac1, Mac2, Common1 to Common3 and Metal3 keep the platform's answer for
|
||
now, though their rows need some of the same pieces: argument encoders
|
||
for Mac1, Mac2 and Metal3, and the heaps, sample positions and IO
|
||
queues for each of them.
|
||
- `architecture.name` is the host platform's: Metal's own on a Mac, and
|
||
on the Vulkan platform `vulkan_` with the GPU's PCI vendor and device
|
||
IDs and its driver's `pipelineCacheUUID`. The name keys binary archives,
|
||
so it stays one GPU's from boot to boot and changes where compiled
|
||
pipelines would (another GPU, driver or driver build). It names no Apple
|
||
GPU.
|
||
- Binary archives are the bundle's own (`RgfxBinaryArchive`): no compiled
|
||
code crosses the wire, so an archive keeps the keys Metal looks each
|
||
function's compile up by, per architecture, and writes them to a file of
|
||
its own format. Its answers and errors are Metal's, measured on the M3
|
||
Max (guest/bundle/tools/archive_probe.m), including the miss of
|
||
`MTLPipelineOptionFailOnBinaryArchiveMiss`. Apple frameworks that load
|
||
one at start (IconRendering, RenderBox) get a working archive, not the
|
||
base class's, which needs a target architecture the device has none of.
|
||
- Where the lane's own device can do less than the host GPU, it answers
|
||
no (Metal4, ray tracing, function pointers, dynamic libraries and the
|
||
rest). One table in `crates/reims-vgpu/src/graphics/device_info.rs`
|
||
lists each such answer with what it waits on.
|
||
- The guest's architecture, which the host names in the device's config
|
||
(`guest_arch`, from QEMU's target), decides one answer:
|
||
`isFramebufferReadSupported` is the host GPU's for an arm64 guest, as
|
||
an Apple silicon Mac answers yes, and no for an x86-64 guest, as an AMD
|
||
Mac answers (an Intel UHD 630 answers yes). CoreAnimation in an arm64
|
||
guest blends its generic shader against a destination it reads by
|
||
framebuffer fetch, which it compiles in by this answer: with no, the
|
||
menu bar drew black (2026-11-09).
|
||
- It also decides the class of Mac the host's GPU device presents to
|
||
metal2vulkan's runtime (`GuestArch::mac_class`), whose GPU results
|
||
Metal leaves to the Mac's GPU: an Apple silicon Mac's for an arm64
|
||
guest, an Intel or AMD Mac's for an x86-64 guest, whatever GPU the
|
||
host has. On Apple silicon a new `Private` texture reads Metal's
|
||
fixed pattern where Metal keeps it compressed (an `RGBA8Unorm` one
|
||
opaque magenta), blits through such a texture write three formats'
|
||
canonical encodings, a `half` NaN clear keeps its sign, and a `Clear`
|
||
load in a pass without a draw call reaches the whole level of a
|
||
compressed texture and the render area's 32x32 tiles of another; on
|
||
an Intel or AMD Mac a new `Private` texture holds what its memory held
|
||
(zero, filled so, on an Apple GPU), blits keep their bytes, the NaN
|
||
clear goes through `half`, and the `Clear` load reaches the whole
|
||
level. The runtime fixes the class of a device as it makes it, so it
|
||
is the process's, taken from its first graphics device; QEMU makes
|
||
every device of a process for its own target's guests.
|
||
11. **Stage 2 lays the final transport.** The rings, doorbells, interrupts,
|
||
contexts and the display path are the final ones from stage 2 on, and
|
||
stage 3 adds commands to them. The stage 2 display scans out host memory
|
||
with no copy on its way to the host window.
|
||
12. **The stage 2 guest stack.** The kext subclasses `IOFramebuffer` on our
|
||
PCI device. It implements the required methods (modes, pixel format,
|
||
aperture, cursor, vblank and connect interrupts, display info), and
|
||
matches with a probe score above Apple's generic IONDRV driver, which
|
||
matches any display-class device. WindowServer composites in software
|
||
with no Metal device: x86-64 macOS 26.5.2, 26.6.1 and 26.7.1 reach the
|
||
desktop that way ("Software compositor activated"; measured).
|
||
13. **Loading: through OpenCore, bound by Graft.** OpenCore injects kexts
|
||
into the Boot kernel collection and links them only against
|
||
Boot-collection symbols, but a display kext uses IOGraphicsFamily and
|
||
AppleGraphicsDeviceControl, which are in the System collection. So
|
||
ReimsGraphics is built with Graft's consumer rules
|
||
(`guest/graft/sdk/consumer.mk`): its System-collection imports point at
|
||
placeholders inside the kext, and it carries a manifest
|
||
(`__DATA,__graft`) of every imported site and of the library classes it
|
||
derives from, with no System-collection `OSBundleLibraries`. Its
|
||
personalities stay, each gated by an `IOPropertyMatch` requiring
|
||
`ai.aneesiqbal.ReimsGraphics.graft-bound` on its provider, and the
|
||
manifest carries each personality's provider matching (its
|
||
`IOProviderClass` and `IOPCIPrimaryMatch`: the 1234:5247 device).
|
||
The personalities hold those and the keys that name the driver
|
||
(`IOClass`, `CFBundleIdentifier`, `IOProbeScore`, `IOMatchCategory`)
|
||
alone: the accelerator sets its driver keys on its registry entry in
|
||
`start` ("Stage 3 accelerator kext").
|
||
OpenCore links that dormant kext in the Boot collection. Graft
|
||
(`guest/graft`, a copy of Graft's release build) starts from its own
|
||
kext start and finds ReimsGraphics among the placed kexts by its
|
||
manifest. Once the libraries are registered, it checks each parent
|
||
class's size and vtable against the running library, resolves each site
|
||
by name, writes the sites and vtables, then sets the gate property on
|
||
each nub a personality's provider matching matches, the 1234:5247 nub,
|
||
and registers the nub again. The registry root's
|
||
`GraftClient.ai.aneesiqbal.ReimsGraphics` reads `bound: imports and
|
||
vtables committed; waiting for a provider of personality <names> to
|
||
open the gate` once the sites and vtables are written while no such nub
|
||
is published yet, and `bound: imports and vtables committed; activation
|
||
gate open on a provider of personality <name>` once the property is set
|
||
on one, which the lane gate's `graft-bind` check requires. Until then the passive property match fails,
|
||
so IOKit does not even construct ReimsGraphics' classes, whose parent
|
||
constructors run through the sites (an `IOResourceMatch` would hold
|
||
back only `start()`). On a missing symbol or a layout that
|
||
differs, Graft declines ReimsGraphics by name in its log and in the
|
||
registry root's `GraftClient.ai.aneesiqbal.ReimsGraphics`, and the
|
||
guest boots on. The image carries the set `make -C guest set` builds,
|
||
in this order: Graft.kext, ReimsGraphics.kext and RgfxGate.kext.
|
||
OpenCore injects it from Darwin 20 (macOS 11), the releases whose
|
||
x86-64 matrix row passes in full (`MIN_KERNEL` in
|
||
guest/tools/prebuilt.py); a release joins once its row passes.
|
||
Nothing of the guest OS is patched or hooked beyond what Graft does for
|
||
these two.
|
||
- Iterating: patch a copy of a VM's OpenCore image directly
|
||
(scripts/internal/opencore-add-kexts.sh). No rebuild inside the guest.
|
||
Graft reads the sites from the kext's own manifest, so a new
|
||
ReimsGraphics binds without a new Graft. Swap in the kext
|
||
`make -C guest/kext` builds: that build stages it dormant with its
|
||
manifest. A kext built without Graft's rules carries personalities
|
||
and System-collection libraries, which OpenCore refuses.
|
||
- Checking: `make -C guest set-check` links the set into a release's
|
||
Boot collection with OpenCore's own linker, in user space, and checks
|
||
with Graft's `graft-kext check-prelinked`, built from the SDK's
|
||
sources, that the manifest and every site survive it.
|
||
- Shipping: the repository carries the set prebuilt in guest/prebuilt,
|
||
with its Kernel > Add entries in `set.toml` and the record of its
|
||
sources in `sources.toml` (`make -C guest prebuilt`;
|
||
`make -C guest prebuilt-check` fails when they differ from the tree).
|
||
reims-ctl adds the set to an image, since a Linux host cannot build it.
|
||
- Arm64 guests: the same sources build for arm64e (`ARCH_NAME=arm64e`)
|
||
into a second set, guest/prebuilt-arm64e (`make -C guest
|
||
prebuilt-arm64e`), for the arm64 guests from macOS 14 that Ambrosia
|
||
boots (arm64 macOS 11 to 13 are not supported for now: 13.6 offers
|
||
the device no MSI, and the kexts have no INTx path); Ambrosia's config bundle adds it to the guest's kernel
|
||
collection (docs/qemu.md, "arm64 guests"). An arm64 kernel collection
|
||
has no AppleGraphicsDeviceControl and no IOAcceleratorFamily2, so the
|
||
arm64e kext has a Graft declaration and an Info.plist of its own
|
||
(src/graft-arm64e.json, src/Info-arm64e.plist): IOFramebuffer and
|
||
IOAccelerator from IOGraphicsFamily, and no device control. The set
|
||
starts with Graft's arm64e build, Graft-arm64e.kext from guest/graft,
|
||
which starts each library the arm64e manifest declares,
|
||
IOMobileGraphicsFamily among them, before it binds against it.
|
||
- The arm64 display (owner, 2026-11-08): an arm64 WindowServer drives no
|
||
IOFramebuffer (measured on 27.0.1 with SIP on: a bound IOFramebuffer
|
||
consumer got no user client, and the system had no
|
||
IOFramebufferUserClient with WindowServer up), so the arm64e display
|
||
is an IOMobileFramebuffer: a subclass of IOMobileFramebufferLegacy,
|
||
as Apple's own paravirtual display, AppleParavirtDisplay, is on every
|
||
release from 13 to 27. Its vtable grows release by release (Legacy's
|
||
has 445 slots on 13.6 and 484 on 27.0.1), so Graft builds the
|
||
subclass's vtable from the live parent at bind time and places its
|
||
overrides by method. The front end (ReimsGraphicsMobile.cpp)
|
||
publishes the display as the paravirtual display does: its
|
||
attributes, and its modes as IOAVFamily's timing and colour elements,
|
||
a timing for each mode the device lists and one 8-bit colour mode.
|
||
WindowServer sets one of them by its colour and timing IDs
|
||
(set_digital_out_mode), which the device then shows by `SET_SCANOUT`,
|
||
as x86-64's setDisplayMode does. The display is external and
|
||
plugged in from its start (`hotPlug_notify`), as the paravirtual
|
||
display's are: WindowServer reads an external display's modes, and
|
||
sets one, at its start and at each hot-plug notice, and asks for an
|
||
internal display's notices only on 27 (QuartzCore's AccelServer and
|
||
IOMFBDisplay). The display starts in its preferred mode
|
||
(start_hardware), which WindowServer then sets.
|
||
- The arm64 display's cursor and mode changes, as the paravirtual
|
||
display has them: a swap's layer 1 is the display's cursor
|
||
(RgfxMobileCursor.hpp), and the display publishes `CursorPlane`. A
|
||
swap that gives layer 1 sets the device's cursor from its surface's
|
||
image (`SET_CURSOR`, through the cursor's slot) and moves it
|
||
(`MOVE_CURSOR`, the swap's place plus the hot spot), or hides it
|
||
where the layer has no surface; a surface with no image is shown as
|
||
the swap's in place of layer 0's. A change of the device's modes
|
||
(`DISPLAY_CHANGED`, as a resize of the host's window makes one)
|
||
publishes the display's attributes and modes again, shows the new
|
||
preferred mode where the device no longer lists the one shown, and
|
||
tells WindowServer through the class's hot-plug notice
|
||
(`hotPlug_notify`) and `kIOMessageServicePropertyChange`.
|
||
14. **IOSurfaces follow the discrete model.** IOSurface.kext allocates
|
||
surfaces in guest RAM, CAMetalLayer drawables and window backing stores
|
||
included. The accelerator gets a per-surface device cache with a sync
|
||
callback when the CPU locks the surface. So a surface's guest pages are
|
||
its CPU copy, and its GPU copy lives in VRAM as the device cache, synced
|
||
at the points IOSurface and the bundle define: CPU lock and unlock, and
|
||
the GPU's use of a CPU-written surface. Surfaces the CPU never touches
|
||
are never copied. A surface the GPU renders and the CPU locks is two
|
||
copies synced at lock and unlock, as Managed textures are. A texture over
|
||
host memory (over a Shared buffer, or a CPU-locked surface) follows
|
||
metal2vulkan's host-page rules: in place where only sampled, otherwise a
|
||
shadow copy that is announced. Stage 2 needs none of this, since its
|
||
compositor is software.
|
||
- **Today:** the GPU works on a surface's own guest pages in place, and
|
||
copies them only where the host cannot use them. Where the device has
|
||
`RGFX_FEATURE_SURFACE_PAGES` and the host's linear textures can lie
|
||
over every plane (the base is a page's, each plane's offset from it and
|
||
its rows are multiples of the host's linear texture alignment, every
|
||
plane lies in the allocation), the bundle asks the kext for the surface's shared
|
||
block in place. The kext wires the surface's whole allocation, writes
|
||
its page runs into the block past the part the processes map, and
|
||
hands them to the host (`SURFACE_PAGES`, answered), which maps them as
|
||
one view. Each process's buffer lies over the view
|
||
(`BUFFER_OVER_SURFACE_PAGES`), and each texture over its plane's own
|
||
offset and rows. The block holds only the header and the writers, and
|
||
nothing is copied or synced: the GPU and every CPU use the same
|
||
pages, so such a surface has no GPU copy to keep in step. A surface
|
||
whose layout misses the host's alignment, a device
|
||
without the feature, or pages the host refuses (not whole pages of
|
||
guest RAM, or a view it cannot map) keep the copy below; so does every
|
||
other holder of that surface, since the kext gives a surface's blocks
|
||
in one mode.
|
||
- **The copy:** a surface's GPU copy is one region block, holding every
|
||
plane in plane order, that every process holding the surface shares
|
||
(the kext's, found by plane 0's pages; "Processes name only their
|
||
own"), so one process's GPU writes reach another's GPU with no copy, and
|
||
a texture over one plane that reads another (a two-plane YCbCr texture
|
||
over plane 0 would read plane 1's chroma; the bundle ends the process
|
||
at one, as the x86 Macs do, dgpu-oracle.md Q13) finds both in one
|
||
buffer. In
|
||
either mode, its `TEXTURE_FROM_IOSURFACE` carries the surface's facts
|
||
(`RgfxSurfaceFacts`: OSType, planes, size, plane 1's place, YCbCr
|
||
matrix), which the host's surface creator reads as Metal reads the
|
||
surface. The copy syncs from the pages before
|
||
a commit where the surface's seed moved since any holder synced it, and
|
||
back to the pages, with no lock of the surface, at the completion of
|
||
each command buffer that writes it. The block's header holds the seed
|
||
every holder agrees on (`guest/bundle/src/RgfxIOSurface.h`). Moving the
|
||
copy's write-back to the CPU's lock (the device cache's op 0) is what is
|
||
left of this item.
|
||
- **CPU locks** wait for the GPU's pending writes, as Metal's do on the
|
||
x86-64 Macs (measured on a MacBook Pro's AMD Radeon Pro 5300M and Intel
|
||
UHD 630 under macOS 26.7, `guest/bundle/tools/lock_probe.m`). Where the
|
||
Macs measured agree, their answer is the contract and is kept exactly;
|
||
where they differ, the docs promise neither answer and the cheapest one
|
||
within them is taken:
|
||
- a read-only or read-write lock of a surface, in any process, returns
|
||
once every buffer that writes the surface has finished and its
|
||
results are in the pages. The AMD, the Intel and the M3 Max agree:
|
||
contract, kept exactly;
|
||
- a pending buffer that only reads the surface holds no lock. The AMD
|
||
and the Intel agree; the M3 Max's read-write lock waits for it.
|
||
Divergent, so the cheaper rule, which tracks writes only. A buffer
|
||
writes a surface it draws to, a blit writes to, it uses with Write
|
||
usage, or binds where a draw's or dispatch's function declares a
|
||
`write` or `read_write` texture: the bundle reads each entry point's
|
||
arguments from the AIR metadata of its bitcode in the `.metallib`
|
||
(`guest/bundle/src/RgfxAirArguments.hpp`), since the host gives no
|
||
binding reflection. Those declared under function constants are the
|
||
function's whatever the constants' values. Where the arguments do
|
||
not read (a binding of a kind the reader does not know among them),
|
||
or a written texture's binding index is an expression of function
|
||
constants, a bound texture counts as written where its usage has
|
||
ShaderWrite or is unknown. A surface used without Write usage counts
|
||
as written at a draw or dispatch whose function's arguments do not
|
||
read or whose argument buffer may write a texture: Metal takes
|
||
useResource's usage for the app's promise, but a discrete Mac's
|
||
driver lands a write the promise left out. Narrowing may only drop a
|
||
write the function cannot make. The same rule decides the copy's
|
||
write-back: a buffer writes a copy back to the pages only where it
|
||
writes the surface, never for a surface it only reads;
|
||
- the committer's own lock waits from the buffer's submission on. At
|
||
the commit itself the AMD's returns at once, a race. Loose: ours
|
||
waits from the commit on;
|
||
- a read of the pages with no lock after the buffer completes sees the
|
||
GPU's pixels on ours and stale ones on the AMD and the Intel. The
|
||
docs ask for a lock before the CPU reads, so either holds.
|
||
|
||
The kext drives IOSurface's
|
||
device caches as those Macs' drivers do (measured with fbt on the AMD's
|
||
IOAcceleratorFamily2 and the guest's IOGPU; the kext's
|
||
`RgfxIOSurfaceKPI.hpp`). At the first write a process names of a
|
||
surface's shared block, the kext looks the surface up by the
|
||
IOSurfaceID the process gives and takes it only where its memory holds
|
||
the block's first page, makes its device cache for the accelerator with
|
||
the kext's control function, and keeps both with the block. Each write
|
||
named marks the cache current, which moves the surface's seed once, as
|
||
Metal's submission does, and has IOSurface call the control function in
|
||
every CPU lock of the surface: op 2 waits while a write is pending, and
|
||
op 3 releases the reference IOSurface took on the cache for the lock,
|
||
or for a purgeable change (ops 6 and 7), as the AMD's driver does. A
|
||
write retires at the bundle's retire call after the buffer's completion
|
||
and write-back, or, for a surface drawn in place, once the queue's
|
||
completion ring's `completed_seqno` reaches the buffer, whichever comes
|
||
first. A lock still waiting after 2 s goes on with an "RGFX: WARN" line
|
||
(`guest/kext/src/RgfxAcceleratorLocks.cpp`).
|
||
- **The device cache:** where the host's GPU does not share the CPU's
|
||
memory, the device has `RGFX_FEATURE_SURFACE_CACHE`, and a block the
|
||
kext marks cached (`RGFX_SURFACE_PAGES_CACHED`) gets a device cache on
|
||
the host: a Private buffer of the surface's bytes, which every buffer
|
||
over the block is, so every texture over the surface, of any shape,
|
||
plane or format, lies over the same bytes. The
|
||
block's `SURFACE_PAGES` carries the surface's `RgfxSurfacePagesLayout`
|
||
where the bundle gave it, a deferred block's too, and the host lays
|
||
the cache out by it as by an ask's layout (below, *Device caches on a
|
||
GPU that shares the CPU's memory*): its first plane's first byte where
|
||
the host's GPU's textures over the cache may start in place, as
|
||
CoreVideo lays a frame's planes 32 bytes into their surface, past every
|
||
linear image's alignment measured (128 bytes on an RTX 5080 Laptop
|
||
GPU, 256 on RADV), so the textures over a decoder's planes are images
|
||
of the cache's own memory, not the runtime's shadows, which copy them
|
||
in before each command buffer's use; and its copies into the pages
|
||
take the surface's texels alone, each plane's rows, so its buffer
|
||
declares the bytes between a texture's rows unobserved, and a texture
|
||
whose rows lie with bytes between them may be an image over the
|
||
cache's memory too, where the runtime makes one (on an RTX 2080 it
|
||
makes none, for reasons of its own: `decode::surface_cache`). Where a
|
||
plane's rows lie at another pitch than the GPU's own linear images lay
|
||
them (CoreAnimation names its backing stores' rows at multiples of 64
|
||
bytes, and RADV lays its images' at 256), the host lays the cache's
|
||
planes out at the GPU's pitch instead, each texture over a plane at
|
||
the same byte of the same row there, and the cache's copies move each
|
||
row between its place in the pages and its place in the cache
|
||
(`decode::surface_cache`, "Laid out at the GPU's pitch"). A texture
|
||
over the surface that does not lie in its plane's texels there (wider
|
||
than the plane's row, or taller, which Metal makes inside the
|
||
surface's rows) lies over the block's wide home at the surface's own
|
||
place and pitch: over its view of the pages where it has one, else a
|
||
stand-in of their layout; each encoder that writes through either side
|
||
is followed in its command buffer by a copy of its texel rows into the
|
||
other (`decode::surface_cache`, "Wider than the plane";
|
||
dgpu-oracle.md Q37). The
|
||
answer is that of a message with no layout. Each
|
||
command buffer names the cached surfaces it uses
|
||
(`RGFX_OP_SURFACE_USE`) with the kext's count of the surface's
|
||
read-write locks when it was committed; the host fills the cache from
|
||
the pages before the first buffer of a newer count, on its own transfer
|
||
queue, after every buffer that used the cache before. A new cache is
|
||
made as zeros and owes its first fill from the pages, as of the count in
|
||
the block's header then, which the first thing that reads it makes: a
|
||
named use, a present, a buffer of render, compute or blit work in the
|
||
process that made the block's first buffer, and a buffer over the block
|
||
in any other, so a texture that a buffer reaches through an argument
|
||
buffer with no `useResource:` (which no `RGFX_OP_SURFACE_USE` names)
|
||
reads the pages. A buffer of decodes alone that writes the whole of both
|
||
planes of a new two-plane 4:2:0 surface (a decoder's new output) takes
|
||
the fill as met instead: its picture lands over the zeros, and the
|
||
cache's copies into the pages copy those planes' rows alone from then
|
||
on, so the pages' other bytes (CoreVideo's header) stay as the CPU wrote
|
||
them; a decode that answers no picture makes the fill. A block named
|
||
again over the same pages is filled again, as of the count then. The pages
|
||
are written from the cache only at `SURFACE_DOWNLOAD`, which the kext asks
|
||
at a CPU lock that follows a GPU write, and at the block's
|
||
`BLOCK_RELEASE`, and only where a buffer that may write the surface was
|
||
committed since the last copy (`reims-vgpu`'s
|
||
`graphics/decode/surface_cache.rs`). The one exception is a surface the
|
||
CPU reads back after each GPU write: once a download copied a write that
|
||
was the only one since the cache's last copy, the next command buffer
|
||
that is again the surface's only writer is followed by a copy of the
|
||
host's into the pages, which starts as the write ends, and the lock's
|
||
download is answered as that copy lands; a write no download followed
|
||
stops it. A writer that holds a video encoder has the copy on its own
|
||
queue; any other's goes on the host's read-back queue, waiting on the
|
||
GPU for the writer, so the writer's queue goes on behind it. A write the host's
|
||
own devices make into the pages (a video device's frame, in a CPU lend
|
||
or by a device of the host) moves no count: the host watches each
|
||
cache's pages, and such a write has the cache's next use fill it
|
||
whatever the count, and keeps a download or a release before that from
|
||
copying the cache over the write (`reims-vgpu`'s `device_writes.rs`).
|
||
Each choice, by what real GPUs show (M3, AMD and Intel Macs):
|
||
- *Contract, where all agree:* a CPU lock after a GPU write sees it,
|
||
and a GPU use after a read-write lock sees the CPU's writes; the
|
||
seed moves at a read-write lock (not at its unlock), not at a
|
||
read-only one, and by one at a GPU write's commit (the kext's).
|
||
- *Loose, where they diverge, the cheapest chosen:* a CPU write without
|
||
a read-write lock reaches the GPU only at the next fill, as on a GPU
|
||
of its own memory (the M3 sees it at once); a command buffer
|
||
committed before a CPU write and still running reads what it read,
|
||
since a fill waits for it; a buffer of an older count taken after a
|
||
fill of a newer one (two queues' buffers committed apart and taken in
|
||
the other order) reads the newer bytes; a download of a cache nothing
|
||
wrote since its last copy copies nothing; a decoder's new output whose
|
||
picture fails to land, or lands short of its planes, reads zeros where
|
||
the picture did not write, where the pages would give their bytes
|
||
(Metal leaves a failed decode's output undefined, and a new surface's
|
||
texels are the kernel's zero-filled pages unless its client wrote them
|
||
under a lock, which moves the count and has the decode's use fill the
|
||
cache); and a host whose GPU shares
|
||
the CPU's memory keeps a cache only of a surface whose textures
|
||
cannot lie in place over its pages (below), the rest in place as
|
||
above.
|
||
- *Which surfaces are cached:* the guest's choice, and the host's
|
||
invalidation. The bundle asks every block in place cached, of any
|
||
planes and format, as a GPU of its own memory keeps a copy of each
|
||
surface it uses: the windows, layers and drawables the guest's
|
||
compositors and apps draw, and video frames, which the GPU writes as
|
||
a decode's output or a conversion's destination. Measured on the RTX
|
||
5080: VideoToolbox's 10-to-8-bit conversion of a 1080p frame into a
|
||
420v surface not cached takes 4.8 ms of the GPU, its writes crossing
|
||
the bus into the pages. The outputs of the bundle's own video driver
|
||
ask no cache where the host lands no picture in one (no
|
||
`RGFX_VIDEO_CAPS_OUTPUT_CACHED`, item 16), its decode writing their
|
||
pages: their textures ask under `RgfxAskUncachedScope`. A host
|
||
whose hardware video lands pictures in device caches says the flag
|
||
wherever the kext makes them, on a GPU of its own memory
|
||
(`SURFACE_CACHE`) or one that shares the CPU's
|
||
(`SURFACE_CACHE_REFUSED`), where the outputs then ask with their
|
||
layout as any other surface does. Correctness
|
||
does not rest on that choice:
|
||
a surface a host-side device writes (the M2 scaler, the VideoToolbox
|
||
decoder) may be cached all the same, and the host invalidates the
|
||
cache of a block whose pages such a device wrote, so the next
|
||
`SURFACE_USE` fills it from the pages and a download copies nothing.
|
||
The device says `RGFX_FEATURE_SURFACE_CACHE` only with that
|
||
invalidation in place.
|
||
- *The guest's side:* the kext makes a cached block's IOSurface device
|
||
cache with the block, and its control function, at op 2 of a CPU
|
||
lock once the GPU's writes are done, asks `SURFACE_DOWNLOAD` where
|
||
the GPU wrote the surface since the pages last took the cache, and
|
||
waits for the answer, one lock of a surface asking at a time. A
|
||
read-write lock then moves the surface's CPU generation, the count
|
||
the kext writes into the block's header for the processes. IOSurface
|
||
calls op 2 at every read-write lock of a surface with a device cache,
|
||
current or not, and at a read-only lock only where a GPU write made
|
||
the cache current (`RgfxIOSurfaceKPI.hpp`), so the count misses no
|
||
read-write lock and a read-only lock after a GPU write downloads.
|
||
Once the block's last holder lets it go, the block sleeps rather
|
||
than going: dormant, it keeps the host's cache, its generation and
|
||
its watch of device writes, the kext keeping the surface and its
|
||
device cache retained and the surface's memory wired, so its
|
||
IOSurfaceID and its cache are no other surface's meanwhile. The next
|
||
ask of the surface, which IOSurface answers with the same device
|
||
cache, holds the block again (`BLOCK_SHARE` with no `SURFACE_PAGES`),
|
||
and the cache is used again rather than made and filled anew, as a
|
||
GPU of its own memory keeps a surface's copy past the textures over
|
||
it: in a window drag 98% of the blocks asked were such a surface's,
|
||
most back within 100 ms. A dormant block is let go on the release
|
||
thread, never in IOSurface's call: at op 5 (a client of the surface
|
||
going, or the surface made nonvolatile after empty); at op 7 to
|
||
empty, and a surface made empty while held does not sleep; at its
|
||
sleep where the surface has no client left, its last gone while the
|
||
block was held (IOSurface's client count, read once there); past
|
||
1024 dormant blocks or an eighth of the guest's memory in their
|
||
surfaces' wired bytes, and where the table or the region has no room
|
||
for a new block, those of surfaces made volatile first (IOSurfaceRef.h
|
||
lets a volatile surface's contents go), then the oldest; and where an
|
||
ask of the pages names another cache or the other mode. Made
|
||
nonvolatile again (op 6, or op 7), a surface is neither volatile nor
|
||
empty for this. A let-go block's `BLOCK_RELEASE` copies the cache
|
||
into the pages where a buffer wrote it since the last copy, and a
|
||
lock waits for the answer; the kext releases the device cache, then
|
||
the surface, then unwires the memory. Where the surface has no
|
||
client left as the release is posted, the release says so
|
||
(`RGFX_BLOCK_RELEASE_NO_CLIENT`), and the host copies all the same,
|
||
counting it: a mach port or an XPC object holds a surface with no
|
||
client, and a process that looks the surface up from one reads its
|
||
pages (a Dock icon showed another app's icon, the bytes its pages
|
||
held before the GPU drew it, while the host dropped such a cache
|
||
uncopied). The kext logs the dormant
|
||
blocks' count and the let-gos by cause. Op 6, which IOSurface calls
|
||
as a surface turns nonvolatile again, is answered as the AMD's driver
|
||
does (a byte set to 0xff), so IOSurface answers the old state
|
||
volatile, after volatile and after empty alike, the contents kept,
|
||
which IOSurfaceRef.h's old states allow. A present of a cached
|
||
surface carries its generation. In the
|
||
bundle, a commit names each cached surface its buffer binds,
|
||
attaches, blits or declares it uses, with the generation the header
|
||
holds and whether the buffer writes it, before the first encoder;
|
||
and a texture's own CPU access (`getBytes`, `replaceRegion`) locks
|
||
the surface as a CPU access does (`guest/kext/src/RgfxSurfaceCaches.hpp`,
|
||
`guest/bundle/src/RgfxIOSurface.h`).
|
||
- *Deferred pages:* a fresh surface only the GPU touches has no guest
|
||
pages until a CPU lock needs them, as on a GPU of its own memory (the
|
||
AMD 5300M's footprint grew 0 KiB from a 3840x2054 surface's first GPU
|
||
use). Where the kext took `RGFX_FEATURE_SURFACE_DEFERRED`, and no
|
||
IOSurface mapper device (`IOSurfaceParavirtMapperService`) is matched,
|
||
a cacheable ask in place of a surface that reads fresh (its seed 0,
|
||
none of its pages resident, compressed or paged out) defers its
|
||
block: the kext makes the device cache and sets its control function
|
||
first, then reads the seed and the pages' counts under a read-only
|
||
`lockSurface`, which waits out any lock calling the control
|
||
functions, so a read-write lock either moved the seed before the read
|
||
or calls the control function after it (`RgfxIOSurfaceKPI.hpp`). A
|
||
page a writer that takes no lock dirtied is resident, or, compressed
|
||
or paged out since, counted so, and holds bytes the cache's zeros
|
||
would lose. The kext counts only a surface whose memory is a buffer
|
||
the kernel allocated (`IOBufferMemoryDescriptor`, anonymous memory,
|
||
never a client's own, which may be a file's). It counts them on every
|
||
kernel the same way: it maps the memory read-only into the kernel's
|
||
map for the count (IOKit puts a pageable buffer's kernel mapping
|
||
inside one of its pageable maps, a submap of the kernel's, which the
|
||
kext finds through `IOIteratePageableMaps`), and `mach_vm_region`'s
|
||
`VM_REGION_EXTENDED_INFO` walks the mapping's regions, which count
|
||
each page resident or compressed or paged out (`pages_swapped_out`;
|
||
**measured** on 11.7.11 against each page's disposition, with the
|
||
pages in the compressor and on swap). `mach_vm_region` and
|
||
`kernel_map` are strong imports from `com.apple.kpi.unsupported`,
|
||
which every release kernel checked exports (x86-64 11.7.10 to 26.7.2,
|
||
arm64 13 to 26). The regions must be the mapping exactly, none a
|
||
pager's: a region past it, a gap, or one with nothing to count
|
||
refuses the count. A surface not counted is never fresh, so its
|
||
block's pages are named at its ask
|
||
(`guest/kext/src/RgfxAcceleratorLocks.cpp`). Found fresh, its `SURFACE_PAGES`
|
||
carries `DEFERRED` and no runs, the block keeping room for one run a
|
||
page of the whole allocation, every plane's; the host makes the cache
|
||
as zeros. Not fresh, or refused, the kext names the pages at once, as
|
||
for any block. A surface no CPU lock touched may still have a few
|
||
pages resident, written by a process that takes no lock:
|
||
**measured** on the 780M, VTDecoderXPCService writes page 0 of each
|
||
new decoder output before the first decode (all 208 of a 4K HEVC
|
||
session's in Safari, macOS 26, the other pages never resident), so a
|
||
test of no page resident named each one's 12 MiB at once, wired and
|
||
filled with zeros (5 to 7 ms of the guest's each). Where the kext
|
||
took `RGFX_FEATURE_SURFACE_DEFERRED_CARRY`, the bundle's cacheable
|
||
ask lists after the layout the surface's resident pages it finds in
|
||
its mapping (`mach_vm_page_range_query`), 16 at most, and the kext
|
||
defers a surface fresh but for them: under the same read, the fresh
|
||
test's own verdict on its counts with as many pages resident as listed
|
||
and none compressed or paged out (so where nothing is counted nothing
|
||
is carried), the listed runs wired with `kIODirectionPrepareNoFault`,
|
||
and the counts read again after the wire the same, so a listed page
|
||
not resident either fails the wire or, faulted in, raises the count,
|
||
and a page written or compressed meanwhile shows too (**measured** on
|
||
a macOS 26.7.2 guest: such a wire fails, `kIOReturnNoResources`,
|
||
faulting nothing in; `guest/kext/src/RgfxDeferCarry.hpp`). Its
|
||
`SURFACE_PAGES` then carries `DEFERRED` with runs: the surface's bytes
|
||
in order, each carried page at its guest address, every other run
|
||
`RGFX_PAGE_RUN_ZEROS`. The host makes the cache of zeros and copies
|
||
the carried pages into it as a new cache's first fill, after the
|
||
zeros: before what reads the cache next, or never where a decode
|
||
writes the planes whole first. The kext keeps the carried pages wired
|
||
until the block's pages are named or its release is answered, and
|
||
lets them go at a refusal; any other read, a wire refused or a page
|
||
faulted in names the pages at once, as before. A deferred block is
|
||
found by its surface, never by
|
||
pages, and its holders wire none. Its first read-write lock, or a
|
||
read-only one after a GPU write, wires the pages and names them
|
||
(`ATTACH`) before it goes on, one lock at a time, under no lock of the
|
||
contexts'; a read-only lock of a surface the GPU never wrote names
|
||
none, a fresh page reading as the zeros the cache holds. A dormant
|
||
deferred block stays at a client's going (op 5) while others are
|
||
left. Its release names its pages first where the GPU wrote it and
|
||
the surface is retained past the kext's own three references (the
|
||
table's, the device cache's, and the release thread's), so the
|
||
release copies the cache into them; else nothing reads them. Deferred
|
||
blocks fit the host's budget (`DEFERRED_BUDGET_LO` and `_HI`), held
|
||
and dormant, and dormant ones are let go past half of it, the oldest
|
||
first (`guest/kext/src/RgfxSurfaceBlocks.hpp`).
|
||
- **Device caches on a GPU that shares the CPU's memory:** there a
|
||
surface's textures use its pages in place, but not every surface's
|
||
can. The runtime makes a texture over pages it cannot place one over
|
||
(rows that end inside the line of memory the GPU writes back whole, on
|
||
an Intel GPU; more pieces than one dma-buf takes, on RADV) its own copy,
|
||
a shadow, which every command buffer copies in before its first use
|
||
and merges back after a write. Such a surface takes a device cache
|
||
instead, copied only at CPU locks and unlocks, as on a GPU of its own
|
||
memory: IOSurface's own protocol, with no tracking of its own, while
|
||
every other surface stays in place. The host offers
|
||
`RGFX_FEATURE_SURFACE_CACHE_REFUSED` and not `SURFACE_CACHE`, and
|
||
decides surface by surface: the kext asks at a new cacheable block in
|
||
place (`RGFX_SURFACE_PAGES_ASK_CACHE`), with the surface's planes as
|
||
the bundle gives them (each plane's offset, rows, row pitch and the
|
||
bytes of a row's texels), and the host maps the pages and asks its
|
||
platform whether textures over them, for any access (a read, a render,
|
||
a shader's write), lie in place (`GpuDevice::surface_pages_in_place`;
|
||
the Vulkan platform's `gpu/pages_in_place.rs`, which asks the runtime
|
||
where a texture over each plane lies, as its making decides: the
|
||
device's check of the pages, the rows' pitch and place, the texels'
|
||
reach). Where they do, where the runtime's verdict is not known yet,
|
||
or where a texture over a cache would be the runtime's copy too, it
|
||
answers OK, the block in place. Where they do not, it answers
|
||
`RGFX_STATUS_CACHE`, its view of
|
||
the pages left in its cache of views, and the kext makes the surface's
|
||
device cache and posts the block again cached, which takes that view
|
||
and the host's cache, kept from then on as above. It answers
|
||
`RGFX_STATUS_CACHE` too, with no view made, where the platform has no
|
||
room for the view's kernel mappings (`HostVm::view_room`; on Linux the
|
||
views' budget short of its headroom, which Intel's ANV, importing a
|
||
view's pages only mapped from their files, reaches at a stock
|
||
`vm.max_map_count`): past that room the view's buffers would be copied
|
||
rather than imported. Such a cache's copies
|
||
into the pages copy the surface's texels alone, each plane's rows from
|
||
the layout the ask gave, so the bytes between rows stay as the guest's
|
||
CPU wrote them, whatever a render over the cache leaves in its own
|
||
(`decode/surface_cache.rs`, "Download"). So the cache's buffer
|
||
declares the bytes between a texture's rows unobserved
|
||
(`GpuDevice::new_buffer_of_length_padding_unobserved`; metal2vulkan's
|
||
`BufferDescriptor::padding_unobserved`), and a texture over it whose
|
||
rows lie with bytes between them, the desktop's among them, is an
|
||
image over the cache's own memory that holds them, not another copy
|
||
of the texels. A block asked with no
|
||
layout (an older bundle's) stays in place, as every block of such a
|
||
host did before (`reims-vgpu`'s `graphics/decode/surface_pages.rs`,
|
||
"Device caches where the pages cannot serve").
|
||
Such a surface's pages are the CPU's copy alone, so where it is fresh
|
||
they wait for a CPU lock that needs them, as *Deferred pages* above
|
||
has them on a GPU of its own memory. The host offers
|
||
`RGFX_FEATURE_SURFACE_DEFERRED_ASK` beside `SURFACE_CACHE_REFUSED`,
|
||
with a budget as `SURFACE_DEFERRED`'s, and the kext's deferral then
|
||
asks with the surface's layout (`DEFERRED` with `ASK_CACHE` and no
|
||
runs). The host defers the block only where textures over the layout
|
||
would lie in place over no import of any pages the surface may come
|
||
to have (`GpuDevice::fresh_surface_never_in_place`, the runtime's
|
||
answer before any import of the pages, which makes no image): rows
|
||
that end inside the GPU's lines, which no pages change, or, on RADV, a
|
||
plane of more pages than one dma-buf takes pieces, each counted a piece
|
||
of its own, as a fresh surface's come (**measured** on the 780M: Safari's
|
||
WebKit tiles of 1,824 pages came in 1,379 to 1,824 runs). It refuses
|
||
every other with nothing made, as it refuses one past its budget, and
|
||
the kext then names the block's pages asking as above: answered a
|
||
cache, it posts them again cached; answered OK, the surface is not
|
||
cached, and the device cache's entry the deferral made goes. So no
|
||
surface whose pages could serve in place takes a cache for being
|
||
deferred, and a full budget leaves a surface as it was without the
|
||
feature. A deferred block is the deferred block above from then on:
|
||
its pages wired, named (`ATTACH`) and copied into the cache only at a
|
||
CPU lock that needs them. Before it, Safari's WebKit tiles, which the
|
||
GPU alone draws, wired each its 7 MiB of the guest's memory at its
|
||
first use, with the host copying the zeros into the cache, and the
|
||
wired pages counted in the owner's footprint though WebKit marked the
|
||
tiles volatile: about 400 of them took a WebContent past its 2 GB
|
||
footprint limit (**measured** on the 780M and the Iris, an 8 GiB
|
||
macOS 26.7.2 guest scrolling a long page), whose corpse and memory
|
||
pressure stalled it for 100 to 800 ms.
|
||
The guest lays its surfaces' rows out as the GPU's images take them
|
||
in place: where the host's GPU aligns a linear image's rows to more
|
||
than IOSurface's 64 bytes (256 on RADV), the host says so in the
|
||
device info's `linear_row_alignment`, and the kext has IOSurface align
|
||
the bytes per row and the plane offsets it works out for a surface to
|
||
it, at the accelerator's start, as a GPU's accelerator does
|
||
(`IOSurfaceRoot::updateLimits`; `guest/kext/src/RgfxSurfaceRows.hpp`),
|
||
since the GPU's linear image of a plane starts at such an offset too.
|
||
IOSurfaceGetPropertyAlignment answers both to the processes that work
|
||
out their own. A client that places its planes or rows itself keeps
|
||
them (CoreVideo's first plane 32 bytes into its surface, its rows at
|
||
its own alignment, measured in a macOS 26.7.2 guest whose IOSurface
|
||
answered 256): a device cache of the surface places that plane where
|
||
the GPU's images may start (above), and a texture over it in the
|
||
pages that the GPU's linear images cannot hold is the runtime's
|
||
shadow. Macs answer 64 bytes there (Intel) and 128 (the M3),
|
||
and an Intel Mac's GPUs answer 256 for
|
||
`minimumLinearTextureAlignmentForPixelFormat:`, so rows at 256 bytes
|
||
lie inside what Macs do. A host whose GPU has memory of its own
|
||
answers its GPU's alignment as well (the runtime's
|
||
`minimumLinearTextureAlignmentForPixelFormat:` of BGRA8: 256 on RADV,
|
||
discrete or not, and 128 on the RTX 3090 and RTX 2080, docs/lessons.md):
|
||
a texture over a surface's pages takes the GPU's own linear image
|
||
there only where its rows lie at the GPU's pitch, and otherwise is the
|
||
runtime's shadow; a device cache of a surface whose layout the kext
|
||
gives lays the planes' rows at the GPU's pitch (*The device cache*,
|
||
above), so a texture over it takes the GPU's image whatever the
|
||
surface's pitch.
|
||
At the same start the kext lowers the largest surface IOSurface
|
||
answers to `IOSurfaceGetPropertyMaximum`, as a Mac's GPU accelerators
|
||
do: as wide and as tall as the device's 2D textures (the device
|
||
info's `max_texture_width_2d` and `max_texture_height_2d`, which the
|
||
bundle answers to Metal: 16384 on our device), and 16 bytes a pixel
|
||
of that width a row, the largest pixel a texture over a surface has
|
||
(`guest/kext/src/RgfxSurfaceLimits.hpp`). Macs answer 16384 wide and
|
||
tall (the Intel and AMD Mac with 131072 bytes a row, the M3 with
|
||
32768). Left at IOSurface's own INT_MAX, Safari 16.6 under macOS 13
|
||
drew no tiles of a page that scrolls only vertically at 1x
|
||
(**measured**, 13.7.8; docs/lessons.md).
|
||
- **Measured, 2026-11-13: surfaces in place first on a GPU of its own
|
||
memory.** A host whose GPU has memory of its own caches every surface
|
||
(*The device cache*, above). The unlanded branch `steelbrain/routeb`
|
||
has such a host offer what a GPU that shares the CPU's memory offers
|
||
(`SURFACE_CACHE_REFUSED`, `SURFACE_DEFERRED_ASK` and
|
||
`SURFACE_DEFERRED_CARRY`, never `SURFACE_CACHE` or
|
||
`SURFACE_DEFERRED`), so every surface lies in place first and takes a
|
||
device cache only where its pages cannot serve (*Device caches on a
|
||
GPU that shares the CPU's memory*, above). One walk per GPU, the same
|
||
in each run: the desktop, Finder, Launchpad, Mission Control, Safari
|
||
(a page's scroll and autoscroll, WebGL, a GL 3D page, a video) and
|
||
Maps. Each GPU ran it on development at b615cec64 and on the branch
|
||
over the same base, and the runs counted the compositor's presents,
|
||
the GPU's busy time per present, and the bytes on the GPU's link
|
||
(`nvidia-smi dmon`). In place first laid 3800 to 6900 textures in
|
||
place where the base laid 240 to 590, and on the NVIDIA GPUs the link
|
||
then carried 100 to 560 MB a present where the base's carried 1 to
|
||
44 MB: the GPU reads the layers it composites from guest RAM at each
|
||
present, changed or not.
|
||
- RTX 5080 (laptop, PCIe 5.0 x16): presents 6839 to 6415 (-6%), GPU
|
||
time 2.6 to 7.8 ms a present. Safari's scroll fell from 636
|
||
presents to 543, its longest gaps (p99) from 92 to 309 ms. The link
|
||
carried 130 MB/s to 6.6 GB/s over the walk, 16 GB/s at Launchpad.
|
||
- RX 7900 XTX (PCIe 4.0 x16): level, 5468 presents to 5503, 3.4 to
|
||
3.8 ms a present; the GL 3D page's GPU time 2.0 to 4.5 ms a present.
|
||
Its link's bytes were not read: amdgpu gives this GPU no `pcie_bw`.
|
||
- RTX 3090 (PCIe 3.0, the link trained at x4): presents 4818 to 1236
|
||
(-74%), GPU time 19.9 to 109 ms a present, and a present shown
|
||
3.5 to 110 ms (median) after its take. Launchpad fell from 197
|
||
presents to 30 with 559 MB a present at 2.1 GB/s, Mission Control
|
||
from 602 to 203 with the GPU 99% busy, Safari's scroll from 369 to
|
||
90 with its longest gaps (p99) from 0.4 to 6.3 s.
|
||
- RTX 2080 (Thunderbolt 3), the steps up to the GL 3D page: the GPU
|
||
fell off its bus (Xid 79) in the in-place run's video step, as it
|
||
had once before that day with neither run going. Launchpad fell
|
||
from 219 presents to 30 with 429 MB a present at 1.6 GB/s, Mission
|
||
Control from 607 to 200 with the GPU 99% busy, Safari's scroll from
|
||
374 to 91 with its longest gaps (p99) from 0.6 to 6.4 s, the GL 3D
|
||
page from 498 to 56; a present was shown 3.5 to 84 ms (median)
|
||
after its take.
|
||
The cost is the reads, and the link sets how much it is. At 16 GB/s
|
||
(the 5080) the GPU's time per present triples and the presents fall
|
||
6%; at the x4 links' 1.6 to 2.4 GB/s the GPU waits on them, and the
|
||
steps' presents fall three- to ninefold. The path's other work did
|
||
not grow: the runtime's first copies into its shadows over host pages
|
||
fell (10.1 to 9.8 GB on the XTX, 2.8 to 2.7 GB on the 5080, 1.7 to
|
||
0.4 GB on the 3090). On the XTX, in place first also took the
|
||
runtime's shadows off most of the video's frames: in the walk's 57 s
|
||
of 1080p video the runtime copied 74.0 million texels into shadow
|
||
images with every surface cached and 1.6 million in place first
|
||
(shadow copies 2230 to 977), the decoder's NV12 frames taking device
|
||
caches through the ask, whose textures are images over the caches'
|
||
own memory. A host whose GPU has memory of its own keeps caching
|
||
every surface until a cache can follow measured use (below).
|
||
- **Proposed, not built: in place first, caches by measured use.** In
|
||
place first (above) keeps a surface in place for its whole life, so
|
||
the GPU reads every layer it composites across its link at each
|
||
present. The proposal keeps every surface in place first and gives
|
||
one a device cache only once the guest's own use shows it re-read
|
||
unchanged, from guest behaviour alone, never from a table of hosts or
|
||
drivers:
|
||
- *Counting, on the host.* For each block in place, the decoder counts
|
||
the command buffers that read the surface (a texture over it
|
||
sampled or read, a blit from it, a render pass that loads it) since
|
||
its last write. A write is a command that writes it (a render
|
||
pass's store, a shader's write, a blit into it), or a CPU write by
|
||
the guest. The host sees a CPU write as the surface's CPU generation
|
||
moving in the block's header (`surface_cache::cpu_generation`), the
|
||
count the kext moves at each read-write lock in its op 2. IOSurface
|
||
calls op 2 only for a surface with a device cache, and a block in
|
||
place has none today, so the proposal gives each block in place a
|
||
device cache that copies nothing, for op 2's count alone. Whether
|
||
such a cache changes IOSurface's lock path in any other way is to
|
||
be checked (`RgfxIOSurfaceKPI.hpp`). A block read by N command
|
||
buffers with no write between them is promoted. N is measured, not
|
||
guessed: from the walks' counts of reads between writes per
|
||
surface, the least N at which the copy a promotion costs (the
|
||
surface's bytes across the link once, and back once at the next CPU
|
||
lock where the GPU wrote it) is below the reads it saves.
|
||
- *The step.* The host posts the kext a notice naming the block. The
|
||
kext names the block again, cached (`SURFACE_PAGES` with
|
||
`RGFX_SURFACE_PAGES_CACHED`, the naming a block takes today only
|
||
before any process holds it), once no submitted command buffer
|
||
holds it, and makes the surface's IOSurface device cache with it.
|
||
The host fills the cache from the pages and moves every buffer and
|
||
texture over the block onto it. From then on the block is a cached
|
||
block as any other: its command buffers name it in `SURFACE_USE`,
|
||
and its locks download as a cached block's do. A surface written by
|
||
the guest's CPU, or written between its reads, never leaves its
|
||
pages. Whether IOSurface takes a device cache for a surface that is
|
||
already in use is the first thing to check (`RgfxIOSurfaceKPI.hpp`).
|
||
- *The reverse.* A CPU write ends a promotion. IOSurface calls the
|
||
kext's op 2 at every read-write lock of a surface with a device
|
||
cache. There the kext asks `SURFACE_DOWNLOAD` where the GPU wrote
|
||
the surface since the pages last took the cache, as it does today,
|
||
and then names the block in place again. The host moves the block's
|
||
buffers and textures back over the pages, which by then hold every
|
||
GPU write, and lets the cache go once the command buffers that use
|
||
it finish. The CPU then writes the pages, and the block's count
|
||
starts over. A read-only lock leaves the promotion as it is.
|
||
- *The contract.* Every value that reached the guest stays: object
|
||
ids, GPU addresses, resource ids, and every texture's contents and
|
||
layout. CPU locks wait as they do now. The notice is a new event
|
||
behind a new `FEATURES` bit: a host whose GPU has memory of its own
|
||
offers in place first only with it, and a kext without it keeps
|
||
every surface cached, as now. Where the host can't promote (no room
|
||
in the GPU's memory, a texture the GPU can't place there) the block
|
||
stays in place: the fallback is at the refusal, on every driver.
|
||
- *What it needs.* The host can't move live objects today: each
|
||
`BUFFER_OVER_SURFACE_PAGES` buffer is made over either the view or
|
||
the cache when it is created (`decode::surface_pages`), and
|
||
metal2vulkan's runtime rebinds a no-copy buffer only to other host
|
||
pages (`Buffer::detach_backing`, `rebind_bytes_no_copy`). It needs
|
||
the runtime to move a no-copy buffer, and the textures over it,
|
||
into device memory at the same GPU address and back (asked of
|
||
metal2vulkan 2026-11-13), then the event, the kext's naming, the
|
||
host's counting, and the offer of in place first from
|
||
`steelbrain/routeb`.
|
||
- **Measured, 2026-11-13: what crosses a GPU's link at each present
|
||
with every surface cached.** On development at 459e76e6a, the walk
|
||
above, the link of a GPU whose compositor runs on another GPU
|
||
carries the window's presents, and little else:
|
||
- RTX 3090 on PCIe 3.0 x4, its host's one screen (3840 x 2160, scale
|
||
2.1) on a Radeon 780M, which KWin composites on: the window's
|
||
swapchain (3648 x 2039) handed KWin four LINEAR XRGB8888 buffers
|
||
of 29.75 MB, and each of its 4010 presents moved one across the
|
||
link, 0.93 to each of the guest's 4324. nvidia-smi counted 34.8 MB
|
||
from the GPU a window present and 2.3 MB to it a guest present,
|
||
and the GPU was busy 20.2 ms a present (Mission Control: 43 window
|
||
presents a second, the GPU 96% busy, in P2).
|
||
- RTX 5080 Laptop GPU, which drives its panel: the window's buffers
|
||
are the GPU's own tiled images, and nothing crosses: 5985 window
|
||
presents to 5984 of the guest's, 0.8 MB from the GPU and 1.4 MB
|
||
to it a present, the GPU busy 2.8 ms a present.
|
||
- On the host of the RX 7900 XTX and the RTX 2080 the screen is the
|
||
XTX's: the XTX's presents cross nothing, and the 2080's cross its
|
||
Thunderbolt link (28.4 MB from the GPU a present, the base runs
|
||
above).
|
||
- The link is the limit, not the GPU's engines. The 3090's carries
|
||
1.83 GB/s from the GPU to the host: a 3648 x 2060 image (30.1 MB)
|
||
copied into host memory takes 16.4 ms from its graphics family,
|
||
its compute family and its family of transfers alone alike, and
|
||
a bare swapchain of that size presenting a cleared image to the
|
||
780M's compositor reaches 61 presents a second, 1.84 GB/s. Only
|
||
the graphics family presents to the window's surface. Smaller
|
||
copies keep the rate: 16 regions of 256 x 256 (4.2 MB) in 2.4 ms,
|
||
64 of 64 x 64 (1.05 MB) in 0.63 to 0.69 ms.
|
||
- The compositor's GPU does its part fast: the 780M copies a 30.1 MB
|
||
image from host memory in 1.25 to 1.44 ms, and presents a cleared
|
||
image of the window's size 4656 times a second.
|
||
- **Built: the window shown by the compositor's GPU.**
|
||
Where the compositor runs on another GPU, the window's swapchain is
|
||
made on that GPU, whose buffers are its own, and only what changed of
|
||
each frame crosses the runtime's GPU's link. Two routes were weighed.
|
||
Route 2 was measured and rejected (below); route 1 is built:
|
||
- *Which device, either route.* The GPU the compositor composites on
|
||
is the main device of the window's surface's dma-buf feedback
|
||
(`zwp_linux_dmabuf_feedback_v1`), matched to a physical device by
|
||
its DRM nodes (`VK_EXT_physical_device_drm`). Where it is the
|
||
runtime's own GPU, the window stays as it is. Otherwise the window
|
||
makes a second `VkDevice` there (one graphics queue,
|
||
`VK_KHR_swapchain`, `VK_EXT_external_memory_host`), apart from the
|
||
runtime's, and its swapchain over the window's surface.
|
||
- *Route 1, built: a mirror of the changed tiles* (reims-vgpu's
|
||
`graphics::mirror`). The window's mirror is a frame-sized buffer
|
||
of host memory of its own. The runtime's device and the window's
|
||
device each make a buffer over it. At each draw of a presented
|
||
surface on the compositor's GPU:
|
||
- The runtime's GPU copies the presented texture into a buffer of
|
||
its own memory, as rows of the mirror's pitch.
|
||
- It compares that copy with the frame it sent last, in 64 x 64
|
||
tiles (`displayMirrorTile`, the display's shaders). It copies
|
||
each tile that differs into the mirror, and a tile that changed
|
||
nothing crosses no link. The copy then stands for the frame sent.
|
||
A mirror made again (its first sync, a frame of another format
|
||
or size) sends every tile.
|
||
- The compositor's GPU draws from a linear texture over its import
|
||
of the mirror, through the draw the runtime's device would make:
|
||
the same bytes, so the same pixels.
|
||
- The compositor's GPU waits for the sync. The sync's command
|
||
buffer exports its completion as a sync file (metal2vulkan's
|
||
`add_completion_sync_file`), which the draw that reads the
|
||
mirror imports and waits for before its work, so the window's
|
||
thread waits for no GPU work of the sync's. The next sync waits
|
||
on the host for that draw and for the sync before it. Where the
|
||
runtime exports no sync file (MoltenVK), the sync finished
|
||
before the export looked, or the compositor's device imports
|
||
none, the window's thread waits for the sync before it encodes
|
||
the draw.
|
||
- It touches the window's path alone: no guest, kext or placement
|
||
change. Its fallback, at each refusal on every driver, is the
|
||
window's present from the runtime's GPU, as before: no feedback,
|
||
the runtime's own GPU, no second device or swapchain, a surface
|
||
the mirror does not carry (not 4 or 8 bytes a pixel), or a
|
||
mirror, sync, import or texture refused.
|
||
- *Measured 2026-11-13: route 1 against today.* The walk above on
|
||
um870's RTX 3090, whose compositor composites on its Radeon 780M,
|
||
with every GPU's driver listed to QEMU and the 3090 picked: route
|
||
1 (`steelbrain/x4route`) against development at fe56cae17, on the
|
||
same runtime, both mostly in P2. For each guest present: the
|
||
megabytes the 3090's link carried from and to the GPU
|
||
(nvidia-smi), the window's presents, the 3090's busy time, and
|
||
the time from a present's take to its show (median / 99th
|
||
percentile):
|
||
|
||
| step | build | link MB, from / to the GPU | window presents | busy ms | take to show, ms |
|
||
|---|---|---|---|---|---|
|
||
| Mission Control | today | 28.3 / 2.2 | 0.92 | 20.1 | 2.2 / 55.5 |
|
||
| | route 1 | 1.2 / 2.7 | 1.00 | 6.7 | 14.4 / 45.7 |
|
||
| autoscroll | today | 28.7 / 0.3 | 0.88 | 17.0 | 5.1 / 15.0 |
|
||
| | route 1 | 9.9 / 0.6 | 1.00 | 8.9 | 3.3 / 7.1 |
|
||
| GL 3D | today | 23.8 / 0.4 | 0.84 | 17.0 | 5.7 / 8.4 |
|
||
| | route 1 | 16.6 / 0.3 | 1.00 | 12.9 | 3.6 / 4.3 |
|
||
| the walk | today | 31.2 / 2.0 | 0.93 | 21.0 | |
|
||
| | route 1 | 6.1 / 2.5 | 1.00 | 9.5 | |
|
||
|
||
- The guest's presents a second held: 47.8 and 57.7 in Mission
|
||
Control, 45.7 and 45.0 in the autoscroll, 40.9 and 40.5 in GL
|
||
3D. The pages' own rates were 60, 59.8 and 60 both times.
|
||
- The window presents every guest present.
|
||
- Ordered on the CPU, as route 1 was first built, each sync
|
||
cost the render thread a wait for the 3090's copy of the
|
||
changed tiles over its link: 1.6 ms a present in Mission
|
||
Control (1.0 MB of tiles at most), 7.3 ms in the autoscroll
|
||
(11.8 MB) and 10.8 ms in GL 3D (18.5 MB). The guest does not
|
||
wait for it.
|
||
- Mission Control's median from take to show rose from 2.2 to
|
||
14.4 ms, while its mean fell from 18.2 to 10.0 ms. Its presents
|
||
fall in two groups: those whose writers had finished by their
|
||
take, shown within 4 ms (55% of them, then 46%), and those whose
|
||
writers still ran, shown at a median of 39.1 ms, then 15.2 ms.
|
||
Route 1 makes the second group faster and, at 57.7 presents a
|
||
second against 47.8, larger, so the median moves from the first
|
||
group into the second. From take to answer, the mean fell from
|
||
29.1 to 23.3 ms (1.94 to 1.61 refreshes). The XTX, whose
|
||
compositor composites on the runtime's own GPU, shows the same
|
||
two groups: 37% within 4 ms, the rest at a median of 12.0 ms.
|
||
- The runtime's memory log shows the mirror's host pages
|
||
imported by their pointer on both devices.
|
||
- *Measured 2026-11-13: the sync waited for on the compositor's
|
||
GPU.* The same walk on metal2vulkan's pin 83, with each sync
|
||
waited for by the render thread (development at 36b382f9e) and
|
||
by the compositor's GPU (`steelbrain/x4route`), each after a walk
|
||
that filled the caches the pin left cold: um870's RTX 3090,
|
||
whose compositor composites on its Radeon 780M, and um790's
|
||
Radeon 780M, whose compositor composites on its RX 7900 XTX.
|
||
The render thread's wait for the syncs:
|
||
|
||
| runtime's GPU | sync waited for by | syncs | on the compositor's GPU | render thread's wait a sync |
|
||
|---|---|---|---|---|
|
||
| 3090 | the render thread | 6447 | 0 | 4.63 ms |
|
||
| | the compositor's GPU | 6416 | 6416 | 0.45 ms |
|
||
| 780M | the render thread | 6709 | 0 | 4.25 ms |
|
||
| | the compositor's GPU | 6746 | 6746 | 0.99 ms |
|
||
|
||
- On the 3090, by step: Mission Control 1.61 ms a sync, then
|
||
0.38 ms; the autoscroll 7.27, then 0.37 ms; GL 3D 10.79, then
|
||
0.34 ms.
|
||
- The runtime exported a sync file for each sync, none of them
|
||
after host copies (its work counts `sync_files_exported` and
|
||
`sync_files_after_host_copies`), and neither compositor's
|
||
device refused one.
|
||
- The guest's presents a second, the 3090's link and busy time,
|
||
and the times from take to show stayed as they were. On the
|
||
3090: 57.7 and 57.6 presents a second in Mission Control, 44.9
|
||
and 45.2 in the autoscroll, 40.3 and 40.6 in GL 3D. On the
|
||
780M: 59.7 and 59.1, 45.8 and 45.5, 37.3 and 36.6.
|
||
- Mission Control's take to show on the 3090, median / 99th
|
||
percentile: 14.7 / 59.1 ms in the walk that filled the caches,
|
||
14.2 / 48.6 ms with the render thread's wait, 14.1 / 52.4 ms
|
||
with the GPU's. Its two groups stayed as they were: 46% of the
|
||
presents within 4 ms, the rest at a median of 15.6, 15.1 and
|
||
15.1 ms. The render thread's wait did not hold the shows, and
|
||
the median above is where the two groups split.
|
||
- What the render thread still spends on a sync is its encoding,
|
||
commit and export, and its wait for the last draw and the sync
|
||
before it.
|
||
- *Route 2: the presented surfaces in place.* The surfaces the
|
||
display pipe presents lie in place in guest RAM (route B's
|
||
placement for them alone; every other surface keeps its device
|
||
cache), and the compositor's GPU imports their pages and copies
|
||
from them into its image. Nothing computes damage: the runtime's
|
||
GPU writes into guest RAM what the guest's composite draws,
|
||
through the runtime's shadow of the surface, whose copies in and
|
||
back cover only the rectangle a pass loads and writes inside its
|
||
draws' scissors (metal2vulkan's `shadow.rs` at 522a8245e2, read
|
||
from its code). The link carries the composite's passes over the
|
||
surface, its loads as well as its writes, and each of the
|
||
compositor's two or three surfaces catches up on the frames it was
|
||
not drawn in. It is in place: the runtime's GPU writes the guest's
|
||
pages, and the compositor's GPU reads them.
|
||
- It touches placement and the window: the kext names the
|
||
presented surfaces' blocks in place on a host whose GPU has
|
||
memory of its own (route B's offer, for those blocks alone), and
|
||
the window's second device imports the pages of the surface each
|
||
present shows. The window part is route 1's but the copy.
|
||
- Its fallback: a presented surface whose pages the compositor's
|
||
GPU cannot import, or no second device, keeps today's device
|
||
cache and the window's present from the runtime's GPU, at the
|
||
refusal, on every driver.
|
||
- *Route 2, measured 2026-11-13: rejected.* A prototype placed the
|
||
presented surfaces alone in place. The kext named WindowServer's
|
||
single-plane surfaces of the scanout's shape in place, not route B
|
||
wholesale. The window stayed as today. The build was
|
||
`steelbrain/x4route-proto` on development at 9cb5693ab. It ran
|
||
the walk above on the RTX 3090, against the same walk on
|
||
development at 459e76e6a, both mostly in P2. Megabytes a guest
|
||
present (route 2's are the prototype's, less today's 34.8 MB
|
||
window copy):
|
||
|
||
| step | today, from / to the GPU | route 2, from + to the GPU | what changed (below) |
|
||
|---|---|---|---|
|
||
| Finder | 48.3 / 4.4 | 54.8 + 304.6 | 2.7 |
|
||
| Apps | 34.5 / 5.0 | 99.6 + 257.1 | 0.65 |
|
||
| Mission Control | 30.2 / 2.0 | 28.6 + 63.6 | 1.6 |
|
||
| Safari's scroll | 41.6 / 4.9 | 132.7 + 107.5 | 6.1 |
|
||
| autoscroll | 26.2 / 0.3 | 91.9 + 93.3 | 12.1 |
|
||
| the WebGL page | 34.6 / 0.1 | 9.4 + 37.4 | 0.3 |
|
||
| GL 3D | 23.9 / 0.4 | 93.2 + 66.0 | 18.2 |
|
||
| video | 31.0 / 0.8 | 122.3 + 44.3 | 6.2 |
|
||
| Maps | 31.1 / 11.3 | 77.0 + 203.6 | 1.6 |
|
||
| the walk | 30.8 / 2.2 | 90.5 + 78.8 | 6.27 |
|
||
|
||
- About 169 MB crossed the link a present, five times today's
|
||
copy, and the guest slowed to match. Its presents over the walk
|
||
fell from 4324 to 1735, and the GPU's busy time went from 20.2 to
|
||
80.0 ms a present.
|
||
- Rates fell in Mission Control from 47 to 20 presents a second,
|
||
in the autoscroll from 45 to 9, and in GL 3D from 41 to 7.
|
||
- The median from a present's take to its show went from 23 to
|
||
147 ms in Finder, and from 5.6 to 182 ms in GL 3D.
|
||
- The runtime's shadow counts barely moved: the texels it copied
|
||
into shadows from host pages stayed under 1.3 MB a present. The
|
||
bytes are the composite's own passes. The runtime's GPU renders
|
||
and blends WindowServer's frame straight into guest RAM over the
|
||
link, its loads as well as its writes, several passes a frame:
|
||
an in-place display surface puts the whole composite on the
|
||
link, not one write of the frame.
|
||
- So the presented surfaces keep their device caches, as every
|
||
surface does on a GPU with memory of its own (route B's
|
||
decision holds for them too).
|
||
- Route 1's bytes are the change measured below.
|
||
- *What the guest's frames change.* The same walk on the RX 7900 XTX,
|
||
with a measuring build (`steelbrain/x4link-damage` at 32bfa734c,
|
||
not landed: a thread that reads what the display shows as
|
||
`read_display` does, about once a present, 8 ms a read, and
|
||
compares each read with the one before in 64 x 64 tiles): 6.27 MB
|
||
of the 29.7 MB frame changed a present on average, 136 MB/s over
|
||
the walk, where the 3090's link carried 599 MB/s. By step: the
|
||
GL 3D page 18.2 MB a present, the autoscroll 12.1, the video 6.2,
|
||
Safari's scroll 6.1, Finder 2.7, Maps 1.6, Mission Control 1.6,
|
||
Apps 0.65, the WebGL page 0.3. Presents that come closer together
|
||
than a read are compared as one, so where presents come fast the
|
||
figure a present is low. At the 3090's rate that change is 3.5 ms
|
||
of its link a present on average, where the window's copy takes
|
||
16.4 ms now (the GL 3D page 10 ms, Mission Control 0.9 ms).
|
||
- *The contract, either route.* Nothing the guest sees changes:
|
||
presents are taken, shown and answered as now, and the window
|
||
shows the same pixels.
|
||
|
||
15. **The stage 3 stack is IOGPUFamily.** x86-64 macOS 26 carries IOGPUFamily
|
||
and IOGPU.framework, and the x86-64 port runs Metal compositing on them:
|
||
WindowServer composites with Metal through an IOSurface display pipe on
|
||
IOGPU that the driver provides. Our accelerator does the same.
|
||
|
||
16. **Hardware video is AppleGVA's vendor driver, in our bundle.** On an
|
||
x86-64 Mac, VideoToolbox's hardware decoders and encoders run in
|
||
VTDecoderXPCService and VTEncoderXPCService, one of each per client
|
||
process, through AppleGVA. AppleGVA reads the accelerator's
|
||
`IOVARendererID` and `IODVDBundleName`, loads
|
||
`/Library/GPUBundles/<name>.bundle/Contents/MacOS/<name>`, and calls its
|
||
`AVD_CreateAVDAccelerator` for the driver's identity, its capability block
|
||
and a table of sixteen entry points (sessions, bitstream and pixel buffer
|
||
pools, command scheduling and status, parameters). Both services allow
|
||
the bundle: their library validation is off, and their sandboxes read
|
||
`/Library/GPUBundles` and open IOAccelerator user clients. A video
|
||
plug-in of our own in `/Library/Video/Plug-Ins` is no way in: CoreMedia
|
||
lists only Apple-signed plug-ins.
|
||
- **Identity:** the accelerator's registry entry names the bundle,
|
||
`reims-graphics`, as the video driver, with `IOVARendererID` 0x1020004,
|
||
the AMD Navi family's, and `IOGVACodec`; the bundle exports the two
|
||
entry points beside its Metal device
|
||
(`guest/bundle/src/RgfxVideoDriver.cpp`). AppleGVA drives an AMD driver
|
||
through high-level commands (picture parameters and slice data;
|
||
rate-control settings), which map onto Vulkan Video. The driver decodes
|
||
H.264 and HEVC, each where the host's caps list it; HEVC in the profiles
|
||
they list (Main into NV12, Main 10 into P010).
|
||
- **Routing:** AppleGVA hands a session to the AMD driver only on the
|
||
Macs without an Intel GPU, or where `com.apple.AppleGVA`'s
|
||
`gvaForceAMDKE` is set; elsewhere, an iMac20,1 among them, it looks for
|
||
an Intel GPU and gives up without one. RgfxGate's install thread keeps
|
||
the key set at every boot, after the bundle step
|
||
(`guest/rgfxgate/src/RgfxGatePrefs.cpp`), in two files:
|
||
`/Library/Preferences/com.apple.AppleGVA.plist`, and on x86-64 the
|
||
global domain's for every user,
|
||
`/Library/Preferences/.GlobalPreferences.plist`. In each, a key already
|
||
true leaves the file untouched, an absent file gets a fresh XML plist
|
||
of the key alone, an XML plist gets the key with every other byte kept,
|
||
a binary one, as cfprefsd writes it (`defaults delete` leaves an empty
|
||
one), gets the key with every other object's bytes kept, and an
|
||
unreadable one is left and logged. An arm64 guest keeps the key in the
|
||
AppleGVA file alone, as before: AppleGVA's AMD flow, the key's one
|
||
reader, is x86-64's, and the arm64e shared cache of macOS 27.0.1 holds
|
||
no image with the key's name.
|
||
AppleGVA reads it from the next service start (measured on the guest,
|
||
macOS 26.6.1). The global domain is for the processes that run AppleGVA
|
||
in a sandbox of their own: Safari's H.264 decodes in WebKit's GPU
|
||
process, not in VTDecoderXPCService, and that process's sandbox denies
|
||
it `com.apple.AppleGVA.plist` (the kernel logs `deny(1) file-read-data`)
|
||
while it reads the global domains. With the key in the AppleGVA file
|
||
alone, AppleGVA there found no Intel GPU and every H.264 video in Safari
|
||
decoded in software; with the key in the global domain the same
|
||
process's sessions reached the driver (measured on the guest, macOS
|
||
26.6.1, a 4K60 H.264 clip on the RTX 5080: NVDEC decoded all 980 of its
|
||
pictures). Safari's HEVC decodes in VTDecoderXPCService either way.
|
||
- **The GPU is named GFX0.** AppleGVA's video routing finds the GPU by
|
||
the name real AMD Macs give its PCI device, `GFX0`. HEVC needs it: the
|
||
accelerator names its IOPCIDevice provider `GFX0` in `start`, before
|
||
`registerService`, and without that name `VTDecompressionSessionCreate`
|
||
refuses every HEVC stream with −12913 and the driver is never called.
|
||
H.264 decodes either way, and the `IOGVACodec` string makes no
|
||
difference (measured on the msi 5080, 2026-11-03: three boots with the
|
||
provider's default name refused HEVC with −12913; a fourth that changed
|
||
only the provider's name to `GFX0` decoded every frame, H.264 still
|
||
working). Where a device already carries the name (a renamer such as
|
||
WhateverGreen, or a second GPU), the name is left as it was and that is
|
||
logged, so two are never published
|
||
(`guest/kext/src/RgfxAccelerator.cpp`, `nameProviderForVideo`).
|
||
- **macOS 11 keeps small H.264 pictures off the hardware.** AppleGVA's
|
||
H.264 decoder on 11 declines a picture of at most 480×320 pixels
|
||
(153,600) where the session plays video (read from AppleGVA's code,
|
||
108.7.2). Its session create fails with
|
||
−12913 (`kVTVideoDecoderNotAvailableNowErr`), which
|
||
`VTIsHardwareDecodeSupported` still counts as supported. AppleGVA logs
|
||
why only with its debug preference set. From 12 the floor is 64×64
|
||
(AppleGVA logs "Playback Usage, resolution constrains: 64x64"). A Mac
|
||
on 11 declines the same streams, so nothing of the device answers it,
|
||
and a check of 11's hardware H.264 decodes a larger picture. Measured
|
||
on the 780M host, 2026-11-08: on 11.7.11, 320×240 and 480×320 failed
|
||
their create and 496×320's succeeded; on 12.7.6 all three decoded.
|
||
- **Capabilities are the host's:** the block lists the engines and, per
|
||
codec and direction, a function record (its ID, sub-ID, input format
|
||
`rawb` for a bitstream or `NV12` for frames, and output formats), from
|
||
what the host's Vulkan Video answers (`RgfxVideoCaps` in the device
|
||
info). A codec the host lacks is not listed, so VideoToolbox falls back
|
||
to software, as on a Mac without it.
|
||
- **The wire:** a video session is an object of the device's
|
||
(`VIDEO_SESSION_CREATE`), with a command queue of the driver's; each
|
||
picture is a command buffer of that queue holding one video encoder,
|
||
whose op (`RGFX_OP_VIDEO_DECODE_H264` or `RGFX_OP_VIDEO_DECODE_H265`,
|
||
the 0x4xxx group) names the bitstream buffer and range, the parameter
|
||
sets where they changed (H.264's SPS and PPS; HEVC's SPS and PPS, the
|
||
host making the VPS from the SPS), and textures over the output
|
||
surface's two planes. The host decodes on its Vulkan Video decode queue
|
||
and has the command buffer wait for the decode on the session's shared
|
||
event, so the buffer completes, and AppleGVA's token is answered done,
|
||
once the picture is in the surface. For HEVC the driver writes the
|
||
parameter sets from AppleGVA's parsed form, as for H.264
|
||
(`guest/bundle/src/RgfxVideoH265.cpp`): each short-term reference
|
||
picture set by its pictures, each scaling list and, where the stream's
|
||
random access skips a leading picture, no output for it. AppleGVA
|
||
holds a set the SPS predicts from another by its pictures as well,
|
||
derived, so the driver writes every set by its pictures, a predicted
|
||
one too (measured on the guest with a stream of 25 sets in its SPS, 22
|
||
of them predicted). Encode is to take the same path.
|
||
- **The HEVC output surface is named in the parameters, not on the
|
||
command.** An H.264 decode arrives as a pipeline whose transfer command
|
||
carries the output surface; an HEVC decode is a bare decode command with
|
||
no output on it and no transfer command. AppleGVA names the output frame
|
||
in its own decoded-picture record instead: the record pointer at the
|
||
parameters' `+0x10`, its current frame at the record's `+0x08`, and in
|
||
that frame a description of its surface: the global IOSurface id, a
|
||
size, the width, the height, a pitch, 8 bytes, then the pixel format.
|
||
Where the fields start and how wide each is differ by release: fields
|
||
of 4 bytes from the frame's `+0x70` on macOS 11.7.10 and 11.7.11, from
|
||
`+0x78` on 12.7.6 and from `+0x80` on 13.7.8; fields of 8 bytes from
|
||
`+0x80` on 14.8.9 and from `+0x88` on 15.8.2 and 26.7.2 (measured on
|
||
the guest with the RTX 5080, and 13.7.8 and 26.7.2 with the 780M; on
|
||
26 the id is that of the IOSurface VideoToolbox hands back for the
|
||
picture, 7 for picture 0 and 27 for picture 1, and an IDR with no
|
||
references resolves there too). So the driver searches for the
|
||
layout rather than listing them: every start from `+0x60` to `+0xa0`
|
||
in steps of 4, with fields of 4 or 8 bytes, where the id names a live
|
||
surface whose width, height and pixel format the description gives.
|
||
The window starts two 8-byte steps below 11's `+0x70`, for the 11
|
||
releases before 11.7.10, which no base boots; in the frames of every
|
||
release measured, no start and width in it but the release's own
|
||
reads the surface's width, height and pixel format.
|
||
The first picture of a session whose frame describes its surface in
|
||
exactly one layout shows the session's layout, which the session keeps;
|
||
a picture whose frame describes no surface, or one in more than one
|
||
layout, or none in its session's layout, is refused before it reaches
|
||
the host (`guest/bundle/src/RgfxVideoDriver.cpp`, `hevcOutputSurface`).
|
||
- **A decode the driver cannot complete is a decode error, never a silent
|
||
success.** AppleGVA reports a decode error only when scheduling the
|
||
command fails: a schedule that answers 5 reaches the client as
|
||
`kVTVideoDecoderMalfunctionErr` (-12911). It takes every query of a
|
||
decode for its completion, reading neither its status nor its error
|
||
word (read from AppleGVA's code on macOS 26.7.1), and a detail word, a
|
||
failed query call, and the statuses 0 and 3 alike deliver the picture
|
||
as decoded (measured on the guest with the RTX 5080). So a command the
|
||
driver cannot resolve or send (no output surface, refused parameter
|
||
sets, no command buffer) fails its own schedule, and logs one line. The
|
||
schedule of an HEVC picture the driver sent waits for the host's
|
||
verdict on it, out of the lock that orders the sessions' pictures, and
|
||
fails where the host failed it: AppleGVA reports the error from that
|
||
picture on, and no frame of it reaches the client
|
||
(`guest/bundle/src/RgfxVideoStatus.hpp`, `waitsForHost` and
|
||
`scheduleFails`). AppleGVA's H.264 decoder reports no failure, neither
|
||
a failed schedule nor any query answer tried, and a picture whose
|
||
schedule failed is not decoded at all (measured on the guest with the
|
||
RTX 5080, 2026-11-07); its pipelines schedule their commands one at a
|
||
time and keep no decode's result (read from its code). So an H.264
|
||
schedule waits for no verdict, and an H.264 picture the host fails
|
||
reaches the client as decoded ([D25](../video/bugs.md)). What the
|
||
driver can tell before a picture, the coded size AppleGVA gives each
|
||
context it asks for, it checks at the create: a size outside the
|
||
host's H.264 decode entry fails `CreateContexts` with kUnsupported,
|
||
AppleGVA fails the session's create, and VideoToolbox decodes in
|
||
software (`sizeTaken`, `guest/bundle/src/RgfxVideoStatus.hpp`). The host
|
||
reports a failure as the
|
||
picture's command buffer failing: an op it cannot carry out faults the
|
||
buffer, and a picture it took but could not land (its planes refused,
|
||
or a decode the hardware failed once it ran) still signals the
|
||
session's event, so the buffer completes, failed with Metal's internal
|
||
error (`crates/reims-vgpu/src/graphics/decode/video.rs`, `Landed`).
|
||
- **Bitstreams:** AppleGVA asks for one bitstream buffer and writes the
|
||
next access unit into it as soon as a picture is scheduled, without
|
||
waiting for the decode that reads it. The driver copies each access
|
||
unit, from its first 3-byte start code and padded with zeros to the
|
||
host's `bitstream_alignment`, into the next of its session's eight
|
||
Shared buffers, which the host's decode reads in place. That copy of
|
||
the compressed data is the only one.
|
||
- **Pictures:** AppleGVA's commands name no references, and AppleGVA
|
||
reuses an output surface whatever the stream still references, so the
|
||
host keeps the decoded picture buffer in images of its own, from the
|
||
stream's slice headers. Where the device decodes only into its DPB
|
||
pictures (`DPB_AND_OUTPUT_COINCIDE`, as the RTX 5080's decoder), each
|
||
picture then takes one GPU copy from its DPB image into the output
|
||
surface's planes, and nothing else copies a frame on the GPU.
|
||
AppleGVA's surfaces lie in place (§14, measured on the guest with the
|
||
RTX 5080). On a GPU of its own memory, the host says
|
||
`RGFX_VIDEO_CAPS_OUTPUT_CACHED` in the video caps, each output
|
||
surface's block is cached as every surface's is (item 14, *Which
|
||
surfaces are cached*; without the flag the driver asks them uncached),
|
||
and the copy writes the surface's device cache, within the GPU's
|
||
memory, on the queue the runtime reserves for the decoders (family 0
|
||
on the RTX 5080), which no runtime work runs on, so the copy waits for
|
||
its decode on the GPU and holds no guest work behind it.
|
||
The guest's GPU work then reads the picture where it landed, and it
|
||
crosses the bus only at a CPU lock, as the cache's download. Measured
|
||
on the RTX 5080: a 4K picture lands in 100 us of the GPU, where the
|
||
copy into the pages took 3.5 ms across a link idled down by a load
|
||
of decodes alone; a CPU lock downloads it in 1 to 5 ms. Where the GPU
|
||
shares the CPU's memory, the copy writes the surface's pages, on the
|
||
decode queue.
|
||
|
||
## What metal2vulkan adds in stage 3
|
||
|
||
- No-copy Managed heaps over our host blocks, whose VRAM copy syncs at
|
||
`didModifyRange:` and `synchronizeResource:`, as a no-copy Managed buffer's
|
||
does on a GPU of its own memory since metal2vulkan's runtime 2050.
|
||
- Two-copy Managed textures, whose host copy is one of our blocks.
|
||
- Per-context address and texture-ID tables. Today one device has one
|
||
address space and one texture table of up to 2^16 entries.
|
||
- A completion hook on its waiter thread, saving a thread hop.
|
||
|
||
## Stage 2 wire protocol
|
||
|
||
Stage 2 builds the device, the transport and an unaccelerated display. The
|
||
transport is final: stage 3 adds rings per command queue and commands, in the
|
||
same formats. All values are little-endian.
|
||
|
||
**PCI.** Class 0x0380 (display controller, other). The vendor:device ID is
|
||
the owner's call (Open); development uses the placeholder `1234:5247`.
|
||
Apple's paravirt kext matches only `106b:eeee`. In the guest's registry the
|
||
kext states the class an x86 Mac's GPU states, 0x030000, as the PCI device's
|
||
`class-code`, which software that lists the Mac's GPUs reads
|
||
(`guest/kext/src/RgfxPciClass.hpp`); configuration space keeps 0x0380.
|
||
|
||
**BAR0: registers**, 4 KiB of MMIO, 32-bit accesses. The MSI-X table and PBA
|
||
sit in BAR0 from 0x800.
|
||
|
||
| offset | name | access | meaning |
|
||
|---|---|---|---|
|
||
| 0x000 | `MAGIC` | RO | 0x58464752 ("RGFX") |
|
||
| 0x004 | `VERSION` | RO | the wire's version, `RGFX_VERSION` (below) |
|
||
| 0x008 | `FEATURES_LO` | RO | feature bits 0-31; 0 in stage 2; the device info's `features_lo` holds its low byte for the processes |
|
||
| 0x00c | `FEATURES_HI` | RO | feature bits 32-63 |
|
||
| 0x010 | `STATUS` | RW | writing 0 resets the device; the guest writes 1 (driver ready) once it has read the rings' headers |
|
||
| 0x014 | `REGION_SIZE_LO` | RO | BAR2's size, low 32 bits |
|
||
| 0x018 | `REGION_SIZE_HI` | RO | BAR2's size, high 32 bits |
|
||
| 0x020 | `DOORBELL` | WO | writing a ring's id wakes its consumer (an `ioeventfd`); under `DOORBELL_ASKS` bit 0 set asks for the answer at the doorbell |
|
||
| 0x024 | `DRIVER_FEATURES_LO` | RW | feature bits 0-31 the guest's driver takes; reads back the ones the host took ("Negotiated features", below) |
|
||
| 0x028 | `DRIVER_FEATURES_HI` | RW | feature bits 32-63, likewise |
|
||
| 0x02c | `CONSUMED` | WO | writing a completion ring's offset wakes its producer waiting for room, under `CONSUMED_DOORBELL`; no host handles it yet, so it reads 0 and a write is ignored |
|
||
| 0x030 | `DEFERRED_BUDGET_LO` | RO | under `SURFACE_DEFERRED` or `SURFACE_DEFERRED_ASK`, the bytes of the host GPU's memory deferred blocks' device caches may hold, low 32 bits: a quarter of the device-local heap's budget, the same for the device's life; 0 without either feature |
|
||
| 0x034 | `DEFERRED_BUDGET_HI` | RO | its high 32 bits |
|
||
| 0x038 | `HOST_TIME_LO` | RO | under `HOST_TIME`, the host's monotonic clock at the read in ns, low 32 bits: the clock `VBLANK`s are stamped on; nothing is latched, so the guest reads `HI`, `LO`, `HI` and takes the second `HI` where `LO` is below 2^31, else the first; 0 where the guest did not take the feature |
|
||
| 0x03c | `HOST_TIME_HI` | RO | its high 32 bits |
|
||
|
||
**The wire's version.** `VERSION` reads `RGFX_VERSION`
|
||
(`crates/reims-vgpu-graphics/src/wire.rs`), the version of the wire the host
|
||
speaks. The kext's framebuffer and accelerator, and the option ROM, each
|
||
accept only the version they were built with. They read it right after
|
||
`MAGIC`, before anything else of the device, and on any other version they
|
||
leave the device and say why, naming both versions: the kext in the kernel
|
||
log, the ROM on the firmware's console where it has one.
|
||
|
||
The bundle maps the region and speaks the messages too, so it must be of the
|
||
kext's version, and it says which it is: its package carries an empty
|
||
`Contents/Resources/wire-version-N`, N the `RGFX_VERSION` it was built with,
|
||
under its signature. The kext registers its accelerator only for a bundle
|
||
carrying the marker of its own version ("Registration waits for the bundle",
|
||
below); for any other it says so in the kernel log and stays unregistered,
|
||
so WindowServer composites in software, as with no bundle. The bundle does
|
||
not check the version itself: a bundle that declined to make a device under
|
||
a registered accelerator would leave WindowServer aborting, as with no
|
||
bundle at all.
|
||
|
||
Leaving the device means writing nothing to its registers or its region.
|
||
The framebuffer's start resets the device (`STATUS` 0) only once every check
|
||
that needs no command has passed, and resets it again on the way out only if
|
||
it did so. With the kext refused, or failed after its reset, the OS drives
|
||
the display through the firmware's framebuffer, which the host shows through
|
||
the scanout the firmware set up: a reset keeps the scanout (Reset, below).
|
||
|
||
Every change a guest built before it would misread moves `RGFX_VERSION` on by
|
||
one, in the same commit:
|
||
- a register's offset, width or meaning;
|
||
- an offset or a size in the region: the control rings, the device info, the
|
||
scanout's room, the blocks' room, the cursor;
|
||
- a message's or an op's number, layout or meaning, a ring's format, or a
|
||
status the guest acts on.
|
||
|
||
A change that no guest built before it can misread leaves it: a new feature
|
||
bit (`FEATURES_LO`, `FEATURES_HI`), or a new message or op that older guests
|
||
never send. A version number is never used twice. The host speaks one version,
|
||
and a host and a guest of that version from different builds meet through the
|
||
features they negotiate (below).
|
||
|
||
**Negotiated features.** A change lands as a feature bit, and moves `VERSION`
|
||
only where no negotiation can carry it.
|
||
- The host offers its bits in `FEATURES_LO` and `FEATURES_HI`. Bits 0-2
|
||
(`SURFACE_PAGES`, `SURFACE_CACHE`, `CB_SUBMITTED`) need no answer: the host
|
||
acts on them as it offers them.
|
||
- From bit 3, the host acts on a bit only where the guest's driver took it.
|
||
The framebuffer kext writes `DRIVER_FEATURES_LO` and `_HI` after `STATUS` 0
|
||
and before `STATUS` 1, in `ReimsGraphics::start`, with the bits it and its
|
||
bundle carry out, masked by the offer (`RgfxFeatures.hpp`). It reads back the
|
||
bits the host took: those written that the host offers and knows. It logs
|
||
the three words, and sets them on its service as `RgfxFeaturesOffered`,
|
||
`RgfxFeaturesWanted` and `RgfxFeaturesTaken`, which `ioreg` reads at any
|
||
time after the kernel's message buffer has let go of the line.
|
||
- The host ignores a write while `STATUS` is 1, and a reset (the guest's
|
||
`STATUS` 0 or the host's) clears the set. A guest that never writes it (the
|
||
option ROM, a kext built before the registers) gets the wire as it was, and
|
||
a host built before them reads them as 0, so its guest takes nothing.
|
||
- A feature with a mode per queue rides `QUEUE_CREATE`'s tail,
|
||
`RgfxQueueCreateFlags` (`flags`, `RGFX_QUEUE_*`) after its 56 bytes. The kext
|
||
sends the tail only with a flag set. A flag whose feature the guest did not
|
||
take, or that the host does not carry out, refuses the create
|
||
(`INVALID_ARGUMENT`).
|
||
- New ops and messages are decoded wherever the host offers their bit, as
|
||
`RGFX_OP_SUBMITTED` is.
|
||
- The accelerator answers its processes' `Features` call (selector 3) with
|
||
three words: the device's, which they work by (bits 0-2 as offered, and from
|
||
bit 3 the bits taken), the kext's own, and the kext's selector map (below,
|
||
"The accelerator's user client"). `QueueCreate` (0x103) takes a seventh
|
||
input, the flags the process wants, and answers a second output, the flags
|
||
granted: those whose feature the device's word holds. A kext whose map is
|
||
not the bundle's, one of the map before it (whose `Features` was 0x10f)
|
||
among them, and a sandbox that refuses the call, leave the process with no
|
||
Metal device, logged: the bundle works by no guess at the words.
|
||
- Bits 3-8 are named (`QUIET_SCHEDULED`, `CONSUMED_DOORBELL`, `QUEUE_BARRIER`,
|
||
`CB_PARTS`, `PAGES_BUFFERS`, `QUEUE_VECTORS`; `wire.rs`), and bits 9-12 are
|
||
reserved. Of them the host offers bit 7, `PAGES_BUFFERS`, where it offers
|
||
`SURFACE_PAGES`, and the kext takes it: a process's no-copy buffers lie over
|
||
its own pages, wired by the kext in a pages block (selector 4, "The
|
||
accelerator's user client"; `BUFFER_OVER_PAGES`). No host offers the others
|
||
yet, the kext takes none of them, and the host carries out none of their
|
||
queue flags: each lands with its feature, which says what it changes.
|
||
- Bit 10 is reserved for a pipeline's warm-up, and bit 11 is `SURFACE_ORDER`:
|
||
a command buffer that uses IOSurfaces runs after the buffers of other queues
|
||
it names (`RGFX_OP_SURFACE_ORDER`; "Surface order", below).
|
||
- Bit 13, `UNSHARED_QUEUES`, every host offers and the kext takes: the queue
|
||
flag `RGFX_QUEUE_UNSHARED` (`1 << 3`; `1 << 2` is reserved), which the kext
|
||
sets on WindowServer's queues ("WindowServer's queues are unshared", below).
|
||
- Bit 14 is `MANAGED_AT_OFFSET`: ring 0 carries `BUFFER_MANAGED_AT_OFFSET`, a
|
||
Managed buffer whose CPU copy the host places in a heap over host memory of
|
||
the sender's, so no buffer imports host memory of its own (the slabs,
|
||
below). A host offers it where a Managed buffer is two copies, a GPU that does
|
||
not share the CPU's memory.
|
||
- Bit 15 is `HEAP_OVER_PAGES`: ring 0 carries `HEAP_OVER_PAGES`, a heap over
|
||
the one run of guest RAM a pages block of the sender's holds, made over the
|
||
host's mapping of the guest's RAM rather than the block's view, so the
|
||
buffers placed in it cost what those of a heap over host memory do. A host
|
||
offers it with `PAGES_BUFFERS`.
|
||
- Bit 16 is `SUBMIT_ROOM`: a guest producer that finds a submission ring full
|
||
stores 1 in the ring's `producer_waiting`, fences, and looks once more before
|
||
it waits. After each take that moves the ring's `consumer`, the host fences
|
||
and reads the flag, and where it reads 1 it stores 0 and posts a header-only
|
||
`RGFX_EVT_SUBMIT_ROOM` (0x408) on the ring's completion ring, ring 0's or the
|
||
queue's. The waiting producer looks again at that record: one interrupt after
|
||
the host's take, not at a sleep's end. Every host offers it.
|
||
- Bit 18 is `COMMIT_ORDER`: a command buffer is committed after the buffers of
|
||
its process's other queues it names (`RGFX_OP_COMMIT_ORDER`; "Commit order",
|
||
below).
|
||
- Bit 19 is `SURFACE_DEFERRED`, which means nothing without `SURFACE_CACHE`:
|
||
a fresh cached surface only the GPU touches gets no guest pages until a CPU
|
||
lock needs them (`RGFX_SURFACE_PAGES_DEFERRED` and `_ATTACH`; `wire.rs`). A
|
||
host offers it where it offers `SURFACE_CACHE`, with its budget in
|
||
`DEFERRED_BUDGET_LO` and `_HI`.
|
||
- Bit 20 is `HOST_TIME`: `HOST_TIME_LO` and `_HI` read the host's monotonic
|
||
clock, the one `VBLANK`s are stamped on, so the kext measures the two
|
||
clocks' offset rather than infer it from the `VBLANK`s' delivery ("Refresh
|
||
times", below). Every host offers it, and the kext takes it.
|
||
- Bit 21 is `MANAGED_TEXTURE_SLABS`: a `MANAGED_TEXTURE_CREATE` may name any
|
||
Shared buffer over the sender's memory as its CPU copy, and the host reads
|
||
and writes the copy where the buffer's contents lie, so the bundle takes a
|
||
Managed texture's CPU copy from its slabs ("Managed storage", below). Every
|
||
host offers it, and the kext takes it.
|
||
- Bit 22 is `MANAGED_BUFFER_SLABS`: ring 0 carries `MANAGED_BUFFER_CREATE`, a
|
||
Managed buffer whose CPU copy is the first bytes of any Shared buffer over
|
||
the sender's memory, read and written where that buffer's contents lie, so
|
||
the bundle takes a Managed buffer's CPU copy from its Shared slabs, its own
|
||
pages among them, on every host ("Managed storage", below). Every host
|
||
offers it, and the kext takes it.
|
||
- Bit 23 is `SMALL_ID_CHUNKS`: ring 0 carries `RESOURCE_ID_SMALL_CHUNK`, a grant
|
||
of 16 texture resource ids, so the kext hands each process its ids 16 at a
|
||
time from the same pool ("Texture resource ids", below). Every host offers it,
|
||
and the kext takes it.
|
||
- Bit 24 is `DISPLAY_COLOR`: the guest sends the display pipe's gamma tables
|
||
and colour matrix as `DISPLAY_COLOR` parts, which the next `PRESENT_SURFACE`
|
||
shows, and a present may keep the surface shown and change only the colour
|
||
(`RGFX_PRESENT_KEEP`; "The display's colour", below). Every host offers it;
|
||
one with no window answers its presents at once.
|
||
- Bit 25 is `MESH_PIPELINES`: ring 0 carries `MESH_RENDER_PIPELINE_CREATE`
|
||
(0x22e), answered by a `PIPELINE_REFLECTION` of kind `MESH` (2) whose
|
||
made answer carries the state's object and mesh limits after its 80 bytes
|
||
(`RgfxMeshPipelineReflection`, 104 bytes in all), and command buffers carry
|
||
the object and mesh stages' bindings and the mesh draws (render ops
|
||
0x1051-0x105e). A host offers it where its GPU answers Metal3, and the kext
|
||
takes it. No mesh pipeline supports indirect command buffers: the bundle
|
||
ends the process at one that asks, as the x86 Macs' Metal does
|
||
(dgpu-oracle.md, Q22), so no indirect command carries a mesh draw.
|
||
- Bit 26 is `SHARED_EVENT_NAMES`: ring 0 carries `SHARED_EVENT_NAME`,
|
||
`SHARED_EVENT_IMPORT` and `SHARED_EVENT_UNNAME`, which the kext posts for the
|
||
shared events one process hands another, and the host posts the values one
|
||
holder gives the event to the others' listen queues ("Shared events across
|
||
processes", below). Every host offers it, and the kext takes it.
|
||
- Bit 27 is `OPENCL_MODE`: a `COMPUTE_PIPELINE_CREATE` may carry
|
||
`RGFX_COMPUTE_PIPELINE_OPENCL_MODE`, and the host makes that pipeline of
|
||
OpenCL mode: Metal links the kernel behind three buffers of its own (the
|
||
global offsets and dimension count at 0, then 1 and 2) with its arguments at
|
||
their indices plus three. The bundle makes a kernel's function of OpenCL mode
|
||
(`newFunctionWithPluginData:bitcodeType:2`) only where the kext carries the
|
||
bit. A host offers it where its platform makes such pipelines: the Metal
|
||
platform where Metal's compute pipeline descriptors answer
|
||
`setOpenCLModeEnabled:` (the M3 Max on macOS 27, the AMD 5300M and Intel 630
|
||
on macOS 26.7.1), and the Vulkan platform always, its runtime linking the
|
||
kernel as Metal does.
|
||
- Bit 28 is `PRIVATE_RENDER_STATE`: a `RENDER_PIPELINE_CREATE` may carry
|
||
`RGFX_RENDER_PIPELINE_PRIVATE_STATE` (flag bit 6), and then an
|
||
`RgfxRenderPipelinePrivateState` (24 bytes) follows its head, ahead of the
|
||
tail. It holds the descriptor's private state that Apple's OpenGL renderer
|
||
sets: `openGLModeEnabled`, `sampleMask`, `sampleCoverage`,
|
||
`sampleCoverageInvert`, `logicOperationEnabled`, `logicOperation` and
|
||
`depthStencilWriteDisabled`, each the guest's raw value. The bundle reads
|
||
them by key from every render pipeline descriptor where the kext took the
|
||
bit. Measured on the Intel 630 (macOS 26.7.1), the renderer sets
|
||
`openGLModeEnabled`, a sample mask and copy (2) on every pipeline. It sets
|
||
a GL logic operation, sample mask or sample coverage as their properties.
|
||
It sets `depthStencilWriteDisabled` on a pipeline that writes no depth or
|
||
stencil. It does alpha test, two-sided colour and the point sprite origin
|
||
in its shaders. A host offers it where its platform takes that state. The
|
||
Vulkan platform always does, filling metal2vulkan's `PrivateRenderState`.
|
||
|
||
The guest's renderer sets the same properties on our device. This was
|
||
measured over gl_cases' 48 cases in arm64 macOS 27.0.1 (the M3 Max under
|
||
HVF, job m3-max-17093) and in x86-64 macOS 26.7.2 (ms01's Iris Xe, job
|
||
m3-max-17106). Each case ran in a process of its own, with every setter the
|
||
renderer sends a render pipeline descriptor, its colour attachments and our
|
||
render encoder traced. At each create, the descriptor's properties that
|
||
differ from a new descriptor's were logged.
|
||
- On both architectures, every pipeline gets `openGLModeEnabled` 1,
|
||
`sampleMask` `0xffffffff`, `sampleCoverage` 1, `sampleCoverageInvert` 0,
|
||
`logicOperationEnabled` 0 with `logicOperation` 2, and
|
||
`depthStencilWriteDisabled` (1 where the pipeline writes no depth or
|
||
stencil).
|
||
- GL's XOR gives `logicOperationEnabled` 1 and `logicOperation` 10. GL's
|
||
sample coverage of 0.5 and sample mask of 3 give `sampleCoverage` 0.5 and
|
||
`sampleMask` 3.
|
||
- The renderer also sets `twoSideEnabled`, `pointCoordLowerLeft`,
|
||
`pointSizeOutputVS` and `needsCustomBorderColorSamplers`, always to 0,
|
||
including in the two-sided colour and lower-left point sprite cases. The
|
||
record does not carry these four. metal2vulkan measured that they change
|
||
nothing Metal draws, at any value it tried.
|
||
- The renderer never sets `alphaTestEnabled`, `alphaTestFunction`,
|
||
`clipDistanceEnableMask`, either depth-compare clamp mask,
|
||
`pointSmoothEnabled`, `vertexAmplificationMode` or
|
||
`explicitVisibilityGroupID`. It never calls `setAlphaTestReferenceValue:`
|
||
or `setPointSize:` on the encoder.
|
||
- So every property the renderer sets to something other than Metal's
|
||
default is in the record.
|
||
|
||
On a host whose Vulkan device lacks `logicOp`, such as MoltenVK on a Mac,
|
||
metal2vulkan refuses a pipeline of any logic operation other than copy or
|
||
no-op. The renderer then asks for the same pipeline for its software vertex
|
||
and fragment fallbacks, each create answers nil, and the draw is lost
|
||
(gl_cases' logicop case in arm64 27.0.1 on the M3 Max). x86 guests draw the
|
||
case right on the 780M (RADV), the 3090 (NVIDIA) and the Iris Xe (ANV),
|
||
whose devices have `logicOp`.
|
||
- Bit 29 is `SURFACE_CACHE_REFUSED`: the host's GPU shares the CPU's memory,
|
||
and it keeps a device cache only of the surfaces whose pages its textures
|
||
cannot use in place, which it answers surface by surface (Decided 14,
|
||
"Device caches on a GPU that shares the CPU's memory"). The kext asks at a
|
||
new cacheable block in place (`RGFX_SURFACE_PAGES_ASK_CACHE`, with the
|
||
surface's `RgfxSurfacePagesLayout` after the cache part), and posts the
|
||
block again cached where the host answers `RGFX_STATUS_CACHE`. A host
|
||
offers it where it offers `SURFACE_PAGES` and its GPU shares the CPU's
|
||
memory, where it offers neither `SURFACE_CACHE` nor `SURFACE_DEFERRED`.
|
||
- Bit 30 is `SURFACE_DEFERRED_ASK`, which means nothing without
|
||
`SURFACE_CACHE_REFUSED`: a fresh surface that would need a device cache
|
||
whatever its pages gets none until a CPU lock needs them, as under
|
||
`SURFACE_DEFERRED`. The kext's deferral carries `ASK_CACHE` and the
|
||
surface's layout; the host defers only such a surface and refuses the
|
||
rest, whose pages the kext then names asking (Decided 14, "Device caches
|
||
on a GPU that shares the CPU's memory"). A host offers it where it offers
|
||
`SURFACE_CACHE_REFUSED`, with its budget in `DEFERRED_BUDGET_LO` and
|
||
`_HI`.
|
||
- Bit 32, `FEATURES_HI`'s bit 0, is `SURFACE_DEFERRED_CARRY`, which means
|
||
nothing without `SURFACE_DEFERRED` or `SURFACE_DEFERRED_ASK`: a deferral
|
||
may carry the few resident pages of a surface no CPU lock touched, its
|
||
runs the surface's bytes in order, each run of pages not resident
|
||
`RGFX_PAGE_RUN_ZEROS` (Decided 14, *Deferred pages*). The bundle lists
|
||
them after the layout of its 0x109 call, the kext proves them under its
|
||
read of the surface, and the host fills the cache from them as a new
|
||
cache's first fill. A host offers it where it offers either deferral.
|
||
- Bit 33, `FEATURES_HI`'s bit 1, is `SCHEDULED_ASK`: a queue's ring carries
|
||
`SCHEDULED_ASK` (0x303), a thread's ask of a command buffer's scheduling
|
||
("Scheduled", below). The bundle posts it from `waitUntilScheduled` on the
|
||
rings it writes itself, so the kext takes the bit with nothing of its own
|
||
to do. Every host offers it.
|
||
- Bit 34, `FEATURES_HI`'s bit 2, is `PAGES_16K`: every run of guest RAM the
|
||
guest names, and a `SURFACE_PAGES`' length, is whole 16 KiB pages from a
|
||
16 KiB page's first byte, as an arm64 guest's pages are. A host whose page
|
||
is 16 KiB (a Mac) can map guest RAM for its GPU only in whole pages of its
|
||
own, so it offers its features over guest RAM (`SURFACE_PAGES`,
|
||
`PAGES_BUFFERS`, `HEAP_OVER_PAGES`, and with them `SURFACE_CACHE_REFUSED`,
|
||
`SURFACE_DEFERRED_ASK` and `SURFACE_DEFERRED_CARRY`) only to a guest that
|
||
took `PAGES_16K`, where it maps the guest's RAM at all:
|
||
- until the driver takes it, `FEATURES_LO` and `_HI` read the host's
|
||
other bits and `PAGES_16K`, and `DEFERRED_BUDGET_LO` and `_HI` read 0,
|
||
exactly as from a host that maps no guest RAM, and a write cannot take
|
||
the features over guest RAM;
|
||
- the `DRIVER_FEATURES_HI` write that takes it shows them in `FEATURES_LO`
|
||
and `_HI` (and the budget), and that write and later ones may take them;
|
||
a write that lets `PAGES_16K` go lets them go, and a reset hides them;
|
||
- the arm64 kext writes `DRIVER_FEATURES_HI` with `PAGES_16K` first, reads
|
||
the offer again, and then writes both halves as before. An x86-64 kext
|
||
never takes it, so an x86-64 guest on a Mac reads the features it read
|
||
before the bit: the guest RAM features stay hidden, and its surfaces are
|
||
copied into the region.
|
||
The device info's `features_lo` and `linear_row_alignment` stay as a host
|
||
that maps no guest RAM writes them, as the info is written before any
|
||
guest takes the bit. A host whose page is 4 KiB never offers `PAGES_16K`:
|
||
every guest's runs are whole pages of its own there.
|
||
- Bit 35, `FEATURES_HI`'s bit 3, is `DISPLAY_SCALE`: each display's record in
|
||
`DISPLAYS` is followed by the scale of the host screen that shows it, the
|
||
screen's pixels a point in 120ths (120 at 1x, 240 at 2x, 252 at KDE's 2.1;
|
||
0 while no window has drawn the display), and a change of the scale alone
|
||
is a change of the display's mode, told with `DISPLAY_CHANGED` ("Display",
|
||
below). Every host offers it, and the kext takes it.
|
||
- Bit 36, `FEATURES_HI`'s bit 4, is `TEXTURE_DID_MODIFY_DATA`: ring 0 carries
|
||
`TEXTURE_DID_MODIFY_DATA` (0x232, `RgfxTextureDidModifyData`, the texture's
|
||
`ObjId`), the bundle's post of a mipmapped texture over a buffer's
|
||
`didModifyData` (SPI). Such a texture (`TEXTURE_FROM_BUFFER` of more than
|
||
one level) is a copy of the buffer's bytes with every level made from them,
|
||
taken at its first use, as the x86 Macs' (dgpu-oracle.md, Q11), and the
|
||
platform's `didModifyData` makes it take them again at its next use. The
|
||
host carries it out as a range message ("Range messages", below), so a
|
||
command buffer of the process begun after it takes the bytes, a CPU write
|
||
made after the call among them. Every host offers it, and the kext takes
|
||
it; a guest that did not take it posts nothing, and the copy keeps what it
|
||
took.
|
||
- Bit 37, `FEATURES_HI`'s bit 5, is `DISPLAY_POWER`: ring 0 carries
|
||
`SET_DISPLAY_POWER` (8, `RgfxSetDisplayPower`: display u32, on u32),
|
||
answered by `COMPLETE`, which turns the display's panel off while the
|
||
guest's display sleeps and on at its wake ("The display's sleep", below).
|
||
Every host offers it, and the x86-64 kext takes it.
|
||
- Bit 38, `FEATURES_HI`'s bit 6, is `RATE_MAPS`: ring 0 carries
|
||
`RATE_MAP_CREATE` (0x233) and `RATE_MAP_RESET` (0x234), both
|
||
`RgfxRateMapCreate` (the map's `ObjId`, the descriptor's screen size, its
|
||
private mutability where set, and its layers' `RgfxRateMapLayer` records
|
||
with their samples after them), answered by `RATE_MAP_STATE` (0x40a,
|
||
`RgfxRateMapState`: the status, and the map's screen size, granularity,
|
||
layer count, mutability and parameter data's size and alignment), and
|
||
`RATE_MAP_QUERY` (0x235, `RgfxRateMapQuery`), answered by `RATE_MAP_ANSWER`
|
||
(0x40b, `RgfxRateMapAnswer`): a layer's physical size, a coordinate mapped
|
||
either way, or a copy of the parameter data into a buffer of the sender's,
|
||
which the platform writes where the buffer's contents lie before it
|
||
answers. A render pass names its map after its other records
|
||
(`RGFX_PASS_FLAG_RATE_MAP`, `RgfxRenderPassRateMap`). The platform compiles
|
||
each map, so its answers and its parameter data are the platform's, and the
|
||
layer counts it makes maps of are the device info's
|
||
(`largest_rasterization_rate_map_layer_count`). Every host offers it, and
|
||
the kext takes it; a bundle on a host that did not offer it makes no map and
|
||
supports no layer count.
|
||
- Bit 39, `FEATURES_HI`'s bit 7, is `FUNCTION_POINTERS`: a compute pipeline
|
||
state's function handles and visible function tables. Ring 0 carries
|
||
`FUNCTION_HANDLE_CREATE` (0x236, `RgfxFunctionHandleCreate`: the handle's
|
||
`ObjId`, the pipeline state's, and its function as an `RgfxLinkedFunction`
|
||
record of `RGFX_LINKED_FUNCTIONS`, its strings and constants after the
|
||
head) and `FUNCTION_TABLE_CREATE` (0x237, `RgfxFunctionTableCreate`: the
|
||
table's `ObjId`, the pipeline state's and its entry count), each answered
|
||
by `FUNCTION_POINTER_STATE` (0x40c, `RgfxFunctionPointerState`: the status,
|
||
and for a table its `gpuResourceID`, `allocatedSize` and `resourceOptions`),
|
||
and `FUNCTION_TABLE_SET` (0x238, `RgfxFunctionTableSet`: the table's
|
||
`ObjId`, the first entry and the count, then that many handle `ObjId`s, 0 a
|
||
nil entry), which the device does not answer. The platform makes the handle
|
||
of the function among those the state's kernel links, and a function it
|
||
does not link is `RGFX_STATUS_NOT_FOUND`, Metal's nil; a message naming a
|
||
state still being compiled waits for it. A set is carried out before any
|
||
command buffer the process posts after it, so a dispatch encoded before a
|
||
set and committed after it calls the entry set. A compute pass binds a table
|
||
at a buffer index (`RGFX_OP_COMPUTE_SET_VISIBLE_FUNCTION_TABLE`, 0x201e) or
|
||
a range of them (`RGFX_OP_COMPUTE_SET_VISIBLE_FUNCTION_TABLES`, 0x201f), and
|
||
an argument buffer holds a table by its `gpuResourceID`, which the kernel
|
||
reads with or without `useResource:`. Render stages carry no function
|
||
pointers. Every host offers it, and the kext takes it; a bundle on a host
|
||
that did not offer it makes no handle or table, and answers NO to
|
||
`supportsFunctionPointers`.
|
||
- Bit 40, `FEATURES_HI`'s bit 8, is `DYNAMIC_LIBRARIES`: a compute
|
||
pipeline's dynamic libraries. Ring 0 carries `DYNAMIC_LIBRARY_CREATE`
|
||
(0x239, `RgfxDynamicLibraryCreate`: the dynamic library's `ObjId` and that
|
||
of the sender's library of type dynamic it is made of), answered by
|
||
`COMPLETE` with its status: `RGFX_STATUS_NOT_FOUND` for a library the
|
||
sender does not hold, `RGFX_STATUS_REFUSED` for one the host refused or the
|
||
platform refuses as a dynamic library (one whose code reads a function
|
||
constant). A message naming a library still being made waits for it. A
|
||
`COMPUTE_PIPELINE_CREATE` with a nonzero `library_count` ends with that many
|
||
`RgfxPipelineLibrary` records (the dynamic library's `ObjId`, and the offset
|
||
and length of an install name in the message): one of no name is preloaded
|
||
(`preloadedLibraries`, searched first in the run's order), and one with a
|
||
name is the library that install name loads. Metal reads the file each
|
||
install name names when it creates the pipeline, for a library made from a
|
||
file alone; the bundle reads them in the guest's process, each name the
|
||
kernel's library, its linked functions' libraries and these dynamic
|
||
libraries name, and refuses the pipeline as the AMD Radeon Pro 5300M does
|
||
where one loads nothing or a library made of bytes or source names one, so
|
||
the host links only what the guest sent and reads no file of its own. Render stages carry
|
||
no dynamic libraries. Every host offers it, and the kext takes it; a bundle
|
||
on a host that did not offer it makes no dynamic library, and refuses a
|
||
pipeline whose kernel's libraries name an install name.
|
||
- Bit 41, `FEATURES_HI`'s bit 9, is `PIPELINE_KEYS`: a render or compute
|
||
pipeline create may ask for its pipeline key
|
||
(`RGFX_RENDER_PIPELINE_ANSWER_KEY`, 1 << 7 of its flags;
|
||
`RGFX_COMPUTE_PIPELINE_ANSWER_KEY`, 1 << 3). Where it asks, the device made
|
||
the pipeline, and the device holds every library the create names under a
|
||
content key it checked against the library's bytes (one bound by
|
||
`LIBRARY_LOOKUP`, or made of bytes sent with their key and kept in the
|
||
library cache), the `PIPELINE_REFLECTION` sets `RGFX_PIPELINE_REFLECT_KEYED`
|
||
(1 << 2) and carries the key, 32 bytes, after the reflection
|
||
(`RGFX_PIPELINE_REFLECTION_KEY_OFFSET`, 80; its `size` 112). The key is the
|
||
SHA-256 of `rgfx-pipeline-v1`, then the create's message with its `seqno`,
|
||
its `obj_id` and every library id it names zeroed, then each named
|
||
library's content key in the order the ids lie (a compute create's function
|
||
library, then each linked function's; a render create's vertex and fragment
|
||
libraries, then each vertex and each fragment linked function's), 32 zero
|
||
bytes for an id of 0. A mesh create, and a compute create that links
|
||
dynamic libraries, is never keyed. The kext keeps keyed answers for every
|
||
process's equal creates ("Known pipeline creates"). Every host offers it,
|
||
and the kext takes it; a bundle on a host that did not offer it asks for no
|
||
key.
|
||
- Bit 42, `FEATURES_HI`'s bit 10, is `ICB_SLOTS_IN_PAGES`, which means
|
||
nothing without `ICB_SLOTS` and `PAGES_BUFFERS`: an indirect command
|
||
buffer's slots may lie in the pages of a pages block of the process's, its
|
||
own memory, rather than in a block of the region, which the guest's kernel
|
||
maps uncached on an AMD host. Ring 0 carries `ICB_SLOTS_IN_PAGES` (0x23a,
|
||
`RgfxIcbSlots` then `RgfxIcbSlotPagesRun`s: an `ICB_SLOTS` run whose first
|
||
slot lies `pages_offset` bytes into the pages of the pages block at
|
||
`block_offset`), which the host reads and takes in place, in the guest's RAM
|
||
for a block of one run and in the block's view for one of more. The bundle
|
||
takes a chunked pages block of the kext's for each buffer's slots, its
|
||
table's bytes rounded up to whole 64 KiB chunks, and a block of the region
|
||
where the kext gives none; the block goes back after the buffer's destroy.
|
||
A host offers it where it offers `PAGES_BUFFERS`, and the kext takes it; a
|
||
bundle on a host that did not offer it lays every buffer's slots in the
|
||
region.
|
||
- Bit 43, `FEATURES_HI`'s bit 11, is `DOORBELL_ASKS`: a queue's doorbell is
|
||
written with the ring's id and `RGFX_DOORBELL_ASKS` (bit 0; a ring's id is a
|
||
region offset, a multiple of 8) for a command buffer whose stream ends in its
|
||
ask for its `CB_SUBMITTED`, and with the id alone otherwise. The host
|
||
answers at the doorbell only an asking write ("The answer at the
|
||
doorbell"), and may take a plain one with no exit to its process, waking
|
||
the queue's thread from the guest's vCPU directly ("Routed doorbells").
|
||
A host offers it where it routes doorbells: on Linux, where its host gives
|
||
the library's `route_doorbell` (QEMU's KVM ioeventfds); a Mac host (QEMU
|
||
under HVF or TCG) does not offer it
|
||
(`doorbell_asks_is_offered_only_where_the_host_routes_doorbells_on_linux`).
|
||
The kext takes it, and the bundle sets
|
||
the bit where the device's word holds it; where it does not, every
|
||
doorbell write may be answered, as before the bit.
|
||
- Bit 44, `FEATURES_HI`'s bit 12, is `GUEST_TIMES`, which means nothing
|
||
without `HOST_TIME`: a diagnostic. Each command buffer's stream starts with
|
||
`GUEST_TIMES` (0x000e), the guest's clock as the buffer was made, committed
|
||
and put on its ring, and the framebuffer keeps the offset of the guest's
|
||
clock from the host's in ring 0's header, so the host splits the time before
|
||
it takes each buffer ("Guest times"). Every host offers it, and the kext
|
||
takes it; a bundle on a host that did not offer it stamps nothing, and the
|
||
host reads no times of a guest that did not take it.
|
||
- Bit 45, `FEATURES_HI`'s bit 13, is `READ_ONLY_PAGES`, which means nothing
|
||
without `PAGES_BUFFERS`: the kext makes pages blocks of memory a process
|
||
maps read-only too, wired for reading alone (`kIODirectionOut`), and marks
|
||
their `SURFACE_PAGES` `RGFX_SURFACE_PAGES_READ_ONLY` (1 << 5, with
|
||
`RGFX_SURFACE_PAGES_PRIVATE` alone). The host keeps every object over such
|
||
a block from writing its pages: a `BUFFER_OVER_PAGES` over it carries
|
||
`MTLResourceOptions` bit 24, whose GPU writes the platform drops as Metal
|
||
drops them (accuracy-ledger.md, `read-only-pages-written`), and one without
|
||
the bit, a `HEAP_OVER_PAGES`, an `ICB_SLOTS_IN_PAGES` and a Managed
|
||
object's CPU copy over it are refused. The mark is where the host holds that
|
||
line: a process can post any message on its rings, and the pages may be a
|
||
file's, so the kext makes such a block only where the host took the bit,
|
||
and a kext on a host without it refuses read-only memory, which the bundle
|
||
then copies ("No-copy buffers"). A host offers it where it offers
|
||
`PAGES_BUFFERS`, and the kext takes it.
|
||
|
||
**BAR2: the region.** A 64-bit prefetchable BAR over host memory (1 GiB),
|
||
mapped write-back by the guest. The device places the control rings at fixed
|
||
offsets; the guest places everything else. Its pages are committed on the host
|
||
as they are first touched, and the host imports for the GPU only what it reads:
|
||
the scanout's pages, and each block a `*_OVER_HOST_MEMORY` names.
|
||
|
||
1 GiB is the largest size an x86-64 macOS guest takes (measured on macOS 26,
|
||
q35, OVMF):
|
||
- macOS's PCI configurator lays the bus out again at boot. It places every
|
||
64-bit prefetchable BAR below 4 GiB, never in the host bridge's 64-bit window,
|
||
and it misreads a 4 GiB BAR as an I/O BAR.
|
||
- Below 4 GiB the window ends at 0xE000_0000, so a 2 GiB BAR cannot fit.
|
||
- A 1 GiB BAR needs the window to start at or below 0x4000_0000. q35 keeps
|
||
2 GiB of the guest's RAM below 4 GiB when the guest has more than that, and
|
||
then the BAR gets no address: the kext finds no BAR2 and IONDRVFramebuffer
|
||
keeps the display.
|
||
|
||
So the host starts QEMU with `-machine q35,...,max-ram-below-4g=1G` wherever
|
||
the device is present. QEMU then keeps 1 GiB of RAM below 4 GiB and puts the
|
||
rest above, which leaves the guest's memory size unchanged, and the BAR lands
|
||
at 0x4000_0000. The device stays on `pcie.0`: a root port does not help.
|
||
|
||
| offset | size | what |
|
||
|---|---|---|
|
||
| 0x00000 | 64 KiB | control submission ring, id 0 (the kexts to host) |
|
||
| 0x10000 | 64 KiB | control completion ring (host to kext), MSI-X vector 0; the device info at 0x18100 |
|
||
| 0x400000 | 128 MiB | the framebuffer's scanout (`RGFX_SCANOUT_SPAN`) |
|
||
| 0x8400000 | to the cursor | the accelerator kext's blocks: every process's queue rings, Shared buffers and heaps, surfaces |
|
||
| end − 256 KiB | 256 KiB | the framebuffer's cursor image |
|
||
|
||
The control ring is the kexts' alone: the framebuffer's display commands, and
|
||
the object lifecycle the accelerator posts for the Metal processes, under the
|
||
framebuffer's ring lock. Every other ring is one command queue's own ring pair,
|
||
in a block the accelerator kext handed to the queue's process, so each ring
|
||
keeps a single producer and a single consumer however many processes run
|
||
Metal.
|
||
|
||
**Contexts.** Each process that opens the accelerator's user client gets a
|
||
context from the kext: a number `c`, handed out once from 1 (its object ids are
|
||
`c << 40` and up), and a range of GPU addresses, held until its close, from
|
||
which its bundle picks every buffer's, heap's and texture's address
|
||
(`guest/kext/src/RgfxContextSlots.hpp`). The guest's addresses are
|
||
`[2^46, 2^47)` (`RGFX_CONTEXT_VA_BASE` to `RGFX_CONTEXT_VA_END`), which the
|
||
host's own ranges never reach, in 1024 units of 64 GiB
|
||
(`RGFX_CONTEXT_VA_UNIT`); a context holds an aligned run of units: one, unless
|
||
the device's `maxBufferLength` is more than 32 GiB, and then the least power of
|
||
two that holds twice it (at most 32), so a buffer of `maxBufferLength` always
|
||
fits. The kext reads `maxBufferLength` from the device info at the first open.
|
||
`OpenContext` answers the range's span sixth (kext feature `ContextSpan`); a
|
||
bundle that asks for five values picks through `RGFX_CONTEXT_VA_SPAN`, 2 TiB,
|
||
and gets an aligned run of 32 units, so an older bundle keeps working on a
|
||
newer kext, and a newer bundle on an older kext takes the 2 TiB it hands
|
||
out. Runs go round-robin, so a run given back is the last one the next
|
||
contexts take, and the last 32 units free go to WindowServer alone, as the
|
||
blocks' and queues' reserves do. The host knows none of this: it pins each
|
||
address as given. Sized from what a desktop uses, measured on the RTX 5080 host
|
||
(a6e722f47's host and guest, macOS 26.6.1): 17 processes held a context on an
|
||
idle desktop and 74 with 42 apps and 7 WebGL and WebGPU pages open, where the
|
||
32 slots of 2 TiB the kext had before refused the 33rd process and every later
|
||
one. The most GPU addresses one process held at once was WindowServer's 204 MiB
|
||
(in 1525 picks of `RgfxIdSpace::addressSpan`), the largest single pick 35 MiB,
|
||
and the furthest any process's picks went into its range 1.5 GiB (they go
|
||
forward and come round only at its end), so a 64 GiB unit holds the busiest
|
||
process's addresses over 300 times. Past the last run, `OpenContext` answers
|
||
`kIOReturnNoResources`, and the bundle answers no device in that process
|
||
(`initWithAcceleratorPort:` answers nil), which every Metal client handles,
|
||
where a device whose every create answered nil stopped the frameworks that make
|
||
their first objects at its open (Maps, Journal and Photos aborted, Games
|
||
faulted). The kext hands out its region blocks
|
||
(first fit, page granular). The process hands each create and destroy of its
|
||
objects (ids in its range) to the kext by a user-client call; the kext posts it
|
||
on the control ring and, for a pipeline create, hands the reflection back once
|
||
the host answers it. A queue's `QUEUE_CREATE` goes the same way, its rings
|
||
checked to lie in the process's blocks, and is answered once the host has the
|
||
rings. At the process's close or death the kext destroys its queues, then
|
||
closes its context (`CONTEXT_CLOSE`: the host takes its objects out of its
|
||
tables, lets go of them on a worker of its own, `reims-vgpu.graphics-closes-<n>`,
|
||
and answers once it has and the context's command buffers have finished),
|
||
then, on that answer only, frees its chunks of resource ids, its blocks and its
|
||
slot of GPU addresses. A command
|
||
buffer is decoded once the host has carried out every control-ring message of
|
||
its context's published before its queue's thread took it, and has taken every
|
||
message before those.
|
||
|
||
**A buffer's wait on ring 0.** A buffer names only its own context's objects
|
||
and spans in blocks its context holds, so what it can depend on on ring 0 is
|
||
its context's: a message about an object (every type from `QUEUE_CREATE` below
|
||
`CONTEXT_CLOSE`, which the kext takes from a process only with an object id of
|
||
the process's), whose id carries the context's bits, or one the kext posts for
|
||
a context (`CONTEXT_CLOSE` to `SURFACE_PAGES`), which names it.
|
||
Another process's surface reaches a buffer only through the share of its block
|
||
the kext posts for the buffer's context before the process learns of the block,
|
||
after the surface's `SURFACE_PAGES` was answered: what the buffer reads of the
|
||
surface the host made there, and the buffer names none of the other process's
|
||
objects, so it waits for its own context's share and for none of the other
|
||
process's messages. Textures do not cross processes, and a shared event crosses
|
||
only by its name ("Shared events across processes"): the process that makes an
|
||
event of another's posts its own `SHARED_EVENT_IMPORT`, an object message of
|
||
its context's, which its buffers that name the event wait for, and the kext's
|
||
`SHARED_EVENT_UNNAME` is context 0's, which no buffer is. A
|
||
display command (`GET_DISPLAYS` to `SET_DISPLAY_POWER`) or a `SURFACE_DOWNLOAD`
|
||
holds up no buffer: none reads what they make. A present waits for the writers
|
||
the guest's record of its surface names, whatever the host has taken, those of
|
||
a queue created just before among them: the device tells the host of a queue
|
||
before it answers its create, so the present knows the queue though the host has
|
||
yet to make its handle. A
|
||
download waits for the buffers that used the surface's device cache before it
|
||
was taken, so a buffer posted after it that writes the surface, but taken
|
||
before it, is among them, as one posted before it is: the guest writes a
|
||
surface a CPU lock holds only racing the lock. Every buffer waits for a message
|
||
of any other type, which the host refuses. The queues' threads read
|
||
ring 0 ahead of the control thread, each message once, and keep the count
|
||
through each context's last message (`reims_vgpu_graphics`'s `device::backlog`), so
|
||
a buffer behind another process's backlog on ring 0 is decoded at once.
|
||
Tested by `a_command_buffer_waits_for_no_other_process_s_creates`,
|
||
`a_command_buffer_waits_for_no_other_process_s_later_object_messages`,
|
||
`a_process_s_messages_go_on_while_another_s_create_is_carried_out`,
|
||
`a_command_buffer_waits_for_its_share_of_another_process_s_surface_not_for_that_process`
|
||
and `a_doorbell_write_answers_a_command_buffer_behind_another_process_s_create`.
|
||
|
||
**Ring 0's lanes.** The control thread takes ring 0 in ring order and carries
|
||
out only the display commands itself. It hands each context's messages, in ring
|
||
order, to that context's lane, every `PRESENT_SURFACE` and `DISPLAY_COLOR` to
|
||
the presents' lane, in ring order, and every `SURFACE_PAGES` and
|
||
`SURFACE_DOWNLOAD` to the lane of the block it names, whichever process posted
|
||
it and for whichever context, so a block's pages handed over from another
|
||
process's CPU lock, or after its maker closed, and the download or release
|
||
posted right after them, keep their order without waiting for the maker's lane.
|
||
A lane carries its messages out one at a time and posts their answers, so one
|
||
process's slow message (a heap over pages took 469 ms at the median and 4.25 s
|
||
at most in a boot on an RTX 5080 host) holds up only that process's later
|
||
messages and command buffers. A message
|
||
waits for another context's lane only where it reads what that lane's earlier
|
||
messages change, and only for messages published before it
|
||
(`reims_vgpu_graphics`'s `device::lanes`):
|
||
- a present waits for each lane's `TEXTURE_FROM_IOSURFACE` of its surface's
|
||
plane 0, its destroy of a texture the host names the surface by, and the
|
||
close of a context that holds one: the host shows the newest live texture
|
||
over the surface;
|
||
- a shared block's `BLOCK_RELEASE` waits for each other context that held it:
|
||
the host refuses a release while an object of any context lies in the block;
|
||
- a `BLOCK_GRANT` in the scanout's span waits for every lane: a grant takes the
|
||
span from whoever held it, and WindowServer's contexts are granted it in turn;
|
||
- a `RESOURCE_ID_CHUNK` or `RESOURCE_ID_SMALL_CHUNK` of ids another context
|
||
held waits for that context's close,
|
||
and a context's first message for every close before it, whatever the
|
||
context's number (the kext numbers contexts at their opens, and a process
|
||
may post its first message after one opened later): the kext frees a closed
|
||
context's chunks and its slot of GPU addresses once the close is answered;
|
||
- a context's message waits for each block's lane through the context's last
|
||
`SURFACE_PAGES` on it, and a command buffer for its context's messages on
|
||
the blocks' lanes too, as when they shared the context's lane;
|
||
- a `BUFFER_OVER_PAGES`, `HEAP_OVER_PAGES`, `BUFFER_OVER_SURFACE_PAGES` or
|
||
`BLOCK_RELEASE` waits for its block's lane: each reads the view or device
|
||
cache the block's lane makes and copies;
|
||
- a `SURFACE_PAGES` waits for its context's lane only through the last message
|
||
of those four kinds that names its block, and for each lane through its last
|
||
`BLOCK_RELEASE` of a block described cached whose runs share a page with its
|
||
own: the release copies that block's device cache into the pages, and the
|
||
kext makes a surface's new block over them once it has waited 10 s for the
|
||
release's answer, when a slow message on the release's lane may still hold
|
||
it; a `SURFACE_DOWNLOAD` waits for no other lane, as on the control thread
|
||
before.
|
||
|
||
`reims_vgpu_graphics`'s `device::lanes` lists every message that names a block or
|
||
its pages by offset, and what orders each against the block's lane.
|
||
|
||
A close's job on its lane is its table work: it lets go of the context's
|
||
objects on the closes' worker (`reims-vgpu.graphics-closes-<n>`), which the
|
||
close's answer waits for, so a message that waits for a close waits for none
|
||
of the platform's releases (an event's took 0.4 ms on an RTX 5080 Laptop GPU,
|
||
measured by the decoder's `close_cost`). A reset waits for the closes before it
|
||
to have let go of theirs.
|
||
|
||
Each wait is for a message published earlier, and every lane with a message
|
||
has a thread, so the waits end. What the guest can tell apart from one thread:
|
||
answers to different processes come in another order than their messages,
|
||
which the kext matches by seqno; and two processes' messages that no answer
|
||
orders are carried out in either order, as the processes' own posts race. A
|
||
process that waited for an answer finds its message carried out. A reset drops
|
||
the messages a lane has not begun, and is told to the host once those begun
|
||
have returned. A lane's thread is woken only for its own messages and for the
|
||
lanes its next message waits for, and a lane with nothing to do holds no
|
||
thread, whatever other processes do.
|
||
|
||
Ring 0's threads (`reims-vgpu.graphics-ring0-<i>`) serve the lanes. A lane
|
||
handed a message while it has no thread is given the thread that went idle
|
||
last, or one made for it where none waits, and keeps it until it has no
|
||
message left; the thread then waits for the next lane, and goes once it has
|
||
waited 10 s for one (`reims_vgpu_graphics`'s `keep`). So the device holds as many
|
||
threads as it had lanes busy at once in the last 10 s, whichever contexts and
|
||
blocks they were. With a thread of each lane's own, made as a message came to a
|
||
lane with none and gone after 1 s with none, every new block's first
|
||
`SURFACE_PAGES` made a thread, and so did every lane's message after a pause of
|
||
a second: 345 threads were made in 30 s of a WindowServer probe, and a vCPU sat
|
||
30 ms or more in a page fault while one of them unmapped its 2 MiB stack, a
|
||
write of the process's memory map the fault waits behind (car 12's B1, RTX 5080
|
||
host; measured). Tested by
|
||
`a_present_waits_for_another_context_s_texture_over_its_surface`,
|
||
`a_present_waits_for_a_destroy_or_a_close_of_a_texture_over_its_surface`,
|
||
`a_present_waits_for_no_message_that_leaves_its_surface_s_textures`,
|
||
`a_shared_block_s_release_waits_for_its_other_holders`,
|
||
`an_unshared_block_s_release_waits_for_no_other_context`,
|
||
`a_scanout_grant_waits_for_every_context_s_messages_before_it`,
|
||
`a_chunk_or_a_new_context_waits_for_the_close_before_it`,
|
||
`a_shared_block_s_release_behind_a_holder_s_close_waits_for_none_of_its_releases`,
|
||
`a_reset_waits_for_a_close_s_slow_release`,
|
||
`a_context_s_first_message_waits_for_the_close_before_it_whatever_its_number`,
|
||
`a_sync_create_is_answered_before_its_context_s_later_messages_are_carried_out`,
|
||
`a_context_s_answer_comes_before_one_published_ahead_of_it_by_another_context`,
|
||
`a_reset_drops_what_the_lanes_have_not_begun`,
|
||
`a_steady_load_s_lanes_are_served_by_one_thread_through_its_pauses`,
|
||
`a_burst_s_other_threads_go_once_they_have_waited_keep` and
|
||
`lanes_keep_every_order_over_random_interleavings`, which checks random
|
||
interleavings of several processes' messages against an order worked out from
|
||
the messages alone. A synchronous create's answer takes 7.2 us on average from
|
||
its doorbell, against 4.1 us from the control thread alone
|
||
(`a_sync_create_s_round_trip`, release build, M3 Max). After a pause of 1.2 s,
|
||
in which the lane's thread went to wait for another lane, it took 64 to 171 us
|
||
at the median of three runs, against 116 to 353 us where the pause ended the
|
||
lane's thread and the create made it again (the same test, alternating runs on
|
||
the M3 Max under other builds' load). A context's burst of 200
|
||
messages and a synchronous create take as long beside 75 idle lanes as beside
|
||
none: 0.1 to 1.4 ms at the median either way, on the M3 Max under other builds'
|
||
load (`a_burst_beside_idle_lanes`, release build).
|
||
|
||
A queue's thread waiting for ring 0 before it hands a command buffer on is
|
||
woken once the control thread has taken the messages the buffer waits for, and
|
||
once its context's lane has carried out the context's among them, and by
|
||
nothing else but a reset, its queue's end and the device's
|
||
(`reims_vgpu_graphics`'s `device::gate`): no other process's message wakes it.
|
||
Tested by `the_gate_wakes_each_waiter_once_what_it_waits_for_holds`, which
|
||
moves the count and many contexts' lanes at random beside many waiting
|
||
threads. Beside 75 other processes' queues each waiting on a held create, a
|
||
context's burst of 200 messages and a synchronous create took 11 to 16 ms at
|
||
the median when every lane's message and control step woke every waiting
|
||
queue, and take 49 to 123 us now, as beside none
|
||
(`a_burst_beside_waiting_queues`, release build, M3 Max under other builds'
|
||
load).
|
||
|
||
A queue's thread that waits so for its context's lane carries out the lane's
|
||
next job itself where no thread of the lane's carries one out yet, the buffer
|
||
waits for it, and it is a `BUFFER_AT_OFFSET` or an `OBJECT_DESTROY` of no queue:
|
||
the creates and destroys the bundle holds and posts ahead of each commit
|
||
("Destroys and creates no one waits for go together"). The job is the lane's
|
||
running one meanwhile, so the lane still carries its jobs out one at a time in
|
||
ring order, and the lane's thread waits for it before its next. The buffer
|
||
waits for the same messages as before, carried out through the same host code
|
||
before its begin; only the thread that carries them out changes, and the
|
||
buffer's wait ends with neither a ring-0 thread's wake before the job nor its
|
||
own after it. A queue's destroy routes the queue's doorbell and ends a queue's
|
||
thread, and the other kinds may wait long or for a queue's command buffers, so
|
||
each stays with the lane's thread. Measured before the change in Geekbench
|
||
7.1's Super Resolution on the Radeon 780M (a macOS 26.7.2 guest, development
|
||
cee5813f2's timed pass, 19.19 s): 3480 of 6289 command buffers waited so, 30.2
|
||
us at the median and 87.5 us at the 90th percentile from the take to the gate's
|
||
end, 138 ms in all. Each waited only for those two kinds, 6 jobs at the median
|
||
that ran in 17.5 us, and 8.8 us at the median went on the queue's thread's wake
|
||
after the last of them. 56% of them found a ring-0 thread already carrying one
|
||
out at the take, which carries the rest on as before. For the others, carried
|
||
out on the trace's own times with the wakes taken away, the waits shrink by 42.5
|
||
ms over the workload (45.5 ms in the warm pass), 0.2% of it: under a walk's
|
||
run-to-run spread (about 0.5%), so the change was not walked apart. A wait
|
||
without sleeping before the gate was measured against the same trace and
|
||
dropped: it saves only the queue's thread's own wake, at most 17 ms over the
|
||
workload for 34 ms of a core spinning. Tested by `a_buffer_s_thread_carries_out_the_creates_and_destroys_it_waits_for`,
|
||
`a_buffer_s_thread_leaves_other_kinds_to_the_lane_s_thread`,
|
||
`only_a_buffer_at_offset_and_a_destroy_of_no_queue_are_a_buffer_s_thread_s` and
|
||
`buffers_wait_for_their_context_s_messages_over_random_interleavings`.
|
||
|
||
**The surface and ICB workers.** A lane hands what it would wait long for, and
|
||
the guest learns of only through an answer or a later message, to a worker of
|
||
the host's: a `SURFACE_PAGES`, whose view of a 3840x2400 layer took 9000
|
||
mappings, made in 16 to 478 ms (msi 5080 host), a pages block's
|
||
`BUFFER_OVER_PAGES` that makes or follows such a view, the let-go of a released
|
||
block's views and device cache and of a buffer over a view at its destroy, and
|
||
an `ICB_CREATE`. A worker runs the jobs of one
|
||
key one at a time, in the order they were handed over, and different keys' at
|
||
once, on at most four threads (`reims-vgpu.graphics-surfaces-<i>`,
|
||
`reims-vgpu.icb-create-<i>`), each made as a job finds none waiting and gone
|
||
after 10 s with none; a job wakes the thread that went idle last, so a steady
|
||
load's jobs stay on the threads it runs at once. The surface worker's key is the block, the ICB
|
||
worker's the process. So a block's slow view holds up only that block's later
|
||
jobs, and a key that finds every thread busy waits for the next free one. No
|
||
job waits for a job of another key, so jobs waiting for a thread never wait
|
||
for each other: a `BUFFER_OVER_PAGES` waits only for its own block's
|
||
`SURFACE_PAGES`, done before it, and a `SURFACE_PAGES` for nothing, as a debug
|
||
build checks. What the guest can tell apart from one thread: two
|
||
`BUFFER_OVER_PAGES` of one process on different blocks are made in either
|
||
order, which no answer orders, and the process's later messages wait for
|
||
both. Where the host groups the pages blocks' views (below, "Group dma-bufs of
|
||
the pages blocks' views"), a group's seal is a job under its process's key,
|
||
which waits at most for the group's 1 ms window, never for another key's job,
|
||
and then carries out its members' messages. Tested by
|
||
`a_key_whose_job_hangs_holds_no_other_keys_jobs`,
|
||
`a_key_waits_for_a_free_thread_once_every_thread_is_busy`,
|
||
`each_keys_jobs_run_one_at_a_time_in_handed_order`,
|
||
`an_idle_thread_ends_after_keep` and
|
||
`jobs_after_a_burst_go_to_the_thread_that_went_idle_last`. Beside K blocks that each run 25 ms
|
||
jobs back to back, another block's job starts after its hand-off in 0.015 ms at
|
||
the median for K of 1 or 2, 5 to 6 ms for 4, 22 to 23 ms for 6 and 35 to 38 ms
|
||
for 8, where one thread took 24, 54 to 56, 115 to 117, 179 to 182 and 241 ms
|
||
(`another_blocks_job_beside_busy_blocks`, two runs of each, release build, M3
|
||
Max at load averages of 28 to 52).
|
||
|
||
**WindowServer's reserve.** The blocks have no per-process cap: Metal on a Mac
|
||
refuses an allocation only when memory runs out, never because another process
|
||
holds much, so neither does the kext. The one process whose refusal would stall
|
||
every other is the compositor. So the last 160 MiB of the blocks' room and the
|
||
last 4096 of the table's 16384 entries go only to WindowServer's blocks
|
||
(`RgfxBlockTable`'s reserve). WindowServer takes the first gap from the start
|
||
like any process, and reaches into the reserve only once the rest is full; any
|
||
other process is refused at the reserve's edge, as at the region's end. Of the
|
||
watched rings, the last 64 are WindowServer's alone in the same way, past room
|
||
for one process's 2048 queues beside as many of the others'
|
||
(`RgfxQueueLimits.hpp`). The kext logs the most
|
||
WindowServer's blocks and queues came to, which is what the reserve is sized
|
||
from: on an RTX 5080 host at the display's 3840x2400 mode, WindowServer held
|
||
134 MiB at most, at login, and 118 to 126 MiB in 110 to 366 blocks as five apps
|
||
opened, with 2 queues (measured). With some 70 processes open its blocks came to
|
||
1358 and 169.7 MiB, past the reserve's 160 (measured), most of the bytes its
|
||
no-copy buffers' copies and its Managed textures' CPU copies. Those lie in its own
|
||
pages now, as its Managed buffers' CPU copies and its encoders' upload chunks
|
||
do ("Managed storage"), so what WindowServer keeps in the region is what no page
|
||
of its own can hold: its rings, its command buffers' bodies and its surfaces'
|
||
blocks. The entries hold three times the
|
||
1358 blocks. A larger display, or a second one, needs the reserve measured
|
||
again.
|
||
|
||
The kext knows WindowServer's client by two tests at its open: the opening
|
||
process is named `WindowServer`, and it holds the entitlement
|
||
`com.apple.private.graphics-restart-no-kill`
|
||
(`IOUserClient::copyClientEntitlement`). WindowServer holds that entitlement on
|
||
macOS 26.7.1 and 27, read from its signature (`com.apple.WindowServer`,
|
||
a platform binary). With SIP on, AMFI refuses any `com.apple.private`
|
||
entitlement to a binary Apple did not sign. So a process that only takes
|
||
WindowServer's name fails the second test. The direct tests, the process's
|
||
signing identifier and its platform-binary status (`cs_identity_get`,
|
||
`csproc_get_platform_binary`), are in `com.apple.kpi.private`, which a kext
|
||
outside Apple's namespace cannot link. Resolving them at run time through the
|
||
loader is not worth its risk.
|
||
|
||
**WindowServer's queues are unshared.** The host's runtime may let command
|
||
queues share a GPU queue, which raises the rate of small command buffers on a
|
||
GPU whose switches between queues idle it. A shared queue can then hold
|
||
another process's long command buffer ahead of the compositor's frame. So
|
||
the accelerator flags every queue WindowServer's process creates
|
||
`RGFX_QUEUE_UNSHARED` in its `QUEUE_CREATE`'s tail, where the host offered
|
||
`UNSHARED_QUEUES` and the framebuffer took it (`rgfxQueueFlagsSent`,
|
||
`RgfxFeatures.hpp`). It decides from its own test of the client's task at
|
||
the open (above), never from what the process asks: `QueueCreate`'s seventh
|
||
input never grants the flag. The host makes such a queue with the platform's
|
||
`new_command_queue_unshared` (`GpuDevice`): on the Vulkan platform the
|
||
runtime's queue `unshared_queue` makes, and on Metal the queue any create
|
||
makes. The host logs each unshared queue
|
||
at debug level, on its own target (`reims_vgpu::graphics::queues`). Nothing
|
||
the guest's processes see changes.
|
||
|
||
**Reset.** A reset leaves the device as one just made, as a device's
|
||
function reset does: `STATUS` 0, which the framebuffer writes at its start,
|
||
and QEMU's reset of the device, which a reboot inside one QEMU run makes.
|
||
Every command queue ends, no block is any process's, and the host drops every
|
||
object of every context, as each one's close does, with no answer owed. The
|
||
blocks' surface views and device caches go too, uncopied, since their pages
|
||
are the rebooted guest's again, and so do the library cache, the presents
|
||
waiting and the pipelines compiling. Nothing begun before the reset reaches
|
||
the guest after it. The guest then finds what a new device gives it: the ids
|
||
it picks free from 1 again, every texture resource id and GPU address free
|
||
(a range a buffer of the guest's before the reset still held would refuse the
|
||
rebooted WindowServer's pin of it), a library lookup that misses, and VBLANK
|
||
counts from 0. What the guest wrote in the region stays.
|
||
|
||
The display keeps its scanout across a reset, as a GPU's display engine goes
|
||
on scanning out across a reset of its driver: the host's window shows what
|
||
the guest writes there until the guest sets another scanout or blanks it.
|
||
The kext's start resets the device to take it, and where the start fails
|
||
after that (the device lists no usable display, or `IOFramebuffer`'s start
|
||
fails) it resets it again on the way out; the OS then draws into the
|
||
firmware's framebuffer, which the firmware's scanout, kept through both
|
||
resets, still shows. Tested by
|
||
`a_reset_keeps_the_scanout_and_what_the_guest_writes_there_shows`
|
||
(`reims-vgpu-graphics`) and
|
||
`a_failure_after_the_take_keeps_the_firmware_s_scanout_in_the_window`
|
||
(`graphics/tests.rs`).
|
||
|
||
**Texture resource ids.** Every process's textures share the host's one
|
||
device, whose texture ids end below 16381: Metal ends the process for a texture
|
||
placed at 16381 or more (measured on an M4 and an M3 Max), and metal2vulkan
|
||
imitates that. So ids are not split by slot. The kext keeps one pool for the
|
||
guest, the ids 1 to 16320, in 1020 small chunks of 16 (small chunk `k` holds
|
||
`1 + 16k` to `16 + 16k`), and hands a process a chunk when it asks (user-client
|
||
selector 0x106), posting the grant on the control ring before it returns, so
|
||
the host has it before any create naming its ids. Where the host offers
|
||
`SMALL_ID_CHUNKS` the chunk is one small chunk (`RESOURCE_ID_SMALL_CHUNK`:
|
||
context, small chunk); else it is an aligned run of four, chunk `k` of 64 ids,
|
||
`1 + 64k` to `64 + 64k` (`RESOURCE_ID_CHUNK`: context, chunk), as a host from
|
||
before the bit takes. A process that makes a texture holds a chunk until its
|
||
close, so 64-id chunks let 255 texture-making processes run at once, fewer
|
||
than the 1024 contexts the GPU addresses hold (a busy desktop held 74,
|
||
"Contexts"), where small chunks let 1020; the pool's ids are as many either way.
|
||
The host reserves the pool's ids on its device as it makes the graphics device,
|
||
its first call on the device (`reserve_guest_texture_ids`,
|
||
`crates/reims-vgpu/src/graphics.rs`). The Vulkan platform is told the ids before
|
||
the device is made and reserves them as the device's first call, before its own
|
||
probes: on Linux, a GPU whose imports of views need their pages mapped from
|
||
their files makes a command queue as its device is made, where its driver's
|
||
fold verdict is not kept yet (a cold cache, a new driver or kernel). Metal hands
|
||
the id of a texture placed at one out again to plain allocation, so without it
|
||
the guest's textures would share ids with the host's own (the window's
|
||
drawables, the cursor), and a texture placed past the table a fresh device has
|
||
corrupts Metal's heap (placements from 10000 up
|
||
crashed some runs). The reservation keeps the ids from plain allocation and grows
|
||
the table to hold them (measured on an M3 Max, macOS 27; metal2vulkan imitates
|
||
both). Metal takes one only before the device's first texture, and once the device
|
||
has a queue it hands the pool's first range out twice, so the host checks it with
|
||
a few plain textures and logs an error where one takes a guest id. Were the
|
||
paravirt lane's device in the same process, on the same GPU, the graphics lane's
|
||
reservation would win: it is made as the device is, before any guest runs, while
|
||
the paravirt lane reserves its placed objects as each task starts, and Metal takes only
|
||
a type's first reservation. That would not make the two safe together: both lanes'
|
||
guests place textures in the device's one table, at ids each picks alone. So a
|
||
process runs one lane's device on a GPU, and today a VM has one lane or the other.
|
||
The bundle keeps each small chunk's free ids in one 16-bit mask, takes the lowest
|
||
free id of the first small chunk taken that has one, asks for a chunk only when all of its are
|
||
in use, and gives an id back as its texture goes, after the texture's destroy
|
||
(below), so a later create with the id follows the destroy on ring 0.
|
||
The host names an IOSurface by every live texture over its plane 0, and shows
|
||
the latest. A present holds its own reference to the texture it shows, so a
|
||
destroy after the present leaves the window's frame drawable. A process keeps its chunks
|
||
until its close. With every chunk held, a texture create answers nil, as Metal
|
||
answers a texture it cannot make. The host carries out a texture create only
|
||
where its id lies in a chunk of its own context (by the object id's context);
|
||
any other id, 0 and the limit's included, is refused before any platform call,
|
||
as a refused create is: unanswered, and an id of its own context then stands
|
||
for a refused object, whose uses are dropped ("Guest input the host refuses").
|
||
Sampler states and pipeline states take no guest-picked ids (the host numbers
|
||
them), and the bundle makes no indirect command buffers, so textures are the
|
||
only kind with chunks.
|
||
|
||
**Objects go with their wrappers.** Every host object the bundle makes goes
|
||
from the host as the app lets its wrapper go. A buffer, heap, texture, sampler,
|
||
depth-stencil state, render or compute pipeline, library, event, fence or shared
|
||
event posts its `OBJECT_DESTROY` from its dealloc. Samplers and depth-stencil
|
||
states are made once a descriptor: the device answers an equal descriptor,
|
||
label included, with the object it made, as the M3 Max's Metal does, and keeps
|
||
the last 64 of each kind it made after the app lets them go, so an app that
|
||
makes one every frame pays one create (`guest/bundle/src/RgfxStateCache.h`).
|
||
A queue ends through the kext
|
||
(user-client selector 0x104), which stops watching its completion ring and
|
||
posts the destroy. Command buffers ride their queues' own rings, so a destroy
|
||
must not reach the host before a buffer that names the object. A command buffer
|
||
keeps every object its encoders name, from the encode until its completion
|
||
handlers have run, or until it goes uncommitted, as Metal's with retained
|
||
references keeps what it encodes. One made with unretained references keeps them
|
||
too, though it answers `retainedReferences` NO, since the host must not drop an
|
||
object before a buffer that names it runs. A buffer whose completion never comes
|
||
holds back only what it names. Objects are released in the order they go. What an object lay over goes back only after its destroy: a Shared buffer's
|
||
or heap's region block, an IOSurface plane's block, a queue's ring blocks (its
|
||
completion ring read no more first), and a texture's resource id. The block's
|
||
`BLOCK_RELEASE` then finds nothing of the object on the host. A resource placed
|
||
in a heap keeps the heap alive (its `heap`), a command buffer keeps its queue,
|
||
and a function keeps its library. So a pipeline made from a function whose
|
||
library the app let go names a library the host still holds. The host makes the
|
||
pipeline from the library before the library's destroy, and the pipeline needs
|
||
it no more.
|
||
|
||
**Destroys and creates no one waits for go together.** Each call into the
|
||
kext costs the guest its trip through the kernel, and a post that finds the
|
||
host's control thread asleep a doorbell's exit too: 14 us a destroy in a Vision
|
||
request on the RTX 3090 host (9 to 10 us without the doorbell), 3415 destroys
|
||
and 68 to 70 ms a process, in runs of about 70 an app lets go back to back,
|
||
and 12 to 15 us a `BUFFER_AT_OFFSET`, the buffer a heap places (each small
|
||
buffer of a slab), 3079 and 40 to 48 ms a process, between them; and on the
|
||
RX 7900 XTX host 8 to 13 us each of a Vision process's 276
|
||
`TEXTURE_CREATE`s, 82 `TEXTURE_VIEW`s, 46 `MANAGED_TEXTURE_CREATE`s, 204
|
||
`MANAGED_BUFFER_CREATE`s and 204 `BUFFER_DID_MODIFY_RANGE`s, 8.8 ms a
|
||
process. So where the kext
|
||
carries `SubmitBatch` (selector 5), the bundle holds each of these messages,
|
||
none of which anyone waits for or which names a block
|
||
(`RgfxSerializer::postUnwaited`, `RgfxRingWriter::postLater`), and posts what
|
||
it holds in one call, at most 4096 bytes (170 destroys, 73 buffers, 39
|
||
textures), before anything else the process posts
|
||
or asks of the kext (every `IOConnectCall` of the device's goes through
|
||
`rgfxKextConn`, which posts the held first) and before any command buffer it
|
||
commits (the host reads a command buffer after the control ring's messages
|
||
posted before it), once the held fill a call, or 1 ms after the first held.
|
||
The kext checks each as `Submit` checks one, all before it posts any, puts
|
||
the runs on the ring under one hold of its lock with one doorbell at most,
|
||
ends a queue's as `Submit` does, after the messages before it, and follows a
|
||
buffer made for a context that closed since its check with its destroy, as
|
||
`Submit` does. What an object lay over goes back as its destroy is held, as it
|
||
went back once its destroy was posted: whatever takes it again, a create over
|
||
the bytes or with the id, or a block's free, is posted after the destroy, so
|
||
the host has dropped the object first, and every answer the guest reads (a
|
||
heap's `usedSize`, a new object's GPU address and resource id) is the one it
|
||
read before. A texture over an IOSurface goes at once, made and destroyed: a
|
||
present of the surface, by any process, shows the newest live texture the
|
||
host names it by, and waits for its create and its destroy. So do the creates
|
||
that name a block (`BUFFER_OVER_PAGES`, `BUFFER_OVER_SURFACE_PAGES`), which the
|
||
block's lane orders.
|
||
Where the kext stops taking them (its ring stayed full 5 s, or the device
|
||
stopped), the rest stay held, first: the process's next post retries them,
|
||
under its own post's bound, and is refused only where they are refused again,
|
||
as the full ring refuses it; a commit that finds a buffer still held fails the
|
||
command buffer, unposted, with `MTLCommandBufferErrorInternal`, as a GPU
|
||
recovery's victim fails, as the buffer may name it; so does any message held
|
||
but a destroy, each of the kinds above (a create the buffer may name, a
|
||
Managed range it may read). Two answers differ from an unbatched post's
|
||
then, and only then: an object held when the kext stopped taking them was
|
||
answered as made, where its refused post answered nil (as Metal makes
|
||
objects on a GPU that is gone, and fails the work at commit), and its
|
||
refusal reaches the app at the next post, refused in that call, or the next
|
||
commit, failed, never later; and
|
||
what the held destroys lay over has gone back, which a guest reading a heap's
|
||
`usedSize` through a 5 s stall of the control ring sees lower than it did.
|
||
Tested by `serializer_tests`' `test_held_destroys` and
|
||
`test_held_buffers` and `test_held_creates`, `shell_tests`'
|
||
`test_held_destroys_change_nothing_seen`,
|
||
`test_surface_texture_destroys_go_at_once` and
|
||
`test_commit_behind_an_untaken_buffer_fails`, and the kext's by
|
||
`submit_gate_test`, `spans_test` and `user_client_words_test`.
|
||
|
||
**A commit behind held messages is one call.** A command buffer committed
|
||
while the control ring holds messages (above) made two kext calls: the held
|
||
went in a `SubmitBatch`, and the bundle then published the buffer on its
|
||
queue's ring and, where the host's queue thread slept, rang its doorbell
|
||
through the kext. Where the kext takes it (1 << 11 `QueuePublish`), the
|
||
bundle writes the buffer on its ring and fences its stores, but leaves the
|
||
producer, and hands the queue, the new producer and the doorbell's flags
|
||
(whether the host answers the buffer at the doorbell, and whether that
|
||
doorbell names `RGFX_DOORBELL_ASKS`) to the `SubmitBatch` that posts the held
|
||
(`RgfxRingWriter::tryPost`'s `via`, `RgfxSerializer::publishVia`). Once
|
||
every held message is posted, the kext stores the producer, fences, reads
|
||
`consumer_idle` and rings the queue's doorbell as the bundle would
|
||
(`RgfxQueuePublish.hpp`), so the host sees what it saw before: the held on
|
||
ring 0, then the buffer on its queue's ring. The kext keeps a kernel mapping
|
||
of each queue's ring header for it, made at the queue's create while the
|
||
ring's block is pinned, and let go at the queue's destroy, at the free of
|
||
the block the ring lies in and at the context's close, before the blocks go,
|
||
so it never writes a ring the process no longer holds; a queue past its first
|
||
64, or a ring outside the process's own blocks, has its buffers published by
|
||
the bundle. A commit with nothing held, or behind an encode into an indirect
|
||
command buffer or a refused destroy waiting, goes as before. Where the kext
|
||
leaves a held message other than a destroy unposted, it publishes nothing,
|
||
and the bundle takes the buffer off its ring unseen (its seqno the next
|
||
buffer's, its completion's handlers dropped) and fails it as above; with
|
||
only destroys left, the bundle publishes the buffer itself. The buffer's
|
||
posted time (`GUEST_TIMES`) is stamped before the call, not just before the
|
||
producer moves. Tested by `shell_tests`'
|
||
`test_commit_hands_its_publish_to_the_held` (the route, nothing held, a kext
|
||
without the feature, a refused create and refused destroys) and the kext's
|
||
`queue_publish_test` (the publish against the bundle's own, and the headers'
|
||
table).
|
||
|
||
**A waiter looks for its answer.** A lifecycle message the kext waits for
|
||
(`postLifecycle`: a heap texture's size, a library's lookup, a surface's
|
||
pages) is answered within tens of microseconds of its post, 60 to 110 us for a
|
||
surface's pages on the RTX 3090 host; the answer then waited for the
|
||
interrupt, the work loop's wake and the waiter's, about 25 us more. So the
|
||
waiter looks for it for at most 150 us (`RgfxAnswerLook.hpp`) before it
|
||
sleeps: where the control completion ring holds a record the work loop has
|
||
not taken, it takes the ring in the work loop's gate, as the work loop does,
|
||
and else pauses the CPU. It never waits for the gate: where another thread
|
||
holds it, the waiter pauses and looks again, so a holder that waits for a lock
|
||
the waiter's caller holds is bounded by the waiter's deadline, as before. The
|
||
rest of the work loop's service follows at the interrupt the record raised. Only a thread whose call waits for an answer
|
||
looks, and only that long; a later answer wakes it as before. Tested by the
|
||
kext's `answer_look_test`.
|
||
|
||
**Rings.** A 256-byte header, then a byte ring whose size is a power of two
|
||
(64 KiB minus the header for the control rings). Each header field sits in its
|
||
own 64-byte line:
|
||
|
||
| offset | field | written by |
|
||
|---|---|---|
|
||
| 0x00 | `producer`: u64, free-running byte count | producer |
|
||
| 0x08 | `completed_seqno`: u64, on a queue's completion ring the seqno of the last command buffer that finished OK, 0 before one has | host (queue completion rings) |
|
||
| 0x10 | `producer_waiting`: u32, 1 while a producer waits for room (`SUBMIT_ROOM`, `CONSUMED_DOORBELL`) | the waiting side; host 0 |
|
||
| 0x18 | `guest_clock_offset_ns`: i64, on ring 0 where the guest took `GUEST_TIMES`, the guest's clock less the host's | guest (ring 0) |
|
||
| 0x20 | `guest_clock_bound_ns`: u32, how far that offset may be off; 0 while the guest holds none, stored after it with release | guest (ring 0) |
|
||
| 0x40 | `consumer`: u64, free-running byte count | consumer |
|
||
| 0x80 | `consumer_idle`: u32, 1 (`RGFX_CONSUMER_ASLEEP`) while the consumer sleeps, 2 (`RGFX_CONSUMER_WALKING`) while a queue's consumer walks a command buffer | consumer |
|
||
| 0xc0 | `armed`: u32, 1 when the guest wants an interrupt | guest (completion rings) |
|
||
|
||
- A message starts with `type: u32`, `size: u32` (bytes including this
|
||
16-byte header, a multiple of 8) and `seqno: u64`. The guest numbers its
|
||
commands from 1, per ring. A message never wraps: type 0 pads to the
|
||
ring's end.
|
||
- Doorbell. The producer writes the message, publishes `producer` (release),
|
||
then issues a full fence and reads `consumer_idle`. If it reads 1, it writes
|
||
the ring's id to `DOORBELL`; if it reads 2, it does so only for a command
|
||
buffer whose last op asks for its `CB_SUBMITTED`, which the host may answer
|
||
inside the write. Under `DOORBELL_ASKS` that buffer's write carries
|
||
`RGFX_DOORBELL_ASKS` with the id, and every other write the id alone. Before sleeping, the consumer sets `consumer_idle` to 1,
|
||
issues a full fence and reads `producer` again, so no wake is lost. It
|
||
clears `consumer_idle` when it wakes. A queue's consumer sets it to 2 while
|
||
it walks a buffer on its own thread, after which it takes the ring again
|
||
with no doorbell. A producer that rings only on 1 rings for nothing on 2,
|
||
and its asking buffer is answered at that take.
|
||
- Interrupts. The host publishes a completion, issues a full fence and reads
|
||
`armed`. If it reads 1, it clears it and raises the ring's vector. The guest
|
||
sets `armed` after draining, issues a full fence and checks `producer`
|
||
again.
|
||
- The re-arm. A consumer already awake (the completion thread after a
|
||
buffer's `CB_SCHEDULED`) can take a record between the host's publish and
|
||
its clear, and arm again: the clear then takes an arm made after the take,
|
||
and its vector comes for a record already taken, so the thread sleeps with
|
||
`armed` 0 and the host raises nothing for the next record. So where the
|
||
clear reads 1, the host reads `consumer` too, and where the guest has taken
|
||
every record published, sets `armed` back to 1 and raises nothing
|
||
(`ring.rs`, `rearm_or_raise`). The guest stores `consumer` before it arms,
|
||
so a clear that read its arm sees its take, and only the host writes 0, so
|
||
the 1 undoes nothing of the guest's. The fix is the host's alone: no kext or
|
||
bundle changes, and ring 0's completion ring takes it too.
|
||
- The completion thread's arm, once. The header is uncached memory to the
|
||
guest on an AMD host, so the completion thread writes it only where
|
||
something changed (`RgfxReplyReader::armAndCheck`): a ring its last arm
|
||
found empty, from which it has taken nothing since, it does not arm again
|
||
while `producer` reads as it did then, as the host clears `armed` only in a
|
||
post, after its publish; and a pump that took nothing leaves `consumer` as
|
||
it was.
|
||
`ring/interleavings.rs` walks every interleaving of the host's post, the
|
||
kext's look and the completion thread's take, arm, arm skipped and sleep (up
|
||
to 3 records and 2 vectors for something else): none leaves a record
|
||
untaken or the thread asleep unarmed. The kext's take of ring 0's
|
||
completion ring, at each interrupt of the control vector, which every
|
||
queue's completions share, and at a waiter's look, keeps the same rule
|
||
(`ReimsGraphics::takeCompletions`, `RgfxCompletionArm.hpp`): it arms only
|
||
where it took records since its last arm or that arm found records behind
|
||
it, and stores `consumer` only where it moved; `completion_arm_test` walks
|
||
every interleaving of the host's post against its take. A wake index the
|
||
host only reads (virtio's `used_event`) was weighed and declined: it would
|
||
change a ring's format in the host, the kext and the bundle, and the
|
||
re-arm closes the race without one.
|
||
|
||
**Control commands** (guest to host, ring 0). Each is answered by a
|
||
`COMPLETE` with its `seqno` and a status (0 for success), or by the reply
|
||
named.
|
||
|
||
| type | name | payload | answer |
|
||
|---|---|---|---|
|
||
| 1 | `GET_DISPLAYS` | none | `DISPLAYS` |
|
||
| 2 | `SET_SCANOUT` | display u32, width u32, height u32, stride u32, offset u64 into BAR2, the scanout inside `RGFX_SCANOUT_SPAN`'s room; width 0 blanks the display | `COMPLETE` |
|
||
| 3 | `SET_CURSOR` | display u32, width u32, height u32, hot_x u32, hot_y u32, offset u64 of a BGRA8 premultiplied image; width 0 removes the image | `COMPLETE` |
|
||
| 4 | `MOVE_CURSOR` | display u32, x i32, y i32, visible u32 | none |
|
||
| 5 | `SET_VBLANK` | display u32, enabled u32 | `COMPLETE` |
|
||
| 8 | `SET_DISPLAY_POWER` | display u32, on u32; 0 turns the display's panel off (`DISPLAY_POWER`) | `COMPLETE` |
|
||
|
||
Scanout pixels are 32-bit BGRA8 (`kIO32BGRAPixelFormat`), the one format in
|
||
stage 2.
|
||
|
||
**Events** (host to guest, the control completion ring):
|
||
|
||
| type | name | payload |
|
||
|---|---|---|
|
||
| 0x100 | `COMPLETE` | status u32 |
|
||
| 0x101 | `DISPLAYS` | count u32, then per display: id u32, connected u32, preferred mode index u32, mode count u32, where the guest took `DISPLAY_SCALE` its host screen's scale in 120ths u32 and a reserved u32, then per mode: width u32, height u32, refresh in mHz u32 |
|
||
| 0x102 | `DISPLAY_CHANGED` | display u32; the guest asks `GET_DISPLAYS` again |
|
||
| 0x103 | `VBLANK` | display u32, count u64, host time in ns u64 |
|
||
|
||
**Display.** The modes offered are the host window's size, its width rounded
|
||
down to a multiple of 16 pixels and its height to even, and its screen's
|
||
refresh rate (the guest runs at the host screen's rate). 16 BGRA8 pixels are a
|
||
64-byte line of the GPU's memory: a guest surface of the mode's width over the
|
||
guest's RAM, as the desktop's are, starts and ends each row on a line, which
|
||
Intel's Vulkan driver needs to draw it in place (the window crate's
|
||
`geometry`). The host presents the
|
||
scanout buffer to the display's window at each refresh while the window shows
|
||
no presented surface, with no dirty log: the scanout shows only at boot and in
|
||
recovery, where its full cost is paid for the simpler design (owner,
|
||
2026-11-07). The GPU reads the buffer in place: the host
|
||
pages under the scanout are imported at its first draw, and again only when
|
||
the guest moves the scanout or changes its size, so no copy is made on the way
|
||
to the window, and no other page of the region is pinned for it. While vblank is
|
||
enabled, the host sends `VBLANK` at each refresh of the window's screen. A
|
||
`VBLANK` the control completion ring has no room for is dropped, and the next
|
||
carries the count; the host counts each dropped one (`vblank-dropped`), each
|
||
spell of that ring with no room (`control-ring-full`), and each post onto it
|
||
that waited for room (`control-ring-post-waited`) in its degradation counts,
|
||
and logs the first of each kind.
|
||
|
||
**The display's density.** Where the guest took `DISPLAY_SCALE`, the host
|
||
tells it the scale of the screen its window was last drawn on, and the kext
|
||
gives the OS the display's density from it, 110 pixels per inch a point
|
||
(`guest/kext/src/RgfxDisplayIdentity.hpp`): 110 at 1x, 220 at 2x, 231 at
|
||
2.1, and 110 before the window first draws. The x86-64 kext puts it in each
|
||
mode's size in millimetres and in the EDID's size, which is a 1920 × 1080
|
||
display's at that density whatever the window's size, and the arm64 kext in
|
||
`DisplayAttributes`' size and the dot pitch. The modes are valid for HiDPI
|
||
(`kDisplayModeValidForHiResFlag`, on x86-64) only on a screen above 1x, at
|
||
any size whose pixels halve exactly. arm64's WindowServer follows the
|
||
published size (measured): it runs at 1x on a 1x screen and HiDPI above 1x
|
||
at every size. x86-64 macOS starts a display HiDPI on a default mode of at
|
||
least 3840 × 2160, from 3800 pixels wide where its EDID is 32 inches across
|
||
or more, and, where the display is built in, on a default mode of at least
|
||
2048 × 1536 at more than 160 pixels per inch (read from macOS 26.7.2's
|
||
CoreDisplay). The x86-64 framebuffer says its display is built in
|
||
(`kIOConnectionBuiltIn`, as a Mac's own panel is), and its EDID is at most
|
||
20 inches across, so on a screen at 1.5x or more (above 160 pixels per inch)
|
||
the guest runs HiDPI at every window size from 2048 × 1536, at 1x below
|
||
that, and on a screen at 1.45x or less at 1x up to 3840 × 2160 (measured on
|
||
26.7.2 at 2.1 and at 1, and on 11.7.11 to 15.8.2 at 2.1). Before, with no
|
||
connection flags and the EDID at the window's size, it started at 1x on
|
||
every window from 2400 to 3648 pixels wide at 330 ppi, and HiDPI on a 3888
|
||
pixels wide one on a 1x screen (measured). The EDID names the window's size
|
||
in a text descriptor, so each window size is a display of its own to the
|
||
guest, which keeps a mode chosen for it. WindowServer keeps a mode while the
|
||
framebuffer lists it valid: with an EDID that stayed the same across sizes
|
||
it kept its old mode through every resize, and it restored a mode chosen at
|
||
one size to a display resized to another (measured;
|
||
[lessons](../lessons.md)). The framebuffer lists the mode set until another
|
||
is set, for a WindowServer that reads it mid-change
|
||
(`RgfxDisplayModes.hpp`), and answers it never shown and not valid once the
|
||
device no longer shows it.
|
||
|
||
**Refresh times.** The host stamps each `VBLANK` with its refresh's time on
|
||
the display's grid, a period after the one before, on its monotonic clock. It
|
||
answers a `PRESENT_SURFACE` in the refresh that shows its surface, right after
|
||
that refresh's `VBLANK`: the first refresh after the command buffers that write
|
||
the surface have finished, whether or not the host's window has drawn it yet.
|
||
An answer frees the surfaces of the presents before it, never its own, so the
|
||
host holds it only while a window draw still running may read one of those
|
||
(`crates/reims-vgpu/src/graphics/present.rs`). The kext maps each `VBLANK`'s
|
||
host time into the guest's `mach_absolute_time` by the clocks' offset
|
||
(`guest/kext/src/RgfxVblankClock.hpp`). Where it took `HOST_TIME`, it reads
|
||
the host's clock at each `VBLANK`, `HOST_TIME_LO` between two reads of its
|
||
own, and maps by the reading whose round trip bounds the offset closest, that
|
||
bound widening by 50 ppm of the reading's age. Without the feature it maps by
|
||
the offset with the shortest delivery, which moves with the delivery: under
|
||
Safari's 1080p60 playback the display link's times sat 38 to 76 us rms off a
|
||
straight line (measured), against 0 idle. A
|
||
display pipe transaction completes with the time of the refresh it was
|
||
answered in (or the answer's own time where no `VBLANK` came within a period),
|
||
and a display pipe VBL request is answered once, at the next refresh, with that
|
||
refresh's time and the next one's.
|
||
|
||
**The display's colour.** A Mac's display pipe applies colour stages to what it
|
||
shows: plane 0's gamma table (selector 5), the pipe's gamma table before its
|
||
colour matrix (6), the matrix, which rides the transaction at 0xb0 with dirty
|
||
bit 0x40, and the pipe's gamma table after the matrix (7). CGDisplayFade, Night
|
||
Shift and ColorSync's calibration set them; WindowServer's boot fade is a run
|
||
of transactions about 16 to 30 ms apart that each set only selector 7's table,
|
||
with no surface. CoreDisplay sends tables only to a plane that has gamma, from
|
||
the device control's answer to request 2 of attribute 0x711; a display whose
|
||
answer names no plane gets "Attempting to get capabilities from plane with no
|
||
gamma" and its fades drawn into WindowServer's own frames, whose last showed
|
||
34% of the fade out and 71% of the fade in on car 13's boot (B4). The device
|
||
control answers as macOS 26.7.1's AMD Radeon framebuffer does: plane 0 takes
|
||
tables of type 0x10 (8 bits a channel to CoreDisplay) and 256 entries, values
|
||
0.0 to 1.0 (read; `guest/kext/src/RgfxGammaCapability.hpp`,
|
||
`tests/gamma_capability_test.cpp`). The kext decodes the tables as macOS 26's IOAcceleratorFamily2
|
||
does and stages each for the transaction begun (read;
|
||
`guest/kext/src/RgfxPipeColor.hpp`, `tests/pipe_color_test.cpp`); the submit
|
||
sends them, and the matrix where it is dirty, as `DISPLAY_COLOR` parts of at
|
||
most 256 entries before the transaction's `PRESENT_SURFACE`, with no other pipe
|
||
client's post between them (the framebuffer's presents lock: IOPresentment opens
|
||
several clients, and any may submit), and a transaction
|
||
with no surface that sets a colour as a present that keeps the surface shown
|
||
(`RGFX_PRESENT_KEEP`), which completes the transaction when the host answers
|
||
it, at the refresh that shows the colour, as a surface's present does. The host
|
||
stages the parts on the presents' lane and the present it accepts next applies
|
||
them, with the frame it shows; each stage keeps its table until a transaction
|
||
sets it again, and the device's reset turns them all off, though it keeps the
|
||
scanout: kept, a reset in the middle of a fade would leave the window black,
|
||
with no transaction left to undo it. While any stage is on, the window draws
|
||
the display through them (`crates/reims-vgpu/src/graphics/color.rs`,
|
||
`sink.rs`), each table interpolated linearly between its entries (how a Mac's
|
||
display engine samples between them is not measured). A colour with no matrix
|
||
is drawn through a table of every input value, which the colour's own pass
|
||
draws once per colour from a ramp, so each frame costs a lookup per channel and
|
||
the bytes stay the pass's. Selectors 10 and 11 (the
|
||
pipe's linearization before the matrix and its gamma after it, in
|
||
IOPresentment's configuration format), 12 (a surface copy) and 13 (triage) stay
|
||
refused: no WindowServer seen calls them, and IOPresentment sends 11 only for a
|
||
gamma entry of the configuration type (1), which the AMD adds as a second entry
|
||
where its display path has it and the device control does not answer.
|
||
|
||
**The display's sleep.** A Mac's display goes dark when the OS puts it to
|
||
sleep (Energy Saver's timer, `pmset displaysleepnow`), and lights with the
|
||
desktop at its wake. Where the guest took `DISPLAY_POWER`, the kext sends
|
||
`SET_DISPLAY_POWER` with `on` 0 as the guest's display sleeps and 1 as it
|
||
wakes (`guest/kext/src/RgfxDisplayPower.hpp`). The x86-64 framebuffer stays
|
||
out of power management, so it hears of the sleep from the OS's display
|
||
wrangler (`IODisplayWrangler`), whose power messages its general interest
|
||
takes: the panel goes dark as the wrangler goes below its dimmed state (3),
|
||
and lights as it is dimmed or on again. An arm64 guest has no display
|
||
wrangler, and the arm64e framebuffer does not take `DISPLAY_POWER`, so its
|
||
panel stays lit through the display's sleep. The host's panel follows, as a
|
||
monitor's does: while it is off, the display's window and the host's reads of
|
||
the display (`rvg_graphics_device_read_display`, QEMU's console) show black,
|
||
and the host is told the guest's cursor does not show (`cursor_show`). Nothing
|
||
else changes: the guest's scanout and presents are taken and answered as with
|
||
the panel on, `VBLANK`s go on, and modes and the cursor's image stay, so the
|
||
guest's compositor runs as before and the first frame after the wake shows
|
||
what the guest shows then. The device's reset turns the panel on. The host
|
||
code is `reims_vgpu_graphics`'s `control.rs` (the command) and
|
||
`crates/reims-vgpu/src/graphics/sink.rs` ("The panel").
|
||
|
||
**The display pipe's notification words.** The kext answers a pipe client with
|
||
asynchronous results whose words IOAccelerator's notification callbacks read
|
||
(`guest/kext/src/RgfxDisplayPipeUserClient.cpp`, `completeLocked` and `sendVbl`,
|
||
which build them with `RgfxPipeNotifications.hpp`; `tests/user_client_words_test.cpp`
|
||
pins them).
|
||
A transaction's completion holds the transaction's cookie in word 0, its id in
|
||
the high half of word 1 (the low half 0), the time it was shown in word 3, and,
|
||
where it has nine words or more, the action 1 in word 8, the rest 0. Its word
|
||
count is the one the client's IOAccelerator expects, which differs by release,
|
||
so the kext picks it for each pipe client at the client's first submit
|
||
(`rgfxPipeCompletionCount`):
|
||
- 8 for a client that submits 0x108-byte transactions, as macOS 11.7.11's
|
||
WindowServer does: the 0x118-byte layout without its last 16 bytes, which
|
||
12.7.6's and 26's WindowServers send as zeros. The kext reads it as 0x118
|
||
bytes with zeros past its end;
|
||
- for a client that submits 0x118-byte transactions, 11 where
|
||
IOAcceleratorFamily2 exports
|
||
`IOAccelMemoryMap::getAssignedGPUVirtualAddressLength() const`, and 9 where it
|
||
does not. The kernel collections of macOS 13.7.8 to 26.7.2 export it, and
|
||
those of 11.7.10 to 12.7.6 do not (read). ReimsGraphics references the symbol
|
||
weakly, through its `OSBundleLibraries` and its Graft declaration
|
||
(`guest/kext/src/graft.json`, where the family is verified through its class
|
||
IOAccelMemoryMap, which the KCs of 11.7.11 to 26.7.2 define), never calls
|
||
it, and reads at its start whether its binder resolved it
|
||
(`ReimsGraphics::assignedLengthExported`).
|
||
|
||
Each count was measured by booting the kext with the others: with any other
|
||
count, WindowServer aborts at its first completion (on 11.7.11 its crash report
|
||
names a failed assertion in IOAccelerator's transaction callback that the
|
||
argument count equals its notification's), and with its own it completes every
|
||
transaction: 8 on 11.7.11, 9 on 12.7.6, 11 on 13.7.8, 14.8.9, 15.7.9 and 26.
|
||
The callback reads a completion as follows:
|
||
- it refuses any other word count;
|
||
- it takes word 0 as the completion block the client registered with the
|
||
transaction, so a completion with no cookie is not sent (a null word 0 ends the
|
||
client: WindowServer aborted there when the kext notified its cookie-less
|
||
shutdown frames, `RgfxPipeTransactions.hpp`);
|
||
- it records word 1's high half as the last transaction completed;
|
||
- in the extended mode IOPresentment uses (it registers its handler with
|
||
`IOAccelDisplayPipeTransactionSetCompletionHandlerExt`, the one completion setter
|
||
it imports, on an Intel Mac under macOS 26.7.1 and on the M3 under 27), it accepts
|
||
action 4 or one with a bit of 0xb set, and hands the block word 1's low half,
|
||
words 2 to 7 and words 9 and 10.
|
||
|
||
A VBL request's answer is 6 words: the request's callback and refcon, then the
|
||
refresh's time and the next refresh's, each split over two words, low half first.
|
||
These are the reader's layouts (measured 11-03 from the callbacks' code, read as
|
||
the guest's frameworks run it, for diagnosis only), and the completion's words
|
||
are the ones Apple's own paravirtual display kext sends. WindowServer completes
|
||
every transaction through them on the lane.
|
||
|
||
The bundle presents a drawable when its
|
||
command buffer is scheduled, as Metal does (`guest/bundle/src/RgfxCommandObjects.mm`);
|
||
what an app then sees of it, its presented handlers, `presentedTime` and
|
||
`nextDrawable`'s pacing, `guest/bundle/tools/present_probe.m` measures on a
|
||
guest and on a Mac alike.
|
||
|
||
**Boot display.** The device's option ROM gives firmware a GOP framebuffer in
|
||
BAR2, and the kext takes the display over when it starts. At its start, before
|
||
IOFramebuffer moves the console onto it, `ReimsGraphics` records the boot
|
||
framebuffer the platform expert's console info names as its
|
||
`RgfxBootFramebuffer` property (`Answered`, `Address`, `Width`, `Height`,
|
||
`RowBytes`, `Depth`; `guest/kext/src/RgfxBootConsole.hpp`), so a boot's check
|
||
reads whether the firmware gave the OS a framebuffer from the registry, long
|
||
after the kernel's message ring has wrapped: `ioreg -r -c ReimsGraphics -l |
|
||
grep RgfxBootFramebuffer`. A boot with no GOP mode has an `Address` of 0.
|
||
|
||
**QEMU's console.** `reims-graphics-pci`'s QEMU console carries the window's
|
||
input, and shows what the display shows: at each of its updates the device reads
|
||
the display back from the library (`rvg_graphics_device_read_display`), the
|
||
scanout or the presented IOSurface through the display's colour, drawn as the
|
||
window draws it into a texture of the display's mode, so QEMU's own displays and
|
||
a QMP `screendump` see what the guest shows (docs/qemu.md, "The reims-graphics
|
||
device").
|
||
|
||
## Stage 3 wire protocol: the Metal-call stream
|
||
|
||
Stage 3 keeps the stage-2 transport unchanged — the registers, the region, the
|
||
256-byte ring header, the doorbell and interrupt handshake, and the 16-byte
|
||
message header (`type`, `size`, `seqno`). It adds rings per command queue, a
|
||
family of device-level object-lifecycle messages, command-buffer encodings on
|
||
the per-queue submission rings, and completion records on the per-queue
|
||
completion rings.
|
||
|
||
Our guest Metal GPU bundle is the host of Apple's Metal SPI: every Metal call
|
||
an app makes lands in one of the bundle's objects, and the bundle serialises it
|
||
into this stream. The host reads the stream and drives the library's `Platform`
|
||
(Metal on the Mac, metal2vulkan on Linux), the same trait core
|
||
already drives from the Apple-lane command stream. So the host decoder is: wire
|
||
message → handle-table lookup/insert → `Platform` call → completion. The
|
||
bundle's serialiser is the mirror of that decoder.
|
||
|
||
**Guest input the host refuses.** Everything on the wire comes from the guest,
|
||
which the host does not trust, and no guest input ends QEMU. A message the host
|
||
cannot carry out (one shorter than its record, a span it does not cover, an
|
||
object it does not hold or of the wrong kind, the platform refusing the create)
|
||
is refused at its op, and nothing of it is made. A create the guest waits on (a
|
||
pipeline's reflection, a library create or lookup, a queue's create, a
|
||
context's close) is answered at that op: a refused `PIPELINE_REFLECTION`, or a
|
||
`COMPLETE` with the refusal's status, so no guest thread waits out the kext's
|
||
timeout. A refused command buffer completes with an error status, as a buffer
|
||
Metal could not run does: a stand-in on its queue, holding the buffer's event
|
||
waits and signals alone, finishes in the queue's order, and its completion
|
||
posts the values the buffer signalled its shared events to, then the buffer's
|
||
internal-error `CB_COMPLETE`. So a buffer that names anything the host does
|
||
not hold fails after the buffers committed before it, and nothing waiting for
|
||
one of its events, a later buffer on the GPU or a guest thread, waits for good.
|
||
An object whose create the bundle answered at the call, without the host's
|
||
answer (a buffer, heap, texture, view, depth/stencil state, event, fence, video
|
||
session, or a pipeline equal to an accepted one), is one the guest goes on
|
||
naming where the host refused it, as Metal would have made it. Its id stands
|
||
for a refused object until its destroy (the decoder's `refused`), and what
|
||
names it is dropped, never the command buffer that names it: an op that uses
|
||
it (a copy, a fill, an indexed or indirect draw from it, a fence update or
|
||
wait) is dropped; a binding of it binds nil and marks its slot until the slot
|
||
is bound again. The draws and dispatches of an encoder with a buffer, texture
|
||
or sampler bound so run, as Metal's do with nil bound there (the x86 Macs read
|
||
a texture as zero, `oracle_nilbind`, dgpu-oracle.md Q25), and an offset op at
|
||
such a buffer slot sets nothing; while a pipeline state, depth/stencil state or
|
||
tessellation factor buffer slot is marked, they are dropped. An indirect
|
||
command buffer's CPU encode of it is dropped
|
||
and its command reset, and that command's later draws and dispatches are
|
||
dropped until the guest resets it or copies a command over it; a use list's
|
||
entry of it is nil; a render pass with it as
|
||
an attachment, and a video encoder of its session, are skipped whole; a wait
|
||
for it as an event is dropped, and a signal of it as a shared event still
|
||
reaches the guest's value; a create over it stands refused in turn. The
|
||
buffer then completes as it would have. Where there is no stand-in (a message
|
||
too short to name its queue, a queue the process does not hold), the error
|
||
status is posted at once. Nothing in
|
||
this lane ends the offending context or its process on malformed input. The
|
||
host runs each op in a refusal scope (`reims_vgpu_vulkan::core::raise::refusals`): a
|
||
death at a platform call, where the platform refuses a create or an encode and
|
||
the paravirt device ends the process, unwinds to the op's scope instead, and the
|
||
op is refused there, logged once at WARN with the platform's reason. A panic in
|
||
the lane's code, a bug, is refused there too, logged at ERROR. An assertion
|
||
inside Metal is no death of the library's, which no scope takes on a Mac host,
|
||
so where the lane knows Metal asserts it refuses the op before any platform
|
||
call: a texture, a view, a heap's size for a texture, or a render or mesh
|
||
render pipeline state's attachment, of a pixel format the device describes none
|
||
for. A command buffer refused mid-stream has its open encoder ended and is never committed.
|
||
Work an op registers to run on another thread takes the op's scope with it
|
||
(`refusals::carry`): a command buffer's completed handler runs the platform's
|
||
read of the buffer, and itself, in the scope of the decode that added it. A
|
||
death in that read (a failure no Metal answer matches, which the Vulkan
|
||
platform reads on the runtime's thread) fails the command buffer, whose
|
||
`CB_COMPLETE` is an internal error (`MTLCommandBufferErrorInternal`), and
|
||
nothing else: the context's later command buffers, creates and queries are
|
||
carried out as any context's. On a Mac a GPU error fails the command buffers
|
||
it strikes, WindowServer's among them, and their processes' later buffers run
|
||
(docs/lessons.md, the test that faults the GPU, **measured** on macOS 27.0.1),
|
||
so a failed buffer of WindowServer's leaves its later frames to be carried
|
||
out, and the display goes on. A release the
|
||
platform dies at (at a destroy, a context's close, or the display's swap of
|
||
the texture it shows) is refused alone, and the destroy or the close is
|
||
carried out whole. So is each of the Vulkan platform's releases of what a
|
||
command buffer's commands used, and each change it makes, as the command
|
||
buffer ends on the runtime's thread, and so is each such release while a death
|
||
in the op unwinds past it: a scope a release opens in the unwind takes a death
|
||
in it, where one outside any such scope still ends the process. A draw of the
|
||
display (the window's, and the host's reads of it) reads what the guest set
|
||
and presented, and runs in a scope of its own: a death in it refuses that draw
|
||
alone, its encoder ended and nothing of it committed, and the window keeps the
|
||
frame it shows, while the read answers that the platform refused the draw.
|
||
What dies elsewhere off the op's thread still ends the process: a notice the
|
||
runtime's scheduler thread announces at a host step, which names no command
|
||
buffer, and the runtime's own releases after the platform's handlers ran. This
|
||
is the lane's own rule: the paravirt device's rule of ending the process at the
|
||
op (AGENTS.md, the contract) is Apple's framework's behaviour, which that
|
||
device keeps.
|
||
|
||
**Processes name only their own.** A process names only its own objects and
|
||
its own memory. The accelerator kext checks, before it posts a lifecycle
|
||
message, that the object the message creates or destroys is in the process's
|
||
id range, and that the region the message names lies in the process's own
|
||
blocks: a queue's rings, a heap's or a buffer's block over host memory, and a
|
||
library chunk's bytes and ack slot. The host checks these spans too, and also
|
||
the span a `COMMAND_BUFFER_IN_REGION` on a queue's ring names, which never
|
||
passes the kext. Each span must lie in one block the sender holds. The kext
|
||
posts a block's `BLOCK_GRANT` (context, offset, size) on ring 0 before its
|
||
allocation returns, keeping the block pinned until then so no free overtakes
|
||
it. The host keeps the grant until the block's `BLOCK_RELEASE` or the context's
|
||
`CONTEXT_CLOSE`, and copies a buffer out of a block only while the grant
|
||
stands. An IOSurface's shared block (§14) is held by every process that
|
||
holds the surface: the kext finds it by the physical pages of the surface's
|
||
plane 0, which a process presents through its own CPU mapping of the plane
|
||
(user-client selector 0x109), so only a holder of the surface can reach the
|
||
block, whatever id it claims. The kext wires those pages while the process holds the block,
|
||
posts `BLOCK_SHARE` (context, offset, size) for each holder before the process
|
||
learns of the block, and `BLOCK_UNSHARE` as a holder other than the last lets
|
||
it go (selector 8, or its close). The last holder's let-go frees the block
|
||
as a free does, and its `BLOCK_RELEASE` ends every hold; a cached block in
|
||
place instead sleeps, its last holder's `BLOCK_UNSHARE` posted, until an ask of
|
||
its surface holds it again with a `BLOCK_SHARE` alone or the kext lets it go
|
||
with its `BLOCK_RELEASE` (§14, "The device cache"). A block in place
|
||
(0x109's fourth input) is found by the pages of the surface's whole
|
||
allocation, which every holder's ask wires. Before its first `BLOCK_SHARE`,
|
||
the kext writes their runs into the block, past the part the processes map
|
||
and are granted, and posts `SURFACE_PAGES`; other asks for the surface wait
|
||
for its answer. A refusal frees the block as a share not posted does, and the
|
||
ask answers `kIOReturnUnsupported`, so the process copies the surface. Where
|
||
the device has `RGFX_FEATURE_SURFACE_CACHE`, 0x109's fifth and sixth inputs
|
||
(the surface's IOSurfaceID, and 1 where the process asks it cached) have the
|
||
kext mark a block it makes cached in its `SURFACE_PAGES`, and a fifth output
|
||
answers whether the block is, whichever ask made it. Where the device has
|
||
`RGFX_FEATURE_SURFACE_CACHE_REFUSED` instead, a struct input with the six
|
||
(`RgfxSurfacePagesLayout`) is the surface's layout, with which the kext asks
|
||
the device whether the block needs a cache, and marks it cached only where
|
||
the device answers so; the surface's resident pages may follow the layout
|
||
(`RgfxSurfaceResident`), where the kext took `RGFX_FEATURE_SURFACE_DEFERRED_CARRY`,
|
||
for a deferral that carries them. The kext then writes the
|
||
surface's CPU generation at offset 16 of the block, and asks `SURFACE_DOWNLOAD`
|
||
(block offset) at a CPU lock that follows a GPU write, answered once the
|
||
surface's pages hold the host's device cache (Decided 14, "The device cache").
|
||
A command buffer that writes surfaces' shared blocks is named to the kext
|
||
after it is posted and before its commit returns (selector 0x10c: the queue,
|
||
the buffer's seqno, and a pair of the block's offset and the surface's
|
||
IOSurfaceID for each surface), and its completion retires the queue's writes
|
||
up to it once any copy is written back (selector 9). Only a holder of a
|
||
block names it, only for one of its own queues, and the kext keeps a block's
|
||
surface only where the surface's memory holds the block's pages, so no
|
||
process makes another's locks wait (§14, "CPU locks").
|
||
|
||
**Processes map only their own.** No process maps the region whole: it holds
|
||
every process's blocks, the control rings and the device page. Each
|
||
connection has a window, a range of the process the region's size that the
|
||
kext makes at the context's open (selector 0x100 answers its base and size).
|
||
The window is memory of the connection's own, mapped read-only, and holds no
|
||
page until one is read, which then reads zeros. It is purgeable, never made
|
||
volatile, so the process's footprint counts only the pages it reads there: xnu
|
||
charges an IOKit mapping of anonymous memory to the task's footprint at its
|
||
whole size as it is made, but a purgeable object's resident pages to its
|
||
owner, the process that opened the context (read from the public xnu source:
|
||
`vm_map_enter`, `mach_make_memory_entry`). A window of plain pageable memory
|
||
charged every Metal process the region's size at its open, past many
|
||
processes' memory high watermarks. The spans are device memory, which no
|
||
footprint counts. Region offset `o` of what the process is given lies at the
|
||
base plus `o`, so the bundle's pointers stay base plus offset. The kext maps
|
||
in, over the window at the span's own offset, only the process's blocks, the
|
||
shared blocks of the surface planes it holds, and the scanout it is granted.
|
||
It maps a span in before the process learns of it. Before the span can go to
|
||
anyone else, it maps the window's own memory back over the span, read-only:
|
||
before a block's free marks it freed, and when a hold ends, a scanout grant
|
||
goes or a mode change moves the scanout. At the close the whole window goes,
|
||
every span in it, before the context's blocks are freed. Each span is whole
|
||
pages past the region's head, so no mapped page holds a byte of anything else.
|
||
A page here is the process's: 4 KiB on x86-64 and 16 KiB on arm64, where the
|
||
kext maps the whole 16 KiB pages of a block's part a process uses (a plane's
|
||
bytes, whole 4 KiB guest pages) and of the scanout's rows. Every block is whole
|
||
such pages, and a surface block's runs start past the mapped pages.
|
||
The device info shares its page with the control completion ring's tail, so
|
||
the kext reads it for the process (selector 0x10b), and the region's own map
|
||
(`kRgfxAccelMemoryRegion`) is refused. One difference from Apple's: a process
|
||
that touches a block after releasing it reads zeros, and faults only on a
|
||
write, where Apple's faults on both. Only a guest that uses memory it released
|
||
sees it. A mapping that fails fails its op; a span that cannot be taken back
|
||
closes the window, so the process reaches nothing of the region from then on.
|
||
A placed mapping is IOKit's overwrite mapping, which IOKit never takes down
|
||
itself (read from the public xnu source, `IOMemoryDescriptor::doUnmap`), so
|
||
only another mapping over it takes a span back; vm_protect is not a KPI a
|
||
third-party kext may link.
|
||
|
||
**The scanout is its owner's.** The scanout holds the display's pixels, so
|
||
only the process that drives the display reaches it: the task that holds the
|
||
framebuffer's server connection (`kIOFBServerConnectType`), WindowServer. The
|
||
kext grants the scanout (selector 0x108), locks an IOSurface with no backing
|
||
of its own over it, and gives out the framebuffer's VRAM range (which
|
||
IOFramebuffer maps on its server connection, and on its shared connection into
|
||
any process of the console's user) to that task and the kernel alone. Any
|
||
other process gets `kIOReturnNotPermitted`, or no memory for the VRAM range,
|
||
and nothing is mapped. The server connection is the test because IOFramebuffer
|
||
opens it for one task at a time, and the task that holds it maps the scanout
|
||
through it already (the system aperture), so the rule gives no process what
|
||
IOFramebuffer does not. An open in flight counts too, since IOFramebuffer sets
|
||
the display up inside it. A new connection's task replaces the last one, and
|
||
every other task's hold of the scanout is taken back then: each grant, its
|
||
span mapped back out of the context's window, and each lock's mapping,
|
||
unmapped from the task. What IOFramebuffer itself mapped for a task (the VRAM
|
||
range on its connections) is IOFramebuffer's, and goes only with its
|
||
connection.
|
||
|
||
Command buffers do not pass through the kext, so the host checks each
|
||
object a message names: it must be
|
||
of the message's context, which is the context of the object a ring-0 message
|
||
creates or destroys, or the context of the queue whose ring carried the
|
||
command buffer. A command buffer runs only on the queue whose ring carried it,
|
||
and a queue's ring carries nothing but command buffers: a message of any other
|
||
type there is refused, since it would pass the kext's checks by.
|
||
A create the kext posted but whose answer did not come in time is destroyed by
|
||
the kext right behind it, so a retry under a new id leaves nothing behind.
|
||
|
||
**A block outlives what lies in it.** A region block is given out again only
|
||
once the host has said that nothing of it is in use. A process's free marks the
|
||
block freed: from then on no message of the process can name it, and no one can
|
||
take it. The free returns at once, as Metal's releases never block. The kext's
|
||
one release worker, a thread call that runs one at a time, then posts the
|
||
block's `BLOCK_RELEASE` on ring 0, behind every message the process posted
|
||
before the free. It posts every freed block's release, 16 under one hold of the
|
||
ring's lock with one doorbell at most, up to 256 in flight, and returns without
|
||
waiting. Each release has an entry of its own, which the work loop finds by
|
||
seqno when its answer comes and then runs the worker to retire it. Answers come
|
||
in whatever order the contexts' work finishes, so a slow context holds back
|
||
only its own blocks, and a storm of frees waits for each context's work once,
|
||
not once a release. A full table leaves the rest freed until entries retire.
|
||
The host refuses the release at once where an object it holds lies in the
|
||
block: a buffer or heap over host memory, or a buffer, texture or heap placed
|
||
in one, which keeps its parent's span after the parent's destroy. It also
|
||
refuses one where a live queue's ring lies in the block. Otherwise it answers
|
||
OK once every command buffer the context committed before the release has run
|
||
its completion handler, and, for a shared block, every one each other holder
|
||
committed before its `BLOCK_UNSHARE`, before its close, or before the release
|
||
itself where neither came first: the kext unwired that holder's pages at its
|
||
unshare, or at a close it took for refused, and gives the surface's memory back
|
||
at the answer. The kext posts an unshare out of its lock, so another holder's
|
||
release can come first, and the host then takes the release as that holder's
|
||
unshare too; the unshare that follows is not counted again. It also waits
|
||
while the host's display holds a surface's texture over the block, as a
|
||
compositor holds the IOSurface it shows: from the surface's present until the
|
||
display pipe's next present (or the device's reset), and each window draw of
|
||
it until the draw has finished. Command buffers committed later do not hold it
|
||
up. On OK the block goes back to the pool; on a refusal it stays out of use
|
||
until its process's close posts its release again. A release not answered in
|
||
10 s is logged and stays in flight: the host may still run a buffer over the
|
||
block or copy a cached surface's GPU copy into the surface's pages, so the
|
||
block, its wired pages, and a cached surface with its wire are held, never
|
||
handed back to macOS, until the answer comes. A block a create in flight names
|
||
is pinned from the kext's check until the create is answered, and a free of it
|
||
meanwhile fails busy, so no block changes hands between the check and the
|
||
host's carrying out of the message. A context's close is answered under the
|
||
same rule, after its objects are dropped and its queues' threads are past
|
||
their rings, and the kext frees the process's blocks only on that answer. None
|
||
of them is released from the close's post on, and a release the kext took just
|
||
before and posts behind the close waits for the close's buffers on the host
|
||
too. A close not answered in 10 s keeps everything the process held from every
|
||
other process until its answer comes, however late: its blocks with their wired
|
||
pages, its holds of shared blocks, its GPU address units and its resource-id
|
||
chunks, which the host may still use or map to the context's objects. None of
|
||
its blocks is released meanwhile. The late answer lets go of all of it as an
|
||
answer in time does. A close never answered, or refused, keeps it for good.
|
||
|
||
**Handles and addresses.** Every guest Metal object has a 64-bit `ObjId` the
|
||
guest picks, unique per device; the host keeps an `ObjId` → `Platform` handle
|
||
table (handles are refcounted in core, `clone_ref`/`Drop`). The guest also
|
||
picks buffer/texture/heap GPU addresses and resource IDs, and the host pins
|
||
them — the host never hands a host device address to the guest (m2v's rule). A
|
||
destroy carries the `ObjId` alone; the host drops its handle.
|
||
|
||
**Rings.** Ring 0 stays the control ring: the framebuffer kext's stage-2
|
||
display commands, and the device-level object lifecycle below, which the
|
||
accelerator kext posts there for each process. Every other ring is one
|
||
`MTLCommandQueue`'s ring pair (one submission and one completion ring per
|
||
queue, created on demand), which the bundle places in its kext-given blocks and
|
||
creates through the accelerator kext. Each ring keeps a single producer and a
|
||
single consumer, so their `consumer_idle` handshakes never race. A create carries a priority, which the bundle sends as 0 for every
|
||
queue and the host does not read: each queue is the platform's plain `newCommandQueue`.
|
||
|
||
**Object lifecycle** (ring 0, through the accelerator kext, request/reply). Each `*_CREATE` carries our
|
||
schema for the Metal descriptor (plain little-endian fields, decoded straight
|
||
into the `Platform` descriptor struct — core keeps descriptors as public-field
|
||
structs), the guest-picked `ObjId`, and, where it applies, the address, id or
|
||
offset. Resource creates with a guest-picked id/address are fire-and-forget
|
||
(the host builds the mirror and pins lazily on first use); pipeline creates
|
||
block for the reply, which carries the reflection the guest needs
|
||
(`threadExecutionWidth`, max total threads per threadgroup, static threadgroup
|
||
memory) — m2v's "take state answers from the created pipeline".
|
||
|
||
**Known pipeline creates.** A pipeline create whose message equals, in every
|
||
byte but its header and object id, one the device accepted for the same
|
||
process does not wait for its reply (the bundle's `RgfxKnownPipelines.hpp`).
|
||
It is posted with Submit's `kRgfxSubmitDeferred` flag, and its state takes the
|
||
earlier create's reflection at once. Its `gpuResourceID`, the one value the
|
||
host gives each create alone, waits at its first read for the create's own
|
||
reply, which the kext keeps until the process takes it (`TakeAnswers`). The
|
||
process also takes the replies no one asked for every 32 such posts. Each
|
||
create is still a new object with its own resource ID, as Metal's equal
|
||
creates are. The first create of each message waits as before, so a refusal is
|
||
still known at the create. A refusal is never kept, so its equal create waits
|
||
again. Where the kext has no slot left (64 per process, 256 in all), the create
|
||
waits as any. The bundle posts this way only where the kext's feature word
|
||
has `kRgfxKextFeatureDeferredAnswers`.
|
||
|
||
Across processes, the key is the create's pipeline key (`PIPELINE_KEYS`,
|
||
above), which names its libraries by their content, not by the process's
|
||
ids. The kext keeps the device's answer to every create it waited for that
|
||
carries a key (`RgfxSharedPipelines.hpp`): the reflection with its header,
|
||
object id, `gpuResourceID`, unique identifier and resource index zeroed, in a
|
||
table of 2,048 answers (256 sets of 8, a full set replacing the answer found
|
||
or learnt longest ago), empty at each start of the kext. The bundle computes
|
||
the key of each create whose libraries all have content keys, and posts it
|
||
with Submit's `kRgfxSubmitShared` flag and the key: where the kext keeps an
|
||
answer of that key and has a slot left, it posts the create as a deferred one
|
||
and hands back the kept answer, stamped with the create's seqno and object id,
|
||
which the state takes as it takes a known create's; the process then knows the
|
||
create too. Else the create is posted and waits as any, and its answer is kept.
|
||
A process sees the same answers as with its own equal create before: the
|
||
reflection at once, its own `gpuResourceID` at the first read, and a refusal
|
||
at the create only where no process's equal create was accepted. The kext
|
||
learns only answers the device gave, whose key the host computed, so no
|
||
process can place an answer for another's key; a process naming a key that is
|
||
not its create's only takes a wrong reflection for its own pipeline. The
|
||
bundle posts so only where the kext's feature word has
|
||
`kRgfxKextFeatureSharedPipelines` and the device's has `PIPELINE_KEYS`.
|
||
|
||
Every reason the host refuses a pipeline create is either impossible for an
|
||
equal create or known to the process when it posts:
|
||
- its object id is new;
|
||
- its libraries are held by its functions;
|
||
- its bytes are the accepted create's;
|
||
- the platform's pipeline resource IDs are not refused (measured to
|
||
1,000,000);
|
||
- the ring and the context are checked by the kext before it posts;
|
||
- a command buffer's failure fails no other work of its context ("Guest input
|
||
the host refuses", above).
|
||
|
||
One reason stays: the platform failing to make again what an equal create
|
||
needs (read from metal2vulkan's code at the pinned commit). The Vulkan runtime
|
||
gives a state of an equal descriptor the live variant of an earlier state (its
|
||
shader modules, layouts and `VkPipeline`s) with no driver call, or the objects
|
||
of one among the last 16 it released, and the `VkPipeline` it begins at a
|
||
create never refuses the create. Where no such variant is left, the create
|
||
makes the variant's objects again, which can fail for want of memory; where
|
||
the runtime's memo of compiled pipelines has let the pipeline go and its shader
|
||
cache misses, it compiles it again, under a compile attempt's 20-second
|
||
deadline. That refusal shows at the state's first `gpuResourceID` (as 0) and
|
||
in the command buffers that name it, whose draws with it are dropped on the
|
||
host ("Guest input the host refuses"), instead of at the create. Only a create
|
||
that waits for its answer would close it, at the cost the known creates remove.
|
||
|
||
| group | messages | `Platform` call |
|
||
|---|---|---|
|
||
| memory | `HEAP_OVER_HOST_MEMORY`, `HEAP_CREATE`, `BUFFER_CREATE`, `BUFFER_OVER_HOST_MEMORY`, `BUFFER_AT_OFFSET`, `BUFFER_MANAGED_AT_OFFSET`, `HEAP_OVER_PAGES`, `TEXTURE_CREATE`, `TEXTURE_FROM_BUFFER`, `TEXTURE_FROM_IOSURFACE`, `MANAGED_TEXTURE_CREATE`, `MANAGED_BUFFER_CREATE`, `*_DESTROY` | `new_heap_over_host_memory`, `new_heap`, `new_buffer`, `Heap::new_buffer_at_offset`, `new_texture`, `Buffer::new_texture`, drop |
|
||
| Managed ranges | `BUFFER_DID_MODIFY_RANGE`, `TEXTURE_REPLACE_REGION` | `Buffer::did_modify_range`, `Texture::replace_region` |
|
||
| a texture's bytes changed | `TEXTURE_DID_MODIFY_DATA` (not answered; carried out as a range message) | `Texture::did_modify_data` |
|
||
| heap sizes | `HEAP_TEXTURE_SIZE_AND_ALIGN` (answered `SIZE_AND_ALIGN` on the control completion ring; makes nothing) | `heap_texture_size_and_align` |
|
||
| rasterization rate maps | `RATE_MAP_CREATE`, `RATE_MAP_RESET` (answered `RATE_MAP_STATE`), `RATE_MAP_QUERY` (answered `RATE_MAP_ANSWER`; makes nothing), `*_DESTROY` | `new_rate_map`, `RateMap::reset`, `RateMap::physical_size`, `screen_to_physical` and `physical_to_screen`, `RateMap::copy_parameter_data` |
|
||
| function pointers | `FUNCTION_HANDLE_CREATE`, `FUNCTION_TABLE_CREATE` (answered `FUNCTION_POINTER_STATE`), `FUNCTION_TABLE_SET` (not answered; makes nothing), `*_DESTROY` | `ComputePipeline::function_handle`, `ComputePipeline::new_visible_function_table`, `VisibleFunctionTable::set_functions` |
|
||
| dynamic libraries | `DYNAMIC_LIBRARY_CREATE` (answered `COMPLETE`), `*_DESTROY`; a `COMPUTE_PIPELINE_CREATE`'s run of `RgfxPipelineLibrary` | `new_dynamic_library`; the compute descriptor's `libraries` (`preloaded`, and `loaded` by install name) |
|
||
| state | `SAMPLER_CREATE`, `DEPTH_STENCIL_CREATE`, `*_DESTROY` | `new_sampler_state`, `new_depth_stencil_state` |
|
||
| shaders | `LIBRARY_LOOKUP` (the content key of the `.metallib`'s AIR slice: a hit binds the library the device made for any process, and no bytes cross), `LIBRARY_CREATE` and `LIBRARY_FROM_REGION` (the slice's bytes forwarded unchanged on a miss, answered once made), `RENDER_PIPELINE_CREATE`, `MESH_RENDER_PIPELINE_CREATE`, `COMPUTE_PIPELINE_CREATE`, `*_DESTROY` | the device's library cache, `new_library_with_data`, `new_render_pipeline_state_full`, `new_mesh_render_pipeline_state_full` and `new_compute_pipeline_state_full` (the whole descriptor the guest set: vertex or stage-input descriptor, every colour attachment, each stage's linked functions, those made with options or a specialized name by `Library::new_function_with_options`; the Vulkan platform refuses a specialized name, which its runtime's function descriptor lacks) |
|
||
| sync | `EVENT_CREATE`, `SHARED_EVENT_CREATE`, `FENCE_CREATE`, `*_DESTROY`; the kext's `SHARED_EVENT_NAME` (answered `COMPLETE`), `SHARED_EVENT_IMPORT` (answered `SHARED_EVENT_VALUE`) and `SHARED_EVENT_UNNAME` (not answered) | `new_event`, `new_shared_event`, `new_fence`; an import's value `SharedEvent::signaled_value` |
|
||
| queue | `QUEUE_CREATE` (priority, region offset, vector), `QUEUE_DESTROY` | `new_command_queue` |
|
||
|
||
`*_OVER_HOST_MEMORY` map guest region blocks (Shared) and the host builds a
|
||
placement heap/buffer over them.
|
||
|
||
**Shared and Managed buffers lie in slabs** (`guest/bundle/src/RgfxSlabs.hpp`).
|
||
A device buffer of either mode takes whole 4 KiB pages of a slab, a region
|
||
block the bundle holds, so its create and its free call neither the kext nor
|
||
the host's import, and the kext's block table holds one entry per slab:
|
||
- A Shared slab is one Placement `HEAP_OVER_HOST_MEMORY` of the buffers'
|
||
options, hazard tracking resolved, and each buffer a `BUFFER_AT_OFFSET`
|
||
there, at the heap's GPU address plus its offset. Where the device took
|
||
`MANAGED_BUFFER_SLABS`, a Managed buffer lies in the Shared class of its
|
||
cache and hazard tracking modes: its CPU copy is a Shared buffer of that
|
||
class, made as any (a `BUFFER_AT_OFFSET`, or the `BUFFER_OVER_PAGES` of a
|
||
larger slab of the process's own pages, below), and the buffer a `MANAGED_BUFFER_CREATE`
|
||
over it at an address of its own, so a Managed buffer of any size lies where
|
||
a Shared one of its size does, on every host; its range goes back once the
|
||
copy's destroy follows the buffer's. Without that feature, where the device
|
||
took `MANAGED_AT_OFFSET`, a Managed slab is a Shared Placement heap too, and
|
||
each buffer a `BUFFER_MANAGED_AT_OFFSET` at an address of its own: the host's
|
||
GPU copy, beside a CPU copy placed in the heap at the buffer's range.
|
||
Elsewhere a Managed slab is a plain block, and each buffer a
|
||
`BUFFER_OVER_HOST_MEMORY` over its own range, its CPU copy. The buffer's
|
||
`heap` is nil: the slab is no object of the app's.
|
||
- `allocatedSize` is the pages taken, 4096 for a 256-byte buffer, and contents
|
||
and GPU addresses start a page, as both x86-64 Macs' GPUs answer (AMD 5300M,
|
||
Intel 630, measured with `tools/shmem`). Every new buffer reads zeros: a
|
||
create zeroes what of its range is dirty, and a background thread zeroes
|
||
freed ranges first.
|
||
- A buffer up to 1 MiB shares a slab of its class, the slabs growing from
|
||
128 KiB to 2 MiB; a larger one takes a slab of its own, which is cached for
|
||
reuse at offset 0 once freed (a sixteenth of the region at most, 2 s idle).
|
||
- A class keeps two empty slabs, each for 2 s at most, so a process at rest
|
||
holds only the slabs its buffers lie in. A slab let go destroys its heap,
|
||
then frees its block on the background thread, so no buffer's free waits
|
||
for a `BLOCK_RELEASE`.
|
||
- Where the host maps a process's own pages (`PAGES_BUFFERS`, and the kext's
|
||
`PagesBlock`) and makes heaps over them (`HEAP_OVER_PAGES`), a heaped slab
|
||
of 2 MiB is the process's own memory instead: the kext's chunks where it
|
||
gives them (`PagesChunked`, below), else 2 MiB of plain pages
|
||
(`mach_vm_allocate`, tagged `VM_MEMORY_IOACCELERATOR`), which the take asks
|
||
for, wired into a pages block and made one `HEAP_OVER_PAGES`, its buffers
|
||
placed in it as in a region slab's heap. The host makes the heap over the
|
||
block's view, which it makes off ring 0 as a `BUFFER_OVER_PAGES`'s, or over
|
||
the run where the guest's RAM is mapped where the block is one run. A larger
|
||
dedicated Shared slab is plain pages too, with no heap: its one buffer is a
|
||
`BUFFER_OVER_PAGES` over the block's view, or a Managed buffer's CPU copy. A
|
||
larger Managed slab of a class of its own (no `MANAGED_BUFFER_SLABS`) is the
|
||
region's, as is a slab where the kernel gives no pages or the kext gives no
|
||
pages block. Why the process's own pages: in the region the guest's stores
|
||
ran at 13 MB/s (Decided 5, "The guest maps host memory only"). A queue's
|
||
upload chunks, the bytes `set*Bytes:` hands in, are Shared buffers of the
|
||
slabs too. A slab let go destroys its heap, releases its pages block (the
|
||
kext answers once the host let go of it, and unwires the pages), then
|
||
deallocates its pages.
|
||
- The kext's chunks first (selector 12, `PagesChunked`, where the kext's word
|
||
holds `PagesChunked`): the kext takes the slab's bytes in physically
|
||
contiguous chunks of 64 KiB, zero-filled, maps them into the process in
|
||
order and makes the pages block of their runs, so a 2 MiB slab is 32 runs
|
||
of guest RAM at most, where plain pages are up to 512. The host maps each
|
||
run of a view apart, against a budget of mappings per process
|
||
(`vm.max_map_count` on Linux, 65530 by default): on NVIDIA, views of
|
||
scattered pages, slabs' among them, used it up, and the buffers made after
|
||
were copies (docs/qemu.md). The memory is the block's: the slab's release takes it, the
|
||
kext unmapping it from the process and freeing the chunks once the host has
|
||
let go of the block, and the process unmaps nothing. A 64 KiB run is one the
|
||
kernel finds at once however long the guest has run: on the guest and host
|
||
the superpages below were measured on, 4,096 chunks in a row each took
|
||
0.033 ms, and 0.036 ms once 978 MiB of 4 KiB pages had been taken, the
|
||
slowest 0.74 ms, none refused. A slab the kext gives no chunks for is plain
|
||
pages.
|
||
- Plain pages, never superpages (`VM_FLAGS_SUPERPAGE_SIZE_2MB`, 2 MiB of RAM in
|
||
one run): superpages run out, and asking for one stalls the process, on
|
||
whatever thread asks. Measured on an x86-64 macOS 26.7.2 guest of 8 GiB on
|
||
the Radeon 780M host, a process got 19 at boot with 2.5 GiB free, then
|
||
`KERN_NO_SPACE`, and none three minutes later; each refused ask spent 140 to
|
||
190 ms in the kernel's search for a contiguous 2 MiB (`vm_map_enter`'s
|
||
superpage path, in `cpm_allocate`, which sleeps as it goes and moves pages to
|
||
make a run), sampled with spindump. The search runs with the process's map
|
||
held: in the public xnu-12377.101.15 source, `vm_map_enter` holds the map's
|
||
interlock and the new entry locked exclusive across it, and a walk of the
|
||
map past that entry (`vm_map_region`) waits for it. Sampled with tailspin on
|
||
that guest: asked on the thread that takes the slab, WindowServer's main
|
||
thread, making a texture over a layer's image as a window moved, was in
|
||
`cpm_allocate` in two samples 100 ms apart, and Safari's page drew no frame
|
||
for 151 ms; asked ahead on the slabs' background thread instead, the main
|
||
thread, making such a texture as a window was resized, waited in
|
||
`mach_vm_region` behind it, and the page drew no frame for 179 ms. Plain
|
||
pages are what every slab took once superpages ran out, minutes after a
|
||
boot.
|
||
- Where no source has memory for a new slab, the process's own empty and
|
||
cached slabs go first, then smaller region slabs are tried down to the
|
||
buffer's size; nil only past that. Any other block of the process's the
|
||
kext has no room for (a texture's CPU copy, a heap, an upload chunk, an
|
||
IOSurface's block) is asked again once those slabs went
|
||
(`RgfxRegion::setReclaim`).
|
||
|
||
The host makes an `Automatic` heap a `Placement` heap: the guest places what
|
||
the heap makes itself, as Metal's Automatic heap places it (lowest free offset
|
||
at the resource's alignment; `guest/bundle/src/RgfxHeapRanges.hpp`), a buffer
|
||
at its length and a texture at the size `HEAP_TEXTURE_SIZE_AND_ALIGN` answers,
|
||
and sends each as a placement at that offset. The heap's `usedSize` and
|
||
`maxAvailableSizeWithAlignment:` answer from those placements.
|
||
|
||
**No-copy buffers.** `newBufferWithBytesNoCopy:` over bytes in a block of the
|
||
process's lies over them in place (`BUFFER_OVER_HOST_MEMORY` at their offset).
|
||
Metal makes one over any range the process maps readable, at any alignment:
|
||
malloc'd, `vm_allocate`d, read-only, or a file mapping (measured on an M3 Max,
|
||
16 KiB and 4 KiB pages). Writable Shared or Managed memory the kext wires lies
|
||
in place (`PagesBlock`, `BUFFER_OVER_PAGES`). A Managed one is a Managed buffer
|
||
whose CPU copy is the Shared buffer over the pages (`MANAGED_BUFFER_CREATE`, as
|
||
a slab's, above): two copies where the host's GPU has memory of its own,
|
||
as the AMD Radeon Pro 5300M's no-copy Managed buffer is, its GPU copy filled
|
||
from the pages at the create, and one copy, over the pages, where the GPU
|
||
shares the CPU's memory, as the Intel UHD 630's is (dgpu-oracle.md Q3). Its
|
||
`didModifyRange:`, and a blit's synchronize of it or of a texture over it, go
|
||
to the host as any Managed buffer's do; Apple's OpenCL makes them around its
|
||
maps of a buffer's memory. Shared memory the process maps read-only lies in
|
||
place too, where the device took `READ_ONLY_PAGES`: the kext wires it for
|
||
reading alone and marks its block read-only, and the buffer over it is made
|
||
with `MTLResourceOptions` bit 24, sent to the host alone (the buffer's options
|
||
answer the app's, as Metal's leave the bit out), whose GPU writes the host
|
||
drops as Metal drops them: Metal makes a buffer over read-only memory whose GPU
|
||
reads see the memory and whose blit fills and kernel stores complete with their
|
||
writes dropped, a file mapped under it unchanged (the AMD 5300M and the Intel
|
||
UHD 630, `oracle_bundle` `nocopy.ro`; the M3, accuracy-ledger.md
|
||
`read-only-pages-written`, whose row the host's drop follows). A texture over
|
||
such a buffer takes the same answers: a draw's, a kernel's or a blit's write of
|
||
it completes, dropped, and a render pass that stores into it or resolves into
|
||
it fails its command buffer with a page fault, as the M3's does, where the x86
|
||
Macs, on which bit 24 does nothing, complete it and write the pages
|
||
(dgpu-oracle.md Q38). Over any other
|
||
memory (read-only Managed memory, whose copies the host would write back to
|
||
its pages; read-only memory where the kext makes no block of it; a Managed
|
||
buffer's where the device makes no Managed buffer over a Shared one; or memory
|
||
the kext or host makes no pages block of) the buffer lies
|
||
over a range of a slab of its own options, as a device buffer of them does
|
||
("Shared and Managed buffers lie in slabs"): the process's own pages where
|
||
the device takes them, so no app-sized copy lies in the region. `contents`
|
||
stays the app's pointer. The range syncs with the memory as the IOSurface copies do
|
||
(Decided 14): from the memory before the commit of each command buffer that uses
|
||
the buffer, and back to it as one that may write it completes, before its
|
||
completion is reported. Each side's bytes that moved since the two last agreed go
|
||
to the other, byte by byte, so CPU and GPU writes beside each other both stand
|
||
(`guest/bundle/src/RgfxMemoryShadow.hpp`). A GPU write shows in the memory at
|
||
its command buffer's completion, not as it runs, and memory mapped read-only is
|
||
never written back, though the GPU's writes stay in the range for later command
|
||
buffers to read, where Metal's are dropped.
|
||
|
||
**Group dma-bufs of the pages blocks' views.** The host imports each pages
|
||
block's view once, as a buffer over the whole view that the block's
|
||
`BUFFER_OVER_PAGES` buffers lie in. Where the Vulkan platform imports a view as
|
||
a dma-buf of its own and the driver lists every import in every submission
|
||
(RADV), each live view is one more buffer object every `vkQueueSubmit` lists, at
|
||
about 0.5 us each. Measured on the Radeon 780M (Geekbench 7.1 Metal in a macOS
|
||
26.7.2 guest): at Super Resolution's midpoint about 580 such imports were live,
|
||
under about 1,573 no-copy objects, of the 945 buffer objects the process held
|
||
(about 605 of them the runtime's own memory, by its gauges), and a submission
|
||
took about 494 us; grouping is projected to bring a submission to about 250 us
|
||
or less. In Feature Matching, Particle Physics and Fluid Simulation other buffer
|
||
objects of the process (2,000 to 8,700) outnumber the imports, and grouping cuts
|
||
less there. There the surface worker gathers a process's views for a window: the
|
||
`BUFFER_OVER_PAGES` or `HEAP_OVER_PAGES` that makes a block's view maps it and
|
||
joins its process's open group, which stays open 1 ms from its first member, or
|
||
until its members reach one dma-buf's limits: udmabuf's `list_limit` runs and
|
||
`size_limit_mb` bytes, as the host has them (the host sets neither), and at most
|
||
64 MiB, whatever udmabuf takes (below). The group is then sealed: the views'
|
||
pages go into shared dma-bufs back to back, and each view's import is a piece of
|
||
its group's file, so the driver lists one import for the group. Only then are
|
||
the members' messages carried out, and the process's and the blocks' later
|
||
messages wait for that, so each sees its buffer as right after its create.
|
||
|
||
Some views take no group: a view over 16 MiB, one past a group's limits alone,
|
||
a view the host's cache of views holds, a heap over the guest's RAM, a block of
|
||
pages its process maps read-only and a read-only buffer (both made over a copy
|
||
of the pages), and a texture's import. A view whose group the host refuses is
|
||
imported alone, as before. A process's close and the device's reset drop its
|
||
groups being formed, which make nothing. What the guest sees does not change
|
||
beyond timing: object ids, GPU addresses, refusals, and the order of events and
|
||
interrupts are as before.
|
||
|
||
A member whose buffers went keeps its pages pinned (udmabuf holds them) and
|
||
mapped in the GPU's address space inside its group's import until the group's
|
||
last member goes, though no object covers them: in each group, at most the
|
||
group's bytes, 64 MiB. That cap is the host's own: udmabuf's default
|
||
`size_limit_mb` is 64, but CachyOS's 7.3 kernels boot with it at 2147483647,
|
||
where `list_limit` alone would let a group of large views pin gigabytes. With
|
||
the cap, a simulation over the creates and frees of Geekbench's Super
|
||
Resolution on the Radeon 780M holds 26 to 182 MiB of such pages at once, in all
|
||
groups, by the runs' sizes (4 KiB to 64 KiB), on every host alike. They are the
|
||
guest's RAM, resident anyway, and only a stale GPU address would reach them, as
|
||
it would reach any freed memory; the guest reuses them once the kext unwires
|
||
them.
|
||
|
||
**Managed storage** (Decided 4). A Managed buffer's or texture's CPU copy is
|
||
memory of its process's, which the guest maps: a buffer's a Shared buffer of
|
||
the slabs where the device takes `RGFX_FEATURE_MANAGED_BUFFER_SLABS`, else a
|
||
range of a slab ("Shared and Managed buffers lie in slabs") or a region block;
|
||
a texture's a Shared buffer of the slabs where the device takes
|
||
`RGFX_FEATURE_MANAGED_TEXTURE_SLABS`, else a region block. The slabs are the
|
||
process's own pages where the device takes them, so no app-sized copy
|
||
lies in the region.
|
||
- **A buffer**, on any host: a no-copy Managed buffer over its CPU copy's bytes
|
||
at the guest's address, whose copies the platform keeps as Metal does. Where
|
||
the GPU shares the CPU's memory that is one copy. Otherwise the Vulkan
|
||
platform's runtime keeps a GPU copy in the GPU's memory, with the guest's
|
||
bytes its CPU copy: copied in whole at the create, a range at each
|
||
`didModifyRange:` before the next submission, and out whole at each
|
||
`synchronizeResource:` where the blit encoder runs it. Where the GPU's memory
|
||
has no room for that copy, the buffer lies in its bytes, as a Shared one does,
|
||
which the runtime announces. `BUFFER_DID_MODIFY_RANGE` is the platform's
|
||
`didModifyRange:` of the range, and a blit's synchronize of the buffer the
|
||
platform's own.
|
||
- **A texture** takes its form from the platform's answer of whether the GPU
|
||
shares the CPU's memory:
|
||
- **Shared memory:** one copy. A one-level 2D texture or 2D array of a
|
||
linear format is a texture over its block's Shared buffer (an array by the
|
||
linear SPI, whose slices lie as the layout's); the range messages are
|
||
checked and do nothing more. A texture of any other shape (more levels, a
|
||
cube, a 3D texture, a block-compressed format) is two copies, as below: no
|
||
texture over a buffer has its shape, and without the CPU copy an upload
|
||
would be a staging blit the call waits for, hundreds of times a Managed
|
||
one's (dgpu-oracle.md Q17). The guest's `getBytes:` of it reads its GPU
|
||
copy, copied on the device: on a GPU that shares the CPU's memory Metal's
|
||
CPU reads of a Managed texture see the GPU's writes with no synchronize
|
||
(the Intel UHD 630 and the M3, dgpu-oracle.md Q2).
|
||
- **Otherwise:** two copies. The object the command buffers name is the
|
||
platform's own Managed texture, and the block sits beside it as a Shared
|
||
buffer. `TEXTURE_REPLACE_REGION` is the platform's `replaceRegion:` from
|
||
the block, done before the call returns, and a blit encoder's
|
||
`synchronizeResource:` and `synchronizeTexture:` become copies of the GPU's
|
||
copy into the block at that point of the encoder.
|
||
- Ring 0 is carried out before any later command buffer of the process, on any
|
||
queue, so a range message is ordered before every command buffer committed
|
||
after it, as Metal promises.
|
||
- Where the platform refuses a buffer, or a texture's GPU copy, the create is
|
||
refused, as Metal's answers nil. Metal makes Managed resources past a
|
||
discrete GPU's memory (measured on the AMD 5300M: 12 GiB of Managed buffers,
|
||
three times its 4 GiB, made, used by one command buffer and read back as
|
||
written), and the platform does too (the Vulkan platform's runtime places a
|
||
texture in system memory past a full device-local heap, and lays a buffer in
|
||
its bytes), so it refuses one only where that memory is gone as well.
|
||
- A buffer comes from `BUFFER_OVER_HOST_MEMORY` with Managed options; a texture
|
||
from `MANAGED_TEXTURE_CREATE`, which names the copy's Shared buffer and the
|
||
texel block of its format (bytes, width, height). The host reads the copy
|
||
where the buffer's contents lie: its block, its heap's bytes at its offset
|
||
(over a block or over a pages block's guest RAM), or a pages block's view. Both sides compute the
|
||
copy's linear layout from it (`crates/reims-vgpu-graphics/src/managed.rs`,
|
||
`guest/bundle/src/RgfxManagedLayout.hpp`): levels in order, then slices,
|
||
images and rows of blocks, each row rounded up to 256 bytes.
|
||
- In the guest, `replaceRegion:` and `getBytes:` are memcpys of the block, and
|
||
`replaceRegion:` posts its region; neither waits for the host, but for the
|
||
`getBytes:` of a two-copy texture on shared memory, above. A format the
|
||
layout has no block for (PVRTC) keeps no CPU copy: the texture is the
|
||
platform's alone, one copy on any GPU, and the CPU reaches it through the
|
||
staging blit a Shared texture's calls wait for, which sees the GPU's writes
|
||
with no synchronize, as the Intel 630's and the M3's Managed textures do
|
||
(dgpu-oracle.md Q2). A depth or stencil texture in Managed storage ends the
|
||
process first, as on both x86 oracles.
|
||
- Until the device's identity answers carry `hasUnifiedMemory`, the host takes
|
||
a texture's two copies on every GPU, which hold Metal's contract on any of
|
||
them.
|
||
|
||
**Command buffers** (per-queue submission ring). A `COMMAND_BUFFER` message is
|
||
one command buffer: its `ObjId`, then a byte stream of encoder ops. The decoder
|
||
opens the `Platform` command buffer and walks the ops:
|
||
- `ENCODER_BEGIN_RENDER` (our render-pass schema: colour/depth/stencil
|
||
attachments by texture `ObjId`, load/store actions, clears),
|
||
`ENCODER_BEGIN_BLIT`, `ENCODER_BEGIN_COMPUTE`; `ENCODER_END`.
|
||
- one op per `Platform` encoder method — set pipeline/buffer/texture/sampler/
|
||
bytes, viewport, scissor, draw / draw-indexed / dispatch, copy/blit, update/
|
||
wait fence, `useResource`/`useHeap`. The op set is the trait's encoder
|
||
methods; the first slice is the subset WindowServer and simple Metal apps
|
||
issue.
|
||
- `SIGNAL_EVENT` / `WAIT_EVENT` (event `ObjId`, value), between encoders, as
|
||
Metal's `encodeSignalEvent:value:` and `encodeWaitForEvent:value:` are →
|
||
`encode_signal` / `encode_wait`, for an `MTLEvent` and an `MTLSharedEvent`
|
||
alike (an event op with an encoder open, or naming no event, faults the
|
||
buffer). The end of the message closes it: the host commits and registers an
|
||
`add_completed_handler` that writes the completion record.
|
||
- `SURFACE_USE` (block offset, the kext's count of the surface's read-write
|
||
locks, whether the buffer may write it), one for each IOSurface with a device
|
||
cache the buffer uses, before its first encoder: the host fills the cache
|
||
before the buffer's work where it holds an older count (Decided 14, "The
|
||
device cache"). One naming a block with no cache does nothing.
|
||
- `SUBMITTED` (no body), where the device has `CB_SUBMITTED`: the buffer is
|
||
committed by `commitAndWaitUntilSubmitted`, and asks for its `CB_SUBMITTED`
|
||
("Submitted", below). The bundle puts it last, as it commits; the host reads
|
||
it as it takes the buffer, before its other ops.
|
||
- `GUEST_TIMES` (made, committed and posted, each the guest's clock), where
|
||
the guest took `GUEST_TIMES`: first in the stream, once, a diagnostic the
|
||
host reads as it takes the buffer ("Guest times", below). The walk steps
|
||
past it.
|
||
|
||
A command buffer too large for half its queue's submission ring goes out of
|
||
line: the whole `COMMAND_BUFFER` message lies in a block of the process's own,
|
||
from its queue's pool, and the ring carries a `COMMAND_BUFFER_IN_REGION`
|
||
(region offset and length).
|
||
- The bundle builds the message on its own heap, write-back memory, whatever
|
||
its size. When it outgrows half the ring, its buffer grows at once to the
|
||
queue's recent largest message, and doubles after that.
|
||
- The header and the commit's `SURFACE_USE` ops go into room kept before the
|
||
ops, so they move nothing.
|
||
- At the commit, the whole message is copied once into a block of the pool,
|
||
from the block's start. It is not built there: the block is write-combined
|
||
where the kext maps it so, and on an AMD host, which applies the guest's
|
||
memory type, a write-combined store still pending stalls the encoding
|
||
thread's next locked instruction (an app's retain or release among them) by
|
||
about 90 ns (`RgfxEncoder.hpp`).
|
||
|
||
The queue's service thread copies the message out of the block once, as it
|
||
does a ring's, with the reference's seqno, and the host walks and commits the
|
||
buffer from that copy, on its lane, copying it no more. It does not read the
|
||
block in place: the process may write its block at any time, and what the host
|
||
checked must stay what it carries out (the region's rule, `region.rs`). The
|
||
bundle gives the block back
|
||
to the queue's pool when the buffer completes. The pool keeps every block given
|
||
back and reuses the smallest that holds the next message, so of each size a
|
||
queue makes blocks only up to the most of its buffers in flight at once, and a
|
||
stream of large buffers asks the kext for none past them, where handing a block
|
||
back at each completion beyond a few kept cost a later buffer a block
|
||
allocation, a mapping into the process and a grant and release on the control
|
||
ring. Measured on an RTX 5080 host, an out-of-line buffer costs what an inline
|
||
one does, about 2.1 to 2.5 us a dispatch, up to 2000 in flight either way.
|
||
Encoders do not stream as they end yet (Decided 3): that needs a command buffer
|
||
in several messages, which the wire does not have. The whole buffer goes at its commit. Metal sets no maximum size, so
|
||
nothing is refused for size. A queue holds `maxCommandBufferCount` buffers
|
||
(64 by default) alive and not completed. `-commandBuffer` blocks past that, as
|
||
Metal's does, which keeps the ring from filling in the common case. A commit
|
||
that still finds the ring full rings the doorbell and, where the device's word
|
||
holds `SUBMIT_ROOM`, sets the ring's `producer_waiting`, looks once more, and
|
||
waits for the host's `SUBMIT_ROOM` record on the queue's completion ring, which
|
||
the queue's reader hands to the ring's writer, with a 20 ms backstop. Without
|
||
the bit it sleeps 20 µs, doubling to 1 ms, between looks. Each buffer's
|
||
completion is expected before the host can see it, under the ring's lock.
|
||
|
||
Metal splits one command buffer into several kernel submissions (a render pass;
|
||
a run of blits or of computes with no event between) — m2v's measured
|
||
granularity. The host preserves it so IOGPU error reporting lines up.
|
||
|
||
**Completion** (per-queue completion ring). A `CB_COMPLETE` record: the
|
||
command-buffer `ObjId`, status, GPU start/end time, and on error the
|
||
`CommandBufferError` the host maps 1:1 from the IOGPU code the runtime returns
|
||
(page fault, hang/timeout, recovery victim, access revoked, invalid resource —
|
||
the map m2v gave). The ring's armed/interrupt handshake is the stage-2 one.
|
||
The buffer's completion-seen handler posts it, with the values of the shared
|
||
events it signalled ahead of it: on metal2vulkan the runtime's thread that saw
|
||
the buffer complete runs it, in its queue's commit order, and with no
|
||
completed handler on the buffer no handler thread is woken; on Metal, which
|
||
tells of a completion only on its completed handlers' thread, a completed
|
||
handler.
|
||
|
||
**Scheduled** (per-queue completion ring). A `CB_SCHEDULED` record (the command-buffer
|
||
`ObjId`, at the buffer's seqno; 24 bytes, and the guest reads a record of at least that size)
|
||
goes on the queue's completion ring once, ahead of its `CB_COMPLETE`. A buffer that gets its
|
||
`CB_SUBMITTED` at its take (it asks for one and waits for nothing, below) gets it there too,
|
||
right after its `CB_SUBMITTED`, where no buffer begun before it on its queue owes its own, so a
|
||
queue's records keep their order; one answered on its doorbell's thread gets it there, with its
|
||
`CB_SUBMITTED`, where the same holds there. A buffer that does not ask keeps it to its
|
||
scheduling, or to a waiting thread's ask ("Scheduled at an ask", below): posted at its take, it would need the buffer's ticket in its process's commit order
|
||
there, as the `CB_SUBMITTED` does, and a walk held on one of the process's queues would then hold
|
||
up the commits of its others (`a_walk_held_in_a_draw_holds_up_no_other_queue`). Metal makes such
|
||
a buffer `Scheduled` within a
|
||
fraction of a millisecond of its commit, whatever its queue runs on the GPU before it (below);
|
||
waiting for the platform's submission instead put the scheduled handler of a tiny buffer on an
|
||
idle queue 0.39 ms after the commit on the RTX 5080 host (car 12, `submit_probe`), against
|
||
0.20 ms on an AMD 5300M Mac and 0.05 ms on Apple's paravirtualized device. Such a buffer gets
|
||
no submission handler where it holds nothing. Any other buffer gets it at its commit, behind an
|
||
order on the GPU ("Surface order", below), or once the host's platform has taken the buffer's
|
||
work for the GPU: the buffer's submission handler posts it. On
|
||
metal2vulkan it runs on the thread that took the buffer's last batch for its `VkQueue`, once
|
||
every wait of the buffer is satisfied, before the buffer reads `Scheduled`, and nothing
|
||
committed later on the queue runs before the buffer. That thread may be any that commits, since
|
||
the runtime takes the ready batches inside a commit (`commit_and_submit`): where it is not one
|
||
the header names for the device's raise (the window's render thread, a paravirtualized device's,
|
||
the host's inside `rvg_graphics_device_read_display`), the handler hands the buffer's records to
|
||
its queue's service thread, which posts them and raises, and every later post onto that ring
|
||
goes after them (`a_foreign_commit_hands_a_decoder_buffer_s_records_to_its_queue_s_thread`); on Metal, which tells of no point before
|
||
scheduling, it is a scheduled handler, run once every wait of the buffer is satisfied and its
|
||
work is submitted. A buffer the platform fails before it takes its work runs no submission
|
||
handler, and its completion handler posts its `CB_SCHEDULED` first
|
||
(`a_buffer_never_submitted_is_scheduled_ahead_of_its_completion`). The guest's
|
||
buffer is then submitted (`commitAndWaitUntilSubmitted` returns, before the scheduled handlers
|
||
run), becomes `Scheduled`, runs its scheduled handlers, then lets `waitUntilScheduled` return,
|
||
as Metal's does (measured on the M3 Max, macOS 27: on an idle queue
|
||
`commitAndWaitUntilSubmitted` returns in 0.05-0.1 ms with the buffer `Committed` and its
|
||
scheduled handler about 10 us from running; behind a 120 ms buffer it and `waitUntilScheduled`
|
||
return in 0.1 ms, `Scheduled`; a buffer that waits for an event nothing has signalled is
|
||
neither submitted nor scheduled until the event is signalled, or Metal's timeout fails it after
|
||
5 s). A CPU lock of a surface the buffer writes waits for the GPU's writes from the commit on
|
||
(§14, "CPU locks"), so a reader handed the surface at submission reads the GPU's results. A
|
||
buffer the host could not
|
||
carry out has no `CB_SCHEDULED`, and its `CB_COMPLETE` stands for both; so does every
|
||
`CB_COMPLETE` from a host that posts none.
|
||
|
||
**Scheduled at an ask.** A thread that waits for a buffer that does not ask for its
|
||
`CB_SUBMITTED` to be scheduled (`waitUntilScheduled`) asks for it, where the device's word holds
|
||
`SCHEDULED_ASK`: the bundle posts `SCHEDULED_ASK` (`RgfxScheduledAsk`, the buffer's `ObjId` and
|
||
the seqno of its message; 32 bytes) on the buffer's queue's ring, after the buffer's message,
|
||
once, unless the buffer is held as far as the process knows or is scheduled already. The queue's
|
||
service thread takes the ask after its begin of the buffer. Where the buffer would have got its
|
||
`CB_SCHEDULED` at its take had it asked for its `CB_SUBMITTED` (it waits for no event, follows
|
||
no deferred copy of a device cache, is behind no buffer of its queue that waits for one, and
|
||
found no buffer before it on its queue owing its `CB_SCHEDULED`), the host issues the buffer's
|
||
ticket in the commit order, given back at its commit, and posts the record then, whether or not
|
||
the walk is done; for a buffer already committed, the record goes at once with no ticket. Any
|
||
other ask changes nothing. So a walk held on one of a process's queues holds up the commits of
|
||
its other queues only for buffers sent once a thread has asked to wait for it, as after a
|
||
`CB_SUBMITTED` at its take
|
||
(`a_held_walk_holds_up_its_process_s_other_queues_only_once_waited_for`). Without the ask,
|
||
during a window's live resize on a 780M host (macOS 26.7.2, 11-09), the guest's GPU process
|
||
waited in `waitUntilScheduled` 349 times for 291.5 ms over 50 s, 288 ms of it before the host
|
||
posted the buffer's record at the platform's submission, 1.3 to 1.5 ms after the buffer's begin
|
||
on average; 192 of the waits, 205 ms, came in the busiest second. The ask is posted for blocking
|
||
waits alone: a scheduled handler, which no thread waits on, runs at the buffer's scheduling.
|
||
|
||
**Submitted** (per-queue completion ring), where the device has `CB_SUBMITTED` (`FEATURES_LO`
|
||
bit 2; every host sets it). A command buffer committed by `commitAndWaitUntilSubmitted` carries a
|
||
`SUBMITTED` op, and the host posts its `CB_SUBMITTED` record (the command-buffer `ObjId`, at the
|
||
buffer's seqno; 24 bytes) once, ahead of its `CB_SCHEDULED` and `CB_COMPLETE`: as soon as the
|
||
host takes it, before it walks the buffer's ops and before the fills of device caches it makes
|
||
at the take, where the buffer waits for no event (its `WAIT_EVENT` ops), it follows no copy of a
|
||
device cache asked before it and not yet made, nor needs a fill of one that must wait for buffers
|
||
begun before it (decided at the take from its `SURFACE_USE` ops, which lead the stream; "What a
|
||
walk sees", "Device caches"), and no buffer before it on its queue waits for one and is not yet
|
||
scheduled; else at its scheduling. A fill made at once at the take, or one made before and not
|
||
yet done, holds back nothing, as a wait for another queue's buffer does not ("Surface order"):
|
||
it waits for nothing of the guest's to come. The call returns
|
||
there. A guest whose bundle sends no such op never sees the event,
|
||
and a bundle sends it only where the bit is set, which it reads in the device info's
|
||
`features_lo`. What Metal does, on the M3, the 5300M and the 630
|
||
(docs/graphics-kext/dgpu-oracle.md, Q6 and Q7), and the class of each choice:
|
||
- Contract (all three agree): the call returns once the buffer is submitted, about 0.1 to 0.4 ms
|
||
behind a long buffer, and not before the signal where the buffer, or one before it on its
|
||
queue, waits for an event. A buffer committed on any queue once the call returned is ordered
|
||
after it for a tracked resource. The host answers as it takes the buffer, once its ticket in
|
||
the commit order is issued, and commits every command buffer the buffer's process sends after
|
||
the answer, on any of its queues, after that buffer's commit; a range message the process
|
||
sends after it waits for that commit too ("What a walk sees", below). Another process's
|
||
buffers do not wait for it: a tracked resource is one process's, and what processes share, an
|
||
IOSurface, is ordered on the GPU by the order of IOSurface accesses ("Surface order", below),
|
||
as a Mac orders it (Q16). metal2vulkan orders by commit across
|
||
queues, and Metal orders behind what it has submitted, which a held queue's buffers are not,
|
||
hence the rule for a queue held by a wait. Tested through the decoder on both platforms
|
||
(`a_later_commit_on_another_queue_sees_a_submitted_buffer_s_writes`).
|
||
- Loose (they race): whether the buffer is `Scheduled`, and its scheduled handlers have run, by
|
||
the time the call returns. Ours is the cheapest: still `Committed`, the handlers at its
|
||
`CB_SCHEDULED`, as on an idle queue on all three.
|
||
- Loose (later than Metal, inside the envelope): a buffer that waits for an event already
|
||
reached is answered at its scheduling, not at its take; so is one that follows a deferred copy
|
||
of a device cache, which Metal has none of.
|
||
- Loose (inside the envelope): a buffer whose take fills a device cache at once is answered
|
||
before the fill, as Metal, which has no fill, answers it at once. The host takes its ticket in
|
||
the commit order first and holds the caches it uses from the answer until it has made their
|
||
fills, so no other begin counts a use of one between and defers a fill decided at once. The
|
||
answer comes at the take, not at the doorbell: a doorbell cannot know the fill will be made at
|
||
once, as another queue's begin before the take may count a use of the cache.
|
||
- Loose (what "submitted" means on the host): Metal answers once it has submitted the buffer;
|
||
ours once the host has taken the message, before it encodes the buffer on its platform, which
|
||
the guest cannot tell apart, as nothing the guest sends after the answer is carried out
|
||
before that commit. Where nothing need be waited for, the answer comes earlier still: on the
|
||
guest's vCPU, inside its doorbell write, before the queue's thread takes the buffer
|
||
("The answer at the doorbell", below).
|
||
- Loose (what "scheduled" means on the host), the same way: a buffer that asks for its
|
||
`CB_SUBMITTED` and waits for nothing is `Scheduled` once the host has taken it, or at its
|
||
doorbell, before its platform has its work,
|
||
where Metal makes it so once it has submitted it, which the guest cannot tell apart either:
|
||
nothing of the guest's is ordered by a buffer's scheduling but its later commits, which the
|
||
ticket orders, and what the GPU reads and writes, which a present, a CPU lock and another
|
||
queue's or process's buffer wait for from the commit or the post on, not from the scheduling
|
||
(§14, "CPU locks"; "Surface order", below). A buffer that waits on an event or a deferred copy
|
||
of a device cache, or is behind one that does, is `Scheduled` at its scheduling, past its
|
||
waits, as on a Mac.
|
||
- Inside the envelope (a fault): a buffer whose ops the host cannot carry out after it was
|
||
answered fails at its `CB_COMPLETE`, as Metal reports a command buffer's errors at its
|
||
completion, not at its commit.
|
||
|
||
**Shared events.** The host's event is the one command buffers wait on and
|
||
signal; the bundle keeps the value as the process knows it. It only rises, as
|
||
Metal's does (measured on the M3 Max: a CPU set or a GPU signal to a lower value
|
||
leaves it). A CPU `setSignaledValue:` posts `SHARED_EVENT_SET_VALUE` on the
|
||
control ring, which sets the host's (so its GPU waits are released), and raises
|
||
the bundle's value. A command buffer's signal of a shared event reaches the
|
||
process as `EVENT_SIGNALLED` (`ObjId`, value), which the host posts on the
|
||
buffer's queue completion ring, once for each signal, ahead of the buffer's
|
||
`CB_COMPLETE` and whatever its outcome. Where the buffer has more work after the
|
||
signal (an encoder, or a wait for an event), the host posts it as its own event
|
||
reaches the value: it asks its platform for a notification at that value, on one
|
||
listener of the device's (`notifyListener:atValue:block:` on Metal; on the
|
||
Vulkan platform the runtime sees the value rise as the batch that ends at the
|
||
signal finishes), which may come while the buffer runs, or while it waits to be
|
||
scheduled. A signal at the buffer's end, and any no notification posted, go
|
||
with the buffer's completion; so does a signal of a shared event whose create
|
||
the host refused, wherever it lies ("Guest input the host refuses"): the host
|
||
holds no event to watch for it, and the walk runs ahead of the GPU, so a post
|
||
there could come before the buffer's earlier work is done. So a thread that
|
||
waits on the CPU for such a mid-buffer signal before it sets a value the buffer
|
||
waits for later waits for good, the one case where ours deadlocks where Metal's
|
||
goes on (below). The queue's reader hands each to the device's, where the
|
||
process's shared events listen. `notifyListener:` blocks run on their listener's queue with the value
|
||
they were registered at, at once where the value has reached it, as Metal's do
|
||
(measured). A shared event made at another value is set to it on the host after
|
||
its create.
|
||
|
||
**Shared events across processes.** A process hands its shared event to
|
||
another as Metal's do: by the event's `eventPort` (SPI), or by its handle
|
||
(`newSharedEventHandle`), Metal's own `MTLSharedEventHandle`, which NSXPC
|
||
carries with the port; the other process makes an event of its own from either
|
||
(`newSharedEventWithMachPort:`, SPI, and `newSharedEventWithHandle:`). Both are
|
||
the one host event: each process's command buffers signal and wait on it on the
|
||
GPU's timeline, and each process's CPU sets, waits and listeners work on it.
|
||
What Metal answers was measured on the AMD 5300M and the Intel 630 under macOS
|
||
26.7.1 (`guest/bundle/tools/oracle/oracle_events.m`, identical on both): the
|
||
port is the same name at each ask, and the event holds one send reference of
|
||
it; a handle takes a reference of its own and keeps the event's label; an event
|
||
made from the port or a handle takes one more, is a new object of the same
|
||
value, and is labelled as the handle (nil from a port); each lets its reference
|
||
go at its dealloc; `MACH_PORT_NULL`, a dead name, a port the process receives, a
|
||
task port and a nil handle are answered nil, the references as they were; and
|
||
the event and its handle code only through an NSXPCCoder (a keyed archiver's
|
||
encode and decode raise `NSInvalidArgumentException`, "This object may only be
|
||
encoded by an NSXPCCoder.", and the convenience archiver answers
|
||
`NSCocoaErrorDomain` 4866). An event made from a port keeps working once the
|
||
event that gave it is gone, while the port is held.
|
||
|
||
- **The port is a connection of the kext's.** The kext can give a process no
|
||
port of an object of its own (`IOUserClient::copyPortNameForObjectInTask` is
|
||
in `com.apple.kpi.private` alone), so the bundle opens a connection of its own
|
||
type on the accelerator for each event it hands out
|
||
(`RgfxSharedEventUserClient`, user-client type 'RGSE'), and its send right is
|
||
the event's `eventPort`. Its `Export` (10) has the kext name the event
|
||
device-wide: `SHARED_EVENT_NAME`, a name from 1 the kext never gives again,
|
||
answered `COMPLETE`; the kext answers the bundle only then, so an import that
|
||
follows finds the name. Its `Import` (11), by any process that holds the
|
||
port, has the kext make the caller's new event of the name:
|
||
`SHARED_EVENT_IMPORT`, answered `SHARED_EVENT_VALUE` with the host event's
|
||
value, which the new event starts at. A call on the port proves the caller
|
||
holds it, and each names the caller's context: the kext finds the client of
|
||
the calling task that holds that context open, and posts through its asks, so
|
||
a process names and makes events in no context but its own. `Submit` refuses
|
||
the three messages: only the kext builds them. Before it calls on a port it
|
||
was handed, the bundle asks its own connection whether the port is one of
|
||
these (`IOConnectAddClient`, which the kext's `connectClient` answers): the
|
||
kernel looks the port up in the caller's space and sends it nothing, so a send
|
||
right of another process's own port is answered nil at once, as Metal's, where
|
||
an IOKit call made on it kills the caller (dgpu-oracle.md, Q23).
|
||
- **One host event, its values to every holder.** The host keeps the event of
|
||
each name (`decode::shares`): each holder's id in its own table is that one
|
||
event. The values one holder's command buffers signal it to, as the host
|
||
posts each to that holder, and its CPU's sets, as the host carries them out,
|
||
are posted to every other holder as `EVENT_SIGNALLED` for its own id, on the
|
||
completion ring of a queue the bundle keeps for that (its listen queue, which
|
||
no command buffer uses), each tried at once and kept for a thread of the
|
||
host's where the ring has no room, so a process that stops taking its rings
|
||
holds up no other process's.
|
||
- **The port holds the event.** The name holds the host event as a holder does,
|
||
until the connection goes: once no task holds a send right of it, IOKit frees
|
||
it, and its free posts `SHARED_EVENT_UNNAME`. Its close, and IOKit's word that
|
||
its creator died, only detach it from the accelerator, so a port another
|
||
process holds outlives a creator killed with it. The host event goes once its
|
||
last holder and its last name have.
|
||
- **Residual: a value read across processes waits for its post.** Metal's event
|
||
is a kernel object whose value page each process maps, so a CPU set in one
|
||
process is read at once in the other (measured: "read 8 at once" across a
|
||
spawned pair). Ours raises the other process's value as its post arrives, on
|
||
its listen queue's ring, so a read right after another process's set may see
|
||
the value before it. Two events of one process over one port are one object's
|
||
(the second is the first's alias), so within a process a read sees a set at
|
||
once, as Metal's does.
|
||
|
||
Metal's CPU sees a signal from the middle of a buffer while the buffer runs
|
||
(docs/graphics-kext/dgpu-oracle.md, Q18): on the 5300M and the M3 within a few
|
||
milliseconds of the GPU reaching it, on the 630 about 100 ms after the commit,
|
||
which is later where the buffer runs on. On all three, a thread that waits on the
|
||
CPU for a mid-buffer signal before it sets a value the same buffer waits for
|
||
later goes on, and the buffer completes. So does ours: the host's notification
|
||
comes as its GPU reaches the signal, as the 5300M's and the M3's do. A signal at
|
||
the buffer's end reaches the CPU with the buffer's completion on all three, its
|
||
listener's block within 0.3 ms of the completed handler, either one first, and
|
||
ours comes ahead of the completion record. GPU waits are not affected either
|
||
way: another buffer's `WAIT_EVENT` waits on the host's event, which the host's
|
||
GPU signals at the point Metal's would.
|
||
|
||
A command buffer that waits on an event is watched: one not finished 5 s after
|
||
its commit is named in the log at WARN, with each event and value it waits for,
|
||
and again at INFO once it finishes (at most 32 per device). It is diagnostics
|
||
only: Metal waits without end for a value nothing reaches (measured: the buffer
|
||
stays `Committed`), and so does the host while the process lives. Once its
|
||
context is gone, at its close or a reset of the device, nothing is left to
|
||
set or signal its events: the host sets each shared event past every value and
|
||
signals each plain event past every value from a queue of its own, so a buffer
|
||
still waiting on one runs and finishes. A shared event another process or a
|
||
name still holds is left to them ("Shared events across processes"), and set
|
||
past every value once its last hold goes. It then
|
||
lets go of what it holds (its buffers' GPU addresses among them, which the
|
||
rebooted guest picks again after a reset), and the close's answer, which
|
||
waits for the context's buffers, comes. A Mac drops such a buffer instead
|
||
(measured, the 5300M and the 630 under macOS 26.7.1: a buffer that waits on
|
||
its process's own shared or plain event when the process exits or is killed
|
||
never runs; its writes to a shared-memory buffer and to an IOSurface never
|
||
land, 2 s and 5 s after). The host has committed the buffer to its platform
|
||
behind a GPU wait by then, and a platform takes back no committed buffer:
|
||
running it is the only end that holds nothing for good, so its writes land
|
||
where a Mac's never do.
|
||
|
||
**Who takes the completions.** Every queue raises the device's one vector,
|
||
the control ring's. The accelerator kext maps each queue's completion-ring
|
||
header into the kernel at its `QUEUE_CREATE`. The framebuffer's work loop
|
||
services the vector, and then the accelerator scans the watched rings: a ring
|
||
whose `producer` moved since the last scan, and still holds records its process
|
||
has not taken, wakes that process. The scan takes only the watch table's lock,
|
||
which no submit path takes. Each process has one completion thread in the bundle.
|
||
It sleeps in the kext (user-client selector `0x107`, an interruptible wait on a
|
||
per-client wake count it passes back), and each pass it drains every queue's
|
||
ring, arms it, fences and looks again. A completion posted while it works shows
|
||
in the count or in its last look, so none is missed and nothing polls. The
|
||
thread takes each command buffer's records whether or not anything waits, and
|
||
runs no handler. At a `CB_SUBMITTED` or `CB_SCHEDULED` the buffer is submitted
|
||
there, and at its `CB_COMPLETE` what the host is done with goes back: the
|
||
queue's slot, the message's block and the inline bytes' chunks. The rest runs
|
||
on the queue's completion queue, in ring order: the dispatch queue
|
||
`setCompletionQueue:` gave (WindowServer sets one), or a serial queue of the
|
||
queue's own, labelled `com.Metal.CompletionQueueDispatch` at user-interactive
|
||
QoS. That is where Metal runs a queue's handlers: one queue's one at a time,
|
||
two queues' at once (measured on the M3 Max, an AMD 5300M and an Intel 630).
|
||
The scheduling makes the buffer `Scheduled` and runs its scheduled handlers,
|
||
and the completion runs its write-backs, its status, its completed handlers
|
||
and its waiters. `waitUntilScheduled` and `waitUntilCompleted` return once
|
||
the handlers have run, as Metal's do. A buffer with no scheduled or completed
|
||
handler and nothing to write back (every surface it writes in place, no copy of
|
||
app memory) behind none of its queue's records still to run has its records run
|
||
by the completion thread itself, which wakes its waiters: one wake where the
|
||
queue's would be two, as Metal's waiter for a buffer with no completed handler
|
||
is woken by the thread that saw it complete. So does the scheduling of a buffer
|
||
with no scheduled handler, behind none of its queue's records still to run,
|
||
whatever its completion runs: it flips the status and lets
|
||
`waitUntilScheduled` go there, so a buffer with only a completed handler pays
|
||
the completion queue's wake once, for its completion. A wait for a buffer of a queue
|
||
from that queue's completion queue, a handler's for its own buffer or a later
|
||
buffer of its queue, waits for good, as Metal's does on all three GPUs; a wait
|
||
for another queue's buffer is released. `commitAndWaitUntilSubmitted` returns at
|
||
the submission, whatever handlers run. Waiters take the ring themselves only
|
||
once the thread has ended (its context closed), and then run the records too.
|
||
|
||
**Enqueue order.** A queue's command buffers go on its submission ring in the
|
||
order they were enqueued, whatever order they are committed in, as Metal runs
|
||
them (measured on the M3 Max, an AMD 5300M and an Intel 630). The queue keeps
|
||
its enqueued buffers that are not yet posted, oldest first; a commit with no
|
||
`enqueue` before it enqueues the buffer there. A buffer committed behind one
|
||
not yet committed stays `Committed` and unposted, and the commit that readies
|
||
the front posts every ready buffer behind it, in order, on its own thread. An
|
||
enqueued buffer let go uncommitted stays, holding back the buffers after it,
|
||
as Metal's does.
|
||
|
||
**Surface order**, where the guest took `SURFACE_ORDER` (`FEATURES_LO` bit 11).
|
||
On a Mac, a GPU access to an IOSurface committed after another process's
|
||
pending GPU access to it runs after that access, where either writes:
|
||
read after write, write after read and write after write. Accesses to other
|
||
surfaces are not ordered (measured on the MBP16's AMD 5300M, macOS 26.7.1: a
|
||
blit of the surface committed just after another process committed a 212 ms
|
||
pass over it waited for the pass in all three cases, and read or left what
|
||
the order says; a blit of another surface took 2.4-4 ms; the Intel 630
|
||
runs one process's work at a time, so it orders all of it). Queues and
|
||
processes here reach the host on rings of their own, which the host takes
|
||
apart, so the order the host takes buffers in is not the order they were
|
||
committed in. The bundle names the order instead, as it posts each buffer:
|
||
- Each surface's shared block holds its writers (`RgfxSurfaceWriters`, one
|
||
slot a queue: its latest buffer that writes the surface) and, after them, its
|
||
readers (the same record, the latest buffer of each queue that only reads
|
||
it), which only the bundles read. Every block has both: a copy's planes start
|
||
and end on 256 bytes, so its header, its writers and its readers (152 bytes)
|
||
fit in the page its planes end in, and a block in place holds the header and
|
||
the slots alone, from its start. Every holder asks a block's size from the
|
||
writers' end, as a bundle without readers did.
|
||
- A slot names a buffer only while it runs: once the host has finished it, and
|
||
its post has named it, its process empties the slot where no later buffer of
|
||
the queue raised it, as a buffer that named it would wait for nothing. Four
|
||
slots of each record are shared by every process's queues. A queue that finds
|
||
none free takes one of its process's that names a buffer of another of its
|
||
queues which its own buffer runs after, its post having named that buffer:
|
||
whatever names the slot from then on runs after both. A read that finds no
|
||
reader slot is named among the writers instead (its queue's writer slot, a
|
||
free one, or one taken so), which every later buffer that uses the surface
|
||
names: a later read, and a present, then wait for it too, later than a Mac
|
||
would and never sooner. Only an access whose record holds every slot for
|
||
other processes' queues, or for buffers it does not run after, is not named
|
||
(its process logs it once), so a later write of the surface by another queue
|
||
waits for none of that queue's reads, nor a present or a read for its writes.
|
||
- The post of a buffer that uses surfaces, just before it goes on its queue's
|
||
ring, reads, for each, the writers of other queues, and where the buffer
|
||
writes the surface the readers too, and names each queue once, at its highest
|
||
seqno, in one `SURFACE_ORDER` op before its first encoder. Once the buffer is
|
||
on its queue's ring it raises its own queue's slot: a writer's for a surface
|
||
it writes, else a reader's. The post, not the commit, is where Metal submits
|
||
the buffer: a buffer committed behind one enqueued before it and not yet
|
||
committed is submitted once that one is, as Metal's enqueue order has it, and
|
||
goes on its ring here then, so it runs after the accesses of other queues
|
||
submitted meanwhile (read from Metal's enqueue order; no oracle has measured
|
||
a held buffer's surface order).
|
||
- So each buffer named was posted before the post that names it read the
|
||
slots: the buffers' waits run from later posts to earlier ones, and cannot
|
||
meet in a cycle.
|
||
- The host keeps each queue's surface timeline, a shared event. A buffer that
|
||
holds `SURFACE_ORDER` signals its queue's to its seqno as it ends, and waits
|
||
first, on the GPU, for each named queue's to reach the seqno named, except
|
||
where the host has seen that buffer finish, or the queue is the buffer's own,
|
||
whose order is its ring's. A queue the host does not hold, or a seqno past
|
||
every one the queue's ring has published, names no buffer and waits for
|
||
nothing.
|
||
- A Mac orders no access after a buffer it has not submitted: one that waits on
|
||
an event not yet at its value, or is behind one on its queue (measured, the
|
||
5300M and the 630 under macOS 26.7.1: another process's blit of the surface,
|
||
and its read-only CPU lock, went on at once while the write waited on its
|
||
event, the blit reading the surface as it was). So the bundle holds such a
|
||
buffer's accesses: one that waits on an event below its value as the process
|
||
knows it (a shared event's value as the host posted it and the CPU set it, a
|
||
plain event's as the host finished the buffers of the process that signalled
|
||
it), or is posted behind a held buffer of its queue, raises its slots and
|
||
names its writes to the kext at its `CB_SCHEDULED`, which the host posts once
|
||
its platform has scheduled it, past its waits. A read posted meanwhile names
|
||
none of it and waits for none of it, and nor does a CPU lock.
|
||
- The wait is an order on the GPU and nothing more, as a Mac's is: a Mac answers
|
||
a command buffer it runs after another queue's or process's pending access to
|
||
a surface submitted and scheduled within a millisecond of its commit (the 630,
|
||
and the M3 in a run's first round, within 1 to 5 ms), and completes it after
|
||
that access (dgpu-oracle.md, Q16). So the wait holds back none of the buffer's
|
||
records, nor its queue: it gets its `CB_SUBMITTED` at its take, as a buffer
|
||
that waits for nothing does, and its `CB_SCHEDULED` there too where it gets
|
||
that and no buffer before it on its queue owes its own, else at its commit,
|
||
though the
|
||
platform may hold it until the buffer it waits for finishes (the Vulkan
|
||
platform holds a wait for a shared event's value on the host until it is
|
||
reached). So does every buffer committed behind it on its queue while the
|
||
platform holds it, and each buffer's records still go in its queue's order. A
|
||
buffer that waits for an event, or for a deferred copy of a device cache it
|
||
follows, or is behind one, keeps its records at its scheduling; a fill the
|
||
host makes at once holds back none of them.
|
||
- Work the host starts off a buffer's own GPU timeline waits for the same
|
||
buffers on the CPU first: a video session's decode runs on a queue of its own
|
||
as the host walks the buffer, so its output lands only after the reads and
|
||
writes of other queues the buffer names.
|
||
- What will not signal is signalled for it: a buffer stood in for signals from
|
||
its stand-in, and one with no stand-in from a command buffer of its own on its
|
||
queue. Where the queue makes no command buffer (the platform out of memory),
|
||
the host sets the timeline on the CPU, once it has reached what the queue's
|
||
command buffers committed before signal, so no signal comes before the
|
||
queue's earlier work. A queue's destroy, or its context's close, signals the
|
||
last value a buffer waits for of it. A buffer the host has taken that holds no
|
||
`SURFACE_ORDER` signals where another queue's buffer waits past what the
|
||
queue has signalled.
|
||
- A queue is known to the order from its create's answer on: the device tells
|
||
the host of it before it answers, so a buffer of another queue that names one
|
||
of its buffers waits for it though the host has yet to make the queue's handle.
|
||
|
||
Measured on the lane's RTX 5080 laptop host with a macOS 26.6.1 guest, one boot
|
||
each of the effort's tip before the order (18fd065e5) and with it: the sweep's
|
||
`video.h264.reader`, an AVAssetReader of frames VTDecoderXPCService decodes, failed
|
||
35 of 40 runs, then none of 40; vlprobe's AVAssetReader of 420v frames read
|
||
another frame than its sample's in 96 of 100 runs (39 an earlier one, 56 a
|
||
later one), then in none of 100. A CPU lock needs nothing more: on the MBP16's
|
||
AMD 5300M and Intel 630 (macOS 26.7.1), once a command buffer that writes a
|
||
surface is scheduled, every lock of the surface waits for it, read-only or
|
||
read-write, in its process or another, and then reads what it wrote; a lock
|
||
taken before the buffer is scheduled may not wait. The kext's locks wait for the
|
||
writes named from the commit on, which is inside that.
|
||
|
||
**Commit order**, where the guest took `COMMIT_ORDER` (`FEATURES_LO` bit 18).
|
||
Metal orders a tracked resource across a process's queues by the order the
|
||
command buffers were committed in: a copy committed on a second queue right
|
||
after the first queue's `commit` of a 30 ms kernel that writes its source read
|
||
what the kernel wrote in every run on the AMD 5300M, the Intel 630 and the M3
|
||
(dgpu-oracle.md, Q6). The platform orders a tracked resource across its queues
|
||
by the order the host commits to it, so the host has to commit in the guest's
|
||
order. A plain `commit` returns once the buffer is on its queue's ring, and
|
||
each queue's ring is taken on a thread of its own, so a buffer the guest
|
||
committed later on another queue could reach the platform first (before this
|
||
op, the oracle's two-queue row raced in 4 of 15 runs on the lane, each with
|
||
every word stale). The bundle names the order as it posts each buffer:
|
||
- The process keeps its command queues in a list, each with the seqno of its
|
||
latest buffer on its ring (`posted`), raised once the buffer is there.
|
||
- Before a buffer goes on its ring, it names each other queue of the process
|
||
whose `posted` rose since this queue last named it, at that `posted`, in one
|
||
`COMMIT_ORDER` op before its first encoder; then it goes on its ring, and its
|
||
queue's `posted` rises.
|
||
- So each buffer named was on its ring before the post that names it read
|
||
`posted`: the names run from later posts to earlier ones and cannot meet in a
|
||
cycle. A buffer committed but held behind an uncommitted one on its queue is
|
||
not on its ring, and is not named, as Metal does not submit it either.
|
||
- The host keeps two marks for each queue: the highest seqno whose buffer took
|
||
its place among the commit order's tickets (its begin), and the highest whose
|
||
buffer was committed, stood in for or failed, raised in the queue's order as
|
||
each buffer's job ends. A buffer that holds the op takes its own place among
|
||
the tickets only once each buffer it names has begun, and is committed only
|
||
once each named queue's commit mark reaches the seqno named, after its turn
|
||
in its queue and the tickets. The first wait keeps the tickets from crossing
|
||
the names. Without it, a queue's service thread could take a buffer that
|
||
names another queue's buffer, then a later buffer that asks for its
|
||
`CB_SUBMITTED` and takes a ticket, all before the named buffer's begin. The
|
||
named buffer would then wait for that ticket, the ticket's buffer for its
|
||
turn, and the naming buffer for the named one. With it, every wait of a
|
||
commit is for a buffer begun before it. An answer on a doorbell's thread,
|
||
which waits for nothing, is left to the service thread where a named buffer
|
||
has not begun.
|
||
- A name of its own queue, of another process's queue, of a queue the host
|
||
does not hold, or past every seqno the queue's ring has published, waits for
|
||
nothing. The waits hold no lock. A queue's destroy, its context's close and
|
||
a reset of the device end them, and while a reset is under way none waits,
|
||
so a process that names a cycle holds up only its own queues, until it
|
||
closes.
|
||
- Nothing else changes: no GPU wait is added, the buffer's records go as they
|
||
did, and the platform orders what the buffers share by the commit order.
|
||
|
||
**Guest times**, where the guest took `GUEST_TIMES` (`FEATURES_HI` bit 12), a
|
||
diagnostic. The host sees a command buffer only once its queue's thread takes
|
||
it off the ring, so the time before that, the app's encode and the buffer's
|
||
way to the host, shows as one span with nothing pending on the host. The guest
|
||
stamps each buffer so the host can split it:
|
||
- The bundle reads its clock (`mach_absolute_time` in nanoseconds, the kext's
|
||
clock) as the buffer is made (`commandBuffer`), as its `commit` is entered,
|
||
and as its message goes on its ring: under the ring's lock, after the copy
|
||
and before `producer` is published, written in the ring's copy at
|
||
`RGFX_GUEST_TIMES_POSTED_OFFSET` (64), as the seqno is stamped; for a buffer
|
||
in a block, into the block, under the ring's lock as its reference goes on
|
||
the ring. The op, 32 bytes, goes first, the last op put before the stream.
|
||
- At each `VBLANK`'s reading of `HOST_TIME` the framebuffer writes ring 0's
|
||
`guest_clock_offset_ns`, the held reading's offset, then
|
||
`guest_clock_bound_ns`, its bound (half the reading's round trip, widened by
|
||
50 ppm of its age), with release. The host zeroes both at a reset.
|
||
- The queue's thread stamps the host's clock as it takes the buffer, before
|
||
the gate, and as it comes back to the ring after the buffer before it
|
||
(`ring_free`, 0 for the first of a take). It reads the bound with acquire,
|
||
then the offset, and gives each buffer `encode` (committed − made),
|
||
`post_wait` (posted − committed: the ring's room, the queue's buffers
|
||
committed before it, its commit order's naming), and where the bound is not
|
||
0, `queued` (`ring_free` − posted, where the thread came back after the
|
||
post: behind the queue's buffer before it, the host's) and `transport` (the
|
||
take less the later of posted and `ring_free`: the doorbell, the thread's
|
||
wake and the ring), posted mapped to the host's clock by the offset.
|
||
- The host writes them to its trace (`REIMS_VGPU_TRACE`) as `cbguest queue
|
||
seqno encode post_wait queued transport bound held` (`cbguest queue seqno
|
||
encode post_wait held` with no offset held), `held` the time from the take
|
||
to the event (the buffer's wait at the gate, the read of a block), so a
|
||
reader places the take at the event less it. Once a second a debug line of
|
||
target `reims_vgpu_graphics::guest_times` gives the buffers' count, each
|
||
span's sum and median and the longest transport.
|
||
- The offset is off by at most its bound, microseconds, under the millisecond
|
||
spans it splits. The stamps cost three clock reads a buffer. Nothing else
|
||
the guest or the host observes changes: a guest that did not take the bit
|
||
stamps nothing, and the host ignores the op.
|
||
|
||
**Left for later** (extends the same op families, not the transport):
|
||
command-buffer/queue descriptors and `errorOptions`; labels and debug groups
|
||
answered guest-side; residency sets (`useResource`/`useHeap` are in);
|
||
`MTLIOCommandQueue`; Metal 4.
|
||
|
||
**Where the decoder lives.** In reims-vgpu (`graphics::decode`), generic over `P: Platform`,
|
||
beside the Apple-lane decode it mirrors (same handle machinery, descriptor
|
||
structs and `Platform` calls). The reims-vgpu-graphics crate stays the transport
|
||
(rings, region, registers); the decoder consumes ring bytes and drives
|
||
`Platform`.
|
||
|
||
**What a walk sees.** No lock of the device's is held across a command buffer's
|
||
walk and commit. Each context's objects are in a table of their own, each
|
||
message is carried out on a decoder of its own, and every lock is held for a
|
||
short section (the list is in `crates/reims-vgpu/src/graphics/decode/mod.rs`).
|
||
Ring 0 goes on while a queue walks, and so does every other queue, and the
|
||
queue's own later buffers are walked beside it. Under the single lock this
|
||
replaces, the decoder's lock was held from a command buffer's take to its
|
||
commit, so each other message came wholly before the take or wholly after the
|
||
commit. Each outcome the new design allows is one of those two:
|
||
- **Objects.** A command buffer names objects as its context's table was when
|
||
its first lookup (its queue, at its begin) took its view of the table. A
|
||
create, destroy or close carried out on another thread after that is not
|
||
seen, and each such change began after the buffer's take, so under the lock
|
||
it would have waited for the commit. An object destroyed during the walk is
|
||
named whole, and let go of once the walk's view closes, after the commit, as
|
||
one destroyed after the buffer. An object made during the walk is not named:
|
||
the op naming it faults, as it would before the create. An id destroyed, made
|
||
again and destroyed again during the walk is named as the object it was at
|
||
the begin. A close during the walk empties the table at once and the walk
|
||
keeps naming its objects; the buffer took its context's drain before its
|
||
view, so the close is answered after the buffer's completion handler. The
|
||
begin comes after ring 0 has carried out every message of its context's
|
||
published before the buffer was taken (`reims_vgpu_graphics`'s queue gate, "A
|
||
buffer's wait on ring 0"), so a buffer finds every create its process sent
|
||
before it. Tested by
|
||
`a_walk_names_what_its_table_held_at_its_begin`,
|
||
`a_walk_names_nothing_made_after_its_begin` and
|
||
`a_close_during_a_walk_leaves_it_its_objects` (the decoder's `cmdbuf`
|
||
tests), and through the device by `ring_0_is_carried_out_while_a_walk_is_in_flight`,
|
||
`a_close_during_a_walk_is_answered_after_the_buffer` and
|
||
`a_queue_s_buffer_runs_beside_another_queue_s_walk` (`graphics/tests.rs`).
|
||
- **The commit order.** A buffer answered `CB_SUBMITTED` at its take holds a
|
||
ticket, issued before the answer is posted, until it is committed (or its
|
||
stand-in is); one answered at its doorbell holds the answer's. Every command
|
||
buffer notes the tickets issued at its begin and is committed only once each
|
||
of its own context's is given back. A buffer its process sends after an
|
||
answer is begun after its ticket, so it is committed after the answered
|
||
buffer, as under the lock the answered buffer held through its commit. A
|
||
buffer begun before the answer does not wait: the guest sent it with no
|
||
answer in hand, so under the lock it could have been taken first. Another
|
||
context's buffer waits for no ticket of this one, though the lock held it
|
||
too: it names none of the context's objects, and what it shares with it, an
|
||
IOSurface, is ordered on the GPU (`SURFACE_ORDER`) and by the device cache's
|
||
users, not by commit, as a Mac orders tracked resources by commit only
|
||
within a process (dgpu-oracle.md, Q6 and Q16). So one process's answered
|
||
buffer whose walk is long (a cold make in a draw) holds up only its own
|
||
process's commits, where under a device-wide order every process's buffer
|
||
begun meanwhile, the compositor's among them, waited for it. A ticket
|
||
is issued after its buffer's begin, and a buffer waits only for older
|
||
tickets, so the waits end. Tested by
|
||
`a_buffer_sent_after_an_answer_is_committed_after_it`,
|
||
`a_held_walk_answered_its_submitted_holds_only_its_process_s_later_commits`
|
||
(`graphics/tests.rs`), and the sequencer's
|
||
`a_commit_waits_only_for_the_tickets_issued_before_its_begin`,
|
||
`a_commit_waits_for_its_own_context_s_tickets_alone` and
|
||
`tickets_given_back_out_of_order_hold_through_the_oldest`.
|
||
- **Range messages.** `BUFFER_DID_MODIFY_RANGE`, `TEXTURE_REPLACE_REGION`
|
||
and `TEXTURE_DID_MODIFY_DATA` reach the platform's next submission. One is carried out once every ticket
|
||
its context held when it came is given back, so a buffer answered before the
|
||
message was sent does not see its bytes, as under the lock, where the message
|
||
waited for that buffer's commit. Another context's tickets are not waited
|
||
for: its buffers cannot name the object, which is its own process's. A buffer
|
||
of the same context not answered at its take is not waited for either: the
|
||
guest sent the message with no answer from it, so under the lock the message
|
||
could have come before its take, and the buffer may see the bytes, as it may
|
||
on Metal. Ring 0 does not wait for those tickets: the message is checked
|
||
there (a bad reference or a range past its object is found at once), and its
|
||
platform call is made where the last ticket is given back,
|
||
after that buffer's commit, a context's range messages one at a time in the
|
||
order they came. Every command buffer of the context begun after it came is
|
||
committed after it, as one begun after ring 0 carried it out was, and it
|
||
holds its context's drain, so the context's close and its blocks' releases
|
||
are answered after it. It reads the block when it runs, not when it came: a
|
||
CPU write made after the message and before the next commit may reach the
|
||
GPU with it, as Metal's copy of a `Managed` resource is made at the next
|
||
submission. Tested by `a_buffer_sent_after_an_answer_is_committed_after_it`
|
||
(its range messages), `a_texture_s_modified_data_is_carried_out_before_a_later_command_buffer`
|
||
(`graphics/tests.rs`) and the sequencer's
|
||
`a_range_message_is_carried_out_once_its_context_s_tickets_are_given_back`.
|
||
- **Device caches.** A command buffer counts among the users of each cached
|
||
block it uses from its begin to its commit, each use under a number of its own
|
||
in the order they are counted. A fill follows every user counted before it was
|
||
asked, and a copy out of a cache (a download, a release, the block named
|
||
again) every such user that may write it, so each copy comes before a user's
|
||
begin or after its commit, as under the lock. No thread that asks a copy waits
|
||
for those users: a copy none holds up, and no copy asked before it, is made at
|
||
once; any other is made in the finish of the last of them, after its commit,
|
||
in the order the copies were asked, a download and a release answered once
|
||
their copy is done, as before. So a fill at a begin waits for no other queue's
|
||
walk, nor does a present's fill on the control thread: on a GPU of its own
|
||
memory, a WindowServer buffer whose surface a page's long buffer used waited
|
||
on its queue's thread for that walk (13.5 s behind a WebGPU page's buffer on
|
||
the RTX 5080 Laptop GPU host; measured). A buffer counted after a copy was
|
||
asked is ordered after it on the GPU instead: it waits for the cache's own
|
||
event, which the copy's command buffer signals to the copy's number, where it
|
||
reads what the copy writes (a fill) or may write what the copy reads (any
|
||
copy), and it holds its queue, as a buffer that waits for an event does; its
|
||
marks of the cache and its end value are kept apart until the copy is made, so
|
||
the copy follows none of them. A buffer finished before a copy it follows is
|
||
made stays counted among the users of every cache it used until it is: the
|
||
copies run on one queue in the order they are made, and one made behind the
|
||
buffer would wait there for its end, and so for the copy it follows, behind it
|
||
on that queue. A buffer that only reads follows no copy out, which leaves the
|
||
cache as it is. A copy that copies nothing signals from a command buffer of
|
||
its own, after the copy before it; where the platform makes no event, the
|
||
begin waits for the copy on the CPU, as it did for the users. Nothing of ring
|
||
0's names the block meanwhile that a copy changes: a download leaves the
|
||
block's buffers as they are, and the kext names a released block again only
|
||
once its release is answered. The block named again still waits there, for the
|
||
writers and the copies asked, as the buffers ring 0 makes over the block after
|
||
it lie over what it leaves. A buffer's uses are counted together, after those
|
||
of the buffers begun before it; a copy follows only buffers begun before it
|
||
was asked, and a buffer waits only for copies asked before it was begun, so
|
||
the waits end, on the CPU and on the GPU. Tested by
|
||
`a_fill_follows_the_buffers_using_the_cache`,
|
||
`a_begin_waits_on_the_cpu_for_no_other_queue_s_long_walk`,
|
||
`a_present_s_fill_behind_a_walk_is_made_in_its_finish`,
|
||
`a_begin_behind_a_download_waits_on_the_gpu_only_where_it_writes`,
|
||
`a_copy_behind_a_buffer_waiting_for_a_copy_is_made_after_that_copy`,
|
||
`two_queues_take_one_fill_and_a_download_waits_for_both` and
|
||
`a_copy_out_of_a_cache_is_made_as_its_writers_finish` (`surface_cache`).
|
||
- **The device's reset.** A reset ends every queue at once and is passed to
|
||
the host on the control thread, before anything the guest publishes after
|
||
it. Under the lock, the host's reset waited for the message holding the lock,
|
||
and each message after it found its queue's poster stale and was not carried
|
||
out. Here each message carried out off the control thread (a queue's command
|
||
buffer, create or destroy) holds a gate shared, from before it asks whether
|
||
its poster is stale to its end, and so does each compile's and library
|
||
make's store. The host's reset holds the gate alone. So the reset waits for
|
||
every message that passed its check, each of which could have run whole
|
||
before the reset under the lock. A walk in flight names its objects and
|
||
commits, and then every object goes, none outliving the reset; a message
|
||
after the gate finds its poster stale. Only the reset makes ring 0's thread
|
||
wait for a walk, as the lock did. Tested by `a_reset_during_a_walk_comes_after_it`
|
||
and `a_reset_drops_every_object_the_guest_made` (`graphics/tests.rs`), and
|
||
by the decoder's fuzz (`decode/fuzz.rs`).
|
||
- **A queue's own order.** A queue's service thread begins each of its
|
||
command buffers in the order the guest published them and hands
|
||
the walk and the commit to the queue's lane (`decode/lane.rs`), whose threads
|
||
walk several at once, so one process's busy queue is not bound to one
|
||
thread. Under the lock a queue's next buffer was taken after the commit of
|
||
the one before it. Here each buffer gets its turn in its queue's lane at its
|
||
begin, before anything of it can fail, and its commit, its stand-in's commit
|
||
and the failure posted at once for it wait for every turn before its own, so
|
||
they come in the order the buffers were taken, as under the lock. A walk
|
||
encodes into its own command buffer, which the platform runs in commit order:
|
||
Apple's Metal guide lets a queue's buffers be encoded on several threads and
|
||
run in the order they are committed, and metal2vulkan resolves barriers,
|
||
layouts and fences at submit, in commit order. Four things a buffer does
|
||
before its commit are seen beyond it, and each keeps the lock's order:
|
||
- its hold of its queue: a buffer that waits for an event, or for a deferred
|
||
copy of a device cache it follows, holds its queue from its
|
||
begin, not its commit, so a buffer after it that asks for its `CB_SUBMITTED`
|
||
is answered at its scheduling, as behind one already committed;
|
||
- a video encoder's work, which its session starts as it is walked: a buffer
|
||
that holds one is walked only in its turn, and one whose turn is next at
|
||
its begin is walked and committed on the service thread itself, where it
|
||
waits for no buffer of its queue, rather than handed to a lane thread that
|
||
would first be woken or made for it (so is a short buffer, its message of
|
||
2 KiB at most, whose commit would wait for nothing at its begin: its turn
|
||
next, and no buffer of its process it is committed after still to commit;
|
||
on the lane, each buffer of a drain paid a thread's wake for its walk and
|
||
another for the turn its commit waited on). Such a buffer lets go of its
|
||
queue's claim on its ring's messages once it is begun, and the service
|
||
thread offers the queue's next buffer to the host there, as a doorbell's
|
||
thread does, so a buffer that asks for its `CB_SUBMITTED` behind it is
|
||
answered before the walk, or at its own doorbell during it, as behind a
|
||
walk on a lane thread. Through the walk the thread marks the ring
|
||
walking (`consumer_idle` 2), for which the guest rings a queue's doorbell
|
||
only for a buffer that asks for its `CB_SUBMITTED`; it clears the mark
|
||
when it takes the claim back, and takes what the guest published meanwhile.
|
||
With the ring marked as before a sleep (1), the guest would ring for each
|
||
buffer it publishes during a walk, a VM exit that answers nothing for a
|
||
buffer that does not ask (measured on a 26.7.2 guest of a 780M host:
|
||
11.9 µs a doorbell, in two of three commits of a back-to-back run). Held
|
||
through the walk, the claim kept the doorbell from answering, and with
|
||
the ring marked busy the guest rang none, so a
|
||
guest's `commitAndWaitUntilSubmitted` behind a buffer of fills waited for
|
||
that walk and its commit (tested by
|
||
`a_buffer_that_asks_behind_a_walk_on_its_service_thread_is_answered_before_the_walk_ends`);
|
||
- its signal of its queue's surface timeline ("Surface order"), and the
|
||
release that stands in for one of a buffer that does not run: each is
|
||
decided in the buffer's turn, after its walk, since the order reads a
|
||
queue's buffer taken past a seqno as every buffer up to it taken, and a
|
||
waiter that saw a later buffer taken while an earlier one still walked
|
||
would wait for nothing;
|
||
- its answer at its take, posted at its begin, before the buffers before it
|
||
on its queue commit: everything its process sends after the answer is
|
||
committed after the buffer (its ticket), which commits after them, so
|
||
nothing sent later sees the difference, and those buffers are `Committed`
|
||
or `Scheduled` at the answer by a race, as Metal's are.
|
||
|
||
A turn passes as its buffer's work ends, and a buffer waits only for turns
|
||
and tickets of buffers begun before it. A lane's threads take its jobs in
|
||
the order they came, and every lane with work has a thread of its own, so
|
||
the oldest unfinished buffer of each lane is on a thread, and so is the
|
||
oldest of the device: the waits end, by induction on the begin order. A
|
||
buffer carried out on its service thread is its lane's oldest unfinished
|
||
one, and the lane gets no job while it runs. A
|
||
job that comes while every thread of the lane is busy gets another, only
|
||
where the device-wide budget has one free, which a lane never waits for. At
|
||
most eight of a lane's jobs walk at once; a job that waits for what is
|
||
committed before its buffer (its turn, its tickets, the buffers its
|
||
`COMMIT_ORDER` names, a split of its context) is not among them while it
|
||
waits, so the lane starts its next job meanwhile, up to 64 threads a lane,
|
||
as many command buffers as the host's queue holds uncompleted. The budget is
|
||
twice the host's cores and 64 more, for a busy queue's buffers walked ahead
|
||
of their turns. So 2048 busy queues hold one thread each and the budget's at
|
||
most. The waits are the same and where they were, so the commits, records
|
||
and interrupts are too; only how far the walks run ahead changed. A job
|
||
held back by the eight is later than every job started, so it holds none of
|
||
their waits. A job goes to the thread that went idle last,
|
||
and a thread goes after 10 s with no job, the budget's before the lane's
|
||
own: the threads a burst made go 10 s after it, while a steady load's stay
|
||
through its pauses and jobs that come one at a time stay on one thread
|
||
(`a_lane_keeps_its_thread_through_a_steady_load_s_pauses`,
|
||
`a_burst_s_other_threads_go_after_keep_while_one_takes_the_jobs`). Each lane
|
||
thread gives itself the walk hints as it starts (on Linux, a utilization
|
||
floor; no thread is bound to a CPU). Tested through the device
|
||
by
|
||
`a_queue_s_buffers_are_walked_at_once_and_committed_in_order`,
|
||
`every_buffer_behind_a_held_walk_is_walked_beside_it_and_committed_in_turn`,
|
||
`a_queue_s_buffers_past_its_lane_s_most_threads_wait_to_start_and_commit_in_turn`,
|
||
`a_process_s_buffers_behind_its_held_answered_one_are_walked_and_committed_after_it`,
|
||
`a_buffer_behind_one_that_waits_and_is_still_walked_is_answered_at_its_scheduling`,
|
||
`a_video_buffer_is_walked_in_its_turn` and
|
||
`a_lone_video_buffer_is_walked_on_its_queue_s_service_thread`
|
||
(`graphics/tests.rs`), and by the lane's
|
||
`a_turn_waits_for_every_turn_before_it`,
|
||
`a_turn_is_next_once_every_turn_before_it_has_passed`,
|
||
`many_waiting_turns_each_go_in_their_turn`,
|
||
`a_lane_runs_its_jobs_at_once_on_the_budget_s_threads`,
|
||
`a_lane_starts_its_next_jobs_while_its_jobs_wait`,
|
||
`a_lane_of_waiting_jobs_holds_lane_most_threads_at_most`,
|
||
`a_wait_off_the_lane_s_threads_or_inside_another_is_the_wait_alone`,
|
||
`a_lane_with_no_budget_left_runs_its_jobs_on_its_own_thread_in_order`,
|
||
`busy_lanes_hold_one_thread_each_and_the_budget_s`,
|
||
`a_burst_s_threads_go_while_jobs_come_one_at_a_time`,
|
||
`a_burst_after_the_threads_went_grows_the_lane_to_its_limit_again` and
|
||
`each_thread_gives_itself_the_walk_hints_before_its_first_job`.
|
||
- **A command buffer in parts.** Where the platform starts a command buffer's
|
||
GPU work only at its commit (the Vulkan platform's runtime records it and
|
||
submits it then), a long buffer's walk and its GPU work run in series:
|
||
WindowServer's composite of a Liquid Glass desktop walked 2.6 to 3.5 ms and
|
||
then ran 1.6 to 3.3 ms on an RTX 5080 Laptop GPU, each frame, against a
|
||
refresh of 8.33 ms. So the walk commits such a buffer in parts
|
||
(`decode/split.rs`): at an encoder's end, once the part walked since the last
|
||
took 250 µs, it hands the platform that part (`CommandBuffer::split`), which
|
||
commits it on the buffer's queue and answers a command buffer of the queue
|
||
that goes on from it, and the walk goes on in that one. On the M3 Max (MoltenVK)
|
||
a frame of 60 passes then completed in 6.0 ms from its message's take, where
|
||
it took 9.5 ms whole (`decode/split.rs`, "What it gains"). A part is committed
|
||
only where the whole buffer could be committed then, waiting for nothing:
|
||
its turn is next, every ticket and range message before its begin is done,
|
||
and the buffers its `COMMIT_ORDER` names are committed. Every wait of the
|
||
last commit is met at the first part, so the walk never waits between
|
||
parts. The parts run in their order on the queue, as one buffer's encoders
|
||
do. The buffer's handlers, records, ticket and commit marks are its last
|
||
part's, and its outcome is all of them: the first failed part's error, and
|
||
GPU times that start at the first part's start and span the parts' GPU time
|
||
summed, never ending after the last part's end (`decode/split.rs`, "Its GPU
|
||
times": the GPU's waits between parts are for the host's walk, which a
|
||
Mac's GPU, handed the whole buffer at its commit, never has; one buffer on
|
||
both x86 Macs spans its encoders' GPU time summed, and macOS's compositor
|
||
reads a buffer's GPU times). While a buffer's parts are
|
||
out, from its first part's commit to its last, no other command buffer of
|
||
its context is committed (each waits at its commit, never at its walk), and
|
||
the context's range messages that come are carried out after its last
|
||
commit, so each other message comes wholly before the buffer's commit or
|
||
wholly after it, as under the lock. A buffer splits only while no other
|
||
commit or range message of its context is under way, and only where it
|
||
waits for no event, is behind no buffer of its queue that does, is not a
|
||
video buffer, and its queue holds room for another command buffer. A buffer
|
||
whose walk faults after a part has its failure at its stand-in's
|
||
completion, as one whose walk faults whole; the parts committed before the
|
||
fault ran, as the encoders before a fault of Metal's GPU run. The Vulkan
|
||
platform keeps a buffer whole where a part would answer otherwise than the
|
||
whole (`gpu/command.rs`, "A command buffer in parts"); a buffer of compute
|
||
encoders alone is cut too, its unit of command predication going on in the
|
||
next part, and a buffer shaped like Geekbench 7's Fluid Simulation's, of
|
||
2,600 one-dispatch encoders, then completed in 34.8 ms where it took 87.0 ms
|
||
whole on the M3 Max (`decode/split.rs`, "What it gains"). Tested
|
||
by `a_buffer_walked_long_is_committed_in_parts_with_one_outcome`,
|
||
`a_buffer_is_committed_whole_where_its_parts_would_wait`,
|
||
`another_queue_s_commit_waits_for_a_buffer_s_last_part` and
|
||
`a_walk_that_faults_after_a_part_fails_at_its_stand_in`,
|
||
`a_split_after_a_mid_buffer_signal_keeps_the_signal_before_the_cut` and
|
||
`a_split_after_a_skipped_encoder_answers_as_the_whole` (the decoder's
|
||
`cmdbuf` tests), and the gate's own (`decode/split.rs`).
|
||
- **What still waits on ring 0's thread:** a block named again, for that
|
||
block's writers; a present's fill, for that block's users begun and not
|
||
finished (not for the fill itself: the fill is committed there, and the
|
||
present waits for it in the present queue, shown at the fill's completion);
|
||
and the device's reset, for every message in flight. A context's close waits for no
|
||
walk: `reims_vgpu_graphics` fences each of its queues, which waits only for a take
|
||
of the queue's submission ring or a post onto its completion ring under way,
|
||
and the close is answered once its buffers have finished
|
||
(`a_close_during_a_walk_holds_up_nothing_on_ring_0`). A doorbell's take tries
|
||
every lock it takes, and takes nothing it would have to let go of.
|
||
- **A landed download at ring 0's doorbell.** A write of ring 0's doorbell
|
||
through `Device::mmio_write_taking` takes ring 0's next message on the
|
||
writing thread and answers it there where it is a `SURFACE_DOWNLOAD` the
|
||
host has carried out already (`Host::surface_downloaded`: the block has no
|
||
device cache, or one nothing wrote since its last copy, whose early copy has
|
||
landed), the control thread sleeps with every answer of what it took posted,
|
||
the block's lane has nothing left, and the control completion ring has room;
|
||
each lock is tried, and nothing is allocated or freed. The `COMPLETE` is
|
||
posted and the control vector raised before the write returns, so a CPU
|
||
lock of a decoder's output whose copy has landed no longer waits for the
|
||
control thread's wake. QEMU takes ring 0's doorbell with an ioeventfd,
|
||
whose file the control thread polls, so under QEMU this applies only once
|
||
`reims-graphics-pci` sends that write through `_mmio_write_taking` too.
|
||
- **The answer at the doorbell.** A queue's doorbell write, on the guest's
|
||
vCPU, may answer `CB_SUBMITTED` to the buffer at the head of the queue's ring
|
||
before the queue's thread wakes to take it (`reims_vgpu_graphics`'s
|
||
`Device::mmio_write_taking`), where the buffer would get it at its take and
|
||
nothing need be waited for or allocated: the vCPU copies the message onto its
|
||
stack, reads its ops where they lie, and tries every lock it takes. It reads
|
||
the ops only where the stream's last op is the buffer's `SUBMITTED`, where the
|
||
bundle appends it at the commit, so a buffer that does not ask costs the vCPU
|
||
no scan of its ops. A buffer that does not ask, or whose ask is not its last
|
||
op, or that waits for a copy of a device cache it uses (a fill it needs or
|
||
one not yet done, or a copy asked before it that it follows), waits for an
|
||
event or another queue's buffer, sits behind a held buffer, or finds a lock
|
||
busy is left to the queue's thread, as before. One that uses a device cache
|
||
and waits for none of its copies is answered there: it was left to the
|
||
queue's thread for using one at all. A copy asked between the answer and the
|
||
buffer's begin (a fill a write of the host's devices over the pages asks, a
|
||
present's fill, a download or a release) is followed at the begin all the
|
||
same where the buffer must follow it ("Device caches" above), the buffer
|
||
waiting for it on the GPU with its answer given: the two were concurrent,
|
||
and the buffer is ordered after the copy, as one begun after it is.
|
||
The answer takes the buffer's turn in its queue's lane and its ticket
|
||
in the commit order together, with its mark (every ticket issued before its
|
||
own), keeps them on the queue (`cmdbuf`'s `Answered`), and posts the record.
|
||
The queue's thread then takes the buffer without waiting for ring 0 again
|
||
(the vCPU found ring 0 carried out as far as the buffer waits for), and its
|
||
begin takes the turn, the mark and the ticket in place of its own, so its
|
||
commit and every commit it orders come where they would had it been answered
|
||
at its begin. Its later messages on ring 0 wait for nothing more of it than
|
||
before. A buffer never begun after its answer (its queue gone, the device
|
||
reset) lets them go with its queue's entry, and a buffer the platform refuses
|
||
at its begin fails in its turn. The vCPU neither allocates nor frees, as
|
||
the library's allocator may purge pages in either call: the platform's
|
||
command buffer and every other allocation are made on the queue's thread.
|
||
The answer is on the queue's completion ring before the doorbell write
|
||
returns, so the bundle's post looks for it there as the write returns
|
||
(`RgfxReplyReader::holdsSubmitted`, which takes no record): a buffer
|
||
answered at its doorbell is submitted there, and
|
||
`commitAndWaitUntilSubmitted` returns with no interrupt and no wake of the
|
||
completion thread on its way. That thread takes the record later, in ring
|
||
order, and finds the buffer submitted already. Tested by the bundle's
|
||
`test_submitted_at_the_doorbell_wakes_no_thread` and
|
||
`test_reply_reader_holds_submitted` (`tests/shell_tests.mm`).
|
||
A buffer the doorbell leaves to the queue's thread because ring 0 is behind
|
||
(a create of its process's not yet carried out) is offered the same way on
|
||
the lane's thread whose carrying out ends the queue's thread's wait, before
|
||
that thread is woken (`reims_vgpu_graphics`'s queue gate, its offers), so its
|
||
`CB_SUBMITTED` no longer waits for the queue's thread's wake
|
||
(`a_buffer_behind_its_process_s_create_is_answered_on_the_lane_s_thread`).
|
||
Tested by `a_doorbell_s_answer_allocates_nothing` and
|
||
`a_doorbell_write_answers_a_command_buffer_on_its_thread`
|
||
(`graphics/tests.rs`), the `cmdbuf` tests
|
||
`a_buffer_is_answered_at_the_doorbell_only_where_it_need_wait_for_nothing`,
|
||
`a_buffer_answered_at_the_doorbell_is_carried_out_as_one_decoded`,
|
||
`a_buffer_begun_after_an_answer_is_committed_after_the_answered_buffer`,
|
||
`a_reset_between_an_answer_and_its_begin_lets_the_answer_go` and
|
||
`a_refused_make_after_an_answer_fails_in_turn`, the `surface_cache` test
|
||
`a_buffer_using_a_cache_is_answered_at_its_doorbell_where_it_waits_for_no_copy`,
|
||
the decoder's fuzz (`an_answer_at_the_doorbell_keeps_the_order_of_a_take`),
|
||
and the device's `an_answered_command_buffer_waits_for_no_later_ring_0_message`.
|
||
Under `DOORBELL_ASKS` only a write that carries `RGFX_DOORBELL_ASKS` is
|
||
answered there; a plain write wakes the queue's thread alone
|
||
(`only_an_asking_doorbell_write_is_answered_at_the_doorbell`,
|
||
`a_guest_without_doorbell_asks_is_answered_at_any_doorbell_and_not_routed`).
|
||
- **Routed doorbells.** A plain doorbell write needs nothing of the host but
|
||
the wake of the queue's thread, so where the guest took `DOORBELL_ASKS` each
|
||
queue's thread sleeps on an eventfd of its own as well as on its wake, and
|
||
the device hands the host that eventfd with the ring's id at the queue's
|
||
create (the C API's `route_doorbell`). QEMU registers it with KVM as an
|
||
ioeventfd on `DOORBELL` matching the ring's id exactly, so KVM signals it
|
||
inside the guest's write and the vCPU returns to the guest with no exit to
|
||
QEMU; the asking write, the id with bit 0, matches no route and goes to
|
||
QEMU and the library as before. Measured on the Radeon 780M host before
|
||
the routes: a write QEMU takes as an ioeventfd (ring 0's) costs the guest
|
||
8.9 us, one it runs through the library 13.4 us. The thread drains the
|
||
eventfd and walks the ring on each wake, so writes that coalesce into one
|
||
wake are all taken, in ring order
|
||
(`a_routed_doorbell_wakes_its_queue_which_takes_every_buffer_published`).
|
||
The device routes at most 128 queues' doorbells (KVM holds 1000 devices on
|
||
its MMIO bus, and QEMU ends the VM where KVM refuses one); a queue past them,
|
||
or one whose route the host refuses, keeps its doorbell on the write, logged
|
||
once per kind (`full`, `refused`) and then counted
|
||
(`a_queue_past_the_routes_or_refused_keeps_its_doorbell_on_the_write`). A
|
||
queue's route goes at its destroy, its context's close and the device's
|
||
reset (`a_reset_drops_the_queues_routes`), and QEMU drops every route at its
|
||
teardown. QEMU adds and drops a route under the BQL before the callback
|
||
returns, so the device calls it holding no lock of its own: on the lane's
|
||
thread after the queues' table is let go, and in a reset after its rings
|
||
and table are; and no device function a host calls under the BQL waits
|
||
for a lane
|
||
(`the_host_s_lock_held_around_its_calls_while_a_route_waits_for_it_holds_up_nothing`). A route changes no order: the ring's records, its completions and
|
||
interrupts are the thread's, as for a doorbell the host takes in the write.
|
||
|
||
## Stage 3 guest stack (from the prior-art study)
|
||
|
||
How a Metal bundle plugs into macOS, in Apple's own terms (notes:
|
||
`stage3-apple-metal-iface.md`):
|
||
|
||
- **Discovery/load.** The bundle installs under `/Library/GPUBundles/`. Metal
|
||
does not scan that directory; it loads the bundle from two properties on the
|
||
accelerator service's registry entry — `MetalPluginName` (the path) and
|
||
`MetalPluginClassName` (the Obj-C class Metal instantiates as the
|
||
`MTLDevice`) — under `IOMatchCategory IOAccelerator`. So stage 3 needs a
|
||
guest **accelerator kext** that matches our PCI device and publishes those
|
||
two keys; the bundle ships beside it.
|
||
- **Trusted-bundle gate (with SIP on).** Before it loads a GPU bundle from
|
||
`/Library/GPUBundles`, Metal asks the system whether that path is trusted,
|
||
and the answer is yes only for a path carrying the particular SIP "rootless"
|
||
storage class the OS gives the bundles its own kext-staging writes there (or
|
||
for a path sealed on the system volume). A bundle merely copied onto the data
|
||
volume does not carry it, so with SIP on Metal declines to load it and
|
||
WindowServer, finding the accelerator registered, crashes and restarts in a
|
||
loop.
|
||
Our install kext (`guest/rgfxgate`, a Graft client) therefore writes the
|
||
bundle to the data volume and gives the whole tree that exact storage class
|
||
and the matching restricted flag from kernel context, below the file-system
|
||
MAC layer, so only our bundle's own paths are tagged and SIP is relaxed for
|
||
nothing. The unsigned bundle's executable still has to pass library
|
||
validation when WindowServer and the Metal helpers map it; the same kext
|
||
answers the library-validation, mmap and signature MAC checks for our bundle
|
||
by its code-directory hash, leaving every other binary's signing rules
|
||
untouched. The signature check, the wall that gates the other two, also
|
||
requires the executable's path to be under `/Library/GPUBundles`, so the
|
||
exemption follows the installed bundle and a byte-identical copy of it placed
|
||
elsewhere is not trusted — the same pinning the install writes carry. No
|
||
boot-args and no SIP relaxation are involved — the guest boots
|
||
with SIP fully enabled (measured on msi, x86-64 macOS 26.6.1: desktop
|
||
composites on our Metal device and Safari WebGL renders, `csrutil` enabled).
|
||
`/Library/GPUBundles` itself comes with every install: the data-volume
|
||
template on the sealed system volume holds it, already restricted and of
|
||
that storage class (measured: the x86-64 26.6.1 guest and a 27.0.1 host).
|
||
The install kext waits for the data volume to mount (`/Library/Preferences`
|
||
appears) and creates the container, with the same class, only where it is
|
||
missing.
|
||
- *Checklist (per supported OS).* The three load hooks and the three install
|
||
hooks are Graft routes of six XNU MAC dispatchers
|
||
(`_mac_file_check_library_validation`, `_mac_file_check_mmap`,
|
||
`_mac_vnode_check_signature`, `_mac_vnode_check_{create,open,truncate}`),
|
||
whose argument lists `RgfxGateHooks.cpp` hard-codes. Routing is by symbol,
|
||
not by raw bytes, so a moved patch site is not the risk; a changed
|
||
*prototype* is. RgfxGate has no kernel version range, so when a release
|
||
joins the test matrix, re-verify each of the six prototypes against that
|
||
release's kernel before shipping it, and confirm `_csfg_get_cdhash` and
|
||
`_csblob_get_cdhash` still resolve (a miss on either now logs loudly and
|
||
leaves the gate inert rather than bricking silently).
|
||
- **Bundle updates.** The marker beside the executable (below, "Registration
|
||
waits for the bundle") carries the kext's wire version, and the bundle is the
|
||
kext's own payload, so a newer kext whose executable or wire version differs
|
||
replaces the installed bundle. The replacement is atomic: the whole new tree
|
||
is built and tagged in a sibling staging directory (`NAME.bundle.new`), then
|
||
put in place with a single rename — an existing bundle is exchanged with it
|
||
(`VNOP_RENAMEX`, `VFS_RENAME_SWAP`) and the old tree, swapped aside, dropped;
|
||
where there is none the staged tree is moved in. A reader (WindowServer, a
|
||
Metal helper) therefore sees either the whole old bundle or the whole new
|
||
one, never a half-written one, so an upgrade that keeps the wire version
|
||
cannot leave a torn executable mid-boot (the "RgfxGate rewrite race"). The
|
||
container is never unlocked, so SIP is not widened around it even mid-upgrade.
|
||
A bundle that is byte-current but untagged — staged by a tool under relaxed
|
||
SIP and then first seen on a SIP-on boot — is detected and tagged in place
|
||
without a rewrite. The test is the bundle directory's storage class and
|
||
restricted flag together: a bundle copied into the restricted container is
|
||
given the flag but not the class, and the class is what Metal reads.
|
||
Userspace cannot remove the class even with SIP off, so only the kext writes
|
||
or clears it. A current, tagged bundle is left as it is, and the boot writes
|
||
nothing. The accelerator, in turn, registers only once RgfxGate has signalled
|
||
that its install pass has ended, so it never registers against a tree
|
||
mid-swap.
|
||
- **Device class.** The bundle's device subclasses Apple's private IOAccel
|
||
Metal base class and conforms to `<MTLDevice, MTLDeviceSPI>`; entry
|
||
`-initWithAcceleratorPort:` (may return `nil` to decline). The base fills the
|
||
limit tables (zero limits make CoreImage refuse), and the bundle implements
|
||
the whole `MTLDevice` object graph plus enough of the GL/OpenCL private
|
||
selectors. AIR arrives as `.metallib` through `newLibraryWith*`; the bundle
|
||
takes the AIR slice, asks the host for it by its content key
|
||
(`LIBRARY_LOOKUP`), and forwards the slice's bytes over the wire only where
|
||
the host holds none (`LIBRARY_CREATE`), which the host compiles.
|
||
- **Core Image's link.** Core Image makes its kernel libraries (file type 1,
|
||
whose kernels are extern functions of `functionType` 4, left out of
|
||
`functionNames`) through `newLibraryWith*`, takes each kernel and its own
|
||
helpers with the private `newExternFunctionWithName:`, and links them on the
|
||
CPU in Metal's base device class (`newLibraryWithImageFilterFunctionsSPI:…`,
|
||
which calls `newLibraryWithCIFilters:…` on the device). The link reads
|
||
Metal-internal library data from each function, which no function of ours
|
||
holds. So each library of ours keeps the bytes it was made from and makes, on
|
||
first use, a shadow: Metal's own library over them (the base class's
|
||
`newLibraryWithData:`), whose extern functions ours hold. The device's link
|
||
overrides hand Metal the shadows, and make the library Metal links (the bytes
|
||
it answers as `libraryDataContents`: one kernel, `ciKernelMain`) the device's
|
||
own through `newLibraryWithData:`, so the kernel's pipeline is made on the
|
||
host like any other (measured: macOS 27, and 26.6.1 in the guest;
|
||
`tools/ci_probe.m` renders through it).
|
||
- **Kernel family — the fork.** The prior art builds its accelerator on the
|
||
older `IOAcceleratorFamily2`, but our guest already runs the **ported
|
||
IOGPUFamily stack**, and IOAccel2 cannot start in a kernel where IOGPU runs.
|
||
So our accelerator aligns with **IOGPU** (owner's correction, 2026-10-30),
|
||
and the IOAccel2 user-client selectors do not transfer; our accelerator
|
||
exposes the alloc/map + submit + completion-stamp + IOSurface-sharing
|
||
boundary over our own protocol, not Apple's IOGPU user client.
|
||
- **Compositor/present.** WindowServer composites into IOSurfaces and presents
|
||
through a display pipe. Our ported IOGPU stack already runs Metal compositing
|
||
through its IOSurface display pipe (type-4 adapter), and we already have the
|
||
framebuffer/display kext; stage 3's display work is making the accelerator and
|
||
the framebuffer agree on the IOSurface scanout (flip, else copy).
|
||
- **Load policy.** Loading our unsigned bundle into WindowServer, the Metal
|
||
compiler helpers and sandboxed apps is done with SIP and library validation
|
||
left on, by the install kext's two gates above — the rootless storage-class
|
||
tag that makes the path trusted, and the code-directory-hash answer to the
|
||
library-validation and signature MAC checks. It is a concern of our kext, not
|
||
a boot-args relaxation.
|
||
|
||
## Stage 3 accelerator kext (scaffold)
|
||
|
||
`RgfxAccelerator` (`guest/kext/src/RgfxAccelerator.{hpp,cpp}`) is a second
|
||
IOService in the one kext, on the same PCI device as the Stage-2 framebuffer:
|
||
the framebuffer matches in category `IOFramebuffer`, the accelerator in category
|
||
`IOAccelerator`, both children of the one `IOPCIDevice`. Its `Info.plist`
|
||
personality holds only what matches the provider and names the driver, as
|
||
Graft takes a personality's other keys for the provider's matching ("Graft",
|
||
above). The accelerator sets its driver keys on its registry entry at the
|
||
start of `start`, before it registers (`setDriverKeys`), of the same types on
|
||
x86-64 and arm64: `MetalPluginName = reims-graphics` (the bundle
|
||
`/Library/GPUBundles/reims-graphics.bundle`) and `MetalPluginClassName
|
||
= RgfxMetalDevice`, which is how Metal (`IOServiceMatching("IOAccelerator")`)
|
||
finds and loads the bundle; `IOGLBundleName` (OpenGL, below);
|
||
`IODVDBundleName`, `IOVARendererID` and `IOGVACodec` (hardware video,
|
||
Decided 16); `AcceleratorProperties`, whose
|
||
`IOAccelDisplayPipeCapabilities` say the display pipe and its transactions
|
||
are supported; and `DisplayPortCount` 1. The accelerator maps BAR 0 for the doorbell and
|
||
holds BAR 2 to map each process's part of it in; it touches no pixels and no
|
||
control ring (the framebuffer owns those).
|
||
|
||
**OpenGL.** The accelerator also carries `IOGLBundleName =
|
||
AppleMetalOpenGLRenderer`, the GL renderer OpenGL loads for an accelerator: the
|
||
system's own GL over Metal, which finds its Metal device among
|
||
`MTLCopyAllDevices()` by the accelerator's registry entry ID (the device's
|
||
`registryID`). The renderer hands the device each GL shader as GL IR and each
|
||
variant as plugin data; Metal's own devices lower the two to AIR in their
|
||
compiler service. The bundle has none, so it lowers a variant in the app's
|
||
process, through the GL code generator the system ships beside the renderer
|
||
(`libGLDPlugin<V>.dylib`, called in place), into a .metallib of one function,
|
||
and makes an ordinary library of it (`guest/bundle/src/RgfxGLFunction.h`,
|
||
`RgfxGLLowering.hpp`): the host compiles GL shaders as it compiles any
|
||
library. A tessellated draw's vertex and control shaders are one kernel the
|
||
renderer makes a compute pipeline of under a stage input descriptor; the
|
||
kernel takes the draw's vertices as a patch control point input, which Metal
|
||
compiles in no kernel, so its pipeline is made of the kernel made one without
|
||
the input under that descriptor (`RgfxGLStageInKernel`), whose fetch reads what
|
||
Metal's `[[stage_in]]` fetch reads (bit for bit on the M3 Max, every
|
||
attribute format: `guest/bundle/tests/gl_tests.mm`). Measured on an x86 Mac (macOS 26.7.1, the Intel UHD 630): the
|
||
renderer runs on a non-Apple Metal device, and the bundle's lowering draws what
|
||
Metal's own does (`guest/bundle/tools/gl_probe.m`, `gl_inject.mm`). An
|
||
on-screen context's drawable is the IOGPU base's, over the kext's GL drawable
|
||
and window surface ("A GL window", below). OpenCL lists a GPU for every
|
||
accelerator that names an `IOGLBundleName`, and runs its kernels through the
|
||
same renderer.
|
||
|
||
**The renderer's settings.** The renderer picks a set of per-vendor settings
|
||
for a device when it makes its first context, read from its code (macOS
|
||
27.0.1, both slices): by the device's `vendorName`, "AMD" or "ATI" (AMD's
|
||
settings only where the device's class is the one of AMD's older Metal driver,
|
||
NVIDIA's otherwise), "NVIDIA" or "Intel"; for any other vendor by
|
||
`supportsFamily:` of Apple7, then Apple5; and it ends the process on a device
|
||
that answers none ("Unknown GPU!!"). Among what the settings decide:
|
||
- Whether the renderer sends GL's provoking vertex to the encoder
|
||
(`setProvokingVertexMode:`, 1 for GL's default last-vertex convention, 0
|
||
for the first). The Apple and AMD settings do. Under NVIDIA's and Intel's,
|
||
the renderer reorders each triangle's vertices itself, and a line keeps its
|
||
first vertex's flat value: gl_cases' provoking-line-last fails. Measured:
|
||
the M3 Max sends 1 and 0 to its encoder and passes every provoking case
|
||
(macOS 27.0.1, job m3-max-26643); the Intel 630's Metal GL renderer fails
|
||
that one case (macOS 26.7.1, commit 17b468160's measurement). The AMD
|
||
Radeon Pro 5300M's Metal device is not of the older driver's class, so it
|
||
takes NVIDIA's settings (its class read on macOS 26.7.1, job m3-max-26630).
|
||
- Whether GL's `GL_POINT` polygon mode goes to the encoder as
|
||
`setTriangleFillMode:` 2, which no public `MTLTriangleFillMode` names. The
|
||
Apple and Intel settings send it. Measured with a triangle at mode 2: the M3
|
||
Max and the Intel 630 draw its three vertices' pixels, the 5300M fills it
|
||
(jobs m3-max-26654 and m3-max-26650). The Vulkan platform holds no such
|
||
mode and dies on it (read from its code: `metal_value` of the runtime's
|
||
`TriangleFillMode`), which only a guest given Intel's settings reaches.
|
||
- Whether texture uploads and mipmap generation take the renderer's other
|
||
path (`gldModifyTexSubImage`, `gldGenerateTexMipmaps`): the Apple settings
|
||
alone.
|
||
- Whether it keeps `supportsForceSeamsOnCubemaps`' answer: the Apple settings
|
||
alone; every other vendor's drop it.
|
||
- The largest point the renderer draws (`updateRenderPointSettings` clamps
|
||
GL's point size to it): 16 pixels under Apple5's settings, 64 under every
|
||
other set.
|
||
|
||
Apple7's settings and Apple5's are the same but for that point size: both
|
||
answer each of the settings above as Apple's (read from the five settings
|
||
records and the code that copies them, macOS 27.0.1's arm64e slice). So the
|
||
narrowest answers that give a device the Apple settings are a `vendorName`
|
||
that holds none of "AMD", "ATI", "NVIDIA" and "Intel" and `supportsFamily:`
|
||
of Apple5; "Apple" without Apple5 or Apple7 ends every process that makes a
|
||
GL context.
|
||
|
||
Our device answers `vendorName` with the host GPU's vendor, and "AMD" for any
|
||
other (`rgfxVendorNameOf` in `guest/bundle/src/RgfxCaps.hpp`), and no Apple
|
||
family short of Apple7 (`crates/reims-vgpu/src/graphics/device_info.rs`). So
|
||
its guests get NVIDIA's settings, or Intel's on an Intel host, as the x86
|
||
Macs' GPUs measured above would. An arm64 guest on the M3 Max gets NVIDIA's
|
||
settings where the M3 Max's own renderer takes the Apple ones: GL lines under
|
||
the last-vertex convention take their first vertex's flat value there (arm64
|
||
macOS 27.0.1, a64walk2's walks), whatever the bundle and the host do with the
|
||
setter. The device does not answer Apple5 for it: Apple4's and Apple5's rows
|
||
hold tile shaders, imageblocks and nonsquare tile dispatch, which the device
|
||
does not carry (no tile pipeline crosses the wire) and the Vulkan platform's
|
||
runtime refuses on every device (its family audit, measured on an Iris Xe at
|
||
metal2vulkan c796a88d6a: 26 rows of Apple5's block it, these four among
|
||
them). And the Apple settings send `GL_POINT` polygon mode as
|
||
`setTriangleFillMode:` 2, on which the platform dies. Apple5 without Apple7
|
||
is also no Mac's answer, which is why the device claims no Apple family short
|
||
of Apple7 (`FIRST_MAC_APPLE_FAMILY` in `device_info.rs`).
|
||
|
||
**Registration waits for the bundle.** Where the accelerator is registered and
|
||
its bundle is not on disk, every WindowServer aborts in CoreDisplay as it
|
||
brings the display up, and launchd starts another until it gives up: the
|
||
screen stays black. That is every boot before the bundle is installed: the
|
||
install boot, Recovery, the installer. Where no accelerator is registered,
|
||
WindowServer composites in software on the framebuffer. Measured on msi
|
||
(x86-64 macOS 26, no bundle): an accelerator that does not start leaves
|
||
WindowServer up with a console session and the desktop drawn, the framebuffer
|
||
still naming it in `IOAccelTypes`; a registered accelerator still aborts it,
|
||
the framebuffer naming it or not. So the accelerator starts as before but
|
||
registers only once its bundle is on disk:
|
||
- From its start, a thread call checks every 100 ms for the bundle's
|
||
executable, `/Library/GPUBundles/NAME.bundle/Contents/MacOS/NAME`, NAME its
|
||
`MetalPluginName`, and for the marker of the kext's wire version beside it,
|
||
`Contents/Resources/wire-version-N` ("The wire's version"): nothing before
|
||
the root file system is mounted (`vfs_rootvnode`), then a `vnode_lookup` of
|
||
each. An executable without that marker is a bundle of another version, and
|
||
counts as none. `/Library/GPUBundles` is on the
|
||
data volume, which launchd mounts early in boot, well before it starts
|
||
WindowServer, so with the bundle installed the accelerator is registered
|
||
before WindowServer looks for a GPU.
|
||
- WindowServer's first server connection to the framebuffer settles it.
|
||
`ReimsGraphics::newUserClient` has the accelerator check once more before
|
||
IOFramebuffer makes the connection, with no lock held, and register at once
|
||
where the bundle is there; WindowServer opens that connection before any of
|
||
the accelerator's user clients. No check runs after it.
|
||
- **RgfxGate's install pass comes first.** Where RgfxGate installs the
|
||
bundle, nothing on disk counts while its install pass is under way: an update
|
||
that keeps the wire version would find the old bundle and its marker before
|
||
the pass drops the marker and rewrites the files, and WindowServer could
|
||
then load a bundle mid-rewrite. RgfxGate publishes `RgfxGateInstallDone` on
|
||
IOResources, false from the pass's start and true once the pass has ended,
|
||
on every path (the installer and Recovery, a data volume that never mounts,
|
||
a failed write). The check looks again while it is false. The settling
|
||
connection waits up to 5 s for it, and leaves the accelerator unregistered
|
||
for the boot where the pass is still under way. Without RgfxGate there is no
|
||
property, and the check counts what it finds.
|
||
- **The framebuffer comes first too.** A process's context reaches the
|
||
device only through the framebuffer's rings, so the check registers the
|
||
accelerator only once the framebuffer has started as well: its start has
|
||
taken the device and brought its rings up (`ReimsGraphics::hasStarted`).
|
||
The check says once in the kernel log when the bundle waits for it. A
|
||
context opens only while the framebuffer is started (`kIOReturnNotReady`
|
||
otherwise, taking no units), and a close that finds none started gives its
|
||
context's units back at once: none has carried a message of the context
|
||
since the device's last reset (a failed start's or the stop's), which
|
||
dropped every context's objects ("Reset"). Seen on arm64 27.0.1, where an
|
||
accelerator registered after ReimsGraphics' start failed had its contexts'
|
||
messages and closes refused, and their units kept from use for good.
|
||
- **A bundle installed later takes effect at the next boot**: a running
|
||
WindowServer never sees a GPU appear under it. The guest's install puts the
|
||
bundle in place and reboots.
|
||
- Unregistered, the accelerator refuses every user client
|
||
(`kIOReturnNotReady`): a task can still reach it by the framebuffer's
|
||
`IOAccelTypes` path.
|
||
- Neither the check nor its wait runs on the kext's start or the
|
||
framebuffer's console path.
|
||
|
||
`RgfxAcceleratorUserClient`
|
||
(`guest/kext/src/RgfxAcceleratorUserClient.{hpp,cpp}`) is **our own** transport,
|
||
not Apple's IOGPU user-client ABI: the context's window ("Processes map only
|
||
their own"), where the bundle's `RgfxRegion` / `RgfxRingWriter` write into real
|
||
device memory, the device info (selector 0x10b), and
|
||
`externalMethod(kRgfxAccelMethodDoorbell)`, which writes a ring id to
|
||
`RGFX_REG_DOORBELL`. These ids/selectors are defined in `RgfxUserClientABI.hpp`,
|
||
which the kext and the bundle both include;
|
||
the bundle's wire handshake opens them with `IOServiceOpen` /
|
||
`IOConnectCallStructMethod` / `IOConnectCallScalarMethod`.
|
||
|
||
**The accelerator's user client: its numbers.** This table gives out every
|
||
number of the 'RGFX' user client and of a shared event's port. A new selector
|
||
takes the next free number here first, among the numbers below. A selector or
|
||
a flag that a kext may lack gets a kext feature bit, which the kext sets in
|
||
the second word `Features` answers once it carries it out, and the bundle uses
|
||
it only where that word holds the bit. The numbers and the kext feature bits
|
||
are in `guest/kext/src/RgfxUserClientABI.hpp`, which the kext and the bundle
|
||
include.
|
||
|
||
Every number is one that every WebKit web-content sandbox lets its process
|
||
call on an IOAccelerator connection, on every release from 11 to 26. WebKit's
|
||
web-content profile (`com.apple.WebProcess.sb`, its
|
||
`IOAcceleratorMessageFilter`) lists numbers on macOS 12 alone and refuses any
|
||
other there before the kext sees it: from Safari 15.1 to 17.6 (WebKit 612.2 to
|
||
7618.3) every list holds 0-13, 15-18, 22-24, 28-31, 40, 42, 48, 256-265, 267,
|
||
268 and 512, the numbers Apple's own drivers take (17.6's adds 41, 43, 46, 49,
|
||
266, 269 and 513). On macOS 11 and from 13 on it lists none, and allows every
|
||
number; its asynchronous methods (0 and 47 on 12) and traps the bundle makes
|
||
none of. Read from WebKit's source at each release branch, and on 11.7.11,
|
||
12.7.6 and 13.7.8 guests. `user_client_words_test` holds the set, checks every
|
||
number here against it, and checks that every `IOConnectCall*Method` in the
|
||
bundle's sources names one of these selectors.
|
||
|
||
The numbers move only with the set: the bundle and the kext ship together. A
|
||
move takes the next selector map number (`kRgfxSelectorMap`), which `Features`
|
||
answers third, at a number it keeps in every map. A bundle whose map is not
|
||
the kext's has no Metal device in its process, logged, rather than call a
|
||
number that means another call there. Map 0, before the number, had
|
||
`SurfaceBlockRelease` at 0x10a, `SurfaceRetire` at 0x10d, `PagesBlock` at
|
||
0x10e, `Features` at 0x10f, `TakeAnswers` at 0x112 and the port's selectors at
|
||
0x113 and 0x114, outside the numbers above: macOS 12's web content process
|
||
could not call `Features`, took 64-id chunks where the kext granted 16, and had
|
||
its textures past each chunk's first 16 ids refused (`BadResourceId`). A kext of map 1 gives
|
||
none of those numbers a meaning, so a bundle of map 0 is refused at each.
|
||
|
||
Map 1:
|
||
|
||
| number | name | kext feature bit | what |
|
||
|---|---|---|---|
|
||
| 0 | `Doorbell` | | writes a ring's id to `DOORBELL` |
|
||
| 1 | `Consumed` | 1 << 3 `ConsumedDoorbell` | reserved: a completion ring's room doorbell (`CONSUMED`) |
|
||
| 2 | | | given to none: the IOGPU base's device-info call on its own client type, so a trace names one call per number |
|
||
| 3 | `Features` | | the device's feature word, the kext's and the selector map; at 3 in every map |
|
||
| 4 | `PagesBlock` | 1 << 0 `PagesBlock` | a block of the runs of a process's own pages, wired, for its no-copy buffers |
|
||
| 5 | `SubmitBatch` | 1 << 1 `SubmitBatch`, 1 << 11 `QueuePublish` (three inputs and a second output: a queue's publish after them) | a process's destroys, and its creates and writes no one waits for that name no block, onto ring 0 in one call ("Destroys and creates no one waits for go together"), and with three inputs a command buffer's publish on its queue's ring after them ("A commit behind held messages is one call") |
|
||
| 6 | `WakeCompletions` | 1 << 2 `WakeCompletions` | reserved: wakes the client's completion waiters |
|
||
| 7 | `TakeAnswers` | 1 << 4 `DeferredAnswers` | hands a process its held pipeline-create answers ("Known pipeline creates") |
|
||
| 8 | `SurfaceBlockRelease` | | lets go of a shared block |
|
||
| 9 | `SurfaceRetire` | | a queue's writes up to a seqno retire |
|
||
| 10 | `Export`, on a shared event's port ('RGSE') | 1 << 6 `SharedEvents` | names the caller's shared event for other processes ("Shared events across processes") |
|
||
| 11 | `Import`, on a shared event's port ('RGSE') | 1 << 6 `SharedEvents` | makes the caller's new shared event of the one the port names |
|
||
| 12 | `PagesChunked` | 1 << 8 `PagesChunked` | a block of the runs of 64 KiB chunks of the kext's own, mapped into the process, for its slabs |
|
||
| 13 | `SurfaceSeeds` | 1 << 10 `SurfaceSeeds` | an IOSurface's lock and unlock seeds, for a copy synced while a CPU held the surface locked for writing |
|
||
| 0x100 | `OpenContext` | 1 << 5 `ContextSpan` (its sixth output) | the context and its window; five outputs, or six with its GPU addresses' span |
|
||
| 0x101 | `Alloc` | 1 << 7 `WriteCombined` (its third input) | a region block; 2 inputs, or 3 with the byte its write-combined part starts at |
|
||
| 0x102 | `Free` | | frees a block |
|
||
| 0x103 | `QueueCreate` | | a command queue; 6 inputs, or 7 with the flags wanted |
|
||
| 0x104 | `QueueDestroy` | | closes a queue |
|
||
| 0x105 | `Submit` | 1 << 4 `DeferredAnswers` (its deferred flag), 1 << 9 `SharedPipelines` (its shared flag: the pipeline key in four more inputs, and a second output) | one lifecycle message onto ring 0 |
|
||
| 0x106 | `ResourceIds` | | a chunk of texture resource ids, and with a second output its size |
|
||
| 0x107 | `WaitCompletions` | | waits for the client's completions |
|
||
| 0x108 | `SurfaceScanout` | | the scanout an IOAccel surface is drawn into |
|
||
| 0x109 | `SurfaceBlock` | | an IOSurface plane's shared block |
|
||
| 0x10b | `DeviceInfo` | | the device info and video caps |
|
||
| 0x10c | `SurfaceWrites` | | the surfaces a command buffer writes |
|
||
|
||
A shared event's port is a connection of a second type, 'RGSE' (0x52475345), on
|
||
the accelerator, which the bundle opens for each event it hands out: 10 and 11
|
||
are its own selectors, numbered apart from the accelerator's own so that a call
|
||
on a connection of another kind finds none of that number there.
|
||
|
||
The kext sets 1 << 0 `PagesBlock`, 1 << 1 `SubmitBatch`, 1 << 4 `DeferredAnswers`, 1 << 5 `ContextSpan`, 1 << 6 `SharedEvents`, 1 << 7 `WriteCombined`, 1 << 8 `PagesChunked`, 1 << 9 `SharedPipelines`, 1 << 10 `SurfaceSeeds` and 1 << 11 `QueuePublish`, `SurfaceSeeds` only where the release's IOSurface exports its unlock seed; no other bit yet.
|
||
|
||
**A GL window: the drawable (type 7) and the window surface (type 0x20).**
|
||
These are IOGPU's types, not ours. The bundle leaves `newGLDrawable` to its
|
||
IOGPU base, which opens type 7. The kext serves both types
|
||
(`guest/kext/src/RgfxGLUserClients.{hpp,cpp}`, with the rules in
|
||
`RgfxGLSurfaces.hpp` and their native test). Measured on a macOS 26.6.1
|
||
guest, for window-backed and layer-backed `NSOpenGLView`s alike:
|
||
- the app opens type 7, then its `SLSBindSurface` opens type 0x20 for the
|
||
window's surface: `SetIDMode`(id, 0x4024), then `SetShape` with the
|
||
view's size;
|
||
- the drawable's set surface (selector 1) names that id. Its lookups
|
||
(selector 5) of indexes 0 and 1 get two IOSurfaces, which the kext makes
|
||
in the app's task;
|
||
- the app draws into those IOSurfaces through the bundle, and WindowServer
|
||
composites the window from them (screen dumps show the frames). It opens
|
||
no user client of the accelerator for the window.
|
||
|
||
The rules are IOGPU's, read from IOGPUFamily's x86_64 code in the 26.7.1
|
||
KDK: the mode and shape checks, the request bits a drawable's mode gives,
|
||
the eleven buffer slots and their formats, and when buffers are made again.
|
||
Not served, each answering `kIOReturnUnsupported`:
|
||
- surface modes of IOGPU's shared buffers (0x700000);
|
||
- a drawable's scaled sources and shared events;
|
||
- every surface method but `SetIDMode` and `SetShape`.
|
||
|
||
- **Boot-gated — base class / kernel family (notes UNKNOWN #1).** The scaffold
|
||
subclasses `IOAccelerator`, the base the macOS SDK and KDK expose (the IOGPU
|
||
kernel family — `IOGPU`, its device/queue classes and its submission/
|
||
allocation user-client ABI — is Apple-private and in neither, so it cannot be
|
||
subclassed or linked off the guest). On the guest the base very likely becomes
|
||
the IOGPU family class per Decided 15; the Metal discovery keys, the PCI match
|
||
and our region-map + doorbell user client are expected to carry over. The
|
||
IOGPU user-client ABI is deliberately not invented here.
|
||
|
||
## Stage 3 device control
|
||
|
||
`RgfxDeviceControl` (`guest/kext/src/RgfxDeviceControl.{hpp,cpp}`) is the
|
||
third service on the PCI device, in a category of its own: an
|
||
`AppleGraphicsDeviceControl` (AGDC), the System-KC library class
|
||
AppleGraphicsControl.kext's plug-in defines. WindowServer's IOPresentment
|
||
builds a display pipe only for a framebuffer whose PCI device has an AGDC,
|
||
and AppleGPUWrangler pairs the AGDC with the GPU's record and sets its
|
||
attribute 3 to its `InitFlags`. Without one, CoreDisplay logs "Unable to find
|
||
display pipe for IOFB service" and WindowServer picks the software
|
||
compositor. The kext names the library in `OSBundleLibraries`; the loader
|
||
binds its base-class sites as it binds IOGraphicsFamily's.
|
||
`AppleGraphicsDeviceControl.hpp` is our declaration of the base class, from
|
||
the names and vtable order the KDK's x86_64 binary exports. The control
|
||
answers attributes 1 (its description), 3 (what it makes), 0x301 (the
|
||
wrangler's GPU index), 0x921 and 0x980 (which IOPresentment reads before it
|
||
builds a pipe), and refuses the rest.
|
||
|
||
## Open
|
||
|
||
- **Stage 3 bundle placement — RESOLVED:** the bundle sits in
|
||
`/Library/GPUBundles` and our accelerator's registry entry carries
|
||
`MetalPluginName`/`MetalPluginClassName`. The library-validation boot state
|
||
is settled: the install kext gives the bundle the rootless storage class so
|
||
Metal trusts its path, and answers the library-validation, mmap and signature
|
||
MAC checks for it by its code-directory hash, so WindowServer composites on
|
||
our Metal device and Safari WebGL renders with SIP fully on and no boot-args
|
||
("Trusted-bundle gate", above; measured on msi, x86-64 macOS 26.6.1). Open:
|
||
the exact IOGPU accelerator user-client ABI our kext exposes, settled by a
|
||
guest experiment.
|
||
- **IOSurface details:** whether the device-cache sync runs on every CPU
|
||
access path and on unlock (window buffers wrapped no-copy are written
|
||
without a lock); whether IOGPU accepts a device cache that holds a host
|
||
handle and no guest pages; and which surfaces the guest CPU touches
|
||
(probe on the Apple lane: KVM's dirty bits per mapped surface).
|
||
- **The PCI vendor:device ID** the device ships with (owner call).
|
||
- **Owner calls**, each with a recommendation once the evidence is in:
|
||
- whether host device addresses are ever exposed.
|