diff --git a/LICENSE b/LICENSE
index ee95746..068d00f 100644
--- a/LICENSE
+++ b/LICENSE
@@ -75,5 +75,5 @@ The **licensor** is the individual or entity offering these terms, and the **sof
Required Notice: Copyright 2026 TUNA-NOPE (https://github.com/TUNA-NOPE)
Scope: these terms cover macbox's own files. The files in patches/ modify Reims vGPU and metal2vulkan,
-which are GPL-2.0-or-later OR LGPL-3.0-or-later, and are offered under those same terms
-(patches/README.md). The projects macbox builds and downloads keep their own licenses (CREDITS.md).
+which are GPL-2.0-or-later OR LGPL-3.0-or-later, and are offered under those same terms; those in
+patches/qemu modify QEMU and are GPL-2.0-or-later (patches/README.md). The projects macbox builds and downloads keep their own licenses (CREDITS.md).
diff --git a/README.md b/README.md
index 5770fe5..1bce720 100644
--- a/README.md
+++ b/README.md
@@ -9,11 +9,10 @@ own. One command, `macbox`, sets it up and runs it.
**Website and guides:** [tuna-nope.github.io/macbox](https://tuna-nope.github.io/macbox/): macOS, Xcode and
the iOS Simulator on Linux, Expo apps, the GPU path, and AI coding agents with T3 Code.
-
+
-macOS 26 Tahoe's desktop in macbox on an Intel iGPU, with two of its iOS 26.5 Simulators in front
-(their screens composited onto the desktop's screenshot): GlassBench, a Liquid Glass load, and
-Safari.
+macOS 26 Tahoe's desktop in macbox on an Intel iGPU, captured as it is: Simulator.app with an
+iPhone 17 Pro on iOS 26.5 running Nimbus, a weather app, beside its website in Safari.
```
Linux host (KVM + a Vulkan GPU + Docker)
@@ -28,8 +27,8 @@ Linux host (KVM + a Vulkan GPU + Docker)
- **macOS draws on your GPU.** [Reims vGPU](https://github.com/steelbrain/reims-vgpu) gives QEMU
Apple's paravirtual GPU, and macOS's own driver talks to it, so Metal works with no guest
driver. [metal2vulkan](https://github.com/steelbrain/metal2vulkan) runs Metal's work on Vulkan.
- macbox builds both, with patches that roughly doubled the iOS Simulator's frame rate on the
- GPU it was measured on (see [Performance](#performance)).
+ macbox builds both, with patches that took a 3x iOS Simulator from 17 to 50 fps on the GPU it
+ was measured on, and to 70 with the experimental Coherent switch (see [Performance](#performance)).
- **The screen** opens in a window on your Linux desktop, or in a browser tab (Selkies: H.264 on
the GPU, its bitrate following the link). Agents can see it and click and type into it
(`macbox screenshot`, `click`, `type`), so an agent can drive the macOS installer too.
@@ -91,19 +90,32 @@ floating glass toolbar, counted at the simulator's own screen (frames per second
-
+
-| | Reims 2ce3209, as upstream shipped it on 2026-10-26 | macbox build |
-|---|---|---|
-| iOS Simulator 1x (402x874), glass | 53.5 | **95.8 / 92.5** |
-| iOS Simulator 2x (804x1748), glass | 33.5 | **67.8 / 60.5** |
-| iOS Simulator 3x (1206x2622, an iPhone's pixels), glass | 17.2 | **38.5 / 39.5** |
-| Safari at 3x, a page with a blurred floating bar | n/a | 66.4 / 64.2 |
-| macOS desktop, Genie minimize at 3440x1440 (frames per animation) | ~12 | 19.5 |
-
-The GPU is the limit: a 3x simulator keeps this iGPU 96 to 98% busy. On a faster GPU every number
-moves up. [docs/performance.md](docs/performance.md) has what the patches do, the method, what
+| iOS Simulator at 3x (1206x2622, an iPhone's pixels), glass | fps |
+|---|---|
+| Reims 2ce3209, as upstream shipped it on 2026-10-26 | 17.2 |
+| macbox, 2026-10-28: rendering guest-RAM textures in place | 38.5 / 39.5 |
+| **macbox build now** (cohwl, 2026-11-05) | **50.6** (p95 21 ms) |
+| macbox build with `MACBOX_COHERENT=on` (experimental) | **70.0** (p95 18 ms) |
+
+| | Reims 2ce3209 | macbox, 2026-10-28 | macbox now, Coherent on |
+|---|---|---|---|
+| iOS Simulator 1x (402x874), glass | 53.5 | 95.8 / 92.5 | not measured yet |
+| iOS Simulator 2x (804x1748), glass | 33.5 | 67.8 / 60.5 | not measured yet |
+| macOS desktop, dragging a window (presents/s) | | 105 (Coherent off) | 130 |
+| macOS desktop, Safari scrolling (presents/s) | | 75–79 (Coherent off) | 110 |
+| macOS desktop, Genie minimize at 3440x1440 (frames per animation) | ~12 | 19.5 | 29.5 / 30.5 |
+
+Coherent keeps the GPU's image of the simulator's and the desktop's surfaces ahead of guest RAM,
+and syncs a page only when the guest's CPU touches it: the copies that were left are gone, and the
+GPU drops from 97% to 70% busy at 3x. It is off by default for now: it hung the GPU once on its
+first day of daily use (the next boot came up without it, as designed), and the cause isn't
+settled. [docs/performance.md](docs/performance.md#coherent-experimental-off-by-default) has the details.
+
+The GPU is the limit: without Coherent a 3x simulator keeps this iGPU 96 to 98% busy. On a faster
+GPU every number moves up. [docs/performance.md](docs/performance.md) has what the patches do, the method, what
didn't help, and the known limits (an idle macOS display gets no vblank from its driver, so an
animation starts about 0.1 s late: [reims-vgpu#141](https://github.com/steelbrain/reims-vgpu/issues/141)).
@@ -177,7 +189,7 @@ issue or PR. See [CONTRIBUTING.md](CONTRIBUTING.md) for a few simple guidelines.
| [docs/agents.md](docs/agents.md) | the agent tools, the skill, the instructions to give agents |
| [docs/troubleshooting.md](docs/troubleshooting.md) | when something doesn't work |
| [guest/README.md](guest/README.md) | what runs inside macOS |
-| [patches/README.md](patches/README.md) | the patch series on Reims vGPU and metal2vulkan |
+| [patches/README.md](patches/README.md) | the patch series on Reims vGPU, metal2vulkan and QEMU |
| [site/](site/README.md) | the website's source: the guides at https://tuna-nope.github.io/macbox/guides/ |
## Credits
@@ -194,7 +206,8 @@ purpose: yourself, a hobby, research, teaching, a school, a charity, a public bo
needs the author's permission**: open an issue to ask.
The patches in `patches/` modify Reims vGPU and metal2vulkan, and stay under those projects' terms,
-`GPL-2.0-or-later OR LGPL-3.0-or-later` ([patches/README.md](patches/README.md)). Everything macbox
+`GPL-2.0-or-later OR LGPL-3.0-or-later`; those in `patches/qemu` modify QEMU and are
+`GPL-2.0-or-later` ([patches/README.md](patches/README.md)). Everything macbox
builds or downloads keeps its own license ([CREDITS.md](CREDITS.md)).
## Disclaimer
diff --git a/container/build-reims.sh b/container/build-reims.sh
index d85fe91..430ebe0 100755
--- a/container/build-reims.sh
+++ b/container/build-reims.sh
@@ -70,6 +70,8 @@ else
git -C "$R" submodule update -q --init vendor/qemu
git -C "$R/vendor/qemu" fetch -q origin "$QEMU_REF" 2>/dev/null || true
git -C "$R/vendor/qemu" checkout -q -f --detach "$QEMU_REF"
+ git -C "$R/vendor/qemu" am --abort >/dev/null 2>&1 || true
+ apply "$R/vendor/qemu" "$MACBOX_REPO/patches/qemu"
SUFFIX=-macbox
fi
COMMIT=$(git -C "$R" rev-parse --short HEAD)
diff --git a/docs/architecture.md b/docs/architecture.md
index eb6ac3f..d4730ac 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -40,7 +40,7 @@ It runs with seccomp and AppArmor unconfined, because passt needs a user namespa
`container/build-reims.sh` (run by `macbox build` in a throwaway container) checks out Reims vGPU,
QEMU and metal2vulkan at the commits [versions.env](../versions.env) pins, applies
-[patches/](../patches/README.md), points Reims's Cargo at the patched metal2vulkan, and builds
+[patches/](../patches/README.md) to each of the three, points Reims's Cargo at the patched metal2vulkan, and builds
`reims-ctl`, the library (`cargo xtask dist --platform vulkan`) and QEMU on it. Each QEMU goes into
`~/.local/share/reims-ctl/qemu/--macbox` and `qemu/current` moves to it. A running VM
keeps its QEMU until it restarts, and old builds stay for going back
@@ -59,8 +59,10 @@ and the QEMU command line; `reims-ctl command mac` (inside the container) prints
- `--video-acceleration=false` (no VideoToolbox/M2 scaler devices), a borderless window,
`REIMS_VGPU_STATS=1` (a line of frame statistics a second in `logs/qemu.log`).
- Before each start: `WAYLAND_DISPLAY` (sway's, or the host's), and the GPU tuning:
- `M2V_LIVE=$MACBOX_HOME/run/live.conf` with `host_rt_in_place=1`, and `M2V_ARL_FACTS` on an
- Arrow Lake GPU ([performance.md](performance.md)).
+ `M2V_LIVE=$MACBOX_HOME/run/live.conf` with `host_rt_in_place=1`,
+ `REIMS_VGPU_PRIVATE_SKIP_PAGE_UP=1`, `M2V_ARL_FACTS` on an Arrow Lake GPU, and with
+ `MACBOX_COHERENT=on` the census and Coherent switches ([performance.md](performance.md)).
+ The disk's options in `extra_args` are written again, so a changed `MACBOX_DISK_CACHE` applies.
The system disk starts on SATA, because macOS's installer may not find a disk on NVMe, and moves to
NVMe with `macbox disk nvme` once macOS is installed.
@@ -130,7 +132,7 @@ versions.env the pinned upstream commits
docker/ the image (Dockerfile, sway.conf)
container/ scripts that run inside the container: build-reims.sh, display-up.sh, stream-up.sh
lib/vmctl.py screenshots, mouse and keyboard through QMP
-patches/ the series on Reims vGPU and metal2vulkan
+patches/ the series on Reims vGPU, metal2vulkan and QEMU
guest/ everything copied into macOS (macbox-guest and its tools)
sims/ the agent tools on the host (mac-sim, sim-fps, android-sim) and their user units
skills/ the simulators, phone-builds and macbox (setup) skills
diff --git a/docs/images/fps-dark.svg b/docs/images/fps-dark.svg
index 4285b6a..db56b45 100644
--- a/docs/images/fps-dark.svg
+++ b/docs/images/fps-dark.svg
@@ -1,39 +1,34 @@
-
-
-iOS Simulator frame rate, Liquid Glass benchmark
+
+
+iOS Simulator at 3x (1206×2622), Liquid Glass benchmark
Frames per second on an Intel Arrow Lake iGPU (Core Ultra 7 265). Higher is better.
-
-Reims vGPU as upstream shipped it (2ce3209)
-
-macbox build
-
-0
-
-20
-
-40
-
-60
-
-80
-
-100
-frames per second
-
-60 fps
-1x · 402×874
-
-53.5
-
-94.2
-2x · 804×1748
-
-33.5
-
-64.2
-3x · 1206×2622
-
-17.2
-
-39.0
+
+0
+
+20
+
+40
+
+60
+
+80
+frames per second
+
+60 fps
+Upstream
+Reims 2ce3209, 2026-10-26
+
+17.2
+macbox, Oct 28
+in place rendering
+
+39.0
+macbox now
+cohwl, the default
+
+50.6
++ Coherent
+experimental, off by default
+
+70.0
diff --git a/docs/images/fps-light.svg b/docs/images/fps-light.svg
index f8706e6..6eeefda 100644
--- a/docs/images/fps-light.svg
+++ b/docs/images/fps-light.svg
@@ -1,39 +1,34 @@
-
-
-iOS Simulator frame rate, Liquid Glass benchmark
+
+
+iOS Simulator at 3x (1206×2622), Liquid Glass benchmark
Frames per second on an Intel Arrow Lake iGPU (Core Ultra 7 265). Higher is better.
-
-Reims vGPU as upstream shipped it (2ce3209)
-
-macbox build
-
-0
-
-20
-
-40
-
-60
-
-80
-
-100
-frames per second
-
-60 fps
-1x · 402×874
-
-53.5
-
-94.2
-2x · 804×1748
-
-33.5
-
-64.2
-3x · 1206×2622
-
-17.2
-
-39.0
+
+0
+
+20
+
+40
+
+60
+
+80
+frames per second
+
+60 fps
+Upstream
+Reims 2ce3209, 2026-10-26
+
+17.2
+macbox, Oct 28
+in place rendering
+
+39.0
+macbox now
+cohwl, the default
+
+50.6
++ Coherent
+experimental, off by default
+
+70.0
diff --git a/docs/images/hero.jpg b/docs/images/hero.jpg
index 18ee240..7dc4f60 100644
Binary files a/docs/images/hero.jpg and b/docs/images/hero.jpg differ
diff --git a/docs/images/make-chart.py b/docs/images/make-chart.py
index 7b37caf..51ea13a 100644
--- a/docs/images/make-chart.py
+++ b/docs/images/make-chart.py
@@ -1,59 +1,54 @@
#!/usr/bin/env python3
"""Writes fps-light.svg and fps-dark.svg, the README's frame-rate chart (docs/performance.md's numbers).
-Colors: the validated categorical slots 1 and 2 (blue, orange) for each mode's surface."""
+Colors: the validated categorical slots 1 and 2 (blue, orange) for each mode's surface; the
+experimental bar is the macbox blue at reduced opacity, and its label says so."""
import os
-ROWS = [ # label, before (Reims 2ce3209), after (macbox build, mean of two runs)
- ("1x · 402×874", 53.5, (95.8 + 92.5) / 2),
- ("2x · 804×1748", 33.5, (67.8 + 60.5) / 2),
- ("3x · 1206×2622", 17.2, (38.5 + 39.5) / 2),
+ROWS = [ # label, sublabel, fps (3x, mean of the valid rounds), kind
+ ("Upstream", "Reims 2ce3209, 2026-10-26", 17.2, "before"),
+ ("macbox, Oct 28", "in place rendering", (38.5 + 39.5) / 2, "after"),
+ ("macbox now", "cohwl, the default", 50.6, "after"),
+ ("+ Coherent", "experimental, off by default", 70.0, "exp"),
]
MODES = {
"light": dict(surface="#fcfcfb", text="#0b0b0b", text2="#52514e", grid="#e4e3df", before="#eb6834", after="#2a78d6"),
"dark": dict(surface="#1a1a19", text="#f0efec", text2="#c3c2b7", grid="#3a3a37", before="#d95926", after="#3987e5"),
}
-W, H = 900, 370
-X0, X1, MAX = 190, 840, 100 # bar area and its scale (fps)
-BAR, GAP, GROUP = 22, 2, 30 # bar thickness, gap between a group's bars, space between groups
-TOP = 112
+W, H = 900, 320
+X0, X1, MAX = 230, 840, 80 # bar area and its scale (fps)
+BAR, GAP = 30, 16 # bar thickness, space between bars
+TOP = 96
FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif"
def x(v): return X0 + (X1 - X0) * v / MAX
-def bar(y, v, color): # 4 px rounded at the data end only, square at the baseline
+def bar(y, v, color, opacity=1.0): # 4 px rounded at the data end only, square at the baseline
w, r = x(v) - X0, 4
return (f' ')
+ f'Q{X0 + w},{y + BAR} {X0 + w - r},{y + BAR} H{X0} Z" fill="{color}" fill-opacity="{opacity}"/>')
def svg(m):
c = MODES[m]
o = [f'',
f' ',
- f'iOS Simulator frame rate, Liquid Glass benchmark ',
+ f'iOS Simulator at 3x (1206×2622), Liquid Glass benchmark ',
f'Frames per second on an Intel Arrow Lake iGPU (Core Ultra 7 265). Higher is better. ']
- # legend
- lx = 24
- for name, col in (("Reims vGPU as upstream shipped it (2ce3209)", c["before"]), ("macbox build", c["after"])):
- o.append(f' ')
- o.append(f'{name} ')
- lx += 18 + len(name) * 7.0 + 26
- # grid and axis
- bottom = TOP + len(ROWS) * (2 * BAR + GAP) + (len(ROWS) - 1) * GROUP
- for v in (0, 20, 40, 60, 80, 100):
+ bottom = TOP + len(ROWS) * BAR + (len(ROWS) - 1) * GAP
+ for v in (0, 20, 40, 60, 80):
o.append(f' ')
o.append(f'{v} ')
o.append(f'frames per second ')
# the 60 fps target
o.append(f' ')
- o.append(f'60 fps ')
+ o.append(f'60 fps ')
y = TOP
- for label, before, after in ROWS:
- o.append(f'{label} ')
- for v, col in ((before, c["before"]), (after, c["after"])):
- o.append(bar(y, v, col))
- o.append(f'{v:.1f} ')
- y += BAR + GAP
- y += GROUP - GAP
+ for label, sub, v, kind in ROWS:
+ col = c["before"] if kind == "before" else c["after"]
+ o.append(f'{label} ')
+ o.append(f'{sub} ')
+ o.append(bar(y, v, col, 0.55 if kind == "exp" else 1.0))
+ o.append(f'{v:.1f} ')
+ y += BAR + GAP
o.append(" ")
return "\n".join(o) + "\n"
diff --git a/docs/performance.md b/docs/performance.md
index 9755f02..73b902c 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -10,29 +10,60 @@ work the translation adds per frame (Metal → Vulkan).
Before macbox's patches, most of that added work was copies: macOS's framebuffer and the
simulator's display surface lie in guest RAM, and metal2vulkan copied each into a GPU image and back
around every render pass. Those shadow copies were 51% of all GPU time with the simulator and 67%
-with the desktop. Patch 0004 renders those textures in place ([patches/README.md](../patches/README.md)).
+with the desktop. Patch 0004 renders those textures in place, and Coherent (patches 0009 onwards,
+with QEMU's census) removes most of the copies left ([patches/README.md](../patches/README.md)).
## Measurements
The reference host: Intel Core Ultra 7 265 (Arrow Lake iGPU), 128 GB DDR5 at 4400 MT/s, Mesa 26.2.4,
a NVMe disk; the VM had 8 vCPUs and 12 GB, macOS 26.7.1, iOS 26.5, one simulator booted at a time.
-iOS Simulator, GlassBench (a table scrolling under Liquid Glass bars and a floating glass toolbar),
-frames per second counted at the simulator's own screen, no encoding; two runs each:
+### iOS Simulator at 3x, step by step
-| | Reims 2ce3209 (2026-10-26) | Reims 7198fe6 | 7198fe6 + facts + colour writes | **macbox build** |
+GlassBench (a table scrolling under Liquid Glass bars and a floating glass toolbar) on an iPhone 17
+Pro at 3x (1206x2622), frames per second counted at the simulator's own screen:
+
+| Build | fps | GPU |
+|---|---|---|
+| Reims 2ce3209 as upstream shipped it (2026-10-26) | 17.2 | |
+| macbox, 2026-10-28 (in place rendering, 0004) | 38.5 / 39.5 | 25.0 ms/frame |
+| macbox cohwl, Coherent off (flat32) | **50.6** (p95 21.4 ms, p99 25.8 ms) | 97% busy |
+| macbox cohwl, `MACBOX_COHERENT=on` | **70.0** (p95 17.7 ms, p99 22.0 ms); 63–66 in a later run | 70% busy |
+
+The last two rows are one A/B in one window on 2026-11-05: fresh headless boots, a quiet gate
+before each round (guest background CPU and `mediaanalysisd` low), means of the valid rounds. The
+first two are earlier days, on the same host but not in the same window. With Coherent, QEMU's CPU
+use rises by about 1.6 cores (333% to 491%): the GPU waits less, the CPU traps more.
+
+flat32 also has an A/B of its own against the build before it: 41.6 → 48–50 fps at 3x.
+
+### Earlier measurements, the 2026-10-28 build
+
+| | Reims 2ce3209 (2026-10-26) | Reims 7198fe6 | 7198fe6 + facts + colour writes | macbox, 2026-10-28 |
|---|---|---|---|---|
-| 1x (402x874) | 53.5 | 57.0 | 63.7 | **95.8 / 92.5** (GPU 8.0 ms/frame) |
-| 2x (804x1748) | 33.5 | 37.6 | 38.8 | **67.8 / 60.5** (14.1–14.9 ms) |
-| 3x (1206x2622) | 17.2 | 19.2 | 21.9 | **38.5 / 39.5** (25.0 ms) |
-| Safari at 3x, blurred floating bar | n/a | 39.5 | 44.5 | **66.4 / 64.2** |
+| 1x (402x874) | 53.5 | 57.0 | 63.7 | 95.8 / 92.5 (GPU 8.0 ms/frame) |
+| 2x (804x1748) | 33.5 | 37.6 | 38.8 | 67.8 / 60.5 (14.1–14.9 ms) |
+| 3x (1206x2622) | 17.2 | 19.2 | 21.9 | 38.5 / 39.5 (25.0 ms) |
+| Safari at 3x, blurred floating bar | n/a | 39.5 | 44.5 | 66.4 / 64.2 |
+
+1x and 2x haven't been measured again on cohwl.
+
+### The macOS desktop
-macOS desktop at 3440x1440, a Genie minimize of a 2400x1100 window: about 12 frames per
-animation before, 19.5 with the macbox build (a 0.5 s animation at 60 Hz would be 30).
+| 3440x1440 desktop | Coherent off | Coherent on |
+|---|---|---|
+| dragging a 600x400 window (presents per second) | 105–107 | 129–130 |
+| Safari scrolling a local page (presents per second) | 75–79 | 110 |
+| Genie minimize of a 2400x1100 window (frames per animation; ~12 upstream) | 19.5 (the 10-28 build) | 29.5 / 30.5 |
-Disk, inside macOS, emulated SATA → NVMe: a warm 4K random read 0.54 → 0.36 ms, an app's process
-start 250–430 → 140–250 ms. Moving the VM's disk from a ZFS SATA SSD to an XFS NVMe halved the cold
-read latency again.
+The first two rows are the same A/B as above. The Genie number with Coherent comes from a smoke
+check, not a matched A/B. A 0.5 s animation at 60 Hz would be 30 frames.
+
+### Disk
+
+Inside macOS, emulated SATA → NVMe: a warm 4K random read 0.54 → 0.36 ms, an app's process start
+250–430 → 140–250 ms. Moving the VM's disk from a ZFS SATA SSD to an XFS NVMe halved the cold read
+latency again.
How they were measured:
- `simfps` (in `guest/bench`, if present) counts the frames a simulator's screen produces through
@@ -55,7 +86,9 @@ How they were measured:
blur work. It changes nothing inside the simulator.
- **CPU pinning** (`MACBOX_CPUSET`): on a hybrid CPU, keep QEMU on the performance cores.
- **The disk:** NVMe in the VM (`macbox disk nvme`) and the VM's disk on an SSD or NVMe on the host.
- `MACBOX_DISK_CACHE=unsafe` is faster still, at the risk spelled out in the config.
+ The default `MACBOX_DISK_CACHE=none`: with `writeback`, macOS's NVMe driver panicked under heavy
+ swap (an `IONVMeController` flush timeout), and `none` passed the same 11 GB test.
+ `unsafe` is faster still, at the risk spelled out in the config.
## GPU tuning switches
@@ -65,6 +98,7 @@ With the macbox build (`MACBOX_GPU_TUNING=auto`, the default), `macbox up` sets:
|---|---|
| `M2V_LIVE=$MACBOX_HOME/run/live.conf` | metal2vulkan's live switches (patch 0003). The file holds `host_rt_in_place=1` |
| `M2V_ARL_FACTS=<11 facts>` | only on an Arrow Lake GPU (PCI ids 7d67, 7dd1, 7d41, 7d51, 7d45) |
+| `REIMS_VGPU_PRIVATE_SKIP_PAGE_UP=1` | skips a new Private texture's first page-up (Reims patch 0013) |
`host_rt_in_place` is read when a texture is made: change it in `live.conf`, then remake the
surfaces (change the resolution, or restart the VM). `MACBOX_GPU_TUNING=off` turns all of it off.
@@ -73,6 +107,26 @@ On another GPU, in place rendering still runs its device check per memory kind a
the check fails; it has only been measured on Arrow Lake. Measure your own GPU before and after:
the facts list is specific to Arrow Lake and is never set elsewhere.
+### Coherent (experimental, off by default)
+
+`MACBOX_COHERENT=on` in the config, then `macbox down && macbox up`. macbox then also sets
+`REIMS_VGPU_CENSUS=$MACBOX_HOME/run/coherent`, `REIMS_VGPU_COHERENT=1` and a report a minute, and
+adds `surface_lazy=1`, `surface_lazy_scoped=1` and `surface_coherent=1` to `live.conf`.
+`MACBOX_COHERENT=off` removes them all again.
+
+It is off by default because it isn't settled yet:
+- **One GPU hang with it on.** On 2026-11-05, the day it went into daily use, i915
+ reset the GPU's render engine and QEMU stopped. The guard did its job: the next boot came up without
+ coherent pages. A later hang with Coherent off, on a newer development build, has the same error
+ code, so the cause is open, not pinned on Coherent.
+- **A write-loss risk the counters flagged once,** during a test that killed Safari mid-frame
+ (`overwrite_risk` 1 in the census report), and that hasn't been reproduced or ruled out since.
+
+If a coherent run crashes, `$MACBOX_HOME/run/coherent/coherent.running` stays behind and every later
+start boots without coherent pages. `macbox coherent status` says so; `macbox coherent reset`
+(VM stopped) allows the next try. It needs a kernel with `UFFD_USER_MODE_ONLY` (Linux 5.11 or
+later), which works with `vm.unprivileged_userfaultfd=0`.
+
## Tried, no gain
| | Result |
@@ -85,6 +139,14 @@ the facts list is specific to Arrow Lake and is never set elsewhere.
| 2 MiB hugepages or transparent hugepages for guest RAM | impossible: Reims maps guest RAM in 16 KiB views |
| another vCPU model (`kvm-pv-unhalt`, no IBRS) | within noise |
| QEMU's VNC | 2 to 3 frames a second: it reads every frame back from the GPU |
+| `surface_lazy` without trapping, or presenting every surface | a stale desktop |
+| keeping paged textures' buffers (`REIMS_VGPU_PAGED_BUFFER_CACHE`) | no reuse in practice |
+| grouping submissions (`submit_grouped`) | 0.2 ms a frame or less |
+| a faster idle tick (`REIMS_VGPU_VBLANK_HZ` 240 vs 480) | no gain; macOS never enables the interrupt it re-raises |
+| udmabuf imports, pooled staging buffers | no gain |
+| a reaper for deleted textures | Safari 5–8 fps slower, and Genie breaks |
+| executing the FIFO from its own thread (fifoexec) | a GPU hang on its first day; rolled back |
+| merging adjacent page runs of a mapping | negligible: 49 merges in 629,632 pages of a real trace |
## Known limits
@@ -92,7 +154,7 @@ the facts list is specific to Arrow Lake and is never set elsewhere.
sends no vblank while nothing is presenting, so the first frame of an animation waits a median
114 ms for display timing (8 ms when something already animates).
[steelbrain/reims-vgpu#141](https://github.com/steelbrain/reims-vgpu/issues/141).
-- **3x is GPU-bound** at about 35 to 40 fps on this iGPU in heavy Liquid Glass scenes.
+- **3x is GPU-bound** at about 50 fps on this iGPU in heavy Liquid Glass scenes (70 with Coherent).
- **x86-64 macOS ends with macOS 26.** iOS 27 simulators are arm64 only.
- **Recording** uses `simctl io recordVideo`, H.264 in software in the VM: about 50 fps with one
simulator animating, 18 each with three. `sim-fps` counts what the simulator wrote, and it writes
diff --git a/docs/setup.md b/docs/setup.md
index 355069f..5949bf0 100644
--- a/docs/setup.md
+++ b/docs/setup.md
@@ -37,7 +37,8 @@ node), makes an SSH key `~/.ssh/macbox_ed25519`, and adds a `Host macbox` block
| `MACBOX_RESOLUTION`, `MACBOX_REFRESH` | 1920x1080, 60 | macOS's screen; more pixels cost GPU time |
| `MACBOX_CPUSET` | empty | pin QEMU to some cores, e.g. a hybrid CPU's performance cores (`0-7`) |
| `MACBOX_BUILD_CPUSET` | empty | cores for `macbox build`, e.g. the efficiency cores |
-| `MACBOX_DISK_CACHE` | writeback | `unsafe` is faster, but a crash of the host itself can corrupt the VM's disk |
+| `MACBOX_DISK_CACHE` | none | `writeback` panicked macOS's NVMe driver under heavy swap; `unsafe` is faster, but a crash of the host itself can corrupt the VM's disk. Applies at the next `macbox up` |
+| `MACBOX_COHERENT` | off | `on`: Coherent, zero-copy surfaces, about 40% faster at 3x and experimental ([performance.md](performance.md#coherent-experimental-off-by-default)) |
| `MACBOX_HOME` | ~/.local/share/macbox | everything macbox keeps |
Then:
diff --git a/llms.txt b/llms.txt
index e5b922f..e80aabe 100644
--- a/llms.txt
+++ b/llms.txt
@@ -2,7 +2,7 @@
> Run macOS, Xcode and the real iOS Simulator on a Linux host, in Docker, with GPU acceleration (Metal through Reims vGPU and metal2vulkan on the host's Vulkan GPU), for AI coding agents such as Claude Code, Codex and T3 Code. No Mac and no cloud service: one CLI, `macbox`, builds and runs it, and `mac-sim` gives each agent checkout its own iOS Simulator to build, run, tap, screenshot, record and measure at 60 fps.
-License: PolyForm Noncommercial 1.0.0 for macbox's own code (noncommercial use; commercial use needs permission); the patches stay GPL-2.0-or-later OR LGPL-3.0-or-later.
+License: PolyForm Noncommercial 1.0.0 for macbox's own code (noncommercial use; commercial use needs permission); the patches stay GPL-2.0-or-later OR LGPL-3.0-or-later (GPL-2.0-or-later for the QEMU ones).
Requirements: an x86-64 Linux host with KVM, AVX2, an Intel or AMD GPU with a Mesa Vulkan driver, 16 GB RAM or more, about 150 GB of SSD, and Docker. It runs macOS 26 Tahoe, Xcode 26 and iOS 26 simulators, which is the ceiling on x86-64. Apple's license allows macOS only on Apple hardware.
@@ -33,7 +33,7 @@ publishing on their behalf.
## How it works
- [Architecture](https://github.com/TUNA-NOPE/macbox/blob/main/docs/architecture.md): the container, QEMU and Reims vGPU, the display stream, the network, the guest, the simulator pool
-- [Performance](https://github.com/TUNA-NOPE/macbox/blob/main/docs/performance.md): the metal2vulkan patches, measurements, tuning, known limits
+- [Performance](https://github.com/TUNA-NOPE/macbox/blob/main/docs/performance.md): the patches (in place rendering, flat32, experimental Coherent), measurements, tuning, known limits
- [Patches](https://github.com/TUNA-NOPE/macbox/blob/main/patches/README.md)
- [Troubleshooting](https://github.com/TUNA-NOPE/macbox/blob/main/docs/troubleshooting.md)
- [Credits](https://github.com/TUNA-NOPE/macbox/blob/main/CREDITS.md)
diff --git a/macbox b/macbox
index 6a767fa..1f5bfc0 100755
--- a/macbox
+++ b/macbox
@@ -14,7 +14,8 @@ eval "$_env"
: "${MACBOX_SSH_HOST:=macbox}" "${MACBOX_SSH_PORT:=2226}" "${MACBOX_SCREEN_PORT:=6081}"
: "${MACBOX_GUEST_USER:=dev}" "${MACBOX_CPUS:=8}" "${MACBOX_MEMORY:=12G}" "${MACBOX_DISK_SIZE:=160G}"
: "${MACBOX_RESOLUTION:=1920x1080}" "${MACBOX_REFRESH:=60}" "${MACBOX_CPUSET:=}"
-: "${MACBOX_RENDER_NODE:=/dev/dri/renderD128}" "${MACBOX_DISK_CACHE:=writeback}" "${MACBOX_GPU_TUNING:=auto}"
+: "${MACBOX_RENDER_NODE:=/dev/dri/renderD128}" "${MACBOX_DISK_CACHE:=none}" "${MACBOX_GPU_TUNING:=auto}"
+: "${MACBOX_COHERENT:=off}"
: "${MACBOX_SIM_PREFIX:=macbox}" "${MACBOX_POOL:=full slim-1 slim-2 sharp small}"
: "${MACBOX_T3_HOST_ID:=$MACBOX_SSH_HOST}" "${MACBOX_T3_SETTINGS:=$HOME/.t3/userdata/settings.json}"
DOCKER="${MACBOX_DOCKER:-docker}"
@@ -95,13 +96,27 @@ tuning_on() {
esac
}
apply_tuning() { # before each start
+ local live="$RUN/live.conf"
if tuning_on; then
- [ -s "$RUN/live.conf" ] || printf '# metal2vulkan live switches (patches/metal2vulkan), re-read every second\nhost_rt_in_place=1\n' >"$RUN/live.conf"
- local env=(--env "M2V_LIVE=$RUN/live.conf")
+ [ -s "$live" ] || printf '# metal2vulkan live switches (patches/metal2vulkan), re-read every second\nhost_rt_in_place=1\n' >"$live"
+ sed -i '/^surface_\(lazy\|lazy_scoped\|coherent\)=/d' "$live"
+ local env=(--env "M2V_LIVE=$live" --env REIMS_VGPU_PRIVATE_SKIP_PAGE_UP=1)
if gpu_is_arl; then env+=(--env "M2V_ARL_FACTS=$ARL_FACTS"); else env+=(--env "M2V_ARL_FACTS="); fi
+ if [ "$MACBOX_COHERENT" = on ]; then
+ # QEMU's census traps the guest CPU's touches of the surfaces metal2vulkan renders in place.
+ # A run that doesn't end well leaves coherent/coherent.running, and every later start then
+ # boots without Coherent until that file is removed (macbox coherent reset).
+ mkdir -p "$RUN/coherent"
+ printf 'surface_lazy=1\nsurface_lazy_scoped=1\nsurface_coherent=1\n' >>"$live"
+ env+=(--env "REIMS_VGPU_CENSUS=$RUN/coherent" --env REIMS_VGPU_COHERENT=1 --env REIMS_VGPU_CENSUS_FLUSH_MS=60000)
+ else
+ env+=(--env REIMS_VGPU_CENSUS= --env REIMS_VGPU_COHERENT= --env REIMS_VGPU_CENSUS_FLUSH_MS=)
+ fi
ctl set "$MACBOX_VM" "${env[@]}" >/dev/null
else
- ctl set "$MACBOX_VM" --env "M2V_LIVE=" --env "M2V_ARL_FACTS=" >/dev/null
+ [ -f "$live" ] && sed -i '/^surface_\(lazy\|lazy_scoped\|coherent\)=/d' "$live"
+ ctl set "$MACBOX_VM" --env "M2V_LIVE=" --env "M2V_ARL_FACTS=" --env REIMS_VGPU_PRIVATE_SKIP_PAGE_UP= \
+ --env REIMS_VGPU_CENSUS= --env REIMS_VGPU_COHERENT= --env REIMS_VGPU_CENSUS_FLUSH_MS= >/dev/null
fi
}
@@ -149,10 +164,13 @@ MACBOX_CPUSET=$MACBOX_CPUSET
# Host CPUs for macbox build (taskset list, e.g. the efficiency cores); empty: all
MACBOX_BUILD_CPUSET=${MACBOX_BUILD_CPUSET:-}
MACBOX_RENDER_NODE=${node:-$MACBOX_RENDER_NODE}
-# writeback (safe) or unsafe (faster; a crash of the host itself can corrupt the VM's disk)
+# none (the default: macOS's NVMe driver panicked under heavy swap with writeback), writeback, or
+# unsafe (faster; a crash of the host itself can corrupt the VM's disk)
MACBOX_DISK_CACHE=$MACBOX_DISK_CACHE
# auto: macbox's metal2vulkan tuning with the macbox build; on; off
MACBOX_GPU_TUNING=$MACBOX_GPU_TUNING
+# on: Coherent, zero-copy IOSurfaces (docs/performance.md). Experimental: one GPU hang with it on
+MACBOX_COHERENT=$MACBOX_COHERENT
# iOS Simulator pool: names are " ( )"
MACBOX_SIM_PREFIX=$MACBOX_SIM_PREFIX
MACBOX_POOL="$MACBOX_POOL"
@@ -288,7 +306,7 @@ cmd_up() {
wd=$(in_c "$REPO/container/display-up.sh" | sed -n 's/^WAYLAND_DISPLAY=//p')
fi
if ! vm_running; then
- ctl set "$MACBOX_VM" --env "WAYLAND_DISPLAY=$wd" >/dev/null
+ ctl set "$MACBOX_VM" --env "WAYLAND_DISPLAY=$wd" --extra-args "$(qemu_extra)" >/dev/null
apply_tuning
ctl start "$MACBOX_VM"
fi
@@ -322,6 +340,7 @@ cmd_status() {
in_c test -S /tmp/host-wayland/wayland-0 && say " view: local (a window on the host's desktop)" ||
{ say " view: stream, http://127.0.0.1:$MACBOX_SCREEN_PORT/"; in_c "$REPO/container/stream-up.sh" status | sed 's/^/ /'; }
say " build: $(build_id)$(tuning_on && echo ', GPU tuning on' || echo ', GPU tuning off')"
+ say " coherent: $(coherent_state)"
say " screen: $(resolution)"
ssh_ok && say " ssh $MACBOX_SSH_HOST: ok" || say " ssh $MACBOX_SSH_HOST: no answer"
}
@@ -522,6 +541,25 @@ PY
esac
}
+coherent_state() {
+ if [ "$MACBOX_COHERENT" != on ] || ! tuning_on; then echo "off (MACBOX_COHERENT=on to try it)"
+ elif [ -e "$RUN/coherent/coherent.running" ] && ! vm_running; then
+ echo "on, but held off: the last coherent run did not end well (macbox coherent reset)"
+ else echo "on"; fi
+}
+cmd_coherent() { # Coherent's crash guard (docs/performance.md)
+ case "${1:-status}" in
+ status) say "coherent: $(coherent_state)"
+ [ -s "$RUN/coherent/coherent.running" ] && say " guard: $(cat "$RUN/coherent/coherent.running")"
+ grep -h "coherent pages\|census:" "$VMDIR/logs/qemu.log" 2>/dev/null | tail -3 | sed 's/^/ /' || true ;;
+ reset)
+ vm_running && die "the VM is running: macbox down first"
+ rm -f "$RUN/coherent/coherent.running"
+ say "the guard is cleared: the next macbox up tries Coherent again" ;;
+ *) die "usage: macbox coherent [status|reset]" ;;
+ esac
+}
+
cmd_backup() {
local name=${1:?usage: macbox backup } b="$MACBOX_HOME/backups/$1" disk
vm_running && die "the VM is running: macbox down first"
@@ -563,6 +601,7 @@ Day to day:
macbox ssh [command]
macbox screenshot [out.png] | click X Y [right|double] | move X Y | scroll X Y N
macbox type TEXT|- | key COMBO... | wait SECONDS [out.png]
+ macbox coherent [status|reset] Coherent's crash guard (MACBOX_COHERENT=on, experimental)
macbox backup
EOF
}
@@ -613,6 +652,7 @@ case "$sub" in
pool) ssh_ok || die "ssh $MACBOX_SSH_HOST doesn't answer"; guest "MACBOX_SIM_PREFIX=$(printf '%q' "$MACBOX_SIM_PREFIX") MACBOX_POOL=$(printf '%q' "$MACBOX_POOL") ~/.macbox/macbox-guest pool ${1:-create}" ;;
t3) cmd_t3 "$@" ;;
agents) cmd_agents "$@" ;;
+ coherent) cmd_coherent "$@" ;;
backup) cmd_backup "$@" ;;
help|-h|--help) cmd_help ;;
*) cmd_help >&2; exit 2 ;;
diff --git a/patches/README.md b/patches/README.md
index 086a036..efc2de2 100644
--- a/patches/README.md
+++ b/patches/README.md
@@ -3,42 +3,60 @@
`macbox build` applies these on top of the commits [versions.env](../versions.env) pins
(`container/build-reims.sh`). `macbox build --upstream` applies none of them.
-All of them were built, tested with metal2vulkan's GPU lanes and Reims's screenshots, and run day to
-day on an Intel Arrow Lake iGPU (Core Ultra 7 265, Mesa 26.2.4 ANV). They are not upstream.
+Together they are **cohwl**, the build that has run day to day since 2026-11-05 on an Intel Arrow
+Lake iGPU (Core Ultra 7 265, Mesa 26.2.4 ANV). Each series rebuilds that build's sources exactly:
+metal2vulkan 1502180e, QEMU 82cef5aac4, and Reims 1f87b16 without its local build wiring (the
+path of the metal2vulkan checkout, the `vendor/qemu` pointer). None of it is upstream yet.
-## metal2vulkan (on `development` at 0db5825a)
+Most of the new code sits behind a switch and does nothing until it is set. What macbox turns on
+is in [docs/performance.md](../docs/performance.md#gpu-tuning-switches).
-| Patch | What it does |
+## metal2vulkan (on `development` at 0db5825a), 34 patches
+
+| Patches | What they do |
|---|---|
| 0001 env-gated Arrow Lake-S facts | `M2V_ARL_FACTS=` makes this GPU a measured identity: metal2vulkan then uses the faster paths its tables allow for each named driver fact. The list `macbox` sets (only on an Arrow Lake GPU) was checked fact by fact with metal2vulkan's GPU lanes: no lane fails with it that doesn't fail without it. Unset, nothing changes. |
| 0002 the release's pixel format table without a device | an accessor the Reims port needed |
| 0003 live switches (`M2V_LIVE`) | `name=value` lines in a file, re-read at most once a second, override driver facts (`facts_off=`, `facts_on=`) and a few runtime choices without a restart. For A/B measurements in one boot. |
-| 0004 `host_rt_in_place` | **the big one.** A texture that lies over guest-RAM pages (the macOS desktop's framebuffer, the iOS Simulator's display surface) is rendered straight into those pages as a linear image, after a device check per memory kind, instead of being copied into a GPU image and back around every render pass. Those copies were 51% (simulator) and 67% (desktop) of all GPU time. Live switch `host_rt_in_place=1` (macbox writes it into `$MACBOX_HOME/run/live.conf`). |
+| 0004 `host_rt_in_place` | a texture that lies over guest-RAM pages (the macOS desktop's framebuffer, the iOS Simulator's display surface) is rendered straight into those pages as a linear image, after a device check per memory kind, instead of being copied into a GPU image and back around every render pass. Those copies were 51% (simulator) and 67% (desktop) of all GPU time. Live switch `host_rt_in_place=1`. |
| 0005 ordering two imports of the same pages | a full memory barrier between two imports of the same guest pages, and a remapped memory whose imports follow their address keeps them: fixes a stale read 0004 exposed |
+| 0006, 0007 pass timer | a diagnostic, off unless `M2V_PASS_TIMES` is set: GPU time per render pass and an image census |
+| 0008 `tile_stored_only`, `tile_narrow_barriers` | live switches for two tile-memory experiments; off |
+| 0009–0012 `surface_lazy` | a large surface's optimal image is kept beside its pages, and its bytes are brought up to date only when something reads them, instead of after every pass |
+| 0013–0024, 0027–0034 Coherent (`surface_coherent`) | trap-coherent surfaces: QEMU write-protects or poisons a surface's guest pages (patches/qemu), so the GPU's image can stay ahead of the pages and the guest CPU's first touch of a page syncs exactly that page. This removes the remaining copies between guest RAM and the GPU. The later patches fix ordering cases the lanes found: copies back and in around held batches, writes that reach a held batch past later command buffers, and counters for each fallback. |
+| 0025, 0026 flat32 | a flat dispatch whose grid fits counts in 32 bits (64 bits past 2^32 threads). The simulator's 1206x2622 masked-blit kernel went from 4.85 to 1.13 ms. Always on. |
-Measured on the simulator at 3x: 22.5 → 39 fps, GPU time per frame 44.4 → 24.9 ms; the desktop's
-Genie animation 12 → 19.5 frames. Lanes with 0004 on: 301 of 323 match Metal; of the 22 others, 17
-are ANV rounding a clear of a linear image by one code (0.1 → 0x19 where an optimal image gives
-0x1a), 2 assert the old shadow copies, 3 fail the same way without the patch.
-
-## Reims vGPU (on 7198fe6)
+## Reims vGPU (on 7198fe6), 25 patches
-| Patch | What it does |
+| Patches | What they do |
|---|---|
-| 0001, 0002 `REIMS_VGPU_NON_APPLE_GPU` | an experiment, off unless set: the guest sees an Intel/AMD Mac's GPU instead of an Apple GPU family (parts: `families,tile,imageblocks,rog,xr10`). No speed gain was measured, so macbox never sets it. **Never include `fbread`:** WindowServer's command buffers then fail and macOS resets the GPU. |
-| 0003 port to metal2vulkan development 0db5825a | Reims's Vulkan platform on metal2vulkan's newer runtime (72 commits after the one 7198fe6 names): 3x 20.3–21.8 → 22.5–23.0 fps before 0004. Upstream made the same move later (Reims c8ec271a). |
-| 0004 upstream f6b7e927, video acceleration off | upstream's own commit, cherry-picked: `reims-ctl set --video-acceleration=false` leaves out the VideoToolbox and M2 scaler devices. macbox sets it, so the VM's devices are the ones it was measured with. |
-
-## QEMU
-
-`vendor/qemu` at bd95509 (github.com/steelbrain/qemu-reims-vgpu), the commit these builds used.
+| 0001, 0002 `REIMS_VGPU_NON_APPLE_GPU` | an experiment, off unless set: the guest sees an Intel/AMD Mac's GPU instead of an Apple GPU family. No speed gain was measured, so macbox never sets it. **Never include `fbread`:** WindowServer's command buffers then fail and macOS resets the GPU. |
+| 0003 port to metal2vulkan development 0db5825a | Reims's Vulkan platform on metal2vulkan's newer runtime. Upstream made the same move later (Reims c8ec271a). |
+| 0004, 0005 `REIMS_VGPU_VBLANK`, `REIMS_VGPU_VBLANK_HZ` | re-raise an idle display's present interrupt once a refresh period; off. macOS turned out never to enable that interrupt bit, so macbox doesn't set it. |
+| 0006–0008, 0016, 0018, 0020, 0021, 0024 census | the touch census: how often the guest CPU touches large IOSurfaces, its report script, boot-test guests and a content check. Off unless `REIMS_VGPU_CENSUS` names a directory. |
+| 0009 the presented texture | tells metal2vulkan which texture the display presents (for `surface_lazy`) |
+| 0010 tick experiments | logs the guest's enabled interrupt bits |
+| 0011, 0014, 0019, 0022, 0023 Coherent hooks | the library's side of trap-coherent surfaces: tracks, syncs and host reads and writes, between metal2vulkan and QEMU's census |
+| 0012 `REIMS_VGPU_PAGED_BUFFER_CACHE` | keeps paged textures' buffers; off (no reuse was measured) |
+| 0013 `REIMS_VGPU_PRIVATE_SKIP_PAGE_UP` | skips a new Private texture's first page-up, which nothing can read; macbox sets it |
+| 0015, 0017 NVMe boot tests | coherent pages through NVMe DMA, in the census's boot tests |
+| 0025 upstream f6b7e927, video acceleration off | upstream's own commit, cherry-picked: `reims-ctl set --video-acceleration=false` leaves out the VideoToolbox and M2 scaler devices. macbox sets it, so the VM's devices are the ones it was measured with. |
+
+## QEMU (`vendor/qemu` at bd95509, github.com/steelbrain/qemu-reims-vgpu), 9 patches
+
+| Patches | What they do |
+|---|---|
+| 0001–0003, 0006–0009 the census | memslots move to a second mapping of guest RAM that only KVM uses, and userfaultfd markers there report the guest CPU's touches of tracked pages (`UFFD_USER_MODE_ONLY`: no capability or `/dev/userfaultfd` needed). QEMU's own loads, stores and DMA reach it too. Off unless `REIMS_VGPU_CENSUS` is set. |
+| 0004, 0005 coherent pages | with `REIMS_VGPU_COHERENT=1` the same markers serve metal2vulkan's trap-coherent surfaces. A run that doesn't end well leaves `coherent.running` in the census directory, and every later start boots without coherent pages until it's removed (`macbox coherent reset`), so a fault there costs one crash, not a crash loop. |
## Licenses
Reims vGPU and metal2vulkan are `GPL-2.0-or-later OR LGPL-3.0-or-later`; these patches are offered
-under the same terms. QEMU is GPL-2.0.
+under the same terms. QEMU and its patches are GPL-2.0-or-later.
## Sending them upstream
-0004 and 0005 of metal2vulkan are the ones worth offering, together with 0003, which they use for
-their switch. 0001 would need the facts moved into metal2vulkan's own tables for Arrow Lake.
+Upstream's `development` branches have moved on since these bases (submission, sync and memory
+tracking in metal2vulkan; a graphics device of Reims's own). The series are being rebased onto
+them before anything is offered. flat32 (0025, 0026) is the first candidate: it applies to current
+metal2vulkan and needs only a semantics version bump.
diff --git a/patches/metal2vulkan/0001-env-gated-Arrow-Lake-S-facts-and-deviati.patch b/patches/metal2vulkan/0001-env-gated-Arrow-Lake-S-facts-and-deviati.patch
index 0956cf7..833c50c 100644
--- a/patches/metal2vulkan/0001-env-gated-Arrow-Lake-S-facts-and-deviati.patch
+++ b/patches/metal2vulkan/0001-env-gated-Arrow-Lake-S-facts-and-deviati.patch
@@ -1,7 +1,7 @@
-From c7c4784cc0e261d58ddfb3f650f70401e8abc13b Mon Sep 17 00:00:00 2001
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: macbox
Date: Wed, 28 Oct 2026 15:48:23 +0000
-Subject: [PATCH 1/5] env-gated Arrow Lake-S facts and
+Subject: [PATCH 01/34] env-gated Arrow Lake-S facts and
deviations (M2V_ARL_FACTS)
---
@@ -16,13 +16,13 @@ index 26020bce..36e1d7a6 100644
/// `intel-irisxe-rplp-anv`).
pub(crate) const INTEL_IRIS_XE_RPL_P: u32 = 0xa7a0;
-+/// macbox: the `deviceID` of the Intel Graphics of Arrow Lake-S (Xe-LPG). Every fact and
++/// LOCAL (Atlas): the `deviceID` of the Intel Graphics of Arrow Lake-S (Xe-LPG). Every fact and
+/// deviation any Intel row names applies to it only while `M2V_ARL_FACTS` names it
+/// ([`arl_gate`]): a comma list of `DriverFact` and `DriverDeviation` names, or `all`. Unset,
+/// it takes none, as a GPU no row names.
+pub(crate) const INTEL_ARL_S: u32 = 0x7d67;
+
-+/// macbox: the device-specific facts measured on Raptor Lake's ANV that Arrow Lake-S may
++/// LOCAL (Atlas): the device-specific facts measured on Raptor Lake's ANV that Arrow Lake-S may
+/// take, each only as `M2V_ARL_FACTS` names it (the Intel rows of every vendor stay in `MEASURED`).
+const ARL_FACTS: &[DriverFact] = &[
+ DriverFact::RobustIndexFetchReadsZero,
@@ -39,7 +39,7 @@ index 26020bce..36e1d7a6 100644
+ DriverFact::InterlockOrdersDraws,
+];
+
-+/// macbox: the deviations measured on Raptor Lake's ANV that Arrow Lake-S may take, each
++/// LOCAL (Atlas): the deviations measured on Raptor Lake's ANV that Arrow Lake-S may take, each
+/// only as `M2V_ARL_FACTS` names it.
+const ARL_DEVIATIONS: &[DriverDeviation] = &[
+ DriverDeviation::MetalFloatDenormals,
@@ -48,13 +48,13 @@ index 26020bce..36e1d7a6 100644
+ DriverDeviation::MetalDepth16Stores,
+];
+
-+/// macbox: whether `M2V_ARL_FACTS` names `name` (a `Debug` name) or `all`.
++/// LOCAL (Atlas): whether `M2V_ARL_FACTS` names `name` (a `Debug` name) or `all`.
+pub(crate) fn arl_named(name: &str) -> bool {
+ let Ok(list) = std::env::var("M2V_ARL_FACTS") else { return false };
+ list.split(',').map(str::trim).any(|n| n == "all" || n == name)
+}
+
-+/// macbox: on Arrow Lake-S under ANV, `set` plus `extra`, kept only as `M2V_ARL_FACTS`
++/// LOCAL (Atlas): on Arrow Lake-S under ANV, `set` plus `extra`, kept only as `M2V_ARL_FACTS`
+/// names each; elsewhere `set` as it is.
+fn arl_gate(
+ description: &DeviceDescription,
diff --git a/patches/metal2vulkan/0002-read-the-release-s-pixel-format-table-wi.patch b/patches/metal2vulkan/0002-read-the-release-s-pixel-format-table-wi.patch
index 5ec7829..a8346dc 100644
--- a/patches/metal2vulkan/0002-read-the-release-s-pixel-format-table-wi.patch
+++ b/patches/metal2vulkan/0002-read-the-release-s-pixel-format-table-wi.patch
@@ -1,7 +1,7 @@
-From 0d31d29c8ceccc9bb17e4920ff543dbd112c62a5 Mon Sep 17 00:00:00 2001
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: macbox
Date: Wed, 28 Oct 2026 16:13:56 +0000
-Subject: [PATCH 2/5] read the release's pixel format table
+Subject: [PATCH 02/34] read the release's pixel format table
without a device
Reims answers whether Metal describes a pixel format, the format's name
diff --git a/patches/metal2vulkan/0003-live-experiment-switches-M2V_LIVE-driver.patch b/patches/metal2vulkan/0003-live-experiment-switches-M2V_LIVE-driver.patch
index 712f44f..a864082 100644
--- a/patches/metal2vulkan/0003-live-experiment-switches-M2V_LIVE-driver.patch
+++ b/patches/metal2vulkan/0003-live-experiment-switches-M2V_LIVE-driver.patch
@@ -1,7 +1,7 @@
-From 4d7bde28d0e2369d3a6c5f871ddaf84456bd5290 Mon Sep 17 00:00:00 2001
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: macbox
Date: Wed, 28 Oct 2026 17:00:38 +0000
-Subject: [PATCH 3/5] live experiment switches (M2V_LIVE):
+Subject: [PATCH 03/34] live experiment switches (M2V_LIVE):
driver facts and heap compression change without a restart
---
@@ -37,7 +37,7 @@ index fb683618..ec9acf03 100644
//! runtime announces `shader-resolve` (performance) for the extra pass (naming the copy where the
//! resolve reads one), and `unmeasured-resolve` (precision) at more than 4 samples.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::binding_view::{views_as, VkView};
use super::blit::TRANSFER;
use super::command_buffer::CommandBuffer;
@@ -58,7 +58,7 @@ index 78c7b052..dc2c7a37 100644
//! keeps with their room: the scheduler thread allocates nothing for it
//! (`runtime_lane::frame_costs`, `a_frame_s_commits_allocate_within_their_bound`).
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::submit::Submission;
use super::{submission_error, CommandBufferShared};
use crate::degradation::Degradation;
@@ -79,7 +79,7 @@ index 3b97ede6..a0fbce2a 100644
//! texels the device decodes otherwise than Metal where the device makes it (`texture.rs`,
//! `texture/shared.rs`, `texture/heap.rs`).
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::attachment_stand_in::{Cause, StandIn};
use super::color_resolve;
use super::device::{DebugMessage, Device, MessageKind, MessageSeverity};
@@ -109,7 +109,7 @@ index b749a897..184d2cdd 100644
//! device; a copy's descriptor set and framebuffer are its own, held by its command buffer until
//! it completes.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::binding_view::VkView;
use super::degradation::Degradation;
use super::device::{device_error, lock};
@@ -132,7 +132,7 @@ index 59062a3d..5c24c7e0 100644
//! image or backing that has it, which an image copy fills and empties at the same sample count
//! (`attachment_stand_in.rs`).
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::color_resolve;
use super::depth_stencil_scratch;
use super::device::lock;
@@ -153,7 +153,7 @@ index fd889f83..64dca27b 100644
//! did not fit); the device's dma-buf memories (`dma_buf_memories_live`) and its
//! imports of host pages by their pointer (`host_imports_live`) fall as imports are released.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::buffer::{FixedPages, HostImport, Imported, Pages, Shape};
use super::device::lock;
use super::dma_buf::{DmaBufRequest, DmaBufSource};
@@ -174,7 +174,7 @@ index f3b4901f..13e3c7b4 100644
//! The device's image limits for the result (`vkGetPhysicalDeviceImageFormatProperties2`) are
//! checked by [`check_image_limits`].
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::chroma_pairs::plan_pairs;
use super::framebuffer_fetch;
use super::memory::MemoryClass;
@@ -201,7 +201,7 @@ index 8cb8e6b7..27ef226b 100644
#![warn(missing_docs)]
mod address;
-+/// macbox: live experiment switches (`M2V_LIVE`).
++/// LOCAL (Atlas): live experiment switches (`M2V_LIVE`).
+pub mod live;
mod address_map;
mod address_pool;
@@ -212,7 +212,7 @@ index 00000000..cc6e810b
--- /dev/null
+++ b/crates/metal2vulkan-runtime/src/live.rs
@@ -0,0 +1,129 @@
-+//! macbox experiment switches that change while the process runs. `M2V_LIVE=`
++//! LOCAL (Atlas) experiment switches that change while the process runs. `M2V_LIVE=`
+//! names a file of `name=value` lines (`#` starts a comment); a switch asked re-reads the file
+//! at most once a second, when its modification time changed, so an A/B pair shares one boot.
+//! Unset, every switch answers its default and no file is read. A changed file is logged once
@@ -349,7 +349,7 @@ index 58767624..7f9458e6 100644
//! scratch past `max_buffer_length`, a dispatch past `maxComputeWorkGroupCount`) or the scratch's
//! memory runs out, nothing is recorded and the call is refused.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::binding_view::{views_as, VkView};
use super::blit::BlitCommandEncoder;
use super::error::Error;
@@ -369,7 +369,7 @@ index 851e8b7c..64a9932c 100644
//! [`residual_made`]: RenderVariant::residual_made
//! [`residual_drawn`]: RenderVariant::residual_drawn
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::{DrawPipeline, GraphicsState, RenderVariant};
use crate::degradation::BoundFormats;
use crate::pipeline::graphics::GraphicsKey;
@@ -388,7 +388,7 @@ index 24a90d82..ba3449ed 100644
//! draws at once runs once per group of them: the encoder records the first group's pass, and
//! as it ends each later group's, from its log, over a twin of the depth and stencil.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::address_map::{self, SamplerMaps};
use super::amplification::{Amplification, VertexAmplificationViewMapping};
use super::argument_table::{check_index, ArgumentTable};
@@ -418,7 +418,7 @@ index b39ec934..0f9afa2c 100644
//! reaches the rest through a heap or a sparse heap, which make one of it as the device does
//! (`metal::format::padded_words`).
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::capture::CapturedReach;
use crate::buffer_texture::Texels;
use crate::clear_reach::{DrawnTiles, PassReach};
@@ -439,7 +439,7 @@ index 210b283b..4eaf142d 100644
//! framebuffer limits is refused `Unsupported` (`Feature::RenderTargetSize`), naming the limit
//! (`framebuffer_fits`).
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::attachment_stand_in::{self, Cause, StandIn};
use super::binding_view::views_as;
use super::buffer::Buffer;
@@ -469,7 +469,7 @@ index c37092eb..26da60fe 100644
//! until it completes. A render pass is never changed once made, so one serves every encoder
//! and thread at once. The framebuffer is made per instance; its command buffer holds it.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::attachment_stand_in::Cause;
use super::attachmentless;
use super::binding_view::VkView;
@@ -501,7 +501,7 @@ index bd5918fb..e233cb0b 100644
//! - **Counted.** `WorkCounts::row_copies`, `row_copy_regions`, `row_copy_regions_most` and
//! `row_copies_dispatched`.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::owned_kernel::{OwnedBinds, OwnedKernel, OwnedModule, OwnedSet, OwnedSets};
use super::tracker::Access;
use super::Device;
@@ -522,7 +522,7 @@ index df3a2b2d..99b4df48 100644
//! storage buffer range or workgroup counts, a buffer whose `VkBuffer` went, or a set the device
//! does not make: each copies back as before, the exact form every device takes.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::image_plan::{compatible, ImageFacts, ImagePlan};
use super::owned_kernel::{OwnedBinds, OwnedKernel, OwnedModule, OwnedSet};
use super::Device;
@@ -552,7 +552,7 @@ index 85ab19f3..0eb14cb2 100644
//! in-process handle opens new textures over the same image.
//! - **Not yet:** blits of textures over buffers are refused `NotImplemented`.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::address::{ObjectsToken, RangeToken};
use super::address_map::AddressModeMap;
use super::attachment_stand_in::KeptBacking;
@@ -582,7 +582,7 @@ index 6f15f1b3..1e13281c 100644
//! answers `heap`, `heap_offset`, `make_aliasable` and `is_aliasable` through the buffer, which
//! is no resource of the program's (Metal's texture answers `buffer` nil).
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::first_move::FirstMove;
use super::heap_tiled::{
footprint_size, metal_compresses_layout, metal_heap_layout, modelled_size, own_heap_layout,
@@ -609,7 +609,7 @@ index 6f15f1b3..1e13281c 100644
}
let policy = self.compile_device().policy().heap_compression;
- if compressed && policy == HeapCompressionPolicy::Compressed {
-+ // macbox: the live switch `heap_compressed` overrides the policy for the heaps'
++ // LOCAL (Atlas): the live switch `heap_compressed` overrides the policy for the heaps'
+ // textures made after it changes (`live.rs`).
+ let take_compressed =
+ crate::live::on("heap_compressed", policy == HeapCompressionPolicy::Compressed);
@@ -643,7 +643,7 @@ index 7918bb7c..dec60427 100644
//! usage says. A texture reached through an argument buffer without `use_resource` registers
//! nothing, which Metal's contract does not allow.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use super::super::key_hash::KeyMap;
use super::super::resource::ResourceKey;
use super::super::tracker::{Access, Use, UseRange};
@@ -664,7 +664,7 @@ index afecfa6d..5fe2920c 100644
//! - **Counted.** Each fill counts as one of the two forms (`WorkCounts::fills_recorded` and
//! `fills_by_transfers`), so a run shows which its device took.
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use crate::Device;
use ash::vk;
use metal2vulkan::device::DriverFact;
diff --git a/patches/metal2vulkan/0004-live-switches-host_rt_in_place-and-shado.patch b/patches/metal2vulkan/0004-live-switches-host_rt_in_place-and-shado.patch
index a637fc3..881cb1a 100644
--- a/patches/metal2vulkan/0004-live-switches-host_rt_in_place-and-shado.patch
+++ b/patches/metal2vulkan/0004-live-switches-host_rt_in_place-and-shado.patch
@@ -1,7 +1,7 @@
-From 04698bfc53e104311bd091aef97e12a19460468a Mon Sep 17 00:00:00 2001
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: macbox
Date: Wed, 28 Oct 2026 18:23:46 +0000
-Subject: [PATCH 4/5] live switches host_rt_in_place and
+Subject: [PATCH 04/34] live switches host_rt_in_place and
shadow_compressed for textures over host pages
host_rt_in_place (default off): under HostPageTexturePolicy::InPlace, a
@@ -68,7 +68,7 @@ index 20fd6a1a..70a18c56 100644
/// Its check of the first move of an image over host pages, per class of pages, and its
/// verdicts (`in_place.rs`).
pub(crate) in_place: crate::in_place::InPlaceChecks,
-+ /// macbox: its check of rendering into an image in place over host pages, per class
++ /// LOCAL (Atlas): its check of rendering into an image in place over host pages, per class
+ /// of pages, and its verdicts (`host_rt.rs`).
+ pub(crate) host_rt: crate::in_place::InPlaceChecks,
/// How no-copy buffers import host memory, or why they are refused.
@@ -78,7 +78,7 @@ index 20fd6a1a..70a18c56 100644
textures,
shader_cache,
in_place: crate::in_place::InPlaceChecks::new(fail_in_place_check),
-+ // macbox: the render-target check (`host_rt.rs`).
++ // LOCAL (Atlas): the render-target check (`host_rt.rs`).
+ host_rt: crate::in_place::InPlaceChecks::new(fail_in_place_check),
host_import,
shared_pointer_imports: OnceLock::new(),
@@ -87,7 +87,7 @@ index 20fd6a1a..70a18c56 100644
}
// The verdicts of its check of textures over host pages, where a record holds them.
device.recall_in_place_checks();
-+ // macbox: where the switch `host_rt_in_place` is on as the device is made, its
++ // LOCAL (Atlas): where the switch `host_rt_in_place` is on as the device is made, its
+ // render-target check starts now, on a thread of its own (`host_rt.rs`).
+ device.start_host_rt_checks_if_switched();
device.degrade_argument_buffers_unread();
@@ -101,7 +101,7 @@ index 9990acbf..11b17838 100644
}
all.push(added);
};
-+ // macbox: where textures over host pages render or write in place
++ // LOCAL (Atlas): where textures over host pages render or write in place
+ // (`host_rt_in_place`, `host_rt.rs`), an image's use of a key (an image in place, keyed as its
+ // buffer) takes the uses of every byte the key lies over: a render pass's write through one
+ // import of a surface's pages is ordered before a read through another import of them (the
@@ -123,7 +123,7 @@ index 9990acbf..11b17838 100644
.and_then(|aliases| aliases.get(&used.key))
.map(|alias| alias.key);
if let Some(key) = joined {
-+ // macbox: an image's use takes the memory's every byte (above).
++ // LOCAL (Atlas): an image's use takes the memory's every byte (above).
+ let range = match &used.range {
+ UseRange::Image { .. } => UseRange::Bytes(whole.clone()),
+ range => range.clone(),
@@ -140,7 +140,7 @@ index 00000000..f56f6938
--- /dev/null
+++ b/crates/metal2vulkan-runtime/src/host_rt.rs
@@ -0,0 +1,806 @@
-+//! macbox: textures over host pages that render or write, in place.
++//! LOCAL (Atlas): textures over host pages that render or write, in place.
+//!
+//! Upstream takes a texture over host pages in place only where its declared usage samples or
+//! reads it (`in_place.rs`): one that renders into it or writes it through a shader is a shadow
@@ -431,7 +431,7 @@ index 00000000..f56f6938
+ }
+ }
+
-+ /// macbox: start the render-target check where it has not started (whatever the
++ /// LOCAL (Atlas): start the render-target check where it has not started (whatever the
+ /// switch), and wait until every verdict is known or `timeout` passed: whether they are. A
+ /// runtime extension for the lanes.
+ #[doc(hidden)]
@@ -440,7 +440,7 @@ index 00000000..f56f6938
+ self.shared().host_rt.wait(timeout)
+ }
+
-+ /// macbox: the render-target check's verdicts now, one line per class, its notes, and
++ /// LOCAL (Atlas): the render-target check's verdicts now, one line per class, its notes, and
+ /// its time where it ended. A runtime extension for the lanes.
+ #[doc(hidden)]
+ pub fn host_rt_check_report(&self) -> Vec {
@@ -954,7 +954,7 @@ index 86f42373..420c9ac5 100644
lock(&self.notes).push(line);
}
-+ // macbox: the render-target check's report (`host_rt.rs`).
++ // LOCAL (Atlas): the render-target check's report (`host_rt.rs`).
+ /// What the check noted, a line each.
+ pub(crate) fn notes(&self) -> Vec {
+ lock(&self.notes).clone()
@@ -974,7 +974,7 @@ index 46645681..d0c60be3 100644
-struct ClassPages {
- buffer: Buffer,
- start: NonNull,
-+// macbox: crate-visible for the render-target check (`host_rt.rs`).
++// LOCAL (Atlas): crate-visible for the render-target check (`host_rt.rs`).
+pub(crate) struct ClassPages {
+ pub(crate) buffer: Buffer,
+ pub(crate) start: NonNull,
@@ -993,7 +993,7 @@ index 46645681..d0c60be3 100644
/// The host's page size.
-fn host_page() -> u64 {
-+// macbox: crate-visible for the render-target check (`host_rt.rs`).
++// LOCAL (Atlas): crate-visible for the render-target check (`host_rt.rs`).
+pub(crate) fn host_page() -> u64 {
#[cfg(unix)]
{
@@ -1006,7 +1006,7 @@ index 27ef226b..ca076571 100644
mod host_memory;
#[cfg(unix)]
mod host_residency;
-+/// macbox: textures over host pages that render or write, in place (`host_rt_in_place`).
++/// LOCAL (Atlas): textures over host pages that render or write, in place (`host_rt_in_place`).
+mod host_rt;
#[cfg(unix)]
mod host_shared_pointers;
@@ -1061,7 +1061,7 @@ index 0eb14cb2..10e313a1 100644
Err((refusal, why)) => ShadowCause::Refused(refusal, why),
}
}
-+ // macbox: a texture that renders or writes, in place, where the
++ // LOCAL (Atlas): a texture that renders or writes, in place, where the
+ // switch `host_rt_in_place` is on and the device's render-target check
+ // passed for the class (`host_rt.rs`); the check's own textures always.
+ Err(ShadowCause::RenderTarget | ShadowCause::ShaderWrite)
@@ -1100,7 +1100,7 @@ index 0eb14cb2..10e313a1 100644
{
return Err(Error::NotImplemented(RuntimeGap::Textures));
}
-+ // macbox: where the switch `shadow_compressed` is on, a shadow planned mutable to
++ // LOCAL (Atlas): where the switch `shadow_compressed` is on, a shadow planned mutable to
+ // any format takes the list of the formats its own image is viewed as
+ // (`shadow_compressible`), so a driver that compresses only images of a known list of
+ // compatible formats may compress it (ANV: "Disabling aux: CCS_E incompatible format(s)").
@@ -1115,7 +1115,7 @@ index 0eb14cb2..10e313a1 100644
Some(_) => (plan, None),
None => with_unorm_view(plan, &facts),
};
-+ // macbox diagnostic: the shadow's plan, where `M2V_SHADOW_PLANS` is set.
++ // LOCAL (Atlas) diagnostic: the shadow's plan, where `M2V_SHADOW_PLANS` is set.
+ if std::env::var_os("M2V_SHADOW_PLANS").is_some() {
+ eprintln!(
+ "metal2vulkan shadow plan: {:?} {:?} {}x{} flags {:?} usage {:?} views {:?} \
@@ -1138,7 +1138,7 @@ index 0eb14cb2..10e313a1 100644
}
}
+
-+/// macbox: the plans an image in place of a texture over host pages that renders or
++/// LOCAL (Atlas): the plans an image in place of a texture over host pages that renders or
+/// writes is tried with (`host_rt.rs`), the first the device makes: as a linear image aliasing a
+/// buffer of the runtime's own is (`Device::storage_over_buffer`'s `None` branch): with the
+/// feedback loop usage, then with the usage the texture lacks, then with its own plan. A linear
@@ -1159,7 +1159,7 @@ index 0eb14cb2..10e313a1 100644
+ Ok(plans)
+}
+
-+/// macbox: `plan`, a shadow's image, with the list of the formats the runtime views its own
++/// LOCAL (Atlas): `plan`, a shadow's image, with the list of the formats the runtime views its own
+/// image as where it is mutable to any format (a texture of `PixelFormatView` usage, or one Metal
+/// keeps uncompressed): the list a plan of the texture's usage without `PixelFormatView` takes, or
+/// its own format alone. A view of a texture over a buffer in another pixel format is a texture of
@@ -1199,7 +1199,7 @@ index 3ceaa484..7bff410a 100644
}
}
+
-+ // macbox: the render-target check's view of its texture (`host_rt.rs`).
++ // LOCAL (Atlas): the render-target check's view of its texture (`host_rt.rs`).
+ /// The texture's image in place, where it is one: its `VkImage`, its format, its usage and its
+ /// hazard key (the submission that names the key makes the image's first move).
+ pub(crate) fn in_place_target(
@@ -1231,7 +1231,7 @@ index 2ff62202..c2394df6 100644
mod guarded_effects;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
mod guest_frame_costs;
-+// macbox: the desktop's frames under the host-page render-target switches.
++// LOCAL (Atlas): the desktop's frames under the host-page render-target switches.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod half_output_blends;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -1248,7 +1248,7 @@ index 2ff62202..c2394df6 100644
) -> Result {
fatal_signals::install();
let mut options = validated_options(messages, cache);
-+ // macbox: `M2V_LANE_IN_PLACE=1` gives every lane device the product's policy for
++ // LOCAL (Atlas): `M2V_LANE_IN_PLACE=1` gives every lane device the product's policy for
+ // textures over host pages (`HostPageTexturePolicy::InPlace`) before the lane's own options,
+ // so the lanes over host pages exercise the in-place paths (`host_rt_in_place` among them).
+ if std::env::var_os("M2V_LANE_IN_PLACE").is_some_and(|v| v == "1") {
@@ -1263,11 +1263,11 @@ index 00000000..d1c701b0
--- /dev/null
+++ b/crates/metal2vulkan-validation/src/runtime_lane/host_rt_frames.rs
@@ -0,0 +1,485 @@
-+//! macbox: what a desktop frame of render passes into a texture over host pages costs on
++//! LOCAL (Atlas): what a desktop frame of render passes into a texture over host pages costs on
+//! the device the cfg selects, under each setting of the live switches `host_rt_in_place` and
+//! `shadow_compressed` (`metal2vulkan_runtime::live`): report only, in release builds.
+//!
-+//! The surface is the macOS desktop's framebuffer as the VM's WindowServer renders it: a
++//! The surface is the macOS desktop's framebuffer as the Atlas VM's WindowServer renders it: a
+//! 3440x1440 `BGRA8Unorm` IOSurface plane with rows of 13824 bytes (64 past its 13760 bytes of
+//! texels) over anonymous pages, a `Managed` no-copy buffer over them and a texture of the plane of
+//! `RenderTarget | ShaderRead` usage, on a device that takes textures over host pages in place
@@ -1649,7 +1649,7 @@ index 00000000..d1c701b0
+ }
+}
+
-+/// macbox probe: a pass that clears to (0.1, 0.2, 0.3, 0.4) (and blends over the left
++/// LOCAL (Atlas) probe: a pass that clears to (0.1, 0.2, 0.3, 0.4) (and blends over the left
+/// half, or draws nothing) into a texture in place over host pages, a `Private` texture and a
+/// linear image over a `Private` buffer: the bytes of texel 0 and of a texel in the right half of
+/// each (`RT-PROBE`). On ANV 26.2.4 both linear images' clears write red 0x19 where the
@@ -1758,7 +1758,7 @@ index 73808f3a..9e1acfba 100644
// one that only reads may be in place, counted so.
- let may_alias =
- policy == HostPageTexturePolicy::InPlace && usage == TextureUsage::SHADER_READ;
-+ // macbox: under `host_rt_in_place` one that renders or writes may be in
++ // LOCAL (Atlas): under `host_rt_in_place` one that renders or writes may be in
+ // place too.
+ let rt = metal2vulkan_runtime::live::on("host_rt_in_place", false);
+ let may_alias = policy == HostPageTexturePolicy::InPlace
@@ -1775,7 +1775,7 @@ index 05fb0e6a..cf7ba041 100644
let in_place = counts.host_textures_in_place - before.host_textures_in_place;
let policy = device.compile_device().policy().host_page_textures;
- let may_alias = policy == HostPageTexturePolicy::InPlace && usage == TextureUsage::SHADER_READ;
-+ // macbox: under `host_rt_in_place` one that renders or writes may be in place too.
++ // LOCAL (Atlas): under `host_rt_in_place` one that renders or writes may be in place too.
+ let rt = metal2vulkan_runtime::live::on("host_rt_in_place", false);
+ let may_alias =
+ policy == HostPageTexturePolicy::InPlace && (usage == TextureUsage::SHADER_READ || rt);
diff --git a/patches/metal2vulkan/0005-order-uses-through-two-imports-of-the-sa.patch b/patches/metal2vulkan/0005-order-uses-through-two-imports-of-the-sa.patch
index 57695e1..6d18e30 100644
--- a/patches/metal2vulkan/0005-order-uses-through-two-imports-of-the-sa.patch
+++ b/patches/metal2vulkan/0005-order-uses-through-two-imports-of-the-sa.patch
@@ -1,9 +1,9 @@
-From 0cb65c2d01e8fc3fd3eb6dc68feb1e55fb0d787e Mon Sep 17 00:00:00 2001
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: macbox
Date: Wed, 28 Oct 2026 19:40:43 +0000
-Subject: [PATCH 5/5] order uses through two imports of the same
- pages with MEMORY_WRITE; keep a remapped memory whose imports follow their
- address
+Subject: [PATCH 05/34] order uses through two imports of the
+ same pages with MEMORY_WRITE; keep a remapped memory whose imports follow
+ their address
The host_rt_in_place failure (surface_aliases'
a_second_buffer_that_joined_nothing_reads_what_the_first_wrote, AfterRemap
@@ -37,7 +37,7 @@ still stale.
whose live imports are all by pointer now stays (remapped_keeping,
HostImport::by_pointer): a later buffer over the bytes joins its key and
lies in its import. ARL's device lacks the fact (not in M2V_ARL_FACTS),
- so on the reference host the barrier above is what fixes it; with
+ so on Atlas the barrier above is what fixes it; with
facts_on=PointerImportsFollowTheirAddress the buffer lies in one import.
- host_rt::orders_images: an image use takes its key's bytes while the
switch is on and once a texture was made in place under it, so turning
@@ -72,7 +72,7 @@ index 169f4307..57d569a8 100644
self.shape.drops_writes
}
-+ /// macbox: whether its pages were imported by their pointer, neither as dma-bufs nor
++ /// LOCAL (Atlas): whether its pages were imported by their pointer, neither as dma-bufs nor
+ /// through a read-only view: an import that follows its address where the driver's pointer
+ /// imports do (`host_aliases.rs`).
+ pub(super) fn by_pointer(&self) -> bool {
@@ -90,7 +90,7 @@ index 9045fd4d..51b73aac 100644
use super::values::{ResourceOptions, StorageMode};
use super::work_counts::Counters;
use super::Device;
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use crate::release;
use ash::vk;
use std::ptr::NonNull;
@@ -106,7 +106,7 @@ index 9045fd4d..51b73aac 100644
- /// once, and otherwise it finds the buffers over the range by address, whether the range
- /// covers none of them or many, never reading them all.
+ /// new pages: a buffer made over those bytes while it runs may lie in either pages. LOCAL
-+ /// (macbox): where the driver's pointer imports follow their address, a live buffer's import of
++ /// (Atlas): where the driver's pointer imports follow their address, a live buffer's import of
+ /// the pointer reads the new pages from the call on, as a new import would: a buffer made
+ /// after the call over the bytes a live one was made over, of its memory class, lies in its
+ /// import still, and joins its key, unless an import of the memory is of dma-bufs
@@ -124,7 +124,7 @@ index 9045fd4d..51b73aac 100644
let unit = (shared.host_import.as_ref())
.map_or(1, |importer| importer.page.max(importer.alignment));
- let imports = (shared.aliases).remapped(start, start.saturating_add(length), unit);
-+ // macbox: on a driver whose pointer imports follow their address, a memory whose
++ // LOCAL (Atlas): on a driver whose pointer imports follow their address, a memory whose
+ // imports are all of the pointer stays: they read the new pages from the remap on, as
+ // an import made after it would, so a later buffer over the bytes lies in one of them
+ // (`host_aliases.rs`).
@@ -141,7 +141,7 @@ index 9045fd4d..51b73aac 100644
.aliases
.join(buffer.identity().key, made_over, class, &import);
- shared.aliases.place(buffer.identity().key, made_over);
-+ // macbox: placed with the import it lies in (`host_aliases.rs`).
++ // LOCAL (Atlas): placed with the import it lies in (`host_aliases.rs`).
+ let note = super::host_aliases::import_note(&import);
+ shared.aliases.place(buffer.identity().key, made_over, note);
return Ok(buffer);
@@ -151,7 +151,7 @@ index 9045fd4d..51b73aac 100644
// a later one lies in its import; one whose GPU writes are dropped joins none.
// A buffer just made lies in its pages (`HostCell::current`).
let current = buffer.host_cell().and_then(|cell| cell.current());
-+ // macbox: the import it lies in, which it is placed with (`host_aliases.rs`).
++ // LOCAL (Atlas): the import it lies in, which it is placed with (`host_aliases.rs`).
+ let note =
+ (current.as_ref()).map_or(0, |pages| super::host_aliases::import_note(pages.import()));
if let (false, false, Some(current)) = (of_heap, drops_writes, current) {
@@ -172,7 +172,7 @@ index 9045fd4d..51b73aac 100644
shared.aliases.leave(key);
- // Its uses from now on order against the keys over the new bytes.
- shared.aliases.place(key, (pointer.as_ptr() as u64, length));
-+ // Its uses from now on order against the keys over the new bytes; macbox: placed
++ // Its uses from now on order against the keys over the new bytes; LOCAL (Atlas): placed
+ // with the import of its new pages (`host_aliases.rs`).
+ let note = super::host_aliases::import_note(pages.import());
+ shared
@@ -189,7 +189,7 @@ index 11b17838..330c0690 100644
//! (`WorkCounts::host_imports_remapped`). The lock is a leaf: nothing else is locked, and no buffer, pages hold or
//! deallocator is dropped, while it is held (the imports noted are weak), so the call may be
//! made from any thread, a deallocator's among them.
-+//! - **macbox: a remap over imports that follow their address.** On a driver whose pointer
++//! - **LOCAL (Atlas): a remap over imports that follow their address.** On a driver whose pointer
+//! imports follow their address (`DriverFact::PointerImportsFollowTheirAddress`), an import of
+//! the pointer reads the pages mapped there at each submission, the new ones from a remap on, as
+//! an import made after it would. There a reported remap keeps a memory whose every live
@@ -197,7 +197,7 @@ index 11b17838..330c0690 100644
+//! joins its key and lies in its import, one `VkDeviceMemory` again, where it would otherwise
+//! import the same pages anew. A memory with an import of dma-bufs (which keeps its pages)
+//! still ends.
-+//! - **macbox: two imports of the same pages.** Each import is a `VkDeviceMemory` of its
++//! - **LOCAL (Atlas): two imports of the same pages.** Each import is a `VkDeviceMemory` of its
+//! own, mapped at a GPU address of its own, and on ANV (Mesa 26.2.4, the Arrow Lake iGPU) a
+//! barrier from a pass's color writes through one to a read through another of the same pages
+//! left about 2% of the texels stale within one submission: those still in the GPU's L3 under
@@ -228,7 +228,7 @@ index 11b17838..330c0690 100644
}
}
-+ /// macbox: [`remapped_keeping`](Self::remapped_keeping), keeping no memory (the
++ /// LOCAL (Atlas): [`remapped_keeping`](Self::remapped_keeping), keeping no memory (the
+ /// tests' form, upstream's call).
+ #[cfg(test)]
+ pub(super) fn remapped(&self, start: u64, end: u64, unit: u64) -> usize {
@@ -244,7 +244,7 @@ index 11b17838..330c0690 100644
/// takes anew at its next submission (`WorkCounts::host_imports_remapped`).
- pub(super) fn remapped(&self, start: u64, end: u64, unit: u64) -> usize {
+ ///
-+ /// macbox: but a memory each of whose live imports `keeps` (an import of the pointer
++ /// LOCAL (Atlas): but a memory each of whose live imports `keeps` (an import of the pointer
+ /// on a driver whose pointer imports follow their address, which reads the pages the remap
+ /// put there: the module docs) stays, so a later buffer over its bytes joins it and lies in
+ /// its import. A memory with no live import ends.
@@ -301,7 +301,7 @@ index 11b17838..330c0690 100644
/// its length) from now on, made or rebound there, and no longer where it lay before
- /// ([`Placements`]).
- pub(super) fn place(&self, key: ResourceKey, at: (u64, u64)) {
-+ /// ([`Placements`]). macbox: in the import `import` names (its address; 0 for one not
++ /// ([`Placements`]). LOCAL (Atlas): in the import `import` names (its address; 0 for one not
+ /// known, which no other import is taken to be: the module docs).
+ pub(super) fn place(&self, key: ResourceKey, at: (u64, u64), import: u64) {
let mut inner = lock(&self.inner);
@@ -315,7 +315,7 @@ index 11b17838..330c0690 100644
}
}
-+/// macbox: the note of `import` in the placements: its address, which no other live
++/// LOCAL (Atlas): the note of `import` in the placements: its address, which no other live
+/// import shares (the module docs).
+pub(super) fn import_note(import: &Arc) -> u64 {
+ Arc::as_ptr(import) as usize as u64
@@ -351,7 +351,7 @@ index 11b17838..330c0690 100644
- range,
- ..used.clone()
- });
-+ // macbox: a buffer that joined a memory lies in its import but where two
++ // LOCAL (Atlas): a buffer that joined a memory lies in its import but where two
+ // were made over it at once (the module docs): one placed in another import than
+ // the memory's key's is apart.
+ let other = placements.is_some_and(|placements| placements.apart(used.key, key));
@@ -390,7 +390,7 @@ index 11b17838..330c0690 100644
!all.is_empty()
}
-+/// macbox: `used`, a use added for a key of another import of the same pages where
++/// LOCAL (Atlas): `used`, a use added for a key of another import of the same pages where
+/// `other` (the module docs), with `MEMORY_WRITE` among the access types of its reads and of its
+/// writes: a barrier between it and any use of the key it is added for then carries
+/// `MEMORY_WRITE` on its side, which ANV takes as its full flush, so a write through one import
@@ -418,7 +418,7 @@ index 11b17838..330c0690 100644
- /// Each placed key's bytes: their first byte's host address and their length.
- at: KeyMap,
+ /// Each placed key's bytes: their first byte's host address and their length; LOCAL
-+ /// (macbox): and the import it lies in ([`import_note`]; 0: not known, apart from every
++ /// (Atlas): and the import it lies in ([`import_note`]; 0: not known, apart from every
+ /// other).
+ at: KeyMap,
/// Each range of bytes some key lies over, by its first byte's address and its length.
@@ -428,13 +428,13 @@ index 11b17838..330c0690 100644
keys: usize,
/// Whether its key lies over it still.
first: bool,
-+ /// macbox: the import its key lies in, kept once the key went: the key's uses still
++ /// LOCAL (Atlas): the import its key lies in, kept once the key went: the key's uses still
+ /// recorded lie there, and hold the import, whose address no other import takes meanwhile.
+ import: u64,
/// The other ranges that meet it (share a byte with it), each with its key (a range's key
- /// is its own while it lives), in the order the lookup by address finds them ([`seat`]).
- meets: Vec<((u64, u64), ResourceKey)>,
-+ /// is its own while it lives) and macbox that key's import, in the order the lookup by
++ /// is its own while it lives) and LOCAL (Atlas) that key's import, in the order the lookup by
+ /// address finds them ([`seat`]).
+ meets: Vec<((u64, u64), ResourceKey, u64)>,
}
@@ -473,7 +473,7 @@ index 11b17838..330c0690 100644
}
}
-+/// macbox: whether two imports, as placements note them (0: not known), are apart:
++/// LOCAL (Atlas): whether two imports, as placements note them (0: not known), are apart:
+/// either not known, or two.
+fn imports_apart(a: u64, b: u64) -> bool {
+ a == 0 || b == 0 || a != b
@@ -489,7 +489,7 @@ index 11b17838..330c0690 100644
- /// Place `key`, lying over no bytes, over `at`.
- pub(super) fn place(&mut self, key: ResourceKey, at: (u64, u64)) {
+ /// Place `key`, lying over no bytes, over `at`, in the import `import` names (LOCAL
-+ /// (macbox)).
++ /// (Atlas)).
+ pub(super) fn place(&mut self, key: ResourceKey, at: (u64, u64), import: u64) {
if at.1 == 0 {
return;
@@ -540,7 +540,7 @@ index 11b17838..330c0690 100644
}
}
-+ /// macbox: whether the placed keys `a` and `b` lie in two imports, or either in one not
++ /// LOCAL (Atlas): whether the placed keys `a` and `b` lie in two imports, or either in one not
+ /// known (the module docs); `false` where either is not placed.
+ pub(super) fn apart(&self, a: ResourceKey, b: ResourceKey) -> bool {
+ match (self.at.get(&a), self.at.get(&b)) {
@@ -553,7 +553,7 @@ index 11b17838..330c0690 100644
/// share, and the bytes of it they are (counted from its range's first byte), to `each`: its
/// own range's key where another, and each other range's the bytes meet, clipped to it, in
- /// the order the lookup by address finds them. The ranges the bytes may meet are those that
-+ /// the order the lookup by address finds them; macbox: and whether that key lies in
++ /// the order the lookup by address finds them; LOCAL (Atlas): and whether that key lies in
+ /// another import than `key` ([`imports_apart`]). The ranges the bytes may meet are those that
/// meet the key's own range, which it keeps: they are read from there while no more than the
/// classes of length the lookup by address visits (a range query each, where a kept range is
@@ -667,7 +667,7 @@ index fd28d676..db2af089 100644
/// The host page of the tests that name none of their own: an import's unit.
const PAGE: u64 = 0x1000;
-+/// macbox: the import the tests that name none place every key in: one import.
++/// LOCAL (Atlas): the import the tests that name none place every key in: one import.
+const ONE: u64 = 1;
+
/// A reported remap counts the ranges placed buffers lie over that have a page among its bytes
@@ -789,7 +789,7 @@ index fd28d676..db2af089 100644
changed("forgotten");
}
+
-+/// macbox: `used` as a use added for a key of another import takes it: `MEMORY_WRITE`
++/// LOCAL (Atlas): `used` as a use added for a key of another import takes it: `MEMORY_WRITE`
+/// among the access types of its reads and of its writes.
+fn apart(mut used: Use) -> Use {
+ for side in [&mut used.read, &mut used.write] {
@@ -800,7 +800,7 @@ index fd28d676..db2af089 100644
+ used
+}
+
-+/// macbox: keys over one surface's pages in two imports (one made after a remap of them):
++/// LOCAL (Atlas): keys over one surface's pages in two imports (one made after a remap of them):
+/// a use of the second's bytes carries a use of the first's key with `MEMORY_WRITE` among its
+/// access types, where a key in the first's import carries it as it was; a range in a third
+/// import that meets the surface's last page carries the first's key so too, clipped; and a key
@@ -849,7 +849,7 @@ index fd28d676..db2af089 100644
+ );
+}
+
-+/// macbox: two buffers made at once over one memory, each importing it: the second joins
++/// LOCAL (Atlas): two buffers made at once over one memory, each importing it: the second joins
+/// the first's key, and where they are placed in two imports its uses carry the first's key with
+/// `MEMORY_WRITE`; in one import, as they were.
+#[test]
@@ -883,7 +883,7 @@ index fd28d676..db2af089 100644
+ drop((one, two));
+}
+
-+/// macbox: a remap over a memory each of whose live imports follows its address keeps
++/// LOCAL (Atlas): a remap over a memory each of whose live imports follows its address keeps
+/// it: a later buffer over its bytes lies in its import and joins its key. One whose import does
+/// not, or with no import live, ends.
+#[test]
@@ -930,7 +930,7 @@ index 8df378c2..aaf61433 100644
//! says so and passes.
use super::blit_holds::{device, over_host, until, Host, Scratch, BYTES};
-+use crate::live::LiveFacts as _; // macbox: live fact switches
++use crate::live::LiveFacts as _; // LOCAL (Atlas): live fact switches
use crate::{
BlitOption, Buffer, CommandBufferStatus, CommandQueue, Device, Error, Origin, ResourceOptions,
Size, Texture, TextureDescriptor, WorkCounts,
@@ -939,7 +939,7 @@ index 8df378c2..aaf61433 100644
assert_eq!(remaps(&device)[..3], [reported + 2, over + 1, remapped + 1]);
// A second buffer over the remapped bytes imports them anew (`host_aliases.rs`): two live
- // imports over the same bytes, one placed range, which a report counts once.
-+ // imports over the same bytes, one placed range, which a report counts once. macbox:
++ // imports over the same bytes, one placed range, which a report counts once. LOCAL (Atlas):
+ // where the driver's pointer imports follow their address, it lies in the first's import,
+ // which reads the new pages: one import, the same range.
let again = over_host(&device, &imported, &runs).unwrap();
@@ -971,7 +971,7 @@ index c453e0b2..bda123a2 100644
//! memory a buffer was made over; the runtime orders their uses by the bytes each lies over now
//! (`host_aliases.rs`'s placements), so their reads are fresh wherever one buffer's would be, two
-//! queues in submission order included.
-+//! queues in submission order included. macbox: the one made after a remap imports the
++//! queues in submission order included. LOCAL (Atlas): the one made after a remap imports the
+//! pages anew, a second `VkDeviceMemory` of them (on a driver whose pointer imports follow their
+//! address it joins the first and lies in its import instead), and its uses through that import
+//! carry `MEMORY_WRITE`, so their barriers flush what a pass wrote through the other: on ANV a
@@ -985,7 +985,7 @@ index c453e0b2..bda123a2 100644
Rebound,
/// Made over them after the program reported their range remapped while the first lived
- /// (with no remap made): it joins nothing, and imports them anew.
-+ /// (with no remap made): it joins nothing, and imports them anew (macbox: on a driver
++ /// (with no remap made): it joins nothing, and imports them anew (LOCAL (Atlas): on a driver
+ /// whose pointer imports follow their address it joins the first instead).
AfterRemap,
}
diff --git a/patches/metal2vulkan/0006-diagnostic-pass-timer-M2V_PASS_TIMES-and.patch b/patches/metal2vulkan/0006-diagnostic-pass-timer-M2V_PASS_TIMES-and.patch
new file mode 100644
index 0000000..780b104
--- /dev/null
+++ b/patches/metal2vulkan/0006-diagnostic-pass-timer-M2V_PASS_TIMES-and.patch
@@ -0,0 +1,3090 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Wed, 28 Oct 2026 16:50:52 +0000
+Subject: [PATCH 06/34] diagnostic:pass timer (M2V_PASS_TIMES)
+ and image census (M2V_IMAGE_LOG)
+
+Two default-off diagnostics in metal2vulkan-runtime, to find where a macOS
+guest's GPU time goes on the Arrow Lake iGPU (Mesa's INTEL_MEASURE crashes
+with this runtime). Each switch is read once; unset, nothing changes: no
+query pool, no command, no line. Self-contained: two new modules
+(pass_times.rs, image_log.rs) and small hooks, each marked
+"LOCAL (Atlas) diagnostic", so the commit can be dropped.
+
+M2V_PASS_TIMES=: a command buffer begun while /on exists (checked
+once, as it begins recording) gets vkCmdWriteTimestamp(ALL_COMMANDS) pairs
+around each unit of GPU work, cut at the recorder's routed entry points so
+every recording site is covered: each render pass instance (each instance
+of a split pass), each run of dispatches, each run of transfers. Queries
+come from the diagnostic's own pools, reset on the host. As the command
+buffer completes (completion turn, after its GPU times) one CSV line per
+unit goes to /passes-.csv:
+host_ns,cb_seq,unit_seq,kind,cb_label,encoder_label,attachments,split,draws,gpu_ns
+with the kind (render-pass, guest-, pass:/internal:), the
+queue's label, the encoder's kind and place, each attachment (role, format,
+extent, samples, load/store, memoryless, image purpose), the split (i/n,
+cause, inline or secondary, why not inline) and the draws/dispatches.
+
+M2V_IMAGE_LOG=: one CSV line per vkCreateImage (purpose, format,
+extent, mips, layers, samples, tiling, DRM modifier, usage, create flags,
+format list, external handle types, chained structures, memory
+requirements), per vkBindImageMemory (the memory's kind: own, host-pages,
+dma-buf, dedicated) and per vkDestroyImage: the fields Mesa ANV's CCS
+rules read.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/buffer_texture.rs | 4 +
+ .../src/command_buffer/completion.rs | 2 +
+ .../src/command_buffer/mod.rs | 66 +-
+ crates/metal2vulkan-runtime/src/creation.rs | 63 +-
+ .../src/device/functions.rs | 179 +++
+ crates/metal2vulkan-runtime/src/device/mod.rs | 8 +
+ crates/metal2vulkan-runtime/src/encoder.rs | 10 +
+ crates/metal2vulkan-runtime/src/image_log.rs | 925 +++++++++++++
+ crates/metal2vulkan-runtime/src/lib.rs | 4 +
+ crates/metal2vulkan-runtime/src/pass_times.rs | 1194 +++++++++++++++++
+ .../src/pending_dispatch.rs | 2 +
+ .../src/recorder/thunks.rs | 20 +-
+ crates/metal2vulkan-runtime/src/release.rs | 2 +
+ crates/metal2vulkan-runtime/src/render.rs | 7 +
+ .../src/render/inline_first.rs | 23 +
+ .../src/render/inline_splits.rs | 5 +
+ .../src/render/pass_steps.rs | 11 +
+ crates/metal2vulkan-runtime/src/texture.rs | 27 +
+ 18 files changed, 2535 insertions(+), 17 deletions(-)
+ create mode 100644 crates/metal2vulkan-runtime/src/image_log.rs
+ create mode 100644 crates/metal2vulkan-runtime/src/pass_times.rs
+
+diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs
+index b062a79b..45801900 100644
+--- a/crates/metal2vulkan-runtime/src/buffer_texture.rs
++++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs
+@@ -296,6 +296,8 @@ impl Buffer {
+ offset: u64,
+ bytes_per_row: u64,
+ ) -> Result {
++ // LOCAL (Atlas) diagnostic: the image census's purpose (`image_log.rs`).
++ let _purpose = crate::image_log::api("buffer-texture");
+ self.texture_over(
+ "new_texture",
+ descriptor,
+@@ -434,6 +436,8 @@ impl Buffer {
+ descriptor: &TextureDescriptor,
+ plane: IoSurfacePlane,
+ ) -> Result {
++ // LOCAL (Atlas) diagnostic: the image census's purpose (`image_log.rs`).
++ let _purpose = crate::image_log::api("iosurface-plane");
+ if plane.client_direction.is_some() {
+ return Err(Error::AppleOnly(AppleOnly::SurfaceClientDirection));
+ }
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs
+index 635861b6..cc2497bb 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs
+@@ -453,6 +453,8 @@ fn finish(watch: &Watch, lists: &mut FenceLists, mut finished: Vec<(usize, Submi
+ for buffer in &ending {
+ buffer.read_stamps();
+ buffer.place_gpu_times();
++ // LOCAL (Atlas) diagnostic: the pass timer's units (`pass_times.rs`).
++ buffer.read_pass_times();
+ }
+ }
+ drop(device);
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+index ac0260ac..b08a9994 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+@@ -746,6 +746,8 @@ pub(super) struct State {
+ /// The device's trail mark as it completed (`trails.rs`): its waiters return once no trail
+ /// numbered below is open. 0 before, which waits for none.
+ trail_mark: u64,
++ /// LOCAL (Atlas) diagnostic: its pass timer's capture (`pass_times.rs`).
++ pub(super) pass_times: crate::pass_times::CbSlot,
+ }
+
+ /// A batch whose end went into its last `VkCommandBuffer` ([`State::folds`]).
+@@ -1855,6 +1857,8 @@ impl CommandBuffer {
+ replaying_predication: None,
+ predicated: false,
+ trail_mark: 0,
++ // LOCAL (Atlas) diagnostic: the pass timer (`pass_times.rs`).
++ pass_times: Default::default(),
+ }),
+ changed: Condvar::new(),
+ gate: Arc::default(),
+@@ -1950,6 +1954,11 @@ impl CommandBuffer {
+ self.state().uploads.bytes()
+ }
+
++ /// LOCAL (Atlas) diagnostic: the key the pass timer finds its capture by (`pass_times.rs`).
++ pub(crate) fn pass_times_key(&self) -> usize {
++ self.0.address()
++ }
++
+ /// Whether `waiting` holds this command buffer.
+ pub(crate) fn is(&self, waiting: &dyn Waiting) -> bool {
+ self.0.address() == waiting.address()
+@@ -3707,12 +3716,48 @@ impl CommandBufferShared {
+ level: vk::CommandBufferLevel,
+ ) -> Result {
+ if let Some(pool) = &state.rerun_pool {
+- return hand_out(&self.device, &mut lock(pool), level);
+- }
+- match self.deferred(state, level)? {
+- Some(raw) => Ok(raw),
+- None => self.allocate(state, level),
+- }
++ let raw = hand_out(&self.device, &mut lock(pool), level)?;
++ // LOCAL (Atlas) diagnostic: the pass timer (`pass_times.rs`).
++ self.pass_times_handed_out(state, raw);
++ return Ok(raw);
++ }
++ let raw = match self.deferred(state, level)? {
++ Some(raw) => raw,
++ None => self.allocate(state, level)?,
++ };
++ // LOCAL (Atlas) diagnostic: the pass timer (`pass_times.rs`).
++ self.pass_times_handed_out(state, raw);
++ Ok(raw)
++ }
++
++ /// LOCAL (Atlas) diagnostic: `raw`, handed out, goes to the pass timer's capture of this
++ /// command buffer, decided as it is first asked (`pass_times.rs`).
++ fn pass_times_handed_out(&self, state: &mut State, raw: vk::CommandBuffer) {
++ let key = self.address();
++ crate::pass_times::handed_out(&self.device, &self.queue, key, &mut state.pass_times, raw);
++ }
++
++ /// LOCAL (Atlas) diagnostic: read the pass timer's units, now that its work completed and its
++ /// GPU times were placed: in the completion turn, inside its section (`pass_times.rs`).
++ pub(super) fn read_pass_times(&self) {
++ let mut state = lock(&self.state);
++ let Some(capture) = state.pass_times.take() else {
++ return;
++ };
++ let start = match (state.times.stamped, state.times.gpu) {
++ (Stamped::Read(Some((ticks, _))), Some((host, _))) => Some((ticks, host)),
++ _ => None,
++ };
++ let pair = state.times.pair.map(|reading| reading.pair);
++ let completed = state.times.completed;
++ drop(state);
++ let placement = crate::pass_times::Placement {
++ clock: self.device.shared().timing.clock(),
++ pair,
++ start,
++ completed,
++ };
++ crate::pass_times::read(capture, placement);
+ }
+
+ /// A deferred command buffer of `level` of its replays, where the device records them so and
+@@ -3748,16 +3793,23 @@ impl CommandBufferShared {
+ state: &mut State,
+ level: vk::CommandBufferLevel,
+ ) -> Result {
+- hand_out(&self.device, self.pool(state)?, level)
++ let raw = hand_out(&self.device, self.pool(state)?, level)?;
++ // LOCAL (Atlas) diagnostic: the pass timer (`pass_times.rs`).
++ self.pass_times_handed_out(state, raw);
++ Ok(raw)
+ }
+
+ /// [`CommandBuffer::encoder_primary`]: a deferred one where the device records them so, to
+ /// begin, whose replay takes the primary its replays' pool holds begun ahead (`recorder`).
+ fn encoder_primary(&self, state: &mut State) -> Result<(vk::CommandBuffer, bool), Error> {
+ if let Some(raw) = self.deferred(state, vk::CommandBufferLevel::PRIMARY)? {
++ // LOCAL (Atlas) diagnostic: the pass timer (`pass_times.rs`).
++ self.pass_times_handed_out(state, raw);
+ return Ok((raw, false));
+ }
+ if let Some(buffer) = self.pool(state)?.take_begun() {
++ // LOCAL (Atlas) diagnostic: the pass timer (`pass_times.rs`).
++ self.pass_times_handed_out(state, buffer);
+ return Ok((buffer, true));
+ }
+ Ok((self.allocate_raw(state)?, false))
+diff --git a/crates/metal2vulkan-runtime/src/creation.rs b/crates/metal2vulkan-runtime/src/creation.rs
+index 1d760a06..b4eac3f0 100644
+--- a/crates/metal2vulkan-runtime/src/creation.rs
++++ b/crates/metal2vulkan-runtime/src/creation.rs
+@@ -38,7 +38,13 @@ pub(crate) unsafe fn image(
+ ) -> Result {
+ vk_made(VkMaking::Image, Location::caller());
+ // SAFETY: the caller's.
+- unsafe { device.create_image(info, None) }.map_err(vulkan)
++ let made = unsafe { device.create_image(info, None) }.map_err(vulkan);
++ // LOCAL (Atlas) diagnostic: the image census (`image_log.rs`).
++ if let Ok(image) = made {
++ // SAFETY: the caller's; `image` was just made by `device`.
++ unsafe { crate::image_log::image_made(device, info, image, Location::caller()) };
++ }
++ made
+ }
+
+ /// A `VkImage` of `info`, made by `device`, or the driver's refusal of it: an image whose making
+@@ -57,7 +63,12 @@ pub(crate) unsafe fn image_or_refusal(
+ vk_made(VkMaking::Image, Location::caller());
+ // SAFETY: the caller's.
+ match unsafe { device.create_image(info, None) } {
+- Ok(raw) => Ok(Ok(raw)),
++ Ok(raw) => {
++ // LOCAL (Atlas) diagnostic: the image census (`image_log.rs`).
++ // SAFETY: the caller's; `raw` was just made by `device`.
++ unsafe { crate::image_log::image_made(device, info, raw, Location::caller()) };
++ Ok(Ok(raw))
++ }
+ Err(vk::Result::ERROR_DEVICE_LOST) => Err(Error::DeviceLost),
+ Err(refusal) => Ok(Err(refusal)),
+ }
+@@ -92,7 +103,12 @@ pub(crate) unsafe fn image_view(
+ ) -> VkResult {
+ vk_made(VkMaking::ImageView, Location::caller());
+ // SAFETY: the caller's.
+- unsafe { device.create_image_view(info, None) }
++ let made = unsafe { device.create_image_view(info, None) };
++ // LOCAL (Atlas) diagnostic: the object registry (`image_log.rs`).
++ if let Ok(view) = made {
++ crate::image_log::view_made(info, view);
++ }
++ made
+ }
+
+ /// `VkDeviceMemory` of `info`, allocated by `device`: one call of `vkAllocateMemory`, counted
+@@ -110,7 +126,13 @@ pub(crate) unsafe fn allocate_memory(
+ ) -> VkResult {
+ vk_made(VkMaking::Memory, Location::caller());
+ // SAFETY: the caller's.
+- unsafe { device.allocate_memory(info, None) }
++ let made = unsafe { device.allocate_memory(info, None) };
++ // LOCAL (Atlas) diagnostic: the image census's memory kinds (`image_log.rs`).
++ if let Ok(memory) = made {
++ // SAFETY: the caller's: `info` and its chain are valid.
++ unsafe { crate::image_log::memory_made(info, memory) };
++ }
++ made
+ }
+
+ /// `image` bound to `memory` at `offset`.
+@@ -128,7 +150,12 @@ pub(crate) unsafe fn bind_image(
+ ) -> VkResult<()> {
+ vk_made(VkMaking::ImageBinding, Location::caller());
+ // SAFETY: the caller's.
+- unsafe { device.bind_image_memory(image, memory, offset) }
++ let bound = unsafe { device.bind_image_memory(image, memory, offset) };
++ // LOCAL (Atlas) diagnostic: the image census (`image_log.rs`).
++ if bound.is_ok() {
++ crate::image_log::image_bound(image, memory, offset);
++ }
++ bound
+ }
+
+ /// `buffer` bound to `memory` at `offset`.
+@@ -154,12 +181,19 @@ pub(crate) unsafe fn bind_buffer(
+ /// # Safety
+ ///
+ /// As `vkCreateRenderPass`'s: `device` is live, and `info` and its chain are valid for it.
++#[track_caller]
+ pub(crate) unsafe fn render_pass(
+ device: &ash::Device,
+ info: &vk::RenderPassCreateInfo<'_>,
+ ) -> Result {
+ // SAFETY: the caller's.
+- unsafe { device.create_render_pass(info, None) }.map_err(vulkan)
++ let made = unsafe { device.create_render_pass(info, None) }.map_err(vulkan);
++ // LOCAL (Atlas) diagnostic: the object registry (`image_log.rs`).
++ if let Ok(pass) = made {
++ // SAFETY: the caller's: `info` is valid.
++ unsafe { crate::image_log::render_pass_made(info, pass, Location::caller()) };
++ }
++ made
+ }
+
+ /// A `VkRenderPass` of `info` (`vkCreateRenderPass2`), made by `device`.
+@@ -168,12 +202,19 @@ pub(crate) unsafe fn render_pass(
+ ///
+ /// As `vkCreateRenderPass2`'s: `device` is live and of Vulkan 1.2 or later, and `info` and its
+ /// chain are valid for it.
++#[track_caller]
+ pub(crate) unsafe fn render_pass2(
+ device: &ash::Device,
+ info: &vk::RenderPassCreateInfo2<'_>,
+ ) -> Result {
+ // SAFETY: the caller's.
+- unsafe { device.create_render_pass2(info, None) }.map_err(vulkan)
++ let made = unsafe { device.create_render_pass2(info, None) }.map_err(vulkan);
++ // LOCAL (Atlas) diagnostic: the object registry (`image_log.rs`).
++ if let Ok(pass) = made {
++ // SAFETY: the caller's: `info` and its chain are valid.
++ unsafe { crate::image_log::render_pass2_made(info, pass, Location::caller()) };
++ }
++ made
+ }
+
+ /// A `VkFramebuffer` of `info`, made by `device`.
+@@ -186,5 +227,11 @@ pub(crate) unsafe fn framebuffer(
+ info: &vk::FramebufferCreateInfo<'_>,
+ ) -> Result {
+ // SAFETY: the caller's.
+- unsafe { device.create_framebuffer(info, None) }.map_err(vulkan)
++ let made = unsafe { device.create_framebuffer(info, None) }.map_err(vulkan);
++ // LOCAL (Atlas) diagnostic: the object registry (`image_log.rs`).
++ if let Ok(framebuffer) = made {
++ // SAFETY: the caller's: `info` is valid.
++ unsafe { crate::image_log::framebuffer_made(info, framebuffer) };
++ }
++ made
+ }
+diff --git a/crates/metal2vulkan-runtime/src/device/functions.rs b/crates/metal2vulkan-runtime/src/device/functions.rs
+index be874eac..72ef34e8 100644
+--- a/crates/metal2vulkan-runtime/src/device/functions.rs
++++ b/crates/metal2vulkan-runtime/src/device/functions.rs
+@@ -147,6 +147,8 @@ impl Vk {
+ regions: &[vk::BufferCopy],
+ ) {
+ (self.copies).count("vkCmdCopyBuffer", Location::caller(), regions.len());
++ // LOCAL (Atlas) diagnostic: the caller's place, for the pass timer (`pass_times.rs`).
++ crate::pass_times::site(Location::caller());
+ let splits = regions
+ .iter()
+ .filter(|region| split(region).is_some())
+@@ -194,6 +196,8 @@ impl Vk {
+ regions: &[vk::BufferImageCopy],
+ ) {
+ (self.copies).count("vkCmdCopyBufferToImage", Location::caller(), regions.len());
++ // LOCAL (Atlas) diagnostic: the caller's place, for the pass timer (`pass_times.rs`).
++ crate::pass_times::site(Location::caller());
+ // SAFETY: the caller's contract.
+ unsafe {
+ (self.device).cmd_copy_buffer_to_image(command_buffer, src, dst, layout, regions);
+@@ -216,6 +220,8 @@ impl Vk {
+ regions: &[vk::BufferImageCopy],
+ ) {
+ (self.copies).count("vkCmdCopyImageToBuffer", Location::caller(), regions.len());
++ // LOCAL (Atlas) diagnostic: the caller's place, for the pass timer (`pass_times.rs`).
++ crate::pass_times::site(Location::caller());
+ // SAFETY: the caller's contract.
+ unsafe {
+ (self.device).cmd_copy_image_to_buffer(command_buffer, src, layout, dst, regions);
+@@ -238,6 +244,8 @@ impl Vk {
+ regions: &[vk::ImageCopy],
+ ) {
+ (self.copies).count("vkCmdCopyImage", Location::caller(), regions.len());
++ // LOCAL (Atlas) diagnostic: the caller's place, for the pass timer (`pass_times.rs`).
++ crate::pass_times::site(Location::caller());
+ // SAFETY: the caller's contract.
+ unsafe {
+ (self.device).cmd_copy_image(command_buffer, src, src_layout, dst, dst_layout, regions);
+@@ -245,6 +253,177 @@ impl Vk {
+ }
+ }
+
++/// LOCAL (Atlas) diagnostic: the commands the pass timer labels a unit of work by, each noting its
++/// caller's place for the command's entry point to take (`pass_times.rs`), then `ash`'s. A caller
++/// holding the `ash::Device` itself records through `ash`'s, unnoted.
++impl Vk {
++ /// `vkCmdDispatch`, its caller's place noted.
++ ///
++ /// # Safety
++ ///
++ /// As `ash::Device::cmd_dispatch`'s.
++ #[track_caller]
++ pub(crate) unsafe fn cmd_dispatch(
++ &self,
++ command_buffer: vk::CommandBuffer,
++ x: u32,
++ y: u32,
++ z: u32,
++ ) {
++ crate::pass_times::site(Location::caller());
++ // SAFETY: the caller's.
++ unsafe { (self.device).cmd_dispatch(command_buffer, x, y, z) }
++ }
++
++ /// `vkCmdDispatchIndirect`, its caller's place noted.
++ ///
++ /// # Safety
++ ///
++ /// As `ash::Device::cmd_dispatch_indirect`'s.
++ #[track_caller]
++ pub(crate) unsafe fn cmd_dispatch_indirect(
++ &self,
++ command_buffer: vk::CommandBuffer,
++ buffer: vk::Buffer,
++ offset: vk::DeviceSize,
++ ) {
++ crate::pass_times::site(Location::caller());
++ // SAFETY: the caller's.
++ unsafe { (self.device).cmd_dispatch_indirect(command_buffer, buffer, offset) }
++ }
++
++ /// `vkCmdFillBuffer`, its caller's place noted.
++ ///
++ /// # Safety
++ ///
++ /// As `ash::Device::cmd_fill_buffer`'s.
++ #[track_caller]
++ pub(crate) unsafe fn cmd_fill_buffer(
++ &self,
++ command_buffer: vk::CommandBuffer,
++ buffer: vk::Buffer,
++ offset: vk::DeviceSize,
++ size: vk::DeviceSize,
++ data: u32,
++ ) {
++ crate::pass_times::site(Location::caller());
++ // SAFETY: the caller's.
++ unsafe { (self.device).cmd_fill_buffer(command_buffer, buffer, offset, size, data) }
++ }
++
++ /// `vkCmdUpdateBuffer`, its caller's place noted.
++ ///
++ /// # Safety
++ ///
++ /// As `ash::Device::cmd_update_buffer`'s.
++ #[track_caller]
++ pub(crate) unsafe fn cmd_update_buffer(
++ &self,
++ command_buffer: vk::CommandBuffer,
++ buffer: vk::Buffer,
++ offset: vk::DeviceSize,
++ data: &[u8],
++ ) {
++ crate::pass_times::site(Location::caller());
++ // SAFETY: the caller's.
++ unsafe { (self.device).cmd_update_buffer(command_buffer, buffer, offset, data) }
++ }
++
++ /// `vkCmdClearColorImage`, its caller's place noted.
++ ///
++ /// # Safety
++ ///
++ /// As `ash::Device::cmd_clear_color_image`'s.
++ #[track_caller]
++ pub(crate) unsafe fn cmd_clear_color_image(
++ &self,
++ command_buffer: vk::CommandBuffer,
++ image: vk::Image,
++ layout: vk::ImageLayout,
++ color: &vk::ClearColorValue,
++ ranges: &[vk::ImageSubresourceRange],
++ ) {
++ crate::pass_times::site(Location::caller());
++ // SAFETY: the caller's.
++ unsafe { (self.device).cmd_clear_color_image(command_buffer, image, layout, color, ranges) }
++ }
++
++ /// `vkCmdClearDepthStencilImage`, its caller's place noted.
++ ///
++ /// # Safety
++ ///
++ /// As `ash::Device::cmd_clear_depth_stencil_image`'s.
++ #[track_caller]
++ pub(crate) unsafe fn cmd_clear_depth_stencil_image(
++ &self,
++ command_buffer: vk::CommandBuffer,
++ image: vk::Image,
++ layout: vk::ImageLayout,
++ value: &vk::ClearDepthStencilValue,
++ ranges: &[vk::ImageSubresourceRange],
++ ) {
++ crate::pass_times::site(Location::caller());
++ // SAFETY: the caller's.
++ unsafe {
++ (self.device).cmd_clear_depth_stencil_image(
++ command_buffer,
++ image,
++ layout,
++ value,
++ ranges,
++ )
++ }
++ }
++
++ /// `vkCmdBlitImage`, its caller's place noted.
++ ///
++ /// # Safety
++ ///
++ /// As `ash::Device::cmd_blit_image`'s.
++ #[track_caller]
++ pub(crate) unsafe fn cmd_blit_image(
++ &self,
++ command_buffer: vk::CommandBuffer,
++ src: vk::Image,
++ src_layout: vk::ImageLayout,
++ dst: vk::Image,
++ dst_layout: vk::ImageLayout,
++ regions: &[vk::ImageBlit],
++ filter: vk::Filter,
++ ) {
++ crate::pass_times::site(Location::caller());
++ // SAFETY: the caller's.
++ unsafe {
++ (self.device).cmd_blit_image(
++ command_buffer,
++ src,
++ src_layout,
++ dst,
++ dst_layout,
++ regions,
++ filter,
++ )
++ }
++ }
++
++ /// `vkCmdBeginRenderPass`, its caller's place noted.
++ ///
++ /// # Safety
++ ///
++ /// As `ash::Device::cmd_begin_render_pass`'s.
++ #[track_caller]
++ pub(crate) unsafe fn cmd_begin_render_pass(
++ &self,
++ command_buffer: vk::CommandBuffer,
++ begin: &vk::RenderPassBeginInfo<'_>,
++ contents: vk::SubpassContents,
++ ) {
++ crate::pass_times::site(Location::caller());
++ // SAFETY: the caller's.
++ unsafe { (self.device).cmd_begin_render_pass(command_buffer, begin, contents) }
++ }
++}
++
+ impl Deref for Vk {
+ type Target = ash::Device;
+
+diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs
+index 70a18c56..acc27e6b 100644
+--- a/crates/metal2vulkan-runtime/src/device/mod.rs
++++ b/crates/metal2vulkan-runtime/src/device/mod.rs
+@@ -451,6 +451,8 @@ pub(super) struct DeviceShared {
+ pub(super) residency: super::host_residency::Sweeper,
+ /// How its command buffers are timed on the GPU (`gpu_time.rs`).
+ pub(super) timing: Timing,
++ /// LOCAL (Atlas) diagnostic: the pass timer, where `M2V_PASS_TIMES` is set (`pass_times.rs`).
++ pub(super) pass_times: Option>,
+ /// Its Vulkan views may present an image in another component layout: it has no portability
+ /// subset, or the subset's `imageViewFormatReinterpretation` is enabled, by the runtime on a
+ /// device it made or, on an adopted one, by the consumer, who says so
+@@ -741,6 +743,10 @@ impl Drop for DeviceShared {
+ // Nor a timestamp slot: each command buffer gave its slot back as it finished, or
+ // with its state.
+ self.timing.release(self.vk());
++ // LOCAL (Atlas) diagnostic: the pass timer's pools (`pass_times.rs`).
++ if let Some(times) = &self.pass_times {
++ times.release(self.vk());
++ }
+ }
+ // Nor a kept barrier command buffer: the queues are idle.
+ self.scheduler.release_kept(self.vk());
+@@ -1825,6 +1831,8 @@ impl Device {
+ #[cfg(unix)]
+ residency: Default::default(),
+ timing,
++ // LOCAL (Atlas) diagnostic: the pass timer (`pass_times.rs`).
++ pass_times: crate::pass_times::DeviceTimes::new(timestamp_bits > 0, owned),
+ view_reinterpretation,
+ generated_commands,
+ host_image_copy,
+diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs
+index f4ecfa6c..5b217e85 100644
+--- a/crates/metal2vulkan-runtime/src/encoder.rs
++++ b/crates/metal2vulkan-runtime/src/encoder.rs
+@@ -428,6 +428,14 @@ impl EncoderCore {
+ if let Some(problem) = state.refusal() {
+ return Err(invalid(call, problem));
+ }
++ // LOCAL (Atlas) diagnostic: the pass timer's encoder (`pass_times.rs`).
++ crate::pass_times::encoder_opened(
++ command_buffer.device(),
++ command_buffer.command_queue(),
++ command_buffer.pass_times_key(),
++ &mut state.pass_times,
++ kind,
++ );
+ // The pool's primary begun ahead where it holds one (`spares.rs`).
+ let (raw, begun) = command_buffer.encoder_primary(&mut state)?;
+ let shared = command_buffer.device().shared();
+@@ -1058,6 +1066,8 @@ impl EncoderCore {
+ // SAFETY: as in `barrier`.
+ unsafe { barrier.record(device, raw) };
+ }
++ // LOCAL (Atlas) diagnostic: the program's command, to the pass timer (`pass_times.rs`).
++ let _scope = crate::pass_times::scope(crate::pass_times::Tag::Guest);
+ record(device, raw);
+ }
+
+diff --git a/crates/metal2vulkan-runtime/src/image_log.rs b/crates/metal2vulkan-runtime/src/image_log.rs
+new file mode 100644
+index 00000000..36639493
+--- /dev/null
++++ b/crates/metal2vulkan-runtime/src/image_log.rs
+@@ -0,0 +1,925 @@
++//! LOCAL (Atlas) diagnostic: the image census, `M2V_IMAGE_LOG=`, and the registry of the
++//! objects a render pass instance names, which the pass timer (`pass_times.rs`) labels its
++//! attachments from. Default off; the whole module can be dropped with its hooks (each marked
++//! `LOCAL (Atlas) diagnostic`).
++//!
++//! - **The switch** is read once. Unset (or empty), nothing is recorded, no line is formatted, and
++//! no Vulkan call is added. Set, the census appends to the file it names (made if missing).
++//! - **What the census writes.** One CSV line per event, every line the same columns
++//! ([`HEADER`]), written as it happens (a `write` per line: image creation is rare next to the
++//! work it serves, and the lines survive the process being killed):
++//! - `create`, per `VkImage` the runtime makes (`creation::image`, `creation::image_or_refusal`,
++//! the one door to `vkCreateImage`; the device's priming makes its own and is not logged): the
++//! image, its purpose (`api`: the program's call that made it where one is on the stack,
++//! `texture`, `heap-texture`, `buffer-texture`, `iosurface-plane`; `origin`: where the
++//! texture paths' image making was called from, with the texture's storage mode; `site`: the
++//! call of `creation::image` itself), format, extent, mip levels, array layers, samples,
++//! tiling (and the DRM format modifier or modifier list chained), usage, create flags, the
++//! chained `VkImageFormatListCreateInfo` (`-` where none is chained, else its view formats),
++//! the external memory handle types chained, any other structure chained, and the image's
++//! memory requirements (size, alignment, memory types; `vkGetImageMemoryRequirements`, not
++//! asked of a `DISJOINT` image).
++//! - `bind`, per `vkBindImageMemory` (`creation::bind_image`): the memory and offset, and what
++//! the memory is as the runtime allocated it (`creation::allocate_memory`): an import of host
++//! pages (`host-pages`), of a dma-buf (`dma-buf`) or another fd, an export, or its own, and
++//! whether dedicated to an image.
++//! - `destroy`, per `vkDestroyImage` (`release::object`).
++//! - **The registry** (kept while either switch is on): each image's extent, usage and purpose,
++//! each view's image and base level, each render pass's attachments (subpass 0's roles) and its
++//! making's site, each framebuffer's extent and views, and each memory's kind; entries go as
++//! their objects are released. A handle the driver reuses is registered again as it is made.
++
++use ash::vk;
++use ash::vk::Handle;
++use std::cell::Cell;
++use std::collections::HashMap;
++use std::fmt::Write as _;
++use std::io::Write as _;
++use std::panic::Location;
++use std::path::{Path, PathBuf};
++use std::sync::{Arc, LazyLock, Mutex, OnceLock};
++
++/// The census's columns, its file's first line.
++pub(crate) const HEADER: &str = "host_ns,event,image,api,origin,site,storage,format,width,height,\
++depth,mips,layers,samples,tiling,drm_modifier,usage,flags,format_list,external,chained,mem_size,\
++mem_align,mem_types,bind_memory,bind_offset,memory_kind\n";
++
++/// The census file, where `M2V_IMAGE_LOG` names one: read once.
++fn census_path() -> Option<&'static Path> {
++ static PATH: OnceLock> = OnceLock::new();
++ PATH.get_or_init(|| {
++ std::env::var_os("M2V_IMAGE_LOG")
++ .filter(|value| !value.is_empty())
++ .map(PathBuf::from)
++ })
++ .as_deref()
++}
++
++/// Whether the census is on.
++pub(crate) fn census_on() -> bool {
++ census_path().is_some()
++}
++
++/// Whether the registry is kept: either diagnostic is on.
++pub(crate) fn registry_on() -> bool {
++ census_on() || crate::pass_times::on()
++}
++
++/// The host's clock now, in nanoseconds (`CLOCK_MONOTONIC_RAW`, the runtime's GPU times' clock).
++#[cfg(not(unix))]
++pub(crate) fn host_ns() -> u64 {
++ 0
++}
++
++/// The host's clock now, in nanoseconds (`CLOCK_MONOTONIC_RAW`, the runtime's GPU times' clock).
++#[cfg(unix)]
++pub(crate) fn host_ns() -> u64 {
++ let mut now = libc::timespec {
++ tv_sec: 0,
++ tv_nsec: 0,
++ };
++ // SAFETY: `now` is a valid timespec for the call to fill.
++ if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut now) } != 0 {
++ return 0;
++ }
++ (now.tv_sec as u64) * 1_000_000_000 + now.tv_nsec as u64
++}
++
++/// `file:line` of `at`, its path from the crate's `src/` on.
++pub(crate) fn short(at: &Location<'_>) -> String {
++ let file = at.file();
++ let file = match file.rfind("/src/") {
++ Some(i) => &file[i + 5..],
++ None => file,
++ };
++ format!("{file}:{}", at.line())
++}
++
++/// The bits of `raw` by their registry names in `known`, less `prefix` and `_BIT`, `|`-joined;
++/// bits no name holds in hex; `0` for none. (`ash` is built without its `Debug` impls.)
++fn flag_names<'a>(raw: u32, known: impl Iterator- , prefix: &str) -> String {
++ if raw == 0 {
++ return "0".to_owned();
++ }
++ let mut names = Vec::new();
++ let mut rest = raw;
++ for (bit, name) in known {
++ if bit.count_ones() == 1 && rest & bit != 0 {
++ names.push(name.trim_start_matches(prefix).replace("_BIT", ""));
++ rest &= !bit;
++ }
++ }
++ if rest != 0 {
++ names.push(format!("0x{rest:x}"));
++ }
++ names.join("|")
++}
++
++/// `format`'s registry name less `VK_FORMAT_`, else its number.
++pub(crate) fn format_name(format: vk::Format) -> String {
++ match metal2vulkan::vk::Format::from_raw(format.as_raw()).name() {
++ Some(name) => name.trim_start_matches("VK_FORMAT_").to_owned(),
++ None => format!("format{}", format.as_raw()),
++ }
++}
++
++fn tiling_name(tiling: vk::ImageTiling) -> String {
++ match metal2vulkan::vk::ImageTiling::from_raw(tiling.as_raw()).name() {
++ Some(name) => name.trim_start_matches("VK_IMAGE_TILING_").to_owned(),
++ None => format!("tiling{}", tiling.as_raw()),
++ }
++}
++
++fn usage_names(usage: vk::ImageUsageFlags) -> String {
++ let known = metal2vulkan::vk::ImageUsageFlags::KNOWN.iter();
++ flag_names(
++ usage.as_raw(),
++ known.map(|(v, n)| (v.as_raw(), *n)),
++ "VK_IMAGE_USAGE_",
++ )
++}
++
++fn create_names(flags: vk::ImageCreateFlags) -> String {
++ let known = metal2vulkan::vk::ImageCreateFlags::KNOWN.iter();
++ flag_names(
++ flags.as_raw(),
++ known.map(|(v, n)| (v.as_raw(), *n)),
++ "VK_IMAGE_CREATE_",
++ )
++}
++
++fn external_names(types: vk::ExternalMemoryHandleTypeFlags) -> String {
++ use vk::ExternalMemoryHandleTypeFlags as T;
++ let known = [
++ (T::OPAQUE_FD, "OPAQUE_FD"),
++ (T::OPAQUE_WIN32, "OPAQUE_WIN32"),
++ (T::OPAQUE_WIN32_KMT, "OPAQUE_WIN32_KMT"),
++ (T::D3D11_TEXTURE, "D3D11_TEXTURE"),
++ (T::D3D11_TEXTURE_KMT, "D3D11_TEXTURE_KMT"),
++ (T::D3D12_HEAP, "D3D12_HEAP"),
++ (T::D3D12_RESOURCE, "D3D12_RESOURCE"),
++ (T::HOST_ALLOCATION_EXT, "HOST_ALLOCATION"),
++ (
++ T::HOST_MAPPED_FOREIGN_MEMORY_EXT,
++ "HOST_MAPPED_FOREIGN_MEMORY",
++ ),
++ (T::DMA_BUF_EXT, "DMA_BUF"),
++ ];
++ flag_names(
++ types.as_raw(),
++ known.iter().map(|(v, n)| (v.as_raw(), *n)),
++ "",
++ )
++}
++
++fn load_name(op: vk::AttachmentLoadOp) -> String {
++ match op {
++ vk::AttachmentLoadOp::LOAD => "LOAD".into(),
++ vk::AttachmentLoadOp::CLEAR => "CLEAR".into(),
++ vk::AttachmentLoadOp::DONT_CARE => "DONT_CARE".into(),
++ vk::AttachmentLoadOp::NONE_KHR => "NONE".into(),
++ other => format!("load{}", other.as_raw()),
++ }
++}
++
++fn store_name(op: vk::AttachmentStoreOp) -> String {
++ match op {
++ vk::AttachmentStoreOp::STORE => "STORE".into(),
++ vk::AttachmentStoreOp::DONT_CARE => "DONT_CARE".into(),
++ vk::AttachmentStoreOp::NONE => "NONE".into(),
++ other => format!("store{}", other.as_raw()),
++ }
++}
++
++/// What the registry holds of an image.
++pub(crate) struct ImageEntry {
++ extent: vk::Extent3D,
++ usage: vk::ImageUsageFlags,
++ /// Its purpose, short: the program's call, else the texture path's caller, else the site.
++ purpose: Arc
,
++}
++
++/// A render pass attachment's role in subpass 0.
++#[derive(Clone, Copy)]
++enum Role {
++ Color(u32),
++ Resolve(u32),
++ DepthStencil,
++ DepthStencilResolve,
++ Input(u32),
++ Other(u32),
++}
++
++/// A render pass's attachment, as made.
++#[derive(Clone, Copy)]
++struct PassAttachment {
++ role: Role,
++ format: vk::Format,
++ samples: u32,
++ load: vk::AttachmentLoadOp,
++ store: vk::AttachmentStoreOp,
++ stencil_load: vk::AttachmentLoadOp,
++ stencil_store: vk::AttachmentStoreOp,
++}
++
++/// A render pass, as made.
++struct PassEntry {
++ attachments: Vec,
++ site: &'static Location<'static>,
++}
++
++/// A framebuffer, as made.
++struct FramebufferEntry {
++ width: u32,
++ height: u32,
++ views: Vec,
++}
++
++/// The objects registered.
++#[derive(Default)]
++struct Registry {
++ images: HashMap>,
++ views: HashMap,
++ passes: HashMap>,
++ framebuffers: HashMap>,
++ memories: HashMap,
++}
++
++static REGISTRY: LazyLock> = LazyLock::new(Mutex::default);
++
++fn registry() -> std::sync::MutexGuard<'static, Registry> {
++ REGISTRY
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++}
++
++thread_local! {
++ /// The program's call making a texture on this thread, the outermost.
++ static API: Cell> = const { Cell::new(None) };
++ /// Where the texture paths' image making was called from, and the texture's storage mode.
++ static ORIGIN: Cell , &'static str)>> =
++ const { Cell::new(None) };
++}
++
++/// A purpose set on this thread until dropped ([`api`], [`origin`]).
++pub(crate) struct PurposeGuard(Option);
++
++enum Restore {
++ Api(Option<&'static str>),
++ Origin(Option<(&'static Location<'static>, &'static str)>),
++}
++
++impl Drop for PurposeGuard {
++ fn drop(&mut self) {
++ match self.0.take() {
++ Some(Restore::Api(previous)) => API.with(|api| api.set(previous)),
++ Some(Restore::Origin(previous)) => ORIGIN.with(|origin| origin.set(previous)),
++ None => {}
++ }
++ }
++}
++
++/// The program's call `name` makes textures on this thread until the guard drops: the census's
++/// `api`. The outermost call holds.
++pub(crate) fn api(name: &'static str) -> PurposeGuard {
++ if !registry_on() {
++ return PurposeGuard(None);
++ }
++ let previous = API.with(|api| api.get());
++ if previous.is_some() {
++ return PurposeGuard(None);
++ }
++ API.with(|api| api.set(Some(name)));
++ PurposeGuard(Some(Restore::Api(previous)))
++}
++
++/// The texture paths' image making called from `at`, for a texture of `storage` mode, until the
++/// guard drops: the census's `origin`. The innermost holds.
++pub(crate) fn origin(at: &'static Location<'static>, storage: &'static str) -> PurposeGuard {
++ if !registry_on() {
++ return PurposeGuard(None);
++ }
++ let previous = ORIGIN.with(|origin| origin.replace(Some((at, storage))));
++ PurposeGuard(Some(Restore::Origin(previous)))
++}
++
++/// The census's line writer.
++static CENSUS: Mutex> = Mutex::new(None);
++
++/// Append `line` to the census, opening it (and heading a new one) at the first.
++fn census_line(line: &str) {
++ let Some(path) = census_path() else {
++ return;
++ };
++ let mut file = CENSUS
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
++ if file.is_none() {
++ let opened = std::fs::OpenOptions::new()
++ .create(true)
++ .append(true)
++ .open(path);
++ match opened {
++ Ok(mut opened) => {
++ if opened.metadata().map(|m| m.len() == 0).unwrap_or(false) {
++ let _ = opened.write_all(HEADER.as_bytes());
++ }
++ *file = Some(opened);
++ }
++ Err(error) => {
++ eprintln!("metal2vulkan: M2V_IMAGE_LOG: cannot open {path:?}: {error}");
++ return;
++ }
++ }
++ }
++ if let Some(file) = file.as_mut() {
++ let _ = file.write_all(line.as_bytes());
++ }
++}
++
++/// The structures chained to `next`, as a walk of their headers.
++///
++/// # Safety
++///
++/// `next` is null or a valid chain of Vulkan structures.
++unsafe fn chain(mut next: *const std::ffi::c_void) -> Vec<*const vk::BaseInStructure<'static>> {
++ let mut all = Vec::new();
++ while !next.is_null() {
++ let base = next.cast::>();
++ all.push(base);
++ // SAFETY: the caller's.
++ next = unsafe { (*base).p_next }.cast();
++ }
++ all
++}
++
++/// A slice of `count` from `ptr`, empty where null.
++///
++/// # Safety
++///
++/// `ptr` is null or points at `count` valid values.
++unsafe fn slice<'a, T>(ptr: *const T, count: u32) -> &'a [T] {
++ match ptr.is_null() || count == 0 {
++ true => &[],
++ // SAFETY: the caller's.
++ false => unsafe { std::slice::from_raw_parts(ptr, count as usize) },
++ }
++}
++
++/// Note `image`, made of `info` by `device` at `site` (`creation::image`): registered, and in the
++/// census its `create` line.
++///
++/// # Safety
++///
++/// `info` and its chain are valid; `image` is `device`'s, live.
++pub(crate) unsafe fn image_made(
++ device: &ash::Device,
++ info: &vk::ImageCreateInfo<'_>,
++ image: vk::Image,
++ site: &'static Location<'static>,
++) {
++ if !registry_on() {
++ return;
++ }
++ let api = API.with(|api| api.get());
++ let origin = ORIGIN.with(|origin| origin.get());
++ let site = short(site);
++ let origin_at = origin.map(|(at, _)| short(at));
++ let purpose: Arc = match (api, &origin_at) {
++ (Some(api), _) => api.into(),
++ (None, Some(at)) => format!("<{at}").into(),
++ (None, None) => site.clone().into(),
++ };
++ let entry = ImageEntry {
++ extent: info.extent,
++ usage: info.usage,
++ purpose,
++ };
++ registry().images.insert(image.as_raw(), Arc::new(entry));
++ if !census_on() {
++ return;
++ }
++ let mut format_list = "-".to_owned();
++ let mut external = "0".to_owned();
++ let mut drm_modifier = "-".to_owned();
++ let mut chained = Vec::new();
++ // SAFETY: the caller's: `info`'s chain is valid.
++ for base in unsafe { chain(info.p_next) } {
++ // SAFETY: each is a valid structure of its `s_type`.
++ unsafe {
++ match (*base).s_type {
++ vk::StructureType::IMAGE_FORMAT_LIST_CREATE_INFO => {
++ let list = &*base.cast::>();
++ let formats = slice(list.p_view_formats, list.view_format_count);
++ let names: Vec = formats.iter().map(|f| format_name(*f)).collect();
++ format_list = format!("{}:{}", formats.len(), names.join("|"));
++ }
++ vk::StructureType::EXTERNAL_MEMORY_IMAGE_CREATE_INFO => {
++ let ext = &*base.cast::>();
++ external = external_names(ext.handle_types);
++ }
++ vk::StructureType::IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT => {
++ let explicit =
++ &*base.cast::>();
++ drm_modifier = format!(
++ "0x{:x}:planes={}",
++ explicit.drm_format_modifier, explicit.drm_format_modifier_plane_count
++ );
++ }
++ vk::StructureType::IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT => {
++ let list =
++ &*base.cast::>();
++ let all = slice(list.p_drm_format_modifiers, list.drm_format_modifier_count);
++ let names: Vec = all.iter().map(|m| format!("0x{m:x}")).collect();
++ drm_modifier = format!("list:{}", names.join("|"));
++ }
++ other => chained.push(format!("sType{}", other.as_raw())),
++ }
++ }
++ }
++ let requirements = match info.flags.contains(vk::ImageCreateFlags::DISJOINT) {
++ true => None,
++ // SAFETY: `image` is `device`'s, live, not disjoint.
++ false => Some(unsafe { device.get_image_memory_requirements(image) }),
++ };
++ crate::exit_guard::called(crate::exit_guard::Call::GetImageMemoryRequirements);
++ let (size, align, types) = match requirements {
++ Some(r) => (
++ r.size.to_string(),
++ r.alignment.to_string(),
++ format!("0x{:x}", r.memory_type_bits),
++ ),
++ None => ("-".into(), "-".into(), "-".into()),
++ };
++ let chained = match chained.is_empty() {
++ true => "-".to_owned(),
++ false => chained.join("|").replace(',', ";"),
++ };
++ let (origin_at, storage) = match origin {
++ Some((_, storage)) => (origin_at.unwrap_or_default(), storage),
++ None => ("-".to_owned(), "-"),
++ };
++ let mut line = String::with_capacity(256);
++ let _ = writeln!(
++ line,
++ "{},create,0x{:x},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},,,",
++ host_ns(),
++ image.as_raw(),
++ api.unwrap_or("-"),
++ origin_at,
++ site,
++ storage,
++ format_name(info.format),
++ info.extent.width,
++ info.extent.height,
++ info.extent.depth,
++ info.mip_levels,
++ info.array_layers,
++ info.samples.as_raw(),
++ tiling_name(info.tiling),
++ drm_modifier,
++ usage_names(info.usage),
++ create_names(info.flags),
++ format_list,
++ external,
++ chained,
++ size,
++ align,
++ types,
++ );
++ census_line(&line);
++}
++
++/// Note `memory`, allocated of `info` (`creation::allocate_memory`): its kind registered.
++///
++/// # Safety
++///
++/// `info` and its chain are valid.
++pub(crate) unsafe fn memory_made(info: &vk::MemoryAllocateInfo<'_>, memory: vk::DeviceMemory) {
++ if !census_on() {
++ return;
++ }
++ let mut kind = "own";
++ let mut dedicated = false;
++ // SAFETY: the caller's.
++ for base in unsafe { chain(info.p_next) } {
++ // SAFETY: each is a valid structure of its `s_type`.
++ unsafe {
++ match (*base).s_type {
++ vk::StructureType::IMPORT_MEMORY_HOST_POINTER_INFO_EXT => kind = "host-pages",
++ vk::StructureType::IMPORT_MEMORY_FD_INFO_KHR => {
++ let fd = &*base.cast::>();
++ kind = match fd.handle_type {
++ vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT => "dma-buf",
++ _ => "fd-import",
++ };
++ }
++ vk::StructureType::EXPORT_MEMORY_ALLOCATE_INFO if kind == "own" => {
++ kind = "own-export"
++ }
++ vk::StructureType::MEMORY_DEDICATED_ALLOCATE_INFO => {
++ let info = &*base.cast::>();
++ dedicated = info.image != vk::Image::null();
++ }
++ _ => {}
++ }
++ }
++ }
++ let kind = match (kind, dedicated) {
++ ("own", true) => "own-dedicated",
++ ("own-export", true) => "own-export-dedicated",
++ ("dma-buf", true) => "dma-buf-dedicated",
++ ("host-pages", true) => "host-pages-dedicated",
++ (kind, _) => kind,
++ };
++ registry().memories.insert(memory.as_raw(), kind);
++}
++
++/// Note `image` bound to `memory` at `offset` (`creation::bind_image`): the census's `bind` line.
++pub(crate) fn image_bound(image: vk::Image, memory: vk::DeviceMemory, offset: vk::DeviceSize) {
++ if !census_on() {
++ return;
++ }
++ let kind = registry()
++ .memories
++ .get(&memory.as_raw())
++ .copied()
++ .unwrap_or("unknown");
++ let line = format!(
++ "{},bind,0x{:x},,,,,,,,,,,,,,,,,,,,,,0x{:x},{},{}\n",
++ host_ns(),
++ image.as_raw(),
++ memory.as_raw(),
++ offset,
++ kind
++ );
++ census_line(&line);
++}
++
++/// Note `view`, made of `info` (`creation::image_view`).
++pub(crate) fn view_made(info: &vk::ImageViewCreateInfo<'_>, view: vk::ImageView) {
++ if !registry_on() {
++ return;
++ }
++ let entry = (info.image.as_raw(), info.subresource_range.base_mip_level);
++ registry().views.insert(view.as_raw(), entry);
++}
++
++/// Note `pass`, made of `info` (`creation::render_pass`) at `site`.
++///
++/// # Safety
++///
++/// `info` is valid.
++pub(crate) unsafe fn render_pass_made(
++ info: &vk::RenderPassCreateInfo<'_>,
++ pass: vk::RenderPass,
++ site: &'static Location<'static>,
++) {
++ if !crate::pass_times::on() {
++ return;
++ }
++ // SAFETY: the caller's.
++ let (descriptions, subpasses) = unsafe {
++ (
++ slice(info.p_attachments, info.attachment_count),
++ slice(info.p_subpasses, info.subpass_count),
++ )
++ };
++ let mut roles: Vec> = vec![None; descriptions.len()];
++ if let Some(subpass) = subpasses.first() {
++ // SAFETY: the caller's: subpass 0's references are valid.
++ unsafe {
++ let colors = slice(subpass.p_color_attachments, subpass.color_attachment_count);
++ note_roles(&mut roles, colors.iter().map(|r| r.attachment), Role::Color);
++ if !subpass.p_resolve_attachments.is_null() {
++ let resolves = slice(
++ subpass.p_resolve_attachments,
++ subpass.color_attachment_count,
++ );
++ note_roles(
++ &mut roles,
++ resolves.iter().map(|r| r.attachment),
++ Role::Resolve,
++ );
++ }
++ let inputs = slice(subpass.p_input_attachments, subpass.input_attachment_count);
++ note_roles(&mut roles, inputs.iter().map(|r| r.attachment), Role::Input);
++ if let Some(depth) = subpass.p_depth_stencil_attachment.as_ref() {
++ note_role(&mut roles, depth.attachment, Role::DepthStencil);
++ }
++ }
++ }
++ let attachments = descriptions
++ .iter()
++ .enumerate()
++ .map(|(i, d)| PassAttachment {
++ role: roles[i].unwrap_or(Role::Other(i as u32)),
++ format: d.format,
++ samples: d.samples.as_raw(),
++ load: d.load_op,
++ store: d.store_op,
++ stencil_load: d.stencil_load_op,
++ stencil_store: d.stencil_store_op,
++ })
++ .collect();
++ let entry = PassEntry { attachments, site };
++ registry().passes.insert(pass.as_raw(), Arc::new(entry));
++}
++
++/// Note `pass`, made of `info` (`creation::render_pass2`) at `site`.
++///
++/// # Safety
++///
++/// `info` and its subpasses' chains are valid.
++pub(crate) unsafe fn render_pass2_made(
++ info: &vk::RenderPassCreateInfo2<'_>,
++ pass: vk::RenderPass,
++ site: &'static Location<'static>,
++) {
++ if !crate::pass_times::on() {
++ return;
++ }
++ // SAFETY: the caller's.
++ let (descriptions, subpasses) = unsafe {
++ (
++ slice(info.p_attachments, info.attachment_count),
++ slice(info.p_subpasses, info.subpass_count),
++ )
++ };
++ let mut roles: Vec > = vec![None; descriptions.len()];
++ if let Some(subpass) = subpasses.first() {
++ // SAFETY: the caller's: subpass 0's references and chain are valid.
++ unsafe {
++ let colors = slice(subpass.p_color_attachments, subpass.color_attachment_count);
++ note_roles(&mut roles, colors.iter().map(|r| r.attachment), Role::Color);
++ if !subpass.p_resolve_attachments.is_null() {
++ let resolves = slice(
++ subpass.p_resolve_attachments,
++ subpass.color_attachment_count,
++ );
++ note_roles(
++ &mut roles,
++ resolves.iter().map(|r| r.attachment),
++ Role::Resolve,
++ );
++ }
++ let inputs = slice(subpass.p_input_attachments, subpass.input_attachment_count);
++ note_roles(&mut roles, inputs.iter().map(|r| r.attachment), Role::Input);
++ if let Some(depth) = subpass.p_depth_stencil_attachment.as_ref() {
++ note_role(&mut roles, depth.attachment, Role::DepthStencil);
++ }
++ for base in chain(subpass.p_next) {
++ if (*base).s_type == vk::StructureType::SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE {
++ let resolve =
++ &*base.cast::>();
++ if let Some(at) = resolve.p_depth_stencil_resolve_attachment.as_ref() {
++ note_role(&mut roles, at.attachment, Role::DepthStencilResolve);
++ }
++ }
++ }
++ }
++ }
++ let attachments = descriptions
++ .iter()
++ .enumerate()
++ .map(|(i, d)| PassAttachment {
++ role: roles[i].unwrap_or(Role::Other(i as u32)),
++ format: d.format,
++ samples: d.samples.as_raw(),
++ load: d.load_op,
++ store: d.store_op,
++ stencil_load: d.stencil_load_op,
++ stencil_store: d.stencil_store_op,
++ })
++ .collect();
++ let entry = PassEntry { attachments, site };
++ registry().passes.insert(pass.as_raw(), Arc::new(entry));
++}
++
++/// Give each attachment of `indices` its role, `role` of its place among them.
++fn note_roles(
++ roles: &mut [Option],
++ indices: impl Iterator- ,
++ role: impl Fn(u32) -> Role,
++) {
++ for (place, index) in indices.enumerate() {
++ note_role(roles, index, role(place as u32));
++ }
++}
++
++/// Give attachment `index` `role`, where it is one and has none yet.
++fn note_role(roles: &mut [Option
], index: u32, role: Role) {
++ if let Some(slot) = roles.get_mut(index as usize) {
++ slot.get_or_insert(role);
++ }
++}
++
++/// Note `framebuffer`, made of `info` (`creation::framebuffer`).
++///
++/// # Safety
++///
++/// `info` is valid.
++pub(crate) unsafe fn framebuffer_made(
++ info: &vk::FramebufferCreateInfo<'_>,
++ framebuffer: vk::Framebuffer,
++) {
++ if !crate::pass_times::on() {
++ return;
++ }
++ let imageless = info.flags.contains(vk::FramebufferCreateFlags::IMAGELESS);
++ let views = match imageless {
++ true => Vec::new(),
++ // SAFETY: the caller's.
++ false => unsafe { slice(info.p_attachments, info.attachment_count) }
++ .iter()
++ .map(|view| view.as_raw())
++ .collect(),
++ };
++ let entry = FramebufferEntry {
++ width: info.width,
++ height: info.height,
++ views,
++ };
++ registry()
++ .framebuffers
++ .insert(framebuffer.as_raw(), Arc::new(entry));
++}
++
++/// Forget the object `raw` released by `call` (`release::object`); an image's release is the
++/// census's `destroy` line.
++pub(crate) fn released(call: crate::exit_guard::Call, raw: u64) {
++ use crate::exit_guard::Call;
++ if !registry_on() {
++ return;
++ }
++ let mut registry = registry();
++ match call {
++ Call::DestroyImage => {
++ registry.images.remove(&raw);
++ drop(registry);
++ if census_on() {
++ census_line(&format!(
++ "{},destroy,0x{raw:x},,,,,,,,,,,,,,,,,,,,,,,,\n",
++ host_ns()
++ ));
++ }
++ }
++ Call::DestroyImageView => {
++ registry.views.remove(&raw);
++ }
++ Call::DestroyRenderPass => {
++ registry.passes.remove(&raw);
++ }
++ Call::DestroyFramebuffer => {
++ registry.framebuffers.remove(&raw);
++ }
++ Call::FreeMemory => {
++ registry.memories.remove(&raw);
++ }
++ _ => {}
++ }
++}
++
++/// One attachment of a render pass instance, resolved as it begins.
++struct Attached {
++ pass: PassAttachment,
++ extent: Option<(u32, u32)>,
++ memoryless: bool,
++ purpose: Option>,
++}
++
++/// What the pass timer records of a render pass instance's objects as it begins: its attachments,
++/// each with its image's extent, whether it is memoryless (a transient attachment) and its purpose,
++/// and where its pass was made. Formatted only once its command buffer completed ([`format`]).
++pub(crate) struct PassLabel {
++ attached: Vec,
++ site: Option<&'static Location<'static>>,
++ extent: (u32, u32),
++}
++
++impl PassLabel {
++ /// Where the pass was made, short.
++ pub(crate) fn site(&self) -> Option {
++ self.site.map(short)
++ }
++
++ /// The attachments, `|`-joined: each its role, format, extent, samples, load/store (and the
++ /// stencil's where it has one), `memoryless`, and `@` its image's purpose.
++ pub(crate) fn format(&self) -> String {
++ let mut out = String::new();
++ for (i, a) in self.attached.iter().enumerate() {
++ if i > 0 {
++ out.push('|');
++ }
++ let p = &a.pass;
++ let _ = match p.role {
++ Role::Color(j) => write!(out, "c{j}"),
++ Role::Resolve(j) => write!(out, "r{j}"),
++ Role::DepthStencil => write!(out, "ds"),
++ Role::DepthStencilResolve => write!(out, "dsr"),
++ Role::Input(j) => write!(out, "in{j}"),
++ Role::Other(j) => write!(out, "a{j}"),
++ };
++ let (w, h) = a.extent.unwrap_or(self.extent);
++ let _ = write!(
++ out,
++ ":{}:{w}x{h}:s{}:{}/{}",
++ format_name(p.format),
++ p.samples,
++ load_name(p.load),
++ store_name(p.store)
++ );
++ if matches!(p.role, Role::DepthStencil | Role::DepthStencilResolve)
++ && has_stencil(p.format)
++ {
++ let _ = write!(
++ out,
++ ":st={}/{}",
++ load_name(p.stencil_load),
++ store_name(p.stencil_store)
++ );
++ }
++ if a.memoryless {
++ out.push_str(":memoryless");
++ }
++ if let Some(purpose) = &a.purpose {
++ let _ = write!(out, "@{purpose}");
++ }
++ }
++ if out.is_empty() {
++ out.push('-');
++ }
++ out.replace(',', ";")
++ }
++}
++
++/// Whether `format` has a stencil aspect.
++fn has_stencil(format: vk::Format) -> bool {
++ matches!(
++ format,
++ vk::Format::S8_UINT
++ | vk::Format::D16_UNORM_S8_UINT
++ | vk::Format::D24_UNORM_S8_UINT
++ | vk::Format::D32_SFLOAT_S8_UINT
++ )
++}
++
++/// The label of a render pass instance of `pass` and `framebuffer`, of `area`, as it begins.
++pub(crate) fn pass_label(
++ pass: vk::RenderPass,
++ framebuffer: vk::Framebuffer,
++ area: vk::Extent2D,
++) -> PassLabel {
++ let registry = registry();
++ let pass = registry.passes.get(&pass.as_raw()).cloned();
++ let framebuffer = registry.framebuffers.get(&framebuffer.as_raw()).cloned();
++ let extent = framebuffer
++ .as_ref()
++ .map_or((area.width, area.height), |f| (f.width, f.height));
++ let Some(pass) = pass else {
++ return PassLabel {
++ attached: Vec::new(),
++ site: None,
++ extent,
++ };
++ };
++ let attached = pass
++ .attachments
++ .iter()
++ .enumerate()
++ .map(|(i, attachment)| {
++ let view = framebuffer.as_ref().and_then(|f| f.views.get(i)).copied();
++ let image = view.and_then(|v| registry.views.get(&v)).copied();
++ let entry = image.and_then(|(image, mip)| {
++ registry
++ .images
++ .get(&image)
++ .map(|entry| (Arc::clone(entry), mip))
++ });
++ match entry {
++ Some((entry, mip)) => Attached {
++ pass: *attachment,
++ extent: Some((
++ (entry.extent.width >> mip).max(1),
++ (entry.extent.height >> mip).max(1),
++ )),
++ memoryless: entry
++ .usage
++ .contains(vk::ImageUsageFlags::TRANSIENT_ATTACHMENT),
++ purpose: Some(Arc::clone(&entry.purpose)),
++ },
++ None => Attached {
++ pass: *attachment,
++ extent: None,
++ memoryless: false,
++ purpose: None,
++ },
++ }
++ })
++ .collect();
++ PassLabel {
++ attached,
++ site: Some(pass.site),
++ extent,
++ }
++}
+diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs
+index ca076571..9cdcc6a5 100644
+--- a/crates/metal2vulkan-runtime/src/lib.rs
++++ b/crates/metal2vulkan-runtime/src/lib.rs
+@@ -125,6 +125,8 @@ mod host_rt;
+ #[cfg(unix)]
+ mod host_shared_pointers;
+ mod image_barrier;
++// LOCAL (Atlas) diagnostic: the image census and object registry (M2V_IMAGE_LOG).
++mod image_log;
+ mod image_plan;
+ mod in_place;
+ mod in_place_check;
+@@ -158,6 +160,8 @@ mod nan_clear;
+ mod neutral;
+ mod noted_apart;
+ mod owned_kernel;
++// LOCAL (Atlas) diagnostic: the pass timer (M2V_PASS_TIMES).
++mod pass_times;
+ mod pending_dispatch;
+ mod pipeline;
+ mod pixel_format_info;
+diff --git a/crates/metal2vulkan-runtime/src/pass_times.rs b/crates/metal2vulkan-runtime/src/pass_times.rs
+new file mode 100644
+index 00000000..ca083acb
+--- /dev/null
++++ b/crates/metal2vulkan-runtime/src/pass_times.rs
+@@ -0,0 +1,1194 @@
++//! LOCAL (Atlas) diagnostic: the pass timer, `M2V_PASS_TIMES=`. GPU timestamps around each
++//! unit of GPU work the runtime records, read once its command buffer completed, one CSV line per
++//! unit appended to `/passes-.csv`. Default off; the whole module can be dropped with its
++//! hooks (each marked `LOCAL (Atlas) diagnostic`).
++//!
++//! - **The switch** is read once. Unset (or empty), nothing changes: no query pool, no command,
++//! no line; each hook is one check of a `OnceLock`.
++//! - **The window.** Set, a command buffer is captured only where the file `/on` exists as the
++//! runtime begins recording it (its first encoder's opening, or its first `VkCommandBuffer`
++//! handed out): checked once per command buffer. `touch /on` opens a window, `rm` closes
++//! it; the first command buffer begun after the close flushes the lines held.
++//! - **Where the timestamps go.** Every routed command passes the recorder's entry points
++//! (`recorder/thunks.rs`), whatever the runtime records it from (an encoder, its own kernels, a
++//! pass's steps, a commit's work, the lowering thread), so the units are cut there, on each
++//! `VkCommandBuffer` the captured command buffer handed out: a render pass instance
++//! (`vkCmdBeginRenderPass` to `vkCmdEndRenderPass`, each instance of a split pass its own); a run
++//! of dispatches; a run of transfer commands (copies, blits, clears, fills, updates, query result
++//! copies). A run goes on while the commands are of its class and its label (below) and the
++//! barriers and binds between are part of it; another unit, or the `VkCommandBuffer`'s end, ends
++//! it. Each unit writes a `vkCmdWriteTimestamp` at `ALL_COMMANDS` before its first command and
++//! after its last, into two queries of a block of the diagnostic's own pools ([`BLOCK`] queries,
++//! [`POOL_BLOCKS`] blocks a pool), each block reset on the host as a command buffer takes it
++//! (`hostQueryReset`, which every device the runtime made enables), else by a
++//! `vkCmdResetQueryPool` before the unit's start. The scheduler's own command buffers of
++//! barriers (and the runtime's GPU-time timestamps) are no unit.
++//! - **Labels**, all known where the unit is recorded:
++//! - `kind`: `render-pass` (an instance of a render encoder's pass: inline first, inline after a
++//! split, or in secondaries; `render/inline_first.rs`, `inline_splits.rs`, `pass_steps.rs`),
++//! `render-pass-resolve` (the pass's instance of no draws that resolves it), `pass:`
++//! (another render pass the runtime records, at the place it began it where that goes through
++//! the device's `Vk` door, else where its `VkRenderPass` was made); `guest-` (a
++//! command of the program's encoder: `EncoderCore::command_*`, a pending dispatch), suffixed
++//! with its class where that is not the encoder's own (`guest-blit:compute`); else
++//! `internal:/`, the place that recorded its first command where it went
++//! through the device's `Vk` door (`device/functions.rs`), else the command alone.
++//! - `cb_label`: the command queue's label (no program's label reaches the runtime: Metal's
++//! `label` of a command buffer and of an encoder are not part of Reims's guest protocol, and
++//! the runtime keeps neither). `encoder_label`: the encoder's kind and place in its command
++//! buffer (`render#3`), for the `VkCommandBuffer`s handed out while it was the last opened.
++//! - `attachments`, for a render pass instance: each attachment's role in subpass 0
++//! (`c0`, `r0`, `ds`, `dsr`, `in0`), format, extent, samples, load/store ops (the stencil's
++//! too), `memoryless` where its image is a transient attachment, and `@` its image's purpose
++//! (`image_log.rs`: the program's call that made it, else the place inside the runtime).
++//! - `split`, for a render encoder's instance: `i/n` among the encoder's instances, the split
++//! cause that began it (`work_counts::Split`; `first` for the first, `run` past the causes
++//! counted), how it records (`inline`, `inline-split`, `secondary`), and for the first, why
++//! the pass's first instance did not record inline (`work_counts::NotInline`).
++//! - `draws`: the draws of a render pass instance (its secondaries' too), the dispatches of a
++//! run of them, the commands of a run of transfers.
++//! - **Read as it completed**, in the completion turn after its GPU times (`completion.rs`):
++//! `vkGetQueryPoolResults` per block, without waiting, a unit whose timestamps are not both
++//! available (a command buffer that failed or never ran) has no `gpu_ns`. `host_ns` is the
++//! unit's start on the host's clock (`CLOCK_MONOTONIC_RAW`): placed by the calibration pair the
++//! command buffer's GPU times took where the device has one, else from its placed GPU start.
++//! The lines are held and appended every [`FLUSH_LINES`] lines or [`FLUSH_AFTER`] at the next
++//! completion, as a window closes, and as the device drops.
++
++use crate::command_buffer::CommandBuffer;
++use crate::exit_guard::{self, Call};
++use crate::gpu_time::{GpuClock, Pair};
++use crate::image_log::{self, PassLabel};
++use crate::used_resources::EncoderKind;
++use crate::work_counts::{NotInline, Split};
++use crate::{CommandQueue, Device};
++use ash::vk;
++use ash::vk::Handle;
++use std::cell::Cell;
++use std::collections::HashMap;
++use std::fmt::Write as _;
++use std::io::Write as _;
++use std::panic::Location;
++use std::path::{Path, PathBuf};
++use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
++use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock, Weak};
++use std::time::{Duration, Instant};
++
++/// Queries of a block a command buffer takes at once: 32 units.
++const BLOCK: u32 = 64;
++
++/// Blocks of a query pool.
++const POOL_BLOCKS: u32 = 64;
++
++/// Lines held before they are appended.
++const FLUSH_LINES: usize = 256;
++
++/// Time after which the next completion appends the lines held.
++const FLUSH_AFTER: Duration = Duration::from_millis(500);
++
++/// The CSV's columns, its first line.
++const HEADER: &str =
++ "host_ns,cb_seq,unit_seq,kind,cb_label,encoder_label,attachments,split,draws,gpu_ns\n";
++
++/// The directory `M2V_PASS_TIMES` names: read once.
++fn dir() -> Option<&'static Path> {
++ static DIR: OnceLock> = OnceLock::new();
++ DIR.get_or_init(|| {
++ std::env::var_os("M2V_PASS_TIMES")
++ .filter(|value| !value.is_empty())
++ .map(PathBuf::from)
++ })
++ .as_deref()
++}
++
++/// Whether the pass timer is on.
++#[inline]
++pub(crate) fn on() -> bool {
++ dir().is_some()
++}
++
++fn lock(mutex: &Mutex) -> MutexGuard<'_, T> {
++ mutex
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++}
++
++/// The captures alive: the entry points do nothing more while there is none.
++static LIVE: AtomicUsize = AtomicUsize::new(0);
++
++/// The next captured command buffer's number.
++static NEXT_SEQ: AtomicU64 = AtomicU64::new(0);
++
++/// Each `VkCommandBuffer` a captured command buffer handed out, to its capture.
++static RAWS: LazyLock>>> = LazyLock::new(Mutex::default);
++
++/// Each captured command buffer, by its address, to its capture.
++static BY_KEY: LazyLock>>> = LazyLock::new(Mutex::default);
++
++/// What the code recording a unit says it is, on its thread ([`scope`]).
++#[derive(Clone, Copy, Debug, PartialEq, Eq)]
++pub(crate) enum Tag {
++ /// A command of the program's encoder.
++ Guest,
++ /// A render pass instance of a render encoder's pass, begun at the given place.
++ Pass(PassAt),
++}
++
++/// Where a render encoder's pass instance began.
++#[derive(Clone, Copy, Debug, PartialEq, Eq)]
++pub(crate) enum PassAt {
++ /// Its first instance, inline (`render/inline_first.rs`).
++ Inline,
++ /// An instance after a split, inline (`render/inline_splits.rs`).
++ InlineSplit,
++ /// An instance whose draws a secondary holds (`render/pass_steps.rs`).
++ Instance,
++ /// The instance of no draws that resolves the pass (`render/pass_steps.rs`).
++ Resolve,
++}
++
++thread_local! {
++ static SCOPE: Cell> = const { Cell::new(None) };
++ static SITE: Cell >> = const { Cell::new(None) };
++}
++
++/// A tag set on this thread until dropped ([`scope`]).
++pub(crate) struct Scope(Option >);
++
++impl Drop for Scope {
++ fn drop(&mut self) {
++ if let Some(previous) = self.0.take() {
++ SCOPE.with(|scope| scope.set(previous));
++ }
++ }
++}
++
++/// Tag what this thread records with `tag` until the scope drops: the innermost holds.
++pub(crate) fn scope(tag: Tag) -> Scope {
++ if !on() {
++ return Scope(None);
++ }
++ Scope(Some(SCOPE.with(|scope| scope.replace(Some(tag)))))
++}
++
++/// The place `at` records the next command on this thread (`Vk`'s commands,
++/// `device/functions.rs`); the command's entry point takes it.
++#[inline]
++pub(crate) fn site(at: &'static Location<'static>) {
++ if on() {
++ SITE.with(|site| site.set(Some(at)));
++ }
++}
++
++/// A unit's class.
++#[derive(Clone, Copy, Debug, PartialEq, Eq)]
++pub(crate) enum Class {
++ Pass,
++ Compute,
++ Transfer,
++}
++
++/// A slot's own timestamp commands (`recorder/thunks.rs`), which the units record through: into a
++/// deferred command buffer's log as any command, else the driver's.
++#[derive(Clone, Copy)]
++pub(crate) struct Stamps {
++ pub(crate) write:
++ unsafe extern "system" fn(vk::CommandBuffer, vk::PipelineStageFlags, vk::QueryPool, u32),
++ pub(crate) reset: unsafe extern "system" fn(vk::CommandBuffer, vk::QueryPool, u32, u32),
++}
++
++/// A block of queries.
++#[derive(Clone, Copy)]
++struct Block {
++ pool: vk::QueryPool,
++ first: u32,
++}
++
++#[derive(Default)]
++struct Blocks {
++ pools: Vec,
++ free: Vec,
++ /// The device refused a pool: no more are asked for.
++ refused: bool,
++}
++
++/// The lines held, and where they go.
++struct Out {
++ path: PathBuf,
++ file: Option,
++ held: String,
++ lines: usize,
++ flushed: Instant,
++}
++
++impl Out {
++ fn flush(&mut self) {
++ self.flushed = Instant::now();
++ if self.held.is_empty() {
++ return;
++ }
++ if self.file.is_none() {
++ let opened = std::fs::OpenOptions::new()
++ .create(true)
++ .append(true)
++ .open(&self.path);
++ match opened {
++ Ok(mut file) => {
++ if file.metadata().map(|m| m.len() == 0).unwrap_or(false) {
++ let _ = file.write_all(HEADER.as_bytes());
++ }
++ self.file = Some(file);
++ }
++ Err(error) => {
++ eprintln!(
++ "metal2vulkan: M2V_PASS_TIMES: cannot open {:?}: {error}",
++ self.path
++ );
++ self.held.clear();
++ self.lines = 0;
++ return;
++ }
++ }
++ }
++ if let Some(file) = self.file.as_mut() {
++ let _ = file.write_all(self.held.as_bytes());
++ }
++ self.held.clear();
++ self.lines = 0;
++ }
++}
++
++/// A device's pass timer: its query pools and its lines (`DeviceShared::pass_times`).
++pub(crate) struct DeviceTimes {
++ host_reset: bool,
++ blocks: Mutex,
++ out: Mutex,
++}
++
++impl DeviceTimes {
++ /// The pass timer of a device whose queue family writes timestamps where `timestamps`, which
++ /// resets queries on the host where `host_reset`: `None` while the switch is off.
++ pub(crate) fn new(timestamps: bool, host_reset: bool) -> Option> {
++ let dir = dir()?;
++ if !timestamps {
++ eprintln!("metal2vulkan: M2V_PASS_TIMES: the device's queue writes no timestamps");
++ return None;
++ }
++ let path = dir.join(format!("passes-{}.csv", std::process::id()));
++ Some(Arc::new(DeviceTimes {
++ host_reset,
++ blocks: Mutex::default(),
++ out: Mutex::new(Out {
++ path,
++ file: None,
++ held: String::new(),
++ lines: 0,
++ flushed: Instant::now(),
++ }),
++ }))
++ }
++
++ /// A block of queries, reset: a free one, else one of a pool made now; `None` once the device
++ /// refused a pool.
++ ///
++ /// # Safety
++ ///
++ /// `device` is the live device of this timer.
++ unsafe fn take(&self, device: &ash::Device) -> Option {
++ let mut blocks = lock(&self.blocks);
++ let block = match blocks.free.pop() {
++ Some(block) => block,
++ None => {
++ if blocks.refused {
++ return None;
++ }
++ let info = vk::QueryPoolCreateInfo::default()
++ .query_type(vk::QueryType::TIMESTAMP)
++ .query_count(BLOCK * POOL_BLOCKS);
++ // SAFETY: the caller's; `info` is valid.
++ let made = unsafe { device.create_query_pool(&info, None) };
++ exit_guard::called(Call::CreateQueryPool);
++ let Ok(pool) = made else {
++ blocks.refused = true;
++ eprintln!("metal2vulkan: M2V_PASS_TIMES: the device refused a query pool");
++ return None;
++ };
++ blocks.pools.push(pool);
++ let rest = (1..POOL_BLOCKS).rev().map(|i| Block {
++ pool,
++ first: i * BLOCK,
++ });
++ blocks.free.extend(rest);
++ Block { pool, first: 0 }
++ }
++ };
++ drop(blocks);
++ if self.host_reset {
++ // SAFETY: the device enables `hostQueryReset`; the block is free: its last holder's
++ // work completed, or never ran, and nothing else uses it.
++ unsafe { device.reset_query_pool(block.pool, block.first, BLOCK) };
++ exit_guard::called(Call::ResetQueryPool);
++ }
++ Some(block)
++ }
++
++ fn give_back(&self, blocks: Vec) {
++ if !blocks.is_empty() {
++ lock(&self.blocks).free.extend(blocks);
++ }
++ }
++
++ fn append(&self, text: &str, lines: usize) {
++ let mut out = lock(&self.out);
++ out.held.push_str(text);
++ out.lines += lines;
++ if out.lines >= FLUSH_LINES || out.flushed.elapsed() >= FLUSH_AFTER {
++ out.flush();
++ }
++ }
++
++ /// Append the lines held.
++ pub(crate) fn flush(&self) {
++ lock(&self.out).flush();
++ }
++
++ /// Release the pools, at the device's teardown, its lines appended first.
++ ///
++ /// # Safety
++ ///
++ /// `device` is the live device of this timer, and none of its command buffers is pending.
++ pub(crate) unsafe fn release(&self, device: &ash::Device) {
++ self.flush();
++ let pools = {
++ let mut blocks = lock(&self.blocks);
++ blocks.free.clear();
++ blocks.refused = true;
++ std::mem::take(&mut blocks.pools)
++ };
++ for pool in pools {
++ // SAFETY: the caller's.
++ unsafe { crate::release::object(device, pool) };
++ }
++ }
++}
++
++impl Drop for DeviceTimes {
++ fn drop(&mut self) {
++ self.flush();
++ }
++}
++
++/// A command buffer's capture, its state's (`State::pass_times`): undecided until it begins
++/// recording, then captured or not.
++#[derive(Default)]
++pub(crate) struct CbSlot {
++ decided: bool,
++ capture: Option>,
++}
++
++impl CbSlot {
++ /// Its capture, taken to be read.
++ pub(crate) fn take(&mut self) -> Option> {
++ self.capture.take()
++ }
++}
++
++/// What an encoder of a captured command buffer told.
++struct EncoderNote {
++ kind: EncoderKind,
++ causes: Vec,
++ not_inline: Option,
++}
++
++/// A `VkCommandBuffer` of a captured command buffer.
++#[derive(Default)]
++struct RawState {
++ /// The encoder last opened as it was handed out.
++ encoder: Option,
++ /// Its unit open.
++ open: Option,
++ /// A secondary's draws not yet in a unit.
++ pending_draws: u32,
++ /// The render pass instance that executed it, a secondary.
++ parent: Option,
++}
++
++/// A unit of work.
++struct Unit {
++ class: Class,
++ tag: Option,
++ site: Option<&'static Location<'static>>,
++ command: &'static str,
++ encoder: Option,
++ label: Option,
++ count: u32,
++ /// Its block's index in the capture's and its start query's offset in it.
++ block: usize,
++ offset: u32,
++}
++
++#[derive(Default)]
++struct CaptureState {
++ units: Vec,
++ blocks: Vec,
++ used: u32,
++ out_of_queries: bool,
++ encoders: Vec,
++ current: Option,
++ raws: HashMap,
++}
++
++/// A captured command buffer.
++pub(crate) struct Capture {
++ times: Arc,
++ device: Device,
++ seq: u64,
++ key: usize,
++ queue_label: String,
++ state: Mutex,
++}
++
++impl Drop for Capture {
++ fn drop(&mut self) {
++ let me: *const Capture = self;
++ let state = self
++ .state
++ .get_mut()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
++ {
++ let mut raws = lock(&RAWS);
++ for raw in state.raws.keys() {
++ if raws.get(raw).is_some_and(|w| std::ptr::eq(w.as_ptr(), me)) {
++ raws.remove(raw);
++ }
++ }
++ }
++ {
++ let mut keys = lock(&BY_KEY);
++ if keys
++ .get(&self.key)
++ .is_some_and(|w| std::ptr::eq(w.as_ptr(), me))
++ {
++ keys.remove(&self.key);
++ }
++ }
++ self.times.give_back(std::mem::take(&mut state.blocks));
++ LIVE.fetch_sub(1, Ordering::Relaxed);
++ }
++}
++
++impl CaptureState {
++ /// Two queries for a unit: its block's index and the start's offset.
++ fn queries(&mut self, capture: &Capture) -> Option<(usize, u32)> {
++ if self.out_of_queries {
++ return None;
++ }
++ if self.blocks.is_empty() || self.used + 2 > BLOCK {
++ let device = capture.device.shared().vk();
++ // SAFETY: the capture's device is live.
++ match unsafe { capture.times.take(device) } {
++ Some(block) => {
++ self.blocks.push(block);
++ self.used = 0;
++ }
++ None => {
++ self.out_of_queries = true;
++ return None;
++ }
++ }
++ }
++ let offset = self.used;
++ self.used += 2;
++ Some((self.blocks.len() - 1, offset))
++ }
++}
++
++/// Begin `slot`'s capture where it is undecided: a capture where the device's timer is on and
++/// `/on` exists.
++fn decide<'a>(
++ slot: &'a mut CbSlot,
++ device: &Device,
++ queue: &CommandQueue,
++ key: usize,
++) -> Option<&'a Arc> {
++ if !slot.decided {
++ slot.decided = true;
++ slot.capture = start(device, queue, key);
++ }
++ slot.capture.as_ref()
++}
++
++fn start(device: &Device, queue: &CommandQueue, key: usize) -> Option> {
++ let times = device.shared().pass_times.as_ref()?;
++ let dir = dir()?;
++ if !dir.join("on").exists() {
++ times.flush();
++ return None;
++ }
++ let label = queue.label().unwrap_or_else(|| "-".to_owned());
++ let capture = Arc::new(Capture {
++ times: Arc::clone(times),
++ device: device.clone(),
++ seq: NEXT_SEQ.fetch_add(1, Ordering::Relaxed),
++ key,
++ queue_label: label.replace(',', ";"),
++ state: Mutex::default(),
++ });
++ LIVE.fetch_add(1, Ordering::Relaxed);
++ lock(&BY_KEY).insert(key, Arc::downgrade(&capture));
++ Some(capture)
++}
++
++/// An encoder of `kind` opens on the command buffer at `key` of `device` and `queue`, whose capture
++/// `slot` holds (`EncoderCore::open`): `VkCommandBuffer`s handed out from now on are its.
++pub(crate) fn encoder_opened(
++ device: &Device,
++ queue: &CommandQueue,
++ key: usize,
++ slot: &mut CbSlot,
++ kind: EncoderKind,
++) {
++ if !on() {
++ return;
++ }
++ let Some(capture) = decide(slot, device, queue, key) else {
++ return;
++ };
++ let mut state = lock(&capture.state);
++ state.current = Some(state.encoders.len() as u32);
++ state.encoders.push(EncoderNote {
++ kind,
++ causes: Vec::new(),
++ not_inline: None,
++ });
++}
++
++/// The command buffer at `key` of `device` and `queue`, whose capture `slot` holds, handed out
++/// `raw` (`CommandBufferShared::allocate_deferred` and kin).
++pub(crate) fn handed_out(
++ device: &Device,
++ queue: &CommandQueue,
++ key: usize,
++ slot: &mut CbSlot,
++ raw: vk::CommandBuffer,
++) {
++ if !on() {
++ return;
++ }
++ let Some(capture) = decide(slot, device, queue, key) else {
++ // A handle a capture still alive handed out before goes to no capture now.
++ if LIVE.load(Ordering::Relaxed) > 0 {
++ lock(&RAWS).remove(&raw.as_raw());
++ }
++ return;
++ };
++ {
++ let mut state = lock(&capture.state);
++ let encoder = state.current;
++ state.raws.insert(
++ raw.as_raw(),
++ RawState {
++ encoder,
++ ..RawState::default()
++ },
++ );
++ }
++ lock(&RAWS).insert(raw.as_raw(), Arc::downgrade(capture));
++}
++
++/// The capture of the command buffer at `key`.
++fn by_key(key: usize) -> Option> {
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return None;
++ }
++ lock(&BY_KEY).get(&key)?.upgrade()
++}
++
++/// A render encoder of `command_buffer` split its pass for `cause` (`render.rs`).
++pub(crate) fn note_split(command_buffer: &CommandBuffer, cause: Split) {
++ if !on() {
++ return;
++ }
++ let Some(capture) = by_key(command_buffer.pass_times_key()) else {
++ return;
++ };
++ let mut state = lock(&capture.state);
++ if let Some(at) = state.current {
++ if let Some(note) = state.encoders.get_mut(at as usize) {
++ note.causes.push(cause);
++ }
++ }
++}
++
++/// A render encoder of `command_buffer` did not record its pass's first instance inline, for
++/// `why` (`render.rs`, `render/inline_first.rs`).
++pub(crate) fn note_not_inline(command_buffer: &CommandBuffer, why: NotInline) {
++ if !on() {
++ return;
++ }
++ let Some(capture) = by_key(command_buffer.pass_times_key()) else {
++ return;
++ };
++ let mut state = lock(&capture.state);
++ if let Some(at) = state.current {
++ if let Some(note) = state.encoders.get_mut(at as usize) {
++ note.not_inline.get_or_insert(why);
++ }
++ }
++}
++
++/// The capture `raw` was handed out by.
++fn capture_of(raw: vk::CommandBuffer) -> Option> {
++ lock(&RAWS).get(&raw.as_raw())?.upgrade()
++}
++
++/// Open a unit on `cb`: its start written.
++///
++/// # Safety
++///
++/// `cb` is recording outside a render pass instance, by the caller alone; `st` are its slot's.
++unsafe fn open(
++ st: Stamps,
++ cb: vk::CommandBuffer,
++ capture: &Capture,
++ state: &mut CaptureState,
++ mut unit: Unit,
++) -> Option {
++ let (block, offset) = state.queries(capture)?;
++ let Block { pool, first } = state.blocks[block];
++ // SAFETY: the caller's; the queries are the capture's, reset on the host or here.
++ unsafe {
++ if !capture.times.host_reset {
++ (st.reset)(cb, pool, first + offset, 2);
++ }
++ (st.write)(
++ cb,
++ vk::PipelineStageFlags::ALL_COMMANDS,
++ pool,
++ first + offset,
++ );
++ }
++ unit.block = block;
++ unit.offset = offset;
++ state.units.push(unit);
++ Some(state.units.len() - 1)
++}
++
++/// Close unit `index` on `cb`: its end written.
++///
++/// # Safety
++///
++/// As [`open`]'s.
++unsafe fn close(st: Stamps, cb: vk::CommandBuffer, state: &CaptureState, index: usize) {
++ let unit = &state.units[index];
++ let Block { pool, first } = state.blocks[unit.block];
++ // SAFETY: the caller's.
++ unsafe {
++ (st.write)(
++ cb,
++ vk::PipelineStageFlags::ALL_COMMANDS,
++ pool,
++ first + unit.offset + 1,
++ )
++ };
++}
++
++/// Before `vkCmdBeginRenderPass` of `begin` on `cb`: the open run closed, a render pass unit
++/// opened.
++///
++/// # Safety
++///
++/// As the command's: `cb` recording outside a render pass, `begin` valid; `st` are its slot's.
++pub(crate) unsafe fn begin_pass(
++ st: Stamps,
++ cb: vk::CommandBuffer,
++ begin: *const vk::RenderPassBeginInfo<'_>,
++) {
++ let site = SITE.with(Cell::take);
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let Some(capture) = capture_of(cb) else {
++ return;
++ };
++ let tag = SCOPE.with(Cell::get);
++ // SAFETY: the caller's.
++ let label = unsafe { begin.as_ref() }.map(|begin| {
++ image_log::pass_label(
++ begin.render_pass,
++ begin.framebuffer,
++ begin.render_area.extent,
++ )
++ });
++ let mut guard = lock(&capture.state);
++ let state = &mut *guard;
++ let Some(raw) = state.raws.get_mut(&cb.as_raw()) else {
++ return;
++ };
++ let encoder = raw.encoder;
++ if let Some(open) = raw.open.take() {
++ // SAFETY: the caller's.
++ unsafe { close(st, cb, state, open) };
++ }
++ let unit = Unit {
++ class: Class::Pass,
++ tag,
++ site,
++ command: "vkCmdBeginRenderPass",
++ encoder,
++ label,
++ count: 0,
++ block: 0,
++ offset: 0,
++ };
++ // SAFETY: the caller's.
++ let opened = unsafe { open(st, cb, &capture, state, unit) };
++ if let Some(raw) = state.raws.get_mut(&cb.as_raw()) {
++ raw.open = opened;
++ }
++}
++
++/// After `vkCmdEndRenderPass` on `cb`: its render pass unit closed.
++///
++/// # Safety
++///
++/// As the command's; `st` are its slot's.
++pub(crate) unsafe fn end_pass(st: Stamps, cb: vk::CommandBuffer) {
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let Some(capture) = capture_of(cb) else {
++ return;
++ };
++ let mut guard = lock(&capture.state);
++ let state = &mut *guard;
++ let Some(open) = state.raws.get_mut(&cb.as_raw()).and_then(|r| r.open.take()) else {
++ return;
++ };
++ // SAFETY: the caller's: the pass ended.
++ unsafe { close(st, cb, state, open) };
++}
++
++/// Before `vkEndCommandBuffer` of `cb`: its open unit closed.
++///
++/// # Safety
++///
++/// As the command's; `st` are its slot's.
++pub(crate) unsafe fn end(st: Stamps, cb: vk::CommandBuffer) {
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let Some(capture) = capture_of(cb) else {
++ return;
++ };
++ let mut guard = lock(&capture.state);
++ let state = &mut *guard;
++ let Some(open) = state.raws.get_mut(&cb.as_raw()).and_then(|r| r.open.take()) else {
++ return;
++ };
++ // SAFETY: the caller's.
++ unsafe { close(st, cb, state, open) };
++}
++
++/// Before a dispatch or transfer `command` of `class` on `cb`: counted in the open run where it
++/// is of its class and label, else the run closed and another opened.
++///
++/// # Safety
++///
++/// As the command's: `cb` recording outside a render pass instance; `st` are its slot's.
++pub(crate) unsafe fn work(st: Stamps, cb: vk::CommandBuffer, class: Class, command: &'static str) {
++ let site = SITE.with(Cell::take);
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let Some(capture) = capture_of(cb) else {
++ return;
++ };
++ let tag = SCOPE.with(Cell::get);
++ let mut guard = lock(&capture.state);
++ let state = &mut *guard;
++ let Some(raw) = state.raws.get_mut(&cb.as_raw()) else {
++ return;
++ };
++ let encoder = raw.encoder;
++ // The program's own commands of its encoder's class run on whatever records them; other
++ // work runs by its place.
++ let kind = encoder
++ .and_then(|e| state.encoders.get(e as usize))
++ .map(|n| n.kind);
++ let natural = tag == Some(Tag::Guest) && natural(kind, class);
++ if let Some(at) = raw.open {
++ let unit = &mut state.units[at];
++ let same = unit.class == class
++ && unit.tag == tag
++ && unit.encoder == encoder
++ && (natural || (unit.site == site && unit.command == command));
++ // A command inside a render pass instance (none of these may be) counts in it.
++ if same || unit.class == Class::Pass {
++ unit.count += 1;
++ return;
++ }
++ raw.open = None;
++ // SAFETY: the caller's.
++ unsafe { close(st, cb, state, at) };
++ }
++ let unit = Unit {
++ class,
++ tag,
++ site,
++ command,
++ encoder,
++ label: None,
++ count: 1,
++ block: 0,
++ offset: 0,
++ };
++ // SAFETY: the caller's.
++ let opened = unsafe { open(st, cb, &capture, state, unit) };
++ if let Some(raw) = state.raws.get_mut(&cb.as_raw()) {
++ raw.open = opened;
++ }
++}
++
++/// Before a draw on `cb`: counted in its render pass instance, or the one that executes it.
++pub(crate) fn draw(cb: vk::CommandBuffer) {
++ if LIVE.load(Ordering::Relaxed) == 0 {
++ return;
++ }
++ let Some(capture) = capture_of(cb) else {
++ return;
++ };
++ let mut guard = lock(&capture.state);
++ let state = &mut *guard;
++ let Some(raw) = state.raws.get_mut(&cb.as_raw()) else {
++ return;
++ };
++ match raw.open.or(raw.parent) {
++ Some(at) => state.units[at].count += 1,
++ None => raw.pending_draws += 1,
++ }
++}
++
++/// Before `vkCmdExecuteGeneratedCommandsEXT` on `cb`: a draw inside a render pass instance, else a
++/// dispatch.
++///
++/// # Safety
++///
++/// As [`work`]'s.
++pub(crate) unsafe fn generated(st: Stamps, cb: vk::CommandBuffer, command: &'static str) {
++ let in_pass = LIVE.load(Ordering::Relaxed) > 0
++ && capture_of(cb).is_some_and(|capture| {
++ let state = lock(&capture.state);
++ let open = state.raws.get(&cb.as_raw()).and_then(|r| r.open);
++ let in_pass = open.is_some_and(|at| state.units[at].class == Class::Pass);
++ in_pass
++ });
++ match in_pass {
++ true => {
++ SITE.with(Cell::take);
++ draw(cb);
++ }
++ // SAFETY: the caller's.
++ false => unsafe { work(st, cb, Class::Compute, command) },
++ }
++}
++
++/// Before `vkCmdExecuteCommands` of `count` secondaries at `buffers` on `cb`: their draws counted
++/// in its render pass instance, and their later ones.
++///
++/// # Safety
++///
++/// `buffers` points at `count` command buffers.
++pub(crate) unsafe fn execute(cb: vk::CommandBuffer, count: u32, buffers: *const vk::CommandBuffer) {
++ if LIVE.load(Ordering::Relaxed) == 0 || buffers.is_null() {
++ return;
++ }
++ let Some(capture) = capture_of(cb) else {
++ return;
++ };
++ let mut guard = lock(&capture.state);
++ let state = &mut *guard;
++ let Some(at) = state.raws.get(&cb.as_raw()).and_then(|r| r.open) else {
++ return;
++ };
++ // SAFETY: the caller's.
++ let secondaries = unsafe { std::slice::from_raw_parts(buffers, count as usize) };
++ let mut draws = 0;
++ for secondary in secondaries {
++ if let Some(raw) = state.raws.get_mut(&secondary.as_raw()) {
++ draws += std::mem::take(&mut raw.pending_draws);
++ raw.parent = Some(at);
++ }
++ }
++ state.units[at].count += draws;
++}
++
++/// The routed commands' hooks (`recorder/thunks.rs`): `before` a command is logged or called, and
++/// `after`; a command named nowhere here has none.
++macro_rules! hook {
++ (before cmd_begin_render_pass, $st:expr, $cb:ident, $begin:ident, $contents:ident) => {
++ if $crate::pass_times::on() {
++ unsafe { $crate::pass_times::begin_pass($st, $cb, $begin) }
++ }
++ };
++ (after cmd_end_render_pass, $st:expr, $cb:ident) => {
++ if $crate::pass_times::on() {
++ unsafe { $crate::pass_times::end_pass($st, $cb) }
++ }
++ };
++ (before end_command_buffer, $st:expr, $cb:ident) => {
++ if $crate::pass_times::on() {
++ unsafe { $crate::pass_times::end($st, $cb) }
++ }
++ };
++ (before cmd_execute_commands, $st:expr, $cb:ident, $count:ident, $buffers:ident) => {
++ if $crate::pass_times::on() {
++ unsafe { $crate::pass_times::execute($cb, $count, $buffers) }
++ }
++ };
++ (before cmd_execute_generated_commands, $st:expr, $cb:ident $(, $a:ident)*) => {
++ if $crate::pass_times::on() {
++ unsafe {
++ $crate::pass_times::generated($st, $cb, "vkCmdExecuteGeneratedCommandsEXT")
++ }
++ }
++ };
++ (before cmd_draw, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw $cb)
++ };
++ (before cmd_draw_indexed, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw $cb)
++ };
++ (before cmd_draw_indirect, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw $cb)
++ };
++ (before cmd_draw_indexed_indirect, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw $cb)
++ };
++ (before cmd_draw_mesh_tasks, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw $cb)
++ };
++ (before cmd_draw_mesh_tasks_indirect, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw $cb)
++ };
++ (before cmd_draw_mesh_tasks_indirect_count, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@draw $cb)
++ };
++ (before cmd_dispatch, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Compute, "vkCmdDispatch")
++ };
++ (before cmd_dispatch_indirect, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Compute, "vkCmdDispatchIndirect")
++ };
++ (before cmd_preprocess_generated_commands, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Compute, "vkCmdPreprocessGeneratedCommandsEXT")
++ };
++ (before cmd_copy_buffer, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdCopyBuffer")
++ };
++ (before cmd_copy_image, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdCopyImage")
++ };
++ (before cmd_blit_image, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdBlitImage")
++ };
++ (before cmd_copy_buffer_to_image, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdCopyBufferToImage")
++ };
++ (before cmd_copy_image_to_buffer, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdCopyImageToBuffer")
++ };
++ (before cmd_update_buffer, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdUpdateBuffer")
++ };
++ (before cmd_fill_buffer, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdFillBuffer")
++ };
++ (before cmd_clear_color_image, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdClearColorImage")
++ };
++ (before cmd_clear_depth_stencil_image, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdClearDepthStencilImage")
++ };
++ (before cmd_copy_query_pool_results, $st:expr, $cb:ident $(, $a:ident)*) => {
++ $crate::pass_times::hook!(@work $st, $cb, Transfer, "vkCmdCopyQueryPoolResults")
++ };
++ (@draw $cb:ident) => {
++ if $crate::pass_times::on() {
++ $crate::pass_times::draw($cb)
++ }
++ };
++ (@work $st:expr, $cb:ident, $class:ident, $name:literal) => {
++ if $crate::pass_times::on() {
++ unsafe { $crate::pass_times::work($st, $cb, $crate::pass_times::Class::$class, $name) }
++ }
++ };
++ ($phase:ident $command:ident, $($rest:tt)*) => {};
++}
++pub(crate) use hook;
++
++/// Where a completed command buffer's units are placed on the host's clock ([`read`]).
++pub(crate) struct Placement<'a> {
++ /// The device's clock.
++ pub(crate) clock: Option<&'a GpuClock>,
++ /// The calibration pair its GPU times took.
++ pub(crate) pair: Option,
++ /// Its GPU start's timestamp and host time, where read and placed.
++ pub(crate) start: Option<(u64, u64)>,
++ /// The host time its completion was seen.
++ pub(crate) completed: u64,
++}
++
++/// Whether a command of `class` is one an encoder of `kind` is made for.
++fn natural(kind: Option, class: Class) -> bool {
++ matches!(
++ (kind, class),
++ (Some(EncoderKind::Compute), Class::Compute) | (Some(EncoderKind::Blit), Class::Transfer)
++ )
++}
++
++/// The encoder kind's name.
++fn kind_name(kind: EncoderKind) -> &'static str {
++ match kind {
++ EncoderKind::Blit => "blit",
++ EncoderKind::Compute => "compute",
++ EncoderKind::Render => "render",
++ EncoderKind::ResourceState => "resource-state",
++ }
++}
++
++/// Read `capture`'s units, its command buffer completed, and append their lines: in the
++/// completion turn, inside its section (`command_buffer/mod.rs`, `read_pass_times`).
++pub(crate) fn read(capture: Arc, placement: Placement<'_>) {
++ let state = lock(&capture.state);
++ if state.units.is_empty() {
++ return;
++ }
++ let device = capture.device.shared().vk();
++ // Each block's queries: value and availability.
++ let mut values: Vec> = Vec::with_capacity(state.blocks.len());
++ for block in &state.blocks {
++ let mut results = vec![[0u64; 2]; BLOCK as usize];
++ // SAFETY: the block's queries were reset, and those written were written by work that
++ // completed; 64-bit values with availability, two words each.
++ let read = unsafe {
++ device.get_query_pool_results(
++ block.pool,
++ block.first,
++ &mut results,
++ vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WITH_AVAILABILITY,
++ )
++ };
++ exit_guard::called(Call::GetQueryPoolResults);
++ if !matches!(read, Ok(()) | Err(vk::Result::NOT_READY)) {
++ results.iter_mut().for_each(|r| *r = [0, 0]);
++ }
++ values.push(results);
++ }
++ let value = |block: usize, query: u32| {
++ let [value, available] = values[block][query as usize];
++ (available != 0).then_some(value)
++ };
++ let place = |ticks: u64| match (placement.clock, placement.pair, placement.start) {
++ (Some(clock), Some(pair), _) => clock.place(pair, ticks),
++ (Some(clock), None, Some((start, host))) => host + clock.duration(start, ticks),
++ _ => placement.completed,
++ };
++ // Each encoder's render pass instances, for `i/n`.
++ let instance = |unit: &Unit| match unit.tag {
++ Some(Tag::Pass(at)) => unit.class == Class::Pass && at != PassAt::Resolve,
++ _ => false,
++ };
++ let mut totals: HashMap, u32> = HashMap::new();
++ for unit in state.units.iter().filter(|u| instance(u)) {
++ *totals.entry(unit.encoder).or_default() += 1;
++ }
++ let mut counted: HashMap , u32> = HashMap::new();
++ let mut out = String::with_capacity(state.units.len() * 160);
++ for (index, unit) in state.units.iter().enumerate() {
++ let begin = value(unit.block, unit.offset);
++ let end = value(unit.block, unit.offset + 1);
++ let gpu = match (begin, end, placement.clock) {
++ (Some(begin), Some(end), Some(clock)) => clock.duration(begin, end).to_string(),
++ _ => String::new(),
++ };
++ let host = begin.map_or(placement.completed, place);
++ let note = unit.encoder.and_then(|e| state.encoders.get(e as usize));
++ let encoder = match (unit.encoder, note) {
++ (Some(e), Some(note)) => format!("{}#{e}", kind_name(note.kind)),
++ _ => "-".to_owned(),
++ };
++ let kind = match (unit.class, unit.tag) {
++ (Class::Pass, Some(Tag::Pass(PassAt::Resolve))) => "render-pass-resolve".to_owned(),
++ (Class::Pass, Some(Tag::Pass(_))) => "render-pass".to_owned(),
++ (Class::Pass, _) => {
++ let made = unit.label.as_ref().and_then(PassLabel::site);
++ let at = unit.site.map(image_log::short).or(made);
++ format!("pass:{}", at.as_deref().unwrap_or("?"))
++ }
++ (class, Some(Tag::Guest)) => {
++ let encoder = note.map_or("?", |n| kind_name(n.kind));
++ let what = match class {
++ Class::Compute => "compute",
++ _ => "transfer",
++ };
++ match (natural(note.map(|n| n.kind), class), unit.site) {
++ (true, _) => format!("guest-{encoder}"),
++ (false, Some(at)) => format!(
++ "guest-{encoder}:{what}@{}/{}",
++ image_log::short(at),
++ unit.command
++ ),
++ (false, None) => format!("guest-{encoder}:{what}/{}", unit.command),
++ }
++ }
++ (_, _) => match unit.site {
++ Some(at) => format!("internal:{}/{}", image_log::short(at), unit.command),
++ None => format!("internal:{}", unit.command),
++ },
++ };
++ let attachments = unit
++ .label
++ .as_ref()
++ .map_or_else(|| "-".to_owned(), PassLabel::format);
++ let split = match unit.tag {
++ _ if instance(unit) => {
++ let n = totals.get(&unit.encoder).copied().unwrap_or(1);
++ let i = {
++ let i = counted.entry(unit.encoder).or_default();
++ *i += 1;
++ *i
++ };
++ let cause = match i {
++ 1 => "first".to_owned(),
++ _ => note
++ .and_then(|n| n.causes.get(i as usize - 2))
++ .map_or_else(|| "run".to_owned(), |c| format!("{c:?}")),
++ };
++ let records = match unit.tag {
++ Some(Tag::Pass(PassAt::Inline)) => "inline",
++ Some(Tag::Pass(PassAt::InlineSplit)) => "inline-split",
++ _ => "secondary",
++ };
++ let not_inline = match (i, note.and_then(|n| n.not_inline)) {
++ (1, Some(why)) => format!(";not-inline={why:?}"),
++ _ => String::new(),
++ };
++ format!("{i}/{n}:{cause};{records}{not_inline}")
++ }
++ Some(Tag::Pass(PassAt::Resolve)) => "resolve".to_owned(),
++ _ => "-".to_owned(),
++ };
++ let _ = writeln!(
++ out,
++ "{host},{},{index},{kind},{},{encoder},{attachments},{},{},{gpu}",
++ capture.seq,
++ capture.queue_label,
++ split.replace(',', ";"),
++ unit.count,
++ );
++ }
++ let lines = state.units.len();
++ drop(state);
++ capture.times.append(&out, lines);
++}
+diff --git a/crates/metal2vulkan-runtime/src/pending_dispatch.rs b/crates/metal2vulkan-runtime/src/pending_dispatch.rs
+index b79bb1de..39e17ba3 100644
+--- a/crates/metal2vulkan-runtime/src/pending_dispatch.rs
++++ b/crates/metal2vulkan-runtime/src/pending_dispatch.rs
+@@ -75,6 +75,8 @@ impl Recording {
+ command_buffer: vk::CommandBuffer,
+ pipelines: &[Arc],
+ ) {
++ // LOCAL (Atlas) diagnostic: the program's dispatch, to the pass timer (`pass_times.rs`).
++ let _scope = crate::pass_times::scope(crate::pass_times::Tag::Guest);
+ // SAFETY: the caller's contract; the gates lie in the command buffer's arena.
+ unsafe {
+ if let Some(preprocess) = &self.preprocess {
+diff --git a/crates/metal2vulkan-runtime/src/recorder/thunks.rs b/crates/metal2vulkan-runtime/src/recorder/thunks.rs
+index 0690463b..1c9970ba 100644
+--- a/crates/metal2vulkan-runtime/src/recorder/thunks.rs
++++ b/crates/metal2vulkan-runtime/src/recorder/thunks.rs
+@@ -170,12 +170,16 @@ macro_rules! commands {
+ command_buffer: vk::CommandBuffer,
+ $($a: $t,)*
+ ) $(-> $r)? {
++ // LOCAL (Atlas) diagnostic: the pass timer's hook (`pass_times.rs`).
++ crate::pass_times::hook!(before $f, stamps::(), command_buffer $(, $a)*);
+ // A deferred command buffer's command goes into its log (`recorder`).
+ // SAFETY: the caller records `command_buffer` alone (Vulkan's external
+ // synchronization); its arguments are as the command takes them.
+ let logged =
+ unsafe { super::handles::record(command_buffer, |log| log.$f($($a,)*)) };
+ if let Some(logged) = logged {
++ // LOCAL (Atlas) diagnostic: the pass timer's hook (`pass_times.rs`).
++ crate::pass_times::hook!(after $f, stamps::(), command_buffer $(, $a)*);
+ return logged;
+ }
+ let real = REAL.$f[S].load(Ordering::Acquire);
+@@ -184,18 +188,30 @@ macro_rules! commands {
+ }
+ // SAFETY: the slot's device's driver gave this command (`store`), of this
+ // signature; the caller's arguments are as the command takes them.
+- unsafe {
++ let answer = unsafe {
+ let real = std::mem::transmute::<
+ *mut c_void,
+ unsafe extern "system" fn(vk::CommandBuffer, $($t,)*) $(-> $r)?,
+ >(real);
+ real(command_buffer, $($a,)*)
+- }
++ };
++ // LOCAL (Atlas) diagnostic: the pass timer's hook (`pass_times.rs`).
++ crate::pass_times::hook!(after $f, stamps::(), command_buffer $(, $a)*);
++ answer
+ }
+ )*
+ };
+ }
+
++/// LOCAL (Atlas) diagnostic: slot `S`'s own timestamp commands, which the pass timer records its
++/// units' timestamps through (`pass_times.rs`).
++fn stamps() -> crate::pass_times::Stamps {
++ crate::pass_times::Stamps {
++ write: cmd_write_timestamp::,
++ reset: cmd_reset_query_pool::,
++ }
++}
++
+ commands! {
+ v1_0 {
+ BeginCommandBuffer begin_command_buffer c"vkBeginCommandBuffer"
+diff --git a/crates/metal2vulkan-runtime/src/release.rs b/crates/metal2vulkan-runtime/src/release.rs
+index b8f18a02..684d84ec 100644
+--- a/crates/metal2vulkan-runtime/src/release.rs
++++ b/crates/metal2vulkan-runtime/src/release.rs
+@@ -142,6 +142,8 @@ macro_rules! released {
+ const CALL: Call = Call::$call;
+
+ unsafe fn destroy(self, device: &ash::Device, _: Door) {
++ // LOCAL (Atlas) diagnostic: the image census and registry (`image_log.rs`).
++ crate::image_log::released(Call::$call, vk::Handle::as_raw(self));
+ // SAFETY: the caller's.
+ unsafe { device.$method(self, None) }
+ }
+diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs
+index ba3449ed..de475813 100644
+--- a/crates/metal2vulkan-runtime/src/render.rs
++++ b/crates/metal2vulkan-runtime/src/render.rs
+@@ -1811,6 +1811,11 @@ impl CommandBuffer {
+ None => EncoderCore::open(self, CALL, EncoderKind::Render, false)?,
+ Some(_) => EncoderCore::replaying(self, false)?,
+ };
++ // LOCAL (Atlas) diagnostic: why the pass's first instance does not record inline, to the
++ // pass timer (`pass_times.rs`).
++ if let (Err(why), None) = (&opens, &again) {
++ crate::pass_times::note_not_inline(core.command_buffer(), *why);
++ }
+ if let Some(pass) = &rate_map {
+ let (map, state) = pass.taken();
+ core.take_rate_map(map, state);
+@@ -6368,6 +6373,8 @@ impl RenderLowering {
+ (false, false) => cause,
+ };
+ self.core.device().shared().counts.instance_split(cause);
++ // LOCAL (Atlas) diagnostic: the split's cause, to the pass timer (`pass_times.rs`).
++ crate::pass_times::note_split(self.core.command_buffer(), cause);
+ let previous = std::mem::replace(&mut self.current, *instance);
+ self.earlier.push(previous);
+ self.barrier_splits += usize::from(self.barrier);
+diff --git a/crates/metal2vulkan-runtime/src/render/inline_first.rs b/crates/metal2vulkan-runtime/src/render/inline_first.rs
+index 0b490627..e67b4acd 100644
+--- a/crates/metal2vulkan-runtime/src/render/inline_first.rs
++++ b/crates/metal2vulkan-runtime/src/render/inline_first.rs
+@@ -331,6 +331,11 @@ impl RenderLowering {
+ if matches!(self.inline, Inline::Open { .. }) && records && !capture {
+ self.inline = Inline::Never;
+ (self.core.device().shared().counts).pass_not_inline(NotInline::Draws);
++ // LOCAL (Atlas) diagnostic: to the pass timer (`pass_times.rs`).
++ crate::pass_times::note_not_inline(
++ self.core.command_buffer(),
++ NotInline::Draws,
++ );
+ }
+ None
+ }
+@@ -369,19 +374,30 @@ impl RenderLowering {
+ } => instance,
+ Next::New { split: true, .. } => {
+ counts.pass_not_inline(NotInline::Draws);
++ // LOCAL (Atlas) diagnostic: to the pass timer (`pass_times.rs`).
++ crate::pass_times::note_not_inline(self.core.command_buffer(), NotInline::Draws);
+ return Ok(None);
+ }
+ };
+ if stood.is_some() {
+ counts.pass_not_inline(NotInline::StandIn);
++ // LOCAL (Atlas) diagnostic: to the pass timer (`pass_times.rs`).
++ crate::pass_times::note_not_inline(self.core.command_buffer(), NotInline::StandIn);
+ return Ok(None);
+ }
+ if !instance.shape.storage.is_empty() {
+ counts.pass_not_inline(NotInline::Storage);
++ // LOCAL (Atlas) diagnostic: to the pass timer (`pass_times.rs`).
++ crate::pass_times::note_not_inline(self.core.command_buffer(), NotInline::Storage);
+ return Ok(None);
+ }
+ if writes {
+ counts.pass_not_inline(NotInline::MemorylessWrites);
++ // LOCAL (Atlas) diagnostic: to the pass timer (`pass_times.rs`).
++ crate::pass_times::note_not_inline(
++ self.core.command_buffer(),
++ NotInline::MemorylessWrites,
++ );
+ return Ok(None);
+ }
+ let plain = made
+@@ -405,6 +421,8 @@ impl RenderLowering {
+ && !instance.shader_tests;
+ if !plain {
+ counts.pass_not_inline(NotInline::Draws);
++ // LOCAL (Atlas) diagnostic: to the pass timer (`pass_times.rs`).
++ crate::pass_times::note_not_inline(self.core.command_buffer(), NotInline::Draws);
+ return Ok(None);
+ }
+ let device = self.core.device().clone();
+@@ -498,7 +516,12 @@ impl RenderLowering {
+ // and framebuffer are live until the command buffer completes (the encoder holds them
+ // to its end, which retains them), the render area is the framebuffer's extent, and
+ // every image rests in `GENERAL`.
++ // LOCAL (Atlas) diagnostic: the pass's first instance, to the pass timer (`pass_times.rs`).
++ let scope = crate::pass_times::scope(crate::pass_times::Tag::Pass(
++ crate::pass_times::PassAt::Inline,
++ ));
+ unsafe { raw.cmd_begin_render_pass(held, &info, vk::SubpassContents::INLINE) };
++ drop(scope);
+ device.shared().counts.render_pass_begun(PassBegun::Inline);
+ self.current.draws = held;
+ self.current.inline = true;
+diff --git a/crates/metal2vulkan-runtime/src/render/inline_splits.rs b/crates/metal2vulkan-runtime/src/render/inline_splits.rs
+index c7c9e642..7cd2407c 100644
+--- a/crates/metal2vulkan-runtime/src/render/inline_splits.rs
++++ b/crates/metal2vulkan-runtime/src/render/inline_splits.rs
+@@ -577,7 +577,12 @@ fn record_kept(
+ for step in &instance.before {
+ step.record_in(raw, held);
+ }
++ // LOCAL (Atlas) diagnostic: an instance after a split, to the pass timer (`pass_times.rs`).
++ let scope = crate::pass_times::scope(crate::pass_times::Tag::Pass(
++ crate::pass_times::PassAt::InlineSplit,
++ ));
+ raw.cmd_begin_render_pass(held, &info, vk::SubpassContents::INLINE);
++ drop(scope);
+ let begun = crate::work_counts::PassBegun::InlineSplit;
+ shared.counts.render_pass_begun(begun);
+ let mut draws = kept.room.recordings[..kept.draws].iter();
+diff --git a/crates/metal2vulkan-runtime/src/render/pass_steps.rs b/crates/metal2vulkan-runtime/src/render/pass_steps.rs
+index 61e2f403..9290f127 100644
+--- a/crates/metal2vulkan-runtime/src/render/pass_steps.rs
++++ b/crates/metal2vulkan-runtime/src/render/pass_steps.rs
+@@ -216,11 +216,16 @@ impl PassSteps {
+ .framebuffer(framebuffer)
+ .render_area(self.render_area)
+ .clear_values(self.clear_values.as_slice());
++ // LOCAL (Atlas) diagnostic: the pass's instance, to the pass timer (`pass_times.rs`).
++ let scope = crate::pass_times::scope(crate::pass_times::Tag::Pass(
++ crate::pass_times::PassAt::Instance,
++ ));
+ raw.cmd_begin_render_pass(
+ command_buffer,
+ &begin,
+ vk::SubpassContents::SECONDARY_COMMAND_BUFFERS,
+ );
++ drop(scope);
+ }
+ }
+
+@@ -373,7 +378,13 @@ impl PassSteps {
+ .framebuffer(framebuffer.raw)
+ .render_area(self.render_area)
+ .clear_values(self.clear_values.as_slice());
++ // LOCAL (Atlas) diagnostic: the resolving instance, to the pass timer
++ // (`pass_times.rs`).
++ let scope = crate::pass_times::scope(crate::pass_times::Tag::Pass(
++ crate::pass_times::PassAt::Resolve,
++ ));
+ raw.cmd_begin_render_pass(command_buffer, &begin, vk::SubpassContents::INLINE);
++ drop(scope);
+ raw.cmd_end_render_pass(command_buffer);
+ }
+ }
+diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs
+index 927b65f1..6a13c30a 100644
+--- a/crates/metal2vulkan-runtime/src/texture.rs
++++ b/crates/metal2vulkan-runtime/src/texture.rs
+@@ -1591,6 +1591,8 @@ impl Device {
+ /// runtime extension, for a caller's helper texture).
+ pub fn new_texture(&self, descriptor: &TextureDescriptor) -> Result {
+ const CALL: &str = "new_texture";
++ // LOCAL (Atlas) diagnostic: the image census's purpose (`image_log.rs`).
++ let _purpose = crate::image_log::api("texture");
+ self.keep_room();
+ let descriptor = &self.texture_options(CALL, descriptor)?;
+ // An `Outside` texture takes no ID, so no ID's limit applies.
+@@ -2836,6 +2838,8 @@ impl Device {
+ /// The image of `plan` for a texture of `layout` made with `descriptor` (and its hazard
+ /// tracking mode `hazard`), checked against the device's limits for it, placed, and in the
+ /// `GENERAL` layout.
++ // LOCAL (Atlas) diagnostic: its caller's place, for the image census (`image_log.rs`).
++ #[track_caller]
+ fn new_image(
+ &self,
+ plan: ImagePlan,
+@@ -2855,6 +2859,8 @@ impl Device {
+ /// shape was written and released; those it compresses read a fixed pattern, which the
+ /// runtime does not give yet). The runtime's own images keep [`new_image`](Self::new_image)'s
+ /// start: an image its first command writes in full need not be zeroed first.
++ // LOCAL (Atlas) diagnostic: its caller's place, for the image census (`image_log.rs`).
++ #[track_caller]
+ fn new_texture_image(
+ &self,
+ plan: ImagePlan,
+@@ -3030,6 +3036,8 @@ impl Device {
+ /// [`new_image`](Self::new_image)'s image, of `identity`, its owner made by `owner` of its
+ /// placement and `VkImage` (a heap's unaliased texture and a shadow whose copies leave an
+ /// aspect out, `texture/heap.rs`; a view's shadow, `texture/view_shadow.rs`).
++ // LOCAL (Atlas) diagnostic: its caller's place, for the image census (`image_log.rs`).
++ #[track_caller]
+ fn new_image_owned(
+ &self,
+ plan: ImagePlan,
+@@ -3053,6 +3061,8 @@ impl Device {
+ /// any command reads it: a texture's over a buffer (`storage_over_buffer`), and a heap
+ /// texture's over the heap's bytes (`texture/heap.rs`, `new_heap_shadow` and
+ /// `heap_planes_image`).
++ // LOCAL (Atlas) diagnostic: its caller's place, for the image census (`image_log.rs`).
++ #[track_caller]
+ fn new_image_as_it_lies(
+ &self,
+ plan: ImagePlan,
+@@ -3068,6 +3078,8 @@ impl Device {
+ /// `start` says so, else zeroed: on the host where it takes host copies, else by a clear
+ /// where one writes its format ([`clears_to_zero`](Self::clears_to_zero)), else by copies of
+ /// the device's zeros. (or moved alone, [`Start::Moved`].)
++ // LOCAL (Atlas) diagnostic: its caller's place, for the image census (`image_log.rs`).
++ #[track_caller]
+ fn new_image_starting(
+ &self,
+ plan: ImagePlan,
+@@ -3080,6 +3092,17 @@ impl Device {
+ let held = start == Start::Held;
+ let moved = start == Start::Moved;
+ let storage = descriptor.resource_options.storage_mode()?;
++ // LOCAL (Atlas) diagnostic: where the image was asked for, for the image census
++ // (`image_log.rs`).
++ let _origin = crate::image_log::origin(
++ std::panic::Location::caller(),
++ match storage {
++ StorageMode::Shared => "Shared",
++ StorageMode::Managed => "Managed",
++ StorageMode::Private => "Private",
++ StorageMode::Memoryless => "Memoryless",
++ },
++ );
+ let class = plan.memory_class(storage, &self.properties().driver_defects);
+ // A `Shared` or `Managed` texture's image with host-transfer usage where the device
+ // copies on the host and makes and places it so (`texture/host_copy.rs`), else as
+@@ -3630,6 +3653,8 @@ impl Heap {
+ /// Refused for a placement heap, whose textures take an offset (`Invalid`, as for its
+ /// buffers).
+ pub fn new_texture(&self, descriptor: &TextureDescriptor) -> Result {
++ // LOCAL (Atlas) diagnostic: the image census's purpose (`image_log.rs`).
++ let _purpose = crate::image_log::api("heap-texture");
+ let descriptor = &self.device().texture_options("new_texture", descriptor)?;
+ match self.heap_type() {
+ HeapType::Sparse => self.device().new_sparse_texture(self, descriptor),
+@@ -3664,6 +3689,8 @@ impl Heap {
+ descriptor: &TextureDescriptor,
+ offset: u64,
+ ) -> Result {
++ // LOCAL (Atlas) diagnostic: the image census's purpose (`image_log.rs`).
++ let _purpose = crate::image_log::api("heap-texture");
+ let device = self.device();
+ let descriptor = &device.texture_options("new_texture_at_offset", descriptor)?;
+ device.new_heap_texture(self, descriptor, Some(offset))
diff --git a/patches/metal2vulkan/0007-diagnostic-the-pass-timer-s-window-follo.patch b/patches/metal2vulkan/0007-diagnostic-the-pass-timer-s-window-follo.patch
new file mode 100644
index 0000000..c03c371
--- /dev/null
+++ b/patches/metal2vulkan/0007-diagnostic-the-pass-timer-s-window-follo.patch
@@ -0,0 +1,44 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Wed, 28 Oct 2026 17:09:48 +0000
+Subject: [PATCH 07/34] diagnostic:the pass timer's window
+ follows the live switch pass_times
+
+A command buffer is captured where /on exists or, with M2V_LIVE set,
+where its file says pass_times=1 (live.rs, re-read at most once a second),
+checked once as the command buffer begins recording.
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/pass_times.rs | 11 +++++++----
+ 1 file changed, 7 insertions(+), 4 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/pass_times.rs b/crates/metal2vulkan-runtime/src/pass_times.rs
+index ca083acb..9cd4574c 100644
+--- a/crates/metal2vulkan-runtime/src/pass_times.rs
++++ b/crates/metal2vulkan-runtime/src/pass_times.rs
+@@ -5,9 +5,11 @@
+ //!
+ //! - **The switch** is read once. Unset (or empty), nothing changes: no query pool, no command,
+ //! no line; each hook is one check of a `OnceLock`.
+-//! - **The window.** Set, a command buffer is captured only where the file `/on` exists as the
+-//! runtime begins recording it (its first encoder's opening, or its first `VkCommandBuffer`
+-//! handed out): checked once per command buffer. `touch /on` opens a window, `rm` closes
++//! - **The window.** Set, a command buffer is captured only where the file `/on` exists, or
++//! the live switch `pass_times` is on (`live.rs`: `pass_times=1` in the file `M2V_LIVE` names,
++//! which it re-reads at most once a second), as the runtime begins recording it (its first
++//! encoder's opening, or its first `VkCommandBuffer` handed out): checked once per command
++//! buffer. `touch /on` (or `pass_times=1`) opens a window, `rm` (or `pass_times=0`) closes
+ //! it; the first command buffer begun after the close flushes the lines held.
+ //! - **Where the timestamps go.** Every routed command passes the recorder's entry points
+ //! (`recorder/thunks.rs`), whatever the runtime records it from (an encoder, its own kernels, a
+@@ -521,7 +523,8 @@ fn decide<'a>(
+ fn start(device: &Device, queue: &CommandQueue, key: usize) -> Option> {
+ let times = device.shared().pass_times.as_ref()?;
+ let dir = dir()?;
+- if !dir.join("on").exists() {
++ // The window: `/on`, or the live switch `pass_times=1` (`live.rs`, `M2V_LIVE`).
++ if !dir.join("on").exists() && !crate::live::on("pass_times", false) {
+ times.flush();
+ return None;
+ }
diff --git a/patches/metal2vulkan/0008-live-switches-tile_stored_only-and-tile_.patch b/patches/metal2vulkan/0008-live-switches-tile_stored_only-and-tile_.patch
new file mode 100644
index 0000000..464dc7e
--- /dev/null
+++ b/patches/metal2vulkan/0008-live-switches-tile_stored_only-and-tile_.patch
@@ -0,0 +1,520 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 31 Oct 2026 18:45:32 +0000
+Subject: [PATCH 08/34] live switches tile_stored_only and
+ tile_narrow_barriers; lane gpu_cost
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/render.rs | 1 +
+ .../src/render/tile_dispatch.rs | 40 +++-
+ .../src/render/tile_writes.rs | 136 ++++++++++++
+ crates/metal2vulkan-runtime/src/tracker.rs | 30 +++
+ .../src/runtime_lane.rs | 1 +
+ .../src/runtime_lane/gpu_cost.rs | 195 ++++++++++++++++++
+ 6 files changed, 393 insertions(+), 10 deletions(-)
+ create mode 100644 crates/metal2vulkan-runtime/src/render/tile_writes.rs
+ create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/gpu_cost.rs
+
+diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs
+index de475813..89c399b5 100644
+--- a/crates/metal2vulkan-runtime/src/render.rs
++++ b/crates/metal2vulkan-runtime/src/render.rs
+@@ -413,6 +413,7 @@ mod shadows;
+ mod snapshot;
+ mod table_facts;
+ mod tessellation_scan;
++mod tile_writes; // LOCAL (Atlas)
+ mod tile_dispatch;
+ mod tile_memory;
+ mod untouched;
+diff --git a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs
+index 5bb661dc..f2741878 100644
+--- a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs
++++ b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs
+@@ -154,6 +154,8 @@ pub(super) struct TileDispatch {
+ /// attachment holds them: their origin and extent, inside the scratch images' extent (the
+ /// pixels every dispatch of the pass covers, from the origin).
+ copied: [[u32; 2]; 2],
++ /// LOCAL (Atlas): what the switches of `render/tile_writes.rs` took as the dispatch was made.
++ economy: super::tile_writes::Economy,
+ layout: vk::PipelineLayout,
+ sets: Vec,
+ /// The dynamic offsets set 0 is bound with (`binding::dynamic_writes`).
+@@ -175,6 +177,17 @@ pub(super) struct TileDispatch {
+ /// back, and the scratch's image.
+ pub(super) type Staging = (vk::Image, (vk::ImageCopy, vk::ImageCopy), vk::Image);
+
++/// LOCAL (Atlas): the barrier that ends the copies in or the dispatch where
++/// [`Economy::narrow`](super::tile_writes::Economy) holds: from what just ran alone, the barriers
++/// around it ordering the rest (`render/tile_writes.rs`).
++fn scratch_barrier(narrow: bool, narrowed: Barrier) -> Barrier {
++ if narrow {
++ narrowed
++ } else {
++ Barrier::everything()
++ }
++}
++
+ impl TileDispatch {
+ /// The copies of each staged attachment of `layout` (the pass's, as it ends: a stand-in that
+ /// arrived after the dispatch is what the pass renders) into its scratch and back, over the
+@@ -217,6 +230,7 @@ impl TileDispatch {
+ ) {
+ // SAFETY: the caller's contract.
+ unsafe {
++ let narrow = self.economy.narrow;
+ Barrier::everything().record(raw, command_buffer);
+ for (own, (into, _), scratch) in copies {
+ raw.cmd_copy_image(
+@@ -228,7 +242,7 @@ impl TileDispatch {
+ std::slice::from_ref(into),
+ );
+ }
+- Barrier::everything().record(raw, command_buffer);
++ scratch_barrier(narrow, Barrier::copied_to_dispatch()).record(raw, command_buffer);
+ if let Some(push) = raw.push_descriptor().filter(|_| !self.pushed.is_empty()) {
+ binding::push_set(
+ push,
+@@ -268,16 +282,19 @@ impl TileDispatch {
+ }
+ raw.cmd_dispatch(command_buffer, *x, *y, *z);
+ }
+- Barrier::everything().record(raw, command_buffer);
+- for (own, (_, back), scratch) in copies {
+- raw.cmd_copy_image(
++ // LOCAL (Atlas): nothing to copy back from a dispatch that wrote no staged cell.
++ if self.economy.copies_back {
++ scratch_barrier(narrow, Barrier::dispatched_to_copy()).record(raw, command_buffer);
++ for (own, (_, back), scratch) in copies {
++ raw.cmd_copy_image(
+ command_buffer,
+- *scratch,
+- vk::ImageLayout::GENERAL,
+- *own,
+- vk::ImageLayout::GENERAL,
+- std::slice::from_ref(back),
+- );
++ *scratch,
++ vk::ImageLayout::GENERAL,
++ *own,
++ vk::ImageLayout::GENERAL,
++ std::slice::from_ref(back),
++ );
++ }
+ }
+ Barrier::everything().record(raw, command_buffer);
+ }
+@@ -1199,6 +1216,8 @@ impl RenderLowering {
+ None => None,
+ };
+ // Recording starts here: nothing below can be refused.
++ let economy =
++ super::tile_writes::Economy::now(&variant.pipeline().stage.spirv, cells.is_some());
+ self.scratch.extend(made);
+ self.tile_imageblock |= aliased_past;
+ if let Some(made) = made_imageblock {
+@@ -1220,6 +1239,7 @@ impl RenderLowering {
+ after: self.earlier.len() + 1,
+ staged,
+ copied,
++ economy,
+ layout: objects.layout(),
+ sets: set.into_iter().collect(),
+ offsets,
+diff --git a/crates/metal2vulkan-runtime/src/render/tile_writes.rs b/crates/metal2vulkan-runtime/src/render/tile_writes.rs
+new file mode 100644
+index 00000000..b8e11ef1
+--- /dev/null
++++ b/crates/metal2vulkan-runtime/src/render/tile_writes.rs
+@@ -0,0 +1,136 @@
++//! LOCAL (Atlas): less work around a tile dispatch, under live switches, both off by default.
++//!
++//! - **`tile_stored_only`.** Three of the five tile functions a Tahoe WindowServer frame runs read
++//! the imageblock and write only a texture of their own: the translator stores no cell of such a
++//! function (`lower::access::tile`'s `Pass::Store` skips a slot it did not store), so the scratch
++//! holds what was copied into it, and its copy back rewrites the attachment's own texels. Under
++//! the switch a dispatch that writes no staged image copies nothing back. Decided from the
++//! stage's final SPIR-V ([`writes_staged`]), conservatively: only where every image the module
++//! writes is of `Unknown` format, which a staged attachment never is
++//! (`lower::access::tile::storage_format` declares its format), and nothing takes a texel
++//! pointer. A function that stores the pass's imageblock cells writes through its own storage,
++//! which the copies do not touch: it keeps them, as it does any attachment staged beside.
++//! - **`tile_narrow_barriers`.** A dispatch's copies and scratch sat between four barriers from
++//! everything to everything. The first orders everything before against everything after, its
++//! second scope holding the copies and the dispatch; the last orders the dispatch's and the
++//! copies' writes against everything after. The two between need only move the scratch's bytes:
++//! transfer writes to the dispatch's shader accesses, and its shader writes to the copies back.
++//! Under the switch they are those. The first and the last stay.
++//!
++//! The switches are read as a dispatch is encoded; the dispatch keeps what it read.
++
++/// What a dispatch does around itself (the module docs).
++#[derive(Clone, Copy, Debug)]
++pub(super) struct Economy {
++ /// The scratch is copied back after the dispatch.
++ pub(super) copies_back: bool,
++ /// The two barriers inside the dispatch's copies are narrowed.
++ pub(super) narrow: bool,
++}
++
++impl Economy {
++ /// The dispatch of a stage of `spirv`, `cells` where it stages the pass's imageblock storage.
++ pub(super) fn now(spirv: &[u32], cells: bool) -> Economy {
++ let stored_only = crate::live::on("tile_stored_only", false);
++ Economy {
++ copies_back: !stored_only || cells || writes_staged(spirv),
++ narrow: crate::live::on("tile_narrow_barriers", false),
++ }
++ }
++}
++
++const OP_TYPE_IMAGE: u32 = 25;
++const OP_LOAD: u32 = 61;
++const OP_IMAGE_TEXEL_POINTER: u32 = 60;
++const OP_IMAGE_WRITE: u32 = 99;
++/// `ImageFormat::Unknown`.
++const FORMAT_UNKNOWN: u32 = 0;
++
++/// Whether a module of `spirv` may write an image of a declared format, or reach one's texels
++/// through a pointer: `true` wherever the walk cannot tell, a staged attachment's image being one
++/// of a declared format (the module docs).
++pub(super) fn writes_staged(spirv: &[u32]) -> bool {
++ use std::collections::{HashMap, HashSet};
++ let Some(mut rest) = spirv.get(5..) else {
++ return true;
++ };
++ // The image types of no declared format, and the loads of them.
++ let mut unknown = HashSet::new();
++ let mut loaded = HashMap::new();
++ let mut written = Vec::new();
++ while let Some(&head) = rest.first() {
++ let (words, op) = ((head >> 16) as usize, head & 0xffff);
++ if words == 0 || words > rest.len() {
++ return true;
++ }
++ let at = &rest[..words];
++ match op {
++ OP_TYPE_IMAGE if words >= 9 => {
++ if at[8] == FORMAT_UNKNOWN {
++ unknown.insert(at[1]);
++ }
++ }
++ OP_LOAD if words >= 4 => {
++ loaded.insert(at[2], at[1]);
++ }
++ OP_IMAGE_WRITE if words >= 2 => written.push(at[1]),
++ OP_IMAGE_TEXEL_POINTER => return true,
++ _ => {}
++ }
++ rest = &rest[words..];
++ }
++ written
++ .iter()
++ .any(|image| !loaded.get(image).is_some_and(|ty| unknown.contains(ty)))
++}
++
++#[cfg(test)]
++mod tests {
++ use super::writes_staged;
++
++ fn op(code: u32, operands: &[u32]) -> Vec {
++ let mut words = vec![((operands.len() as u32 + 1) << 16) | code];
++ words.extend(operands);
++ words
++ }
++
++ fn module(format: u32, write: Vec) -> Vec {
++ let mut m = vec![0x0723_0203, 0x0001_0500, 0, 100, 0];
++ // %1 = OpTypeImage %2 2D 0 0 0 2
++ m.extend(op(25, &[1, 2, 1, 0, 0, 0, 2, format]));
++ // %3 = OpLoad %1 %4
++ m.extend(op(61, &[1, 3, 4]));
++ m.extend(write);
++ m
++ }
++
++ #[test]
++ fn a_write_of_a_declared_format_counts() {
++ assert!(writes_staged(&module(33, op(99, &[3, 5, 6]))));
++ }
++
++ #[test]
++ fn a_write_of_no_declared_format_does_not() {
++ assert!(!writes_staged(&module(0, op(99, &[3, 5, 6]))));
++ }
++
++ #[test]
++ fn no_write_does_not() {
++ assert!(!writes_staged(&module(33, Vec::new())));
++ }
++
++ #[test]
++ fn an_image_it_cannot_trace_counts() {
++ assert!(writes_staged(&module(0, op(99, &[9, 5, 6]))));
++ }
++
++ #[test]
++ fn a_texel_pointer_counts() {
++ assert!(writes_staged(&module(0, op(60, &[7, 8, 3, 5, 6]))));
++ }
++
++ #[test]
++ fn a_torn_module_counts() {
++ assert!(writes_staged(&[0x0723_0203, 0, 0, 0, 0, 5 << 16]));
++ }
++}
+diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs
+index 37ab4133..2724bb88 100644
+--- a/crates/metal2vulkan-runtime/src/tracker.rs
++++ b/crates/metal2vulkan-runtime/src/tracker.rs
+@@ -402,6 +402,36 @@ impl Barrier {
+ }
+ }
+
++ /// LOCAL (Atlas): from a tile dispatch's copies into its scratch to the dispatch, which reads
++ /// and writes the scratch (`render/tile_writes.rs`).
++ pub(super) fn copied_to_dispatch() -> Barrier {
++ Barrier {
++ src: Access::new(
++ vk::PipelineStageFlags2::ALL_TRANSFER,
++ vk::AccessFlags2::TRANSFER_WRITE,
++ ),
++ dst: Access::new(
++ vk::PipelineStageFlags2::COMPUTE_SHADER,
++ vk::AccessFlags2::SHADER_READ | vk::AccessFlags2::SHADER_WRITE,
++ ),
++ }
++ }
++
++ /// LOCAL (Atlas): from a tile dispatch to the copies back from its scratch
++ /// (`render/tile_writes.rs`).
++ pub(super) fn dispatched_to_copy() -> Barrier {
++ Barrier {
++ src: Access::new(
++ vk::PipelineStageFlags2::COMPUTE_SHADER,
++ vk::AccessFlags2::SHADER_WRITE,
++ ),
++ dst: Access::new(
++ vk::PipelineStageFlags2::ALL_TRANSFER,
++ vk::AccessFlags2::TRANSFER_READ,
++ ),
++ }
++ }
++
+ /// From a fill's writes (`vkCmdFillBuffer`) to the dispatches after it, which read or write
+ /// what it wrote, as an indirect command too.
+ pub(super) fn after_fill() -> Barrier {
+diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs
+index c2394df6..613e8e37 100644
+--- a/crates/metal2vulkan-validation/src/runtime_lane.rs
++++ b/crates/metal2vulkan-validation/src/runtime_lane.rs
+@@ -518,6 +518,7 @@ mod host_copied_textures;
+ mod host_memory;
+ #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
+ mod host_rt_frames;
++mod gpu_cost;
+ #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
+ mod in_place_textures;
+ #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
+diff --git a/crates/metal2vulkan-validation/src/runtime_lane/gpu_cost.rs b/crates/metal2vulkan-validation/src/runtime_lane/gpu_cost.rs
+new file mode 100644
+index 00000000..ead4119f
+--- /dev/null
++++ b/crates/metal2vulkan-validation/src/runtime_lane/gpu_cost.rs
+@@ -0,0 +1,195 @@
++//! LOCAL (Atlas): what the parts of a WindowServer frame's full-target work cost on the device the
++//! cfg selects, and what the switches of `render/tile_writes.rs` change: report only, run by name.
++//!
++//! `GPU-COST` lines give the median GPU time of one command buffer of one pass.
++//!
++//! - **The render area**: a 40x40 scissored draw into a 3200x1800 target, loaded and stored, against
++//! the same draw into a 64x64 one: the most a smaller render area could save.
++//! - **A memoryless color**: the same pass with a 3200x1800 memoryless `RGBA16Float` beside it,
++//! which no draw writes.
++//! - **A tile dispatch** over 960x1856 pixels of 16x16 tiles, read-only (`cfb_tn_read4`) and
++//! writing (`cfb_tn_round4`), under each setting.
++
++use super::no_copy_textures::{blending, floats, staged};
++use super::tile_states::on_device;
++use crate::air_library::AirLibrary;
++use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage};
++use metal2vulkan::pipeline::{StageSource, TileRenderPipelineDescriptor};
++use metal2vulkan_devtools::{engine_dir, llvm_assemble};
++use metal2vulkan_runtime::{
++ live, CommandQueue, CpuCacheMode, HazardTrackingMode, Device, LoadAction, PipelineOptions, RenderPassDescriptor,
++ RenderPipelineState, ResourceOptions, ScissorRect, Size, StorageMode, StoreAction, Texture,
++ TextureDescriptor,
++};
++use std::time::Duration;
++
++const WAIT: Duration = Duration::from_secs(10);
++const WARM: usize = 8;
++const RUNS: usize = 60;
++
++fn median(mut values: Vec) -> f64 {
++ values.sort_by(f64::total_cmp);
++ values[values.len() / 2]
++}
++
++/// The median GPU time in microseconds of a command buffer `encode` fills.
++fn timed(
++ queue: &CommandQueue,
++ mut encode: impl FnMut(&metal2vulkan_runtime::CommandBuffer),
++) -> f64 {
++ let mut times = Vec::new();
++ for run in 0..WARM + RUNS {
++ let command_buffer = queue.command_buffer().unwrap();
++ encode(&command_buffer);
++ command_buffer.commit().unwrap();
++ command_buffer.wait_until_completed_for(WAIT).unwrap();
++ assert_eq!(command_buffer.error(), None);
++ if run >= WARM {
++ times.push(
++ (command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap()) * 1e6,
++ );
++ }
++ }
++ median(times)
++}
++
++fn target(device: &Device, format: PixelFormat, w: u64, h: u64, mode: Option) -> Texture {
++ let mut d = TextureDescriptor::texture_2d(format, w, h, false);
++ d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
++ d.resource_options = ResourceOptions::private();
++ if mode == Some(StorageMode::Memoryless) {
++ d.usage = TextureUsage::RENDER_TARGET;
++ d.resource_options = ResourceOptions::new(
++ StorageMode::Memoryless,
++ CpuCacheMode::DefaultCache,
++ HazardTrackingMode::Default,
++ );
++ }
++ device.new_texture(&d).unwrap()
++}
++
++/// The target a linear image of the device's own memory, as an in-place surface's form.
++fn linear(device: &Device, w: u64, h: u64) -> Texture {
++ let row = w * 4;
++ let own = device.new_buffer(row * h, ResourceOptions::private()).unwrap();
++ let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, w, h, false);
++ d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
++ d.resource_options = own.resource_options();
++ own.new_texture(&d, 0, row).unwrap()
++}
++
++#[test]
++#[ignore = "a release-mode measurement: run by name"]
++fn gpu_cost_probe() {
++ on_device(|device: &Device| {
++ let queue = device.new_command_queue().unwrap();
++ let blend = blending(device, PixelFormat::BGRA8Unorm);
++ let whole = staged(device, &floats([-1.0, -1.0, 1.0, 1.0]));
++ let color = staged(device, &floats([0.2, 0.4, 0.6, 0.5]));
++ let big = target(device, PixelFormat::BGRA8Unorm, 3200, 1800, None);
++ let small = target(device, PixelFormat::BGRA8Unorm, 64, 64, None);
++ let flat = linear(device, 3200, 1800);
++ let held = target(
++ device,
++ PixelFormat::RGBA16Float,
++ 3200,
++ 1800,
++ Some(StorageMode::Memoryless),
++ );
++ let run = |name: &str, c0: &Texture, c1: Option<&Texture>, draw: Option| {
++ let us = timed(&queue, |command_buffer| {
++ let mut pass = RenderPassDescriptor::new();
++ let a = &mut pass.color_attachments[0];
++ a.texture = Some(c0.clone());
++ a.load_action = LoadAction::Load;
++ a.store_action = StoreAction::Store;
++ if let Some(c1) = c1 {
++ let a = &mut pass.color_attachments[1];
++ a.texture = Some(c1.clone());
++ a.load_action = LoadAction::Clear;
++ a.store_action = StoreAction::DontCare;
++ }
++ let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
++ encoder.set_render_pipeline_state(&blend).unwrap();
++ encoder.set_vertex_buffer(Some(&whole), 0, 0).unwrap();
++ encoder.set_fragment_buffer(Some(&color), 0, 0).unwrap();
++ if let Some(side) = draw {
++ encoder
++ .set_scissor_rect(ScissorRect {
++ x: 0,
++ y: 0,
++ width: side,
++ height: side,
++ })
++ .unwrap();
++ }
++ encoder
++ .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)
++ .unwrap();
++ encoder.end_encoding().unwrap();
++ });
++ eprintln!("GPU-COST {name}: {us:.1} us");
++ };
++ for round in 0..2 {
++ eprintln!("GPU-COST round {round}");
++ run("64x64 target, 40x40 draw", &small, None, Some(40));
++ run("3200x1800 target, 40x40 draw", &big, None, Some(40));
++ run("3200x1800 linear target, 40x40 draw", &flat, None, Some(40));
++ run("3200x1800 + memoryless, 40x40 draw", &big, Some(&held), Some(40));
++ run("3200x1800 linear + memoryless, 40x40 draw", &flat, Some(&held), Some(40));
++ run("3200x1800 target, full blend", &big, None, None);
++ run("3200x1800 linear target, full blend", &flat, None, None);
++ }
++
++ let tile = |entry: &str| -> RenderPipelineState {
++ let bitcode = llvm_assemble(&engine_dir().join("cfb_tile_norm.ll")).unwrap();
++ let library = device.new_library_with_air(&bitcode).unwrap();
++ let function = library.new_function_with_name(entry).unwrap();
++ let mut d = TileRenderPipelineDescriptor::new(StageSource::Function(
++ function.function_descriptor(),
++ ));
++ d.color_attachment_formats[0] = Some(PixelFormat::RGBA8Unorm);
++ d.threadgroup_size_matches_tile_size = true;
++ device
++ .new_tile_render_pipeline_state(&d, &PipelineOptions::default())
++ .unwrap()
++ };
++ let (w, h) = (960u64, 1856u64);
++ let attachment = target(device, PixelFormat::RGBA8Unorm, w, h, None);
++ let cells = device
++ .new_buffer(16 * (16 * h + w + 64), ResourceOptions::private())
++ .unwrap();
++ for round in 0..3 {
++ for (entry, state) in [
++ ("cfb_tn_read4", tile("cfb_tn_read4")),
++ ("cfb_tn_round4", tile("cfb_tn_round4")),
++ ] {
++ for (stored, narrow) in [("0", "0"), ("1", "0"), ("0", "1"), ("1", "1")] {
++ live::set("tile_stored_only", Some(stored));
++ live::set("tile_narrow_barriers", Some(narrow));
++ let us = timed(&queue, |command_buffer| {
++ let mut pass = RenderPassDescriptor::new();
++ let a = &mut pass.color_attachments[0];
++ a.texture = Some(attachment.clone());
++ a.load_action = LoadAction::Load;
++ a.store_action = StoreAction::Store;
++ pass.tile_width = 16;
++ pass.tile_height = 16;
++ let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
++ encoder.set_render_pipeline_state(&state).unwrap();
++ encoder.set_tile_buffer(Some(&cells), 0, 0).unwrap();
++ encoder
++ .dispatch_threads_per_tile(Size::new(16, 16, 1))
++ .unwrap();
++ encoder.end_encoding().unwrap();
++ });
++ eprintln!(
++ "GPU-COST tile round {round} {entry} stored_only={stored} narrow={narrow}: {us:.1} us"
++ );
++ }
++ }
++ }
++ live::set("tile_stored_only", None);
++ live::set("tile_narrow_barriers", None);
++ });
++}
diff --git a/patches/metal2vulkan/0009-live-switch-surface_lazy-a-large-surface.patch b/patches/metal2vulkan/0009-live-switch-surface_lazy-a-large-surface.patch
new file mode 100644
index 0000000..f29edca
--- /dev/null
+++ b/patches/metal2vulkan/0009-live-switch-surface_lazy-a-large-surface.patch
@@ -0,0 +1,732 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 31 Oct 2026 19:12:44 +0000
+Subject: [PATCH 09/34] live switch surface_lazy: a large
+ surface's optimal image kept across command buffers
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../src/buffer_descriptor.rs | 1 +
+ .../src/buffer_texture.rs | 7 +
+ .../src/command_buffer/mod.rs | 4 +
+ crates/metal2vulkan-runtime/src/host_rt.rs | 4 +
+ crates/metal2vulkan-runtime/src/lib.rs | 1 +
+ crates/metal2vulkan-runtime/src/shadow.rs | 40 +++-
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 226 ++++++++++++++++++
+ .../metal2vulkan-runtime/src/tests/shadow.rs | 2 +
+ crates/metal2vulkan-runtime/src/texture.rs | 2 +
+ .../metal2vulkan-runtime/src/texture/heap.rs | 3 +
+ .../src/texture/surface_depth.rs | 1 +
+ .../src/texture/surface_two_planes.rs | 1 +
+ .../src/texture/view_shadow.rs | 1 +
+ .../src/texture/ycbcr_image.rs | 3 +
+ .../src/runtime_lane/host_rt_frames.rs | 55 ++++-
+ 15 files changed, 334 insertions(+), 17 deletions(-)
+ create mode 100644 crates/metal2vulkan-runtime/src/shadow_lazy.rs
+
+diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs
+index 51b73aac..3dfe1a02 100644
+--- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs
++++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs
+@@ -371,6 +371,7 @@ impl Device {
+ /// live it returns at once, and otherwise it finds the buffers over the range by address,
+ /// whether the range covers none of them or many, never reading them all.
+ pub fn host_range_remapped(&self, bytes: NonNull, length: u64) {
++ crate::shadow_lazy::everything_written(); // LOCAL (Atlas)
+ let start = bytes.as_ptr() as u64;
+ let shared = self.shared();
+ // The unit an import's pages round out to: an import by pointer over a page the call
+diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs
+index 45801900..c4c29b08 100644
+--- a/crates/metal2vulkan-runtime/src/buffer_texture.rs
++++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs
+@@ -1142,6 +1142,7 @@ impl Texels {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ })
+ }
+
+@@ -1312,6 +1313,7 @@ impl Texels {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ texels.staged = Some(Arc::new(copies));
+ let (offset, alignment) = (
+@@ -1424,6 +1426,11 @@ impl Texels {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ // LOCAL (Atlas): `shadow_lazy.rs`.
++ lazy: super::shadow_lazy::Lazy::of(
++ self.backing() == super::shadow::Backing::Surface,
++ self.layout.row_bytes / self.texel_bytes * u64::from(self.layout.rows),
++ ),
+ })
+ }
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+index b08a9994..7b19ebee 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+@@ -2505,6 +2505,10 @@ impl CommandBuffer {
+ failure: Option,
+ run: CommitRun,
+ ) -> Result<(), Error> {
++ // LOCAL (Atlas): a later command buffer may take its surfaces' images (`shadow_lazy.rs`).
++ if let Some(id) = self.state().shadow_carry.as_ref().map(ShadowCarry::id) {
++ crate::shadow_lazy::committed(id);
++ }
+ // The waiting fetched render targets take their storage form at this commit where it
+ // allows (`storage_form.rs`): one atomic read where none waits. The scheduler's thread
+ // ends the switch once it submitted the command buffer. None where nothing of it runs.
+diff --git a/crates/metal2vulkan-runtime/src/host_rt.rs b/crates/metal2vulkan-runtime/src/host_rt.rs
+index bffcd13f..fbf18b08 100644
+--- a/crates/metal2vulkan-runtime/src/host_rt.rs
++++ b/crates/metal2vulkan-runtime/src/host_rt.rs
+@@ -259,6 +259,10 @@ impl Device {
+ if max_texels().is_some_and(|max| texels > max) {
+ return false;
+ }
++ // LOCAL (Atlas): an optimal image kept across command buffers instead (`shadow_lazy.rs`).
++ if crate::shadow_lazy::takes_surface(texels) {
++ return false;
++ }
+ if self.compile_device().policy().host_page_textures != HostPageTexturePolicy::InPlace {
+ return false;
+ }
+diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs
+index 9cdcc6a5..48b3a27d 100644
+--- a/crates/metal2vulkan-runtime/src/lib.rs
++++ b/crates/metal2vulkan-runtime/src/lib.rs
+@@ -203,6 +203,7 @@ mod shader_cache;
+ mod shadow;
+ mod shadow_copy_back;
+ mod shadow_copy_in;
++pub mod shadow_lazy; // LOCAL (Atlas)
+ mod shadow_merge;
+ mod shadow_stencil;
+ mod sharing;
+diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs
+index 55c34686..a70e6a7c 100644
+--- a/crates/metal2vulkan-runtime/src/shadow.rs
++++ b/crates/metal2vulkan-runtime/src/shadow.rs
+@@ -215,6 +215,9 @@ pub(super) struct ShadowCopies {
+ /// serve is counted as one an earlier command buffer's standing stands behind, or as one of a
+ /// shadow that never held a standing ([`CarryTally`]).
+ pub(super) stood: AtomicU64,
++ /// LOCAL (Atlas): the image's standing across command buffers, where `shadow_lazy.rs` takes
++ /// the texture.
++ pub(super) lazy: Option>,
+ }
+
+ /// The texels of a texture over an IOSurface's plane from which its shadow's copies in count
+@@ -758,7 +761,12 @@ impl ShadowCopies {
+ pub(super) fn merges_back(&self) -> bool {
+ let bytes = matches!(&self.source, ShadowSource::Bytes { .. });
+ let other_writer = self.backing != Backing::PrivateBuffer || !self.tracked;
+- bytes && other_writer && !self.drops_writes && self.unmerged().is_none()
++ // LOCAL (Atlas): a lazy surface copies back (`shadow_lazy.rs`).
++ bytes
++ && other_writer
++ && !self.drops_writes
++ && self.unmerged().is_none()
++ && self.lazy.is_none()
+ }
+
+ /// Whether two shadowed textures copy some of the same truth.
+@@ -2167,6 +2175,8 @@ impl ShadowSync {
+ /// where each stands; this covers the commands of an encoder that meets none of them, whose
+ /// writes nothing else here would see.
+ pub(super) fn wrote(&mut self, uses: &[Use]) {
++ // LOCAL (Atlas): any surface's, whatever this encoder uses (`shadow_lazy.rs`).
++ super::shadow_lazy::note_writes(uses);
+ if self.carry.entries.is_empty() {
+ return;
+ }
+@@ -2189,6 +2199,16 @@ impl ShadowSync {
+ carry.entries.append(&mut self.carry.entries);
+ for entry in &self.entries {
+ let touched = entry.copies.touched.fetch_add(1, Ordering::Relaxed);
++ // LOCAL (Atlas): what a later command buffer takes (`shadow_lazy.rs`).
++ if let Some(lazy) = &entry.copies.lazy {
++ if entry.standing == Standing::Current && touched == entry.met && !entry.dirty {
++ let (key, range) = entry.copies.truth();
++ let truth = (key, entry.copies.alias(), range);
++ lazy.stand(truth, carry.id, touched + 1, entry.held, entry.stale);
++ } else {
++ lazy.fall();
++ }
++ }
+ if entry.standing != Standing::Current {
+ continue;
+ }
+@@ -2288,6 +2308,11 @@ struct Carried {
+ }
+
+ impl ShadowCarry {
++ /// LOCAL (Atlas): the command buffer's identity (`shadow_lazy.rs`).
++ pub(super) fn id(&self) -> u64 {
++ self.id
++ }
++
+ /// Carry nothing, under the same identity: every shadowed texture copies in again at its
+ /// next use, and a first copy in of one this command buffer stood behind still reads as that.
+ pub(super) fn clear(&mut self) {
+@@ -2326,9 +2351,16 @@ impl ShadowSync {
+ .position(|carried| carried.copies.shadow_key == copies.shadow_key)
+ .map(|at| self.carry.entries.swap_remove(at))
+ .filter(|carried| carried.touched == met);
+- let (standing, held, stale) = match &carried {
+- Some(carried) => (Standing::Current, carried.held, carried.stale),
+- None => (Standing::Unread, None, None),
++ // LOCAL (Atlas): an earlier command buffer's image, where nothing wrote its bytes
++ // since (`shadow_lazy.rs`).
++ let lazily = match (&carried, &copies.lazy) {
++ (None, Some(lazy)) => lazy.take(self.carry.id, met),
++ _ => None,
++ };
++ let (standing, held, stale) = match (&carried, lazily) {
++ (Some(carried), _) => (Standing::Current, carried.held, carried.stale),
++ (None, Some((held, stale))) => (Standing::Current, held, stale),
++ (None, None) => (Standing::Unread, None, None),
+ };
+ self.entries.push(Entry {
+ copies: Arc::clone(copies),
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+new file mode 100644
+index 00000000..e05af1f8
+--- /dev/null
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -0,0 +1,226 @@
++//! LOCAL (Atlas): a large surface over host pages rendered in an optimal image kept across command
++//! buffers, under the live switch `surface_lazy` (default off).
++//!
++//! `host_rt_in_place` renders the macOS desktop and a Simulator's display surface straight into
++//! their pages as a linear image, where a pass costs far more than into an optimal one (a whole
++//! 3200x1800 surface blended, Arrow Lake: 5.1 ms against 1.5). The plain shadow (`shadow.rs`) pays
++//! instead a copy in and a keep and merge at every command buffer, and WindowServer's command
++//! buffers hold about one pass each: the copies cost more than the linear image.
++//!
++//! Under the switch a texture over a surface's plane of at least `surface_lazy_min_texels`
++//! (default 2,000,000) texels is a shadow ([`takes_surface`]), and three things change for it:
++//!
++//! - **No copy in where the image still holds the bytes.** An encoder's end leaves the image's
++//! standing ([`Lazy::stand`]), as `shadow::ShadowCarry` leaves it to the command buffer's later
++//! encoders; a later command buffer's encoder takes it ([`Lazy::take`]), so it copies in nothing,
++//! where nothing wrote the bytes since. Every write a command records of them, through anything
++//! else over them (`shadow::ShadowCopies::meets`, an alias of the same pages too) drops it
++//! ([`note_writes`]), as do a remap of host pages and a CPU write through a texture
++//! ([`everything_written`]).
++//! - **No keep and merge.** Its copy back writes the rectangle the commands wrote in, where their
++//! scissors bound it, or every texel. A CPU write inside that rectangle while the command buffer
++//! runs is lost, where the merge keeps it: the guest's CPU does not write a surface it renders
++//! into at the same time.
++//! - **Copy back as ever: at each encoder's end**, in the command buffer, so before its completion
++//! reaches the guest. So the guest's CPU, a screenshot, ScreenCaptureKit and the display read the
++//! pages as they read them shadowed or in place, at every command buffer's completion, and a
++//! later command's read through another import is ordered after the copy by the tracker.
++//!
++//! **What it cannot see**: a write of the guest's CPU into the pages between command buffers, which
++//! reaches the host through no call. Metal shows it to a later command buffer. Here the image misses
++//! it until the next copy in: at least every `surface_lazy_resync_ms` (default 250, 0 never) a
++//! surface's next encoder takes no standing and copies in as the plain shadow does.
++//!
++//! The switch is read as a texture is made and as an encoder ends: a texture keeps its form.
++//!
++//! **Command buffers encoded out of order**: a standing is taken only from a command buffer already
++//! committed ([`committed`]), whose commands Metal orders before the taker's.
++
++use super::resource::ResourceKey;
++use super::tracker::{Use, UseRange};
++use std::collections::VecDeque;
++use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
++use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak};
++use std::time::Instant;
++
++/// The live switch.
++const SWITCH: &str = "surface_lazy";
++const DEFAULT_MIN_TEXELS: u64 = 2_000_000;
++const DEFAULT_RESYNC_MS: u64 = 250;
++/// The committed command buffers remembered: an older one's standing is not taken.
++const COMMITTED_KEPT: usize = 256;
++
++/// Moved on by what may have written any surface's bytes without a command.
++static EPOCH: AtomicU64 = AtomicU64::new(0);
++/// Whether any surface is registered: every hook returns at once while none is.
++static ANY: AtomicBool = AtomicBool::new(false);
++static TAKEN: AtomicU64 = AtomicU64::new(0);
++static REFUSED: AtomicU64 = AtomicU64::new(0);
++static RESYNCS: AtomicU64 = AtomicU64::new(0);
++static ACTIVE: AtomicUsize = AtomicUsize::new(0);
++
++fn registry() -> &'static RwLock>> {
++ static ALL: OnceLock>>> = OnceLock::new();
++ ALL.get_or_init(RwLock::default)
++}
++
++fn committed_ids() -> &'static Mutex> {
++ static IDS: OnceLock>> = OnceLock::new();
++ IDS.get_or_init(Mutex::default)
++}
++
++/// Whether a texture over host pages of `texels` stays a shadow to render lazily (`host_rt.rs`).
++pub(crate) fn takes_surface(texels: u64) -> bool {
++ crate::live::on(SWITCH, false)
++ && texels
++ >= crate::live::get("surface_lazy_min_texels")
++ .and_then(|v| v.parse().ok())
++ .unwrap_or(DEFAULT_MIN_TEXELS)
++}
++
++/// Note that what may hold any surface's bytes changed without a command.
++pub(crate) fn everything_written() {
++ if ANY.load(Ordering::Relaxed) {
++ EPOCH.fetch_add(1, Ordering::Relaxed);
++ }
++}
++
++/// Note the command buffer of identity `id` committed.
++pub(crate) fn committed(id: u64) {
++ if !ANY.load(Ordering::Relaxed) {
++ return;
++ }
++ let mut ids = committed_ids().lock().unwrap();
++ if ids.len() == COMMITTED_KEPT {
++ ids.pop_front();
++ }
++ ids.push_back(id);
++}
++
++/// Note a recorded command with `uses` (the host memory's among them): each of its writes of a
++/// surface's truth drops that surface's standing. A surface's own copy back counts too: its
++/// encoder's end reads the count after it ([`Lazy::stand`]).
++pub(super) fn note_writes(uses: &[Use]) {
++ if !ANY.load(Ordering::Relaxed) {
++ return;
++ }
++ let all = registry().read().unwrap();
++ for used in uses.iter().filter(|used| !used.write.is_empty()) {
++ for lazy in all.iter().filter_map(Weak::upgrade) {
++ if lazy.meets(used) {
++ lazy.written.fetch_add(1, Ordering::Relaxed);
++ }
++ }
++ }
++}
++
++/// The counts so far, for a lane or a stderr line: standings taken, refused, and resyncs.
++pub fn counts() -> (u64, u64, u64) {
++ (
++ TAKEN.load(Ordering::Relaxed),
++ REFUSED.load(Ordering::Relaxed),
++ RESYNCS.load(Ordering::Relaxed),
++ )
++}
++
++/// What an encoder's end left of the image.
++#[derive(Clone, Copy)]
++struct Stood {
++ /// The command buffer's identity (`shadow::ShadowCarry::id`).
++ id: u64,
++ /// `ShadowCopies::touched` as the encoder left it.
++ touched: u64,
++ held: Option<[u32; 4]>,
++ stale: Option<[u32; 4]>,
++ written: u64,
++ epoch: u64,
++}
++
++/// One surface's standing.
++pub(super) struct Lazy {
++ truth: OnceLock<(ResourceKey, Option, UseRange)>,
++ written: AtomicU64,
++ stood: Mutex>,
++ resynced: Mutex,
++}
++
++impl Lazy {
++ /// The state of a new shadow of `texels` texels with `surface` as its backing, where the switch
++ /// takes it.
++ pub(super) fn of(surface: bool, texels: u64) -> Option> {
++ (surface && takes_surface(texels)).then(|| {
++ Arc::new(Lazy {
++ truth: OnceLock::new(),
++ written: AtomicU64::new(0),
++ stood: Mutex::new(None),
++ resynced: Mutex::new(Instant::now()),
++ })
++ })
++ }
++
++ fn meets(&self, used: &Use) -> bool {
++ self.truth.get().is_some_and(|(key, alias, range)| {
++ (used.key == *key || Some(used.key) == *alias) && used.range.overlaps(range)
++ })
++ }
++
++ /// Leave the image's standing: `id`'s encoder ended with the image holding the truth, inside
++ /// `held` where given, stale inside `stale`. Its own copies back are behind it.
++ pub(super) fn stand(
++ self: &Arc,
++ (key, alias, range): (ResourceKey, Option, UseRange),
++ id: u64,
++ touched: u64,
++ held: Option<[u32; 4]>,
++ stale: Option<[u32; 4]>,
++ ) {
++ if self.truth.set((key, alias, range)).is_ok() {
++ let mut all = registry().write().unwrap();
++ all.retain(|lazy| lazy.strong_count() > 0);
++ all.push(Arc::downgrade(self));
++ ACTIVE.store(all.len(), Ordering::Relaxed);
++ ANY.store(true, Ordering::Relaxed);
++ }
++ *self.stood.lock().unwrap() = Some(Stood {
++ id,
++ touched,
++ held,
++ stale,
++ written: self.written.load(Ordering::Relaxed),
++ epoch: EPOCH.load(Ordering::Relaxed),
++ });
++ }
++
++ /// The encoder's end left the image not holding the truth.
++ pub(super) fn fall(&self) {
++ *self.stood.lock().unwrap() = None;
++ }
++
++ /// Where the image stands for an encoder that met `touched`, of a command buffer of identity
++ /// `id`: `Some((held, stale))` where it needs no copy in (the module docs).
++ pub(super) fn take(&self, id: u64, touched: u64) -> Option<(Option<[u32; 4]>, Option<[u32; 4]>)> {
++ let stood = (*self.stood.lock().unwrap())?;
++ let current = stood.touched == touched
++ && stood.written == self.written.load(Ordering::Relaxed)
++ && stood.epoch == EPOCH.load(Ordering::Relaxed)
++ && stood.id != id
++ && committed_ids().lock().unwrap().contains(&stood.id);
++ if !current {
++ REFUSED.fetch_add(1, Ordering::Relaxed);
++ return None;
++ }
++ let every = crate::live::get("surface_lazy_resync_ms")
++ .and_then(|v| v.parse().ok())
++ .unwrap_or(DEFAULT_RESYNC_MS);
++ if every > 0 {
++ let mut resynced = self.resynced.lock().unwrap();
++ if resynced.elapsed().as_millis() as u64 >= every {
++ *resynced = Instant::now();
++ RESYNCS.fetch_add(1, Ordering::Relaxed);
++ return None;
++ }
++ }
++ TAKEN.fetch_add(1, Ordering::Relaxed);
++ Some((stood.held, stood.stale))
++ }
++}
+diff --git a/crates/metal2vulkan-runtime/src/tests/shadow.rs b/crates/metal2vulkan-runtime/src/tests/shadow.rs
+index 3b723a86..cb943ca2 100644
+--- a/crates/metal2vulkan-runtime/src/tests/shadow.rs
++++ b/crates/metal2vulkan-runtime/src/tests/shadow.rs
+@@ -98,6 +98,7 @@ fn shadow_in(
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ })
+ }
+
+@@ -1430,6 +1431,7 @@ fn view_of(image: ResourceKey, levels: Range, layers: Range) -> Arc Result<(), Error> {
++ crate::shadow_lazy::everything_written(); // LOCAL (Atlas)
+ let upload = Upload::Slice(bytes);
+ self.replace(region, level, slice, upload, bytes_per_row, bytes_per_image)
+ }
+@@ -5393,6 +5394,7 @@ impl Texture {
+ bytes_per_row: u64,
+ bytes_per_image: u64,
+ ) -> Result<(), Error> {
++ crate::shadow_lazy::everything_written(); // LOCAL (Atlas)
+ let upload = Upload::Host {
+ bytes,
+ copy: OnceCell::new(),
+diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs
+index 1e13281c..8aba80f4 100644
+--- a/crates/metal2vulkan-runtime/src/texture/heap.rs
++++ b/crates/metal2vulkan-runtime/src/texture/heap.rs
+@@ -3380,6 +3380,7 @@ impl Device {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ Owner::HeapShadow(Box::new(HeapShadow {
+ placement,
+@@ -3480,6 +3481,7 @@ impl Device {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ Owner::HeapShadow(Box::new(HeapShadow {
+ placement,
+@@ -3557,6 +3559,7 @@ impl Device {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ Owner::HeapShadow(Box::new(HeapShadow {
+ placement,
+diff --git a/crates/metal2vulkan-runtime/src/texture/surface_depth.rs b/crates/metal2vulkan-runtime/src/texture/surface_depth.rs
+index 8617e0c5..563fbde8 100644
+--- a/crates/metal2vulkan-runtime/src/texture/surface_depth.rs
++++ b/crates/metal2vulkan-runtime/src/texture/surface_depth.rs
+@@ -171,6 +171,7 @@ impl Texture {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ let storage = Storage::Shadow {
+ image: image.shared(),
+diff --git a/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs b/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs
+index 322cb108..43c812d2 100644
+--- a/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs
++++ b/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs
+@@ -240,6 +240,7 @@ impl Device {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ self.degrade(Degradation::ShadowedTexture, || {
+ let [width, height, _] = layout.extent;
+diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
+index 654c899d..c73065f2 100644
+--- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
++++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs
+@@ -483,6 +483,7 @@ impl Device {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ Owner::ViewShadow(Box::new(ViewShadow {
+ placement,
+diff --git a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs
+index 2465608d..cf1d6816 100644
+--- a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs
++++ b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs
+@@ -376,6 +376,7 @@ impl Device {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ Ok(Storage::Shadow {
+ image: image.shared(),
+@@ -671,6 +672,7 @@ impl Texture {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ Ok((image, copies))
+ }
+@@ -839,6 +841,7 @@ impl Texture {
+ merge_scratch: ScratchSpares::default(),
+ touched: AtomicU64::new(0),
+ stood: AtomicU64::new(0),
++ lazy: None,
+ };
+ let storage = Storage::Shadow {
+ image: image.shared(),
+diff --git a/crates/metal2vulkan-validation/src/runtime_lane/host_rt_frames.rs b/crates/metal2vulkan-validation/src/runtime_lane/host_rt_frames.rs
+index d1c701b0..491f874d 100644
+--- a/crates/metal2vulkan-validation/src/runtime_lane/host_rt_frames.rs
++++ b/crates/metal2vulkan-validation/src/runtime_lane/host_rt_frames.rs
+@@ -32,7 +32,7 @@ use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage};
+ use metal2vulkan_runtime::{
+ live, Buffer, CommandBuffer, CpuCacheMode, Device, HazardTrackingMode, HostMemory,
+ IoSurfacePlane, LoadAction, RenderPassDescriptor, RenderPipelineState, ResourceOptions,
+- StorageMode, StoreAction, Texture, TextureDescriptor, WorkCounts,
++ ScissorRect, StorageMode, StoreAction, Texture, TextureDescriptor, WorkCounts,
+ };
+ use std::time::Instant;
+
+@@ -56,6 +56,13 @@ enum Shape {
+ /// The iOS Simulator's screen at 3x (1206x2622, rows of 4864 bytes): 42 command buffers of
+ /// one pass each blending a sixteenth of it, as the coordinator measured the sim's frames.
+ SimSmallApart,
++ /// LOCAL (Atlas): the 3200x1800 HiDPI desktop, 8 command buffers of one pass each, each
++ /// blending the whole surface.
++ HidpiWhole,
++ /// As [`Shape::HidpiWhole`], each pass scissored to a window's damage: a 1000x600 rectangle.
++ HidpiDamage,
++ /// LOCAL (Atlas): the Simulator's screen at 3x, 8 passes a frame blending all of it.
++ SimWhole,
+ }
+
+ impl Shape {
+@@ -66,16 +73,21 @@ impl Shape {
+ Shape::PassesApart => (3440, 1440, 13824, 10, true, false),
+ Shape::SmallApart => (3440, 1440, 13824, 10, true, true),
+ Shape::SimSmallApart => (1206, 2622, 4864, 42, true, true),
++ Shape::HidpiWhole | Shape::HidpiDamage => (3200, 1800, 12864, 8, true, false),
++ Shape::SimWhole => (1206, 2622, 4864, 8, true, false),
+ }
+ }
+ }
+
+-const SHAPES: [Shape; 5] = [
++const SHAPES: [Shape; 8] = [
+ Shape::Passes,
+ Shape::PassesViews,
+ Shape::PassesApart,
+ Shape::SmallApart,
+ Shape::SimSmallApart,
++ Shape::HidpiWhole,
++ Shape::HidpiDamage,
++ Shape::SimWhole,
+ ];
+
+ /// The switches' settings weighed.
+@@ -87,6 +99,8 @@ enum Setting {
+ InPlace,
+ /// `shadow_compressed`: the shadow, its image eligible for the driver's compression.
+ Compressed,
++ /// LOCAL (Atlas): `surface_lazy`: the image kept across command buffers (`shadow_lazy.rs`).
++ Lazy,
+ /// For the parts: the passes into a `Private` texture of the surface's size (optimal tiling,
+ /// the device's own memory), no shadow.
+ Private,
+@@ -96,19 +110,21 @@ enum Setting {
+ }
+
+ impl Setting {
+- fn switches(self) -> [(&'static str, &'static str); 2] {
++ fn switches(self) -> [(&'static str, &'static str); 3] {
+ let on = |yes: bool| if yes { "1" } else { "0" };
+ [
+ ("host_rt_in_place", on(self == Setting::InPlace)),
+ ("shadow_compressed", on(self == Setting::Compressed)),
++ ("surface_lazy", on(self == Setting::Lazy)),
+ ]
+ }
+ }
+
+-const SETTINGS: [Setting; 5] = [
++const SETTINGS: [Setting; 6] = [
+ Setting::Shadow,
+ Setting::InPlace,
+ Setting::Compressed,
++ Setting::Lazy,
+ Setting::Private,
+ Setting::LinearOwn,
+ ];
+@@ -158,6 +174,7 @@ fn pass(
+ blend: &RenderPipelineState,
+ rects: &[Buffer],
+ color: &Buffer,
++ damage: Option,
+ ) {
+ let mut descriptor = RenderPassDescriptor::new();
+ let attachment = &mut descriptor.color_attachments[0];
+@@ -167,6 +184,9 @@ fn pass(
+ let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap();
+ encoder.set_render_pipeline_state(blend).unwrap();
+ encoder.set_fragment_buffer(Some(color), 0, 0).unwrap();
++ if let Some(damage) = damage {
++ encoder.set_scissor_rect(damage).unwrap();
++ }
+ for rect in rects {
+ encoder.set_vertex_buffer(Some(rect), 0, 0).unwrap();
+ encoder
+@@ -202,7 +222,7 @@ fn hash(bytes: &[u8]) -> u64 {
+ #[test]
+ #[ignore = "a release-mode measurement: run by name"]
+ fn host_rt_frame_costs() {
+- let len = ((13824 * 1440) as usize).next_multiple_of(16384);
++ let len = ((12864 * 1800) as usize).next_multiple_of(16384);
+ let mapping = Mapping::anonymous(len);
+ // SAFETY: the mapping's bytes, which no device uses between the cases.
+ let bytes = || unsafe { std::slice::from_raw_parts_mut(mapping.pointer().as_ptr(), len) };
+@@ -215,7 +235,8 @@ fn host_rt_frame_costs() {
+ // image on ANV.
+ let parts = matches!(setting, Setting::Private | Setting::LinearOwn);
+ if (shape == Shape::PassesViews && parts)
+- || (shape == Shape::SimSmallApart && setting == Setting::LinearOwn)
++ || (matches!(shape, Shape::SimSmallApart | Shape::SimWhole)
++ && setting == Setting::LinearOwn)
+ {
+ continue;
+ }
+@@ -305,6 +326,12 @@ fn host_rt_frame_costs() {
+ (buffer, surface, form)
+ }
+ };
++ let damage = (shape == Shape::HidpiDamage).then_some(ScissorRect {
++ x: 800,
++ y: 500,
++ width: 1000,
++ height: 600,
++ });
+ let (mut waits, mut gpus) = (Vec::new(), Vec::new());
+ let mut before = device.work_counts();
+ for k in 0..WARM + FRAMES {
+@@ -312,20 +339,21 @@ fn host_rt_frame_costs() {
+ before = device.work_counts();
+ }
+ let mut command_buffers = vec![queue.command_buffer().unwrap()];
+- pass(&command_buffers[0], &surface, &blend, rects, &color);
++ pass(&command_buffers[0], &surface, &blend, rects, &color, damage);
++ let committed = Instant::now();
+ for _ in 1..passes {
+ if apart {
++ // As the guest's: each committed before the next is encoded.
++ let last = command_buffers.last().unwrap();
++ last.commit().unwrap();
+ let command_buffer = queue.command_buffer().unwrap();
+- pass(&command_buffer, &surface, &blend, rects, &color);
++ pass(&command_buffer, &surface, &blend, rects, &color, damage);
+ command_buffers.push(command_buffer);
+ } else {
+- pass(&command_buffers[0], &surface, &blend, rects, &color);
++ pass(&command_buffers[0], &surface, &blend, rects, &color, damage);
+ }
+ }
+- let committed = Instant::now();
+- for command_buffer in &command_buffers {
+- command_buffer.commit().unwrap();
+- }
++ command_buffers.last().unwrap().commit().unwrap();
+ let mut gpu = 0.0;
+ for command_buffer in &command_buffers {
+ command_buffer.wait_until_completed_for(WAIT).unwrap();
+@@ -357,6 +385,7 @@ fn host_rt_frame_costs() {
+ device.name(),
+ per_frame(&before, &after),
+ );
++ eprintln!("LAZY-COUNTS {:?}", metal2vulkan_runtime::shadow_lazy::counts());
+ results.push((shape, setting, digest, between_kept));
+ }
+ }
diff --git a/patches/metal2vulkan/0010-surface_lazy-a-commit-does-nothing-while.patch b/patches/metal2vulkan/0010-surface_lazy-a-commit-does-nothing-while.patch
new file mode 100644
index 0000000..ae1f9b9
--- /dev/null
+++ b/patches/metal2vulkan/0010-surface_lazy-a-commit-does-nothing-while.patch
@@ -0,0 +1,63 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 31 Oct 2026 19:57:22 +0000
+Subject: [PATCH 10/34] surface_lazy: a commit does nothing
+ while no surface is lazy; counts on stderr
+
+Co-Authored-By: Claude Opus 5.5
+---
+ .../metal2vulkan-runtime/src/command_buffer/mod.rs | 6 ++++--
+ crates/metal2vulkan-runtime/src/shadow_lazy.rs | 14 ++++++++++----
+ 2 files changed, 14 insertions(+), 6 deletions(-)
+
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+index 7b19ebee..3c1c74f2 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+@@ -2506,8 +2506,10 @@ impl CommandBuffer {
+ run: CommitRun,
+ ) -> Result<(), Error> {
+ // LOCAL (Atlas): a later command buffer may take its surfaces' images (`shadow_lazy.rs`).
+- if let Some(id) = self.state().shadow_carry.as_ref().map(ShadowCarry::id) {
+- crate::shadow_lazy::committed(id);
++ if crate::shadow_lazy::active() {
++ if let Some(id) = self.state().shadow_carry.as_ref().map(ShadowCarry::id) {
++ crate::shadow_lazy::committed(id);
++ }
+ }
+ // The waiting fetched render targets take their storage form at this commit where it
+ // allows (`storage_form.rs`): one atomic read where none waits. The scheduler's thread
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index e05af1f8..b1d61a39 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -85,11 +85,13 @@ pub(crate) fn everything_written() {
+ }
+ }
+
++/// Whether any surface is lazy, one atomic read: while none is, a commit does nothing here.
++pub(crate) fn active() -> bool {
++ ANY.load(Ordering::Relaxed)
++}
++
+ /// Note the command buffer of identity `id` committed.
+ pub(crate) fn committed(id: u64) {
+- if !ANY.load(Ordering::Relaxed) {
+- return;
+- }
+ let mut ids = committed_ids().lock().unwrap();
+ if ids.len() == COMMITTED_KEPT {
+ ids.pop_front();
+@@ -216,7 +218,11 @@ impl Lazy {
+ let mut resynced = self.resynced.lock().unwrap();
+ if resynced.elapsed().as_millis() as u64 >= every {
+ *resynced = Instant::now();
+- RESYNCS.fetch_add(1, Ordering::Relaxed);
++ let resyncs = RESYNCS.fetch_add(1, Ordering::Relaxed) + 1;
++ if resyncs % 40 == 1 {
++ let (taken, refused, resyncs) = counts();
++ eprintln!("surface_lazy: taken {taken} refused {refused} resyncs {resyncs}");
++ }
+ return None;
+ }
+ }
diff --git a/patches/metal2vulkan/0011-surface_lazy-name-the-refused-takes-scope-them-and-l.patch b/patches/metal2vulkan/0011-surface_lazy-name-the-refused-takes-scope-them-and-l.patch
new file mode 100644
index 0000000..5ac4759
--- /dev/null
+++ b/patches/metal2vulkan/0011-surface_lazy-name-the-refused-takes-scope-them-and-l.patch
@@ -0,0 +1,1587 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: macbox
+Date: Sat, 31 Oct 2026 21:27:15 +0000
+Subject: [PATCH 11/34] surface_lazy: name the refused takes, scope them, and
+ leave a displayed surface's writes ahead
+
+Under surface_lazy, every remap and every replaceRegion of any texture moved
+one global epoch, which refused every surface's next take. stderr now counts
+takes by reason and copies in by cause, per surface too.
+
+New live switches, default off, nothing changes without them:
+- surface_lazy_scoped: a remap or CPU write drops the standing of the
+ surfaces over those pages alone.
+- surface_lazy_present: a surface the display presented leaves its writes
+ ahead in its image; a present, a command buffer using its bytes, a CPU call
+ through a texture or a clock copies them back, once, in a command buffer of
+ its own, inside the union of the scissors.
+- surface_lazy_present_all: every lazy surface.
+- surface_lazy_present_max_ms: the clock's bound (default 100).
+- surface_lazy_min_width: keeps narrower surfaces out (default none).
+
+Co-Authored-By: Claude Opus 5.5
+---
+ crates/metal2vulkan-runtime/src/blit.rs | 16 +-
+ crates/metal2vulkan-runtime/src/buffer.rs | 5 +
+ .../src/buffer_descriptor.rs | 5 +-
+ .../src/buffer_texture.rs | 6 +
+ .../src/command_buffer/mod.rs | 42 +-
+ crates/metal2vulkan-runtime/src/encoder.rs | 20 +-
+ crates/metal2vulkan-runtime/src/host_rt.rs | 2 +-
+ crates/metal2vulkan-runtime/src/shadow.rs | 39 +-
+ .../metal2vulkan-runtime/src/shadow_lazy.rs | 695 +++++++++++++++++-
+ crates/metal2vulkan-runtime/src/texture.rs | 31 +-
+ crates/metal2vulkan-runtime/src/tracker.rs | 5 +
+ .../src/runtime_lane.rs | 2 +
+ .../src/runtime_lane/host_rt_frames.rs | 4 +-
+ .../src/runtime_lane/surface_present.rs | 336 +++++++++
+ 14 files changed, 1170 insertions(+), 38 deletions(-)
+ create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/surface_present.rs
+
+diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs
+index d7ed3c16..523cac1c 100644
+--- a/crates/metal2vulkan-runtime/src/blit.rs
++++ b/crates/metal2vulkan-runtime/src/blit.rs
+@@ -30,7 +30,7 @@ use super::error::{invalid, Error, Problem};
+ use super::fresh_unwritten::FreshRead;
+ use super::replay::{BlitCall, CallLog, Replay, Resource};
+ use super::resource::{ResourceKey, ResourceRef};
+-use super::shadow::{self, Covered, ShadowCopies};
++use super::shadow::{self, Covered, ShadowCopies, ShadowCopy};
+ use super::texture::Texture;
+ use super::tracker::{Access, Use, UseRange};
+ use super::used_resources::EncoderKind;
+@@ -197,6 +197,20 @@ impl CommandBuffer {
+ }
+
+ impl BlitCommandEncoder {
++ /// LOCAL (Atlas): record `copy`, a surface's copy back (`shadow_lazy.rs`), holding `holds` until
++ /// it completes. Never encoded again: the encoder keeps no log.
++ pub(super) fn surface_copy_back(
++ &mut self,
++ copy: &ShadowCopy,
++ holds: Vec,
++ ) {
++ self.log = None;
++ self.core.shadow_copies(std::slice::from_ref(copy));
++ for hold in holds {
++ self.core.retain_shared(hold);
++ }
++ }
++
+ /// An encoder that encodes an ended one of `command_buffer` again (`replay.rs`): it logs
+ /// nothing.
+ pub(super) fn replaying(command_buffer: &CommandBuffer) -> Result {
+diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs
+index 57d569a8..2100fa26 100644
+--- a/crates/metal2vulkan-runtime/src/buffer.rs
++++ b/crates/metal2vulkan-runtime/src/buffer.rs
+@@ -3042,6 +3042,11 @@ impl Buffer {
+ }
+ }
+
++ /// LOCAL (Atlas): where a buffer over host pages lies (`HostCell::host_range`).
++ pub(super) fn host_range(&self) -> Option> {
++ self.pages_cell()?.host_range()
++ }
++
+ /// The key of the host memory a no-copy buffer joined, made over the bytes another covers
+ /// (`host_aliases.rs`): its uses carry one of that key too. `None` for any other buffer.
+ pub(super) fn alias(&self) -> Option {
+diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs
+index 3dfe1a02..ce968ec2 100644
+--- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs
++++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs
+@@ -371,7 +371,10 @@ impl Device {
+ /// live it returns at once, and otherwise it finds the buffers over the range by address,
+ /// whether the range covers none of them or many, never reading them all.
+ pub fn host_range_remapped(&self, bytes: NonNull, length: u64) {
+- crate::shadow_lazy::everything_written(); // LOCAL (Atlas)
++ // LOCAL (Atlas)
++ crate::shadow_lazy::remapped(
++ bytes.as_ptr() as usize..(bytes.as_ptr() as usize).saturating_add(length as usize),
++ );
+ let start = bytes.as_ptr() as u64;
+ let shared = self.shared();
+ // The unit an import's pages round out to: an import by pointer over a page the call
+diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs
+index c4c29b08..d466dd62 100644
+--- a/crates/metal2vulkan-runtime/src/buffer_texture.rs
++++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs
+@@ -1428,7 +1428,13 @@ impl Texels {
+ stood: AtomicU64::new(0),
+ // LOCAL (Atlas): `shadow_lazy.rs`.
+ lazy: super::shadow_lazy::Lazy::of(
++ self.buffer.device(),
+ self.backing() == super::shadow::Backing::Surface,
++ || self.buffer.host_range(),
++ [
++ (self.layout.row_bytes / self.texel_bytes) as u32,
++ self.layout.rows as u32,
++ ],
+ self.layout.row_bytes / self.texel_bytes * u64::from(self.layout.rows),
+ ),
+ })
+diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+index 3c1c74f2..97d01cf3 100644
+--- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
++++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs
+@@ -2505,12 +2505,46 @@ impl CommandBuffer {
+ failure: Option,
+ run: CommitRun,
+ ) -> Result<(), Error> {
+- // LOCAL (Atlas): a later command buffer may take its surfaces' images (`shadow_lazy.rs`).
+- if crate::shadow_lazy::active() {
+- if let Some(id) = self.state().shadow_carry.as_ref().map(ShadowCarry::id) {
+- crate::shadow_lazy::committed(id);
++ // LOCAL (Atlas): a later command buffer may take its surfaces' images, and what this one
++ // needs of the bytes they hold ahead goes back first (`shadow_lazy.rs`).
++ let lazy = match crate::shadow_lazy::active() {
++ true => self.state().shadow_carry.as_ref().map(ShadowCarry::id),
++ false => None,
++ };
++ if let Some(id) = lazy {
++ if crate::shadow_lazy::ahead() {
++ let met = {
++ let state = self.state();
++ let summaries: Vec<_> = (state.recorded.iter())
++ .flat_map(|part| {
++ let segments = (part.segments.iter())
++ .filter_map(|segment| segment.recorded.as_ref());
++ std::iter::once(&part.summary)
++ .chain(segments.map(|recording| &recording.summary))
++ })
++ .collect();
++ crate::shadow_lazy::met_by(&summaries)
++ };
++ for surface in met {
++ surface.flush();
++ }
+ }
++ crate::shadow_lazy::committed(id);
++ }
++ let committed = self.commit_settled_now(call, failure, run);
++ if let Some(id) = lazy {
++ crate::shadow_lazy::after_commit(id);
+ }
++ committed
++ }
++
++ /// [`commit_settled`](Self::commit_settled), the surfaces' notes aside.
++ fn commit_settled_now(
++ &self,
++ call: &'static str,
++ failure: Option,
++ run: CommitRun,
++ ) -> Result<(), Error> {
+ // The waiting fetched render targets take their storage form at this commit where it
+ // allows (`storage_form.rs`): one atomic read where none waits. The scheduler's thread
+ // ends the switch once it submitted the command buffer. None where nothing of it runs.
+diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs
+index 5b217e85..fd64a5b6 100644
+--- a/crates/metal2vulkan-runtime/src/encoder.rs
++++ b/crates/metal2vulkan-runtime/src/encoder.rs
+@@ -458,13 +458,14 @@ impl EncoderCore {
+ // which this one's first uses of them take instead of copying the truth in again
+ // (`shadow::ShadowCarry`).
+ let carry = state.shadows_to_carry();
++ let id = carry.id();
+ drop(state);
+ command_buffer
+ .device()
+ .shared()
+ .identifiers
+ .encoder_opened(kind);
+- Ok(EncoderCore {
++ let mut core = EncoderCore {
+ open: OpenGuard {
+ command_buffer: command_buffer.clone(),
+ ended: false,
+@@ -498,7 +499,19 @@ impl EncoderCore {
+ replaying: false,
+ last_set_zero: LastSetZero::default(),
+ _not_sync: PhantomData,
+- })
++ };
++ // LOCAL (Atlas): this command buffer's earlier encoders may have left writes ahead in a
++ // surface's image, which this one may read through its bytes (`shadow_lazy.rs`).
++ if crate::shadow_lazy::ahead() {
++ for (lazy, copy, holds) in crate::shadow_lazy::deferred_by(id) {
++ let _own = lazy.own();
++ core.shadow_copies(std::slice::from_ref(©));
++ for hold in holds {
++ core.retain_shared(hold);
++ }
++ }
++ }
++ Ok(core)
+ }
+
+ /// The core a segment of `command_buffer` records into at its commit, `ordered` as the
+@@ -2006,7 +2019,8 @@ impl EncoderCore {
+ if sharing > 0 {
+ self.device().shared().counts.shadows_sharing_truth(sharing);
+ }
+- let copies = self.shadows.finish();
++ // LOCAL (Atlas): a surface may leave its writes ahead in its image (`shadow_lazy.rs`).
++ let copies = self.shadows.finish_leaving_ahead();
+ let copies = self.sample_moves(copies);
+ self.count_shadow_copies(&copies);
+ self.shadow_copies(&copies);
+diff --git a/crates/metal2vulkan-runtime/src/host_rt.rs b/crates/metal2vulkan-runtime/src/host_rt.rs
+index fbf18b08..bbee9add 100644
+--- a/crates/metal2vulkan-runtime/src/host_rt.rs
++++ b/crates/metal2vulkan-runtime/src/host_rt.rs
+@@ -260,7 +260,7 @@ impl Device {
+ return false;
+ }
+ // LOCAL (Atlas): an optimal image kept across command buffers instead (`shadow_lazy.rs`).
+- if crate::shadow_lazy::takes_surface(texels) {
++ if crate::shadow_lazy::takes_surface(extent[0], texels) {
+ return false;
+ }
+ if self.compile_device().policy().host_page_textures != HostPageTexturePolicy::InPlace {
+diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs
+index a70e6a7c..2853f759 100644
+--- a/crates/metal2vulkan-runtime/src/shadow.rs
++++ b/crates/metal2vulkan-runtime/src/shadow.rs
+@@ -2060,7 +2060,7 @@ pub(super) struct ShadowUse {
+ }
+
+ /// The rectangle bounding `a` and `b`, each `[x0, y0, x1, y1)`; `None` (anywhere) where either is.
+-fn bounding(a: Option<[u32; 4]>, b: Option<[u32; 4]>) -> Option<[u32; 4]> {
++pub(super) fn bounding(a: Option<[u32; 4]>, b: Option<[u32; 4]>) -> Option<[u32; 4]> {
+ let ([a0, a1, a2, a3], [b0, b1, b2, b3]) = (a?, b?);
+ Some([a0.min(b0), a1.min(b1), a2.max(b2), a3.max(b3)])
+ }
+@@ -2588,6 +2588,10 @@ impl ShadowSync {
+ cause: Some(cause),
+ moves: None,
+ });
++ // LOCAL (Atlas): counted by cause (`shadow_lazy.rs`).
++ if let Some(lazy) = &shadow.copies.lazy {
++ lazy.copied_in(cause);
++ }
+ }
+ entry.standing = Standing::Current;
+ entry.held = needs;
+@@ -2617,6 +2621,10 @@ impl ShadowSync {
+ cause: Some(CopyCause::Bounded),
+ moves: None,
+ });
++ // LOCAL (Atlas): as above.
++ if let Some(lazy) = &shadow.copies.lazy {
++ lazy.copied_in(CopyCause::Bounded);
++ }
+ }
+ }
+ // The command writes every texel before it reads any.
+@@ -2763,4 +2771,33 @@ impl ShadowSync {
+ }
+ copies
+ }
++
++ /// LOCAL (Atlas): [`finish`](Self::finish) at an encoder's own end, where a surface may leave
++ /// what it wrote ahead in its image instead (`shadow_lazy.rs`): one alone in the encoder over
++ /// its bytes, with nothing kept to merge.
++ pub(super) fn finish_leaving_ahead(&mut self) -> Vec> {
++ let mut copies = Vec::new();
++ for i in 0..self.entries.len() {
++ if !self.entries[i].dirty {
++ continue;
++ }
++ let entry = &self.entries[i];
++ let alone = (self.entries.iter().enumerate())
++ .all(|(j, other)| j == i || !other.copies.shares_truth(&entry.copies));
++ let left = alone
++ && entry.merge.is_none()
++ && !entry.two_ways
++ && (entry.copies.lazy.as_ref())
++ .is_some_and(|lazy| lazy.defer(&entry.copies, entry.area, self.carry.id));
++ match left {
++ true => {
++ let entry = &mut self.entries[i];
++ entry.dirty = false;
++ entry.area = None;
++ }
++ false => self.copy_back(i, &mut copies),
++ }
++ }
++ copies
++ }
+ }
+diff --git a/crates/metal2vulkan-runtime/src/shadow_lazy.rs b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+index b1d61a39..013f6559 100644
+--- a/crates/metal2vulkan-runtime/src/shadow_lazy.rs
++++ b/crates/metal2vulkan-runtime/src/shadow_lazy.rs
+@@ -16,7 +16,7 @@
+ //! where nothing wrote the bytes since. Every write a command records of them, through anything
+ //! else over them (`shadow::ShadowCopies::meets`, an alias of the same pages too) drops it
+ //! ([`note_writes`]), as do a remap of host pages and a CPU write through a texture
+-//! ([`everything_written`]).
++//! ([`remapped`], [`cpu_wrote`]).
+ //! - **No keep and merge.** Its copy back writes the rectangle the commands wrote in, where their
+ //! scissors bound it, or every texel. A CPU write inside that rectangle while the command buffer
+ //! runs is lost, where the merge keeps it: the guest's CPU does not write a surface it renders
+@@ -35,18 +35,74 @@
+ //!
+ //! **Command buffers encoded out of order**: a standing is taken only from a command buffer already
+ //! committed ([`committed`]), whose commands Metal orders before the taker's.
++//!
++//! **What refuses a standing** is on stderr every [`REPORT_MS`] ms while a surface is lazy, by
++//! reason and by surface ([`report`]), so a capture names the cause of each copy in.
++//!
++//! **Under the switch `surface_lazy_scoped`** (default off) a remap or a CPU write through a texture
++//! drops the standing of the surfaces over those pages alone ([`remapped`], [`cpu_wrote`]). Off, each
++//! moves [`EPOCH`], which drops every surface's standing whatever the pages or the texture: a
++//! guest's upload into any texture and any Mach VM call that reports pages.
++//!
++//! **Under the switch `surface_lazy_present`** (default off) a surface the display presented once
++//! ([`presented`]; every lazy surface under `surface_lazy_present_all`) copies back only when
++//! something needs its bytes. Its encoders leave what they wrote ahead in the image ([`Pending`]),
++//! the rectangle bounding their writes where their scissors bound them, every texel else. Each of
++//! these copies it back, once, in a command buffer of its own ([`Lazy::flush`]):
++//!
++//! - **A present**, after the command buffer that wrote last is committed ([`after_commit`]).
++//! - **A command buffer that uses the bytes**, through any other import or a blit of the texture
++//! itself, or copies them in: before its commit ([`met_by`]), where the commit-order tracker
++//! orders the copy after the writers committed before it and before that command buffer. Its
++//! summaries hold every use the encoders recorded, the host memory's among them.
++//! - **A later encoder of the writer's own command buffer**, as it opens, inside it
++//! ([`deferred_by`]): the commit-time copy would run after that encoder.
++//! - **A CPU read or write through a texture** over the pages, which waits for it ([`cpu_reads`],
++//! [`cpu_wrote`]).
++//! - **The clock**: `surface_lazy_present_max_ms` (default 100) after the first write left ahead, on
++//! a thread of its own ([`flush_due`]), so nothing stays stale past it after the guest goes idle.
++//!
++//! Each moves only what committed command buffers wrote: a write stays out of every copy back
++//! until its commit returns, as a copy back recorded before it runs before it.
++//!
++//! **Who can read stale bytes**, each for at most that bound and only of a surface left ahead: the
++//! guest's CPU through its own mapping of the pages, which reaches the host through no call, and a
++//! host reader of the pages that goes through no command buffer. Under the switch a CPU write into
++//! the pages that lies inside the rectangle is overwritten by the copy back, where
++//! `surface_lazy` alone keeps it unless a command buffer runs meanwhile.
++//!
++//! **A texture released while ahead** is not copied back where nothing else holds its image: its
++//! pages may be another surface's by then.
+
++use super::command_buffer::CommandBuffer;
++use super::device::Device;
++use super::queue::CommandQueue;
+ use super::resource::ResourceKey;
+-use super::tracker::{Use, UseRange};
++use super::shadow::{bounding, CopyCause, ShadowCopies, ShadowCopy, Step};
++use super::tracker::{Summary, Use, UseRange};
++use crate::exit_guard;
++use std::any::Any;
++use std::cell::Cell;
+ use std::collections::VecDeque;
++use std::ops::Range;
+ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+ use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak};
+-use std::time::Instant;
++use std::time::{Duration, Instant};
+
+ /// The live switch.
+ const SWITCH: &str = "surface_lazy";
+ const DEFAULT_MIN_TEXELS: u64 = 2_000_000;
+ const DEFAULT_RESYNC_MS: u64 = 250;
++/// The live switch that drops a standing by the pages written (the module docs).
++const SCOPED: &str = "surface_lazy_scoped";
++/// The live switch that leaves a displayed surface's writes ahead in its image (the module docs).
++const PRESENT: &str = "surface_lazy_present";
++/// With [`PRESENT`]: every lazy surface, presented or not.
++const PRESENT_ALL: &str = "surface_lazy_present_all";
++/// How long a write stays ahead at most, unless nothing reads it.
++const DEFAULT_PRESENT_MAX_MS: u64 = 100;
++/// How often the counts go to stderr while a surface is lazy.
++const REPORT_MS: u64 = 2000;
+ /// The committed command buffers remembered: an older one's standing is not taken.
+ const COMMITTED_KEPT: usize = 256;
+
+@@ -58,6 +114,49 @@ static TAKEN: AtomicU64 = AtomicU64::new(0);
+ static REFUSED: AtomicU64 = AtomicU64::new(0);
+ static RESYNCS: AtomicU64 = AtomicU64::new(0);
+ static ACTIVE: AtomicUsize = AtomicUsize::new(0);
++/// The takes refused, by [`Refused`]: the first test each failed.
++static REFUSED_BY: [AtomicU64; Refused::COUNT] = [const { AtomicU64::new(0) }; Refused::COUNT];
++/// The copies in made of lazy surfaces, by [`CopyCause`]: first, beyond held, changed, bounded.
++static IN_BY: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
++/// How many surfaces hold writes ahead in their images: every hook returns at once while none does.
++static AHEAD: AtomicUsize = AtomicUsize::new(0);
++static DEFERRED: AtomicU64 = AtomicU64::new(0);
++static FLUSHES: AtomicU64 = AtomicU64::new(0);
++static FLUSHED_WHOLE: AtomicU64 = AtomicU64::new(0);
++static FLUSHED_TEXELS: AtomicU64 = AtomicU64::new(0);
++static DISCARDED: AtomicU64 = AtomicU64::new(0);
++static PRESENTS: AtomicU64 = AtomicU64::new(0);
++static PRESENTS_UNMATCHED: AtomicU64 = AtomicU64::new(0);
++/// Milliseconds since the first report's chance at the last report.
++static REPORTED: AtomicU64 = AtomicU64::new(0);
++
++thread_local! {
++ /// The surface whose own copy back this thread records: neither a write that drops its standing
++ /// nor a use that asks for a copy back.
++ static OWN: Cell<*const Lazy> = const { Cell::new(std::ptr::null()) };
++}
++
++/// Why a take found no standing it could use.
++#[derive(Clone, Copy)]
++enum Refused {
++ /// None stood: the surface's first use, or an encoder's end left the image not holding the truth
++ /// ([`Lazy::fall`]). Not among [`REFUSED`]'s.
++ NoStanding,
++ /// An encoder's end that used the image came between ([`ShadowCopies::touched`]).
++ Touched,
++ /// A write of the truth came between ([`note_writes`], [`remapped`], [`cpu_wrote`]).
++ Written,
++ /// [`EPOCH`] moved.
++ Epoch,
++ /// The standing is the taker's own command buffer's.
++ OwnBuffer,
++ /// The standing's command buffer is not committed.
++ Uncommitted,
++}
++
++impl Refused {
++ const COUNT: usize = 6;
++}
+
+ fn registry() -> &'static RwLock>> {
+ static ALL: OnceLock>>> = OnceLock::new();
+@@ -69,22 +168,108 @@ fn committed_ids() -> &'static Mutex> {
+ IDS.get_or_init(Mutex::default)
+ }
+
+-/// Whether a texture over host pages of `texels` stays a shadow to render lazily (`host_rt.rs`).
+-pub(crate) fn takes_surface(texels: u64) -> bool {
++/// Whether a texture over host pages of `width` and `texels` stays a shadow to render lazily
++/// (`host_rt.rs`): `surface_lazy_min_width` (default none) keeps a narrow surface, a Simulator's
++/// portrait display among them, out, as it is made and whatever is presented later.
++pub(crate) fn takes_surface(width: u32, texels: u64) -> bool {
++ let wide = crate::live::get("surface_lazy_min_width")
++ .and_then(|v| v.parse().ok())
++ .is_none_or(|min: u32| width >= min);
+ crate::live::on(SWITCH, false)
++ && wide
+ && texels
+ >= crate::live::get("surface_lazy_min_texels")
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(DEFAULT_MIN_TEXELS)
+ }
+
+-/// Note that what may hold any surface's bytes changed without a command.
+-pub(crate) fn everything_written() {
+- if ANY.load(Ordering::Relaxed) {
++/// Every surface registered, none held while the caller works.
++fn surfaces() -> Vec> {
++ (registry().read().unwrap().iter())
++ .filter_map(Weak::upgrade)
++ .collect()
++}
++
++/// Whether two ranges of host addresses share a byte.
++fn meet(a: &Range, b: &Range) -> bool {
++ a.start < b.end && b.start < a.end
++}
++
++/// Note a change of the pages under `bytes` without a command (`Device::host_range_remapped`).
++pub(crate) fn remapped(bytes: Range) {
++ if !ANY.load(Ordering::Relaxed) {
++ return;
++ }
++ if !crate::live::on(SCOPED, false) {
++ EPOCH.fetch_add(1, Ordering::Relaxed);
++ return;
++ }
++ for lazy in surfaces() {
++ if lazy.over(&bytes) {
++ lazy.written.fetch_add(1, Ordering::Relaxed);
++ }
++ }
++}
++
++/// Note a CPU write through a texture over the host bytes `bytes`, `None` for one over none: a
++/// surface over them that holds writes ahead copies them back first, so the CPU's write stays.
++pub(crate) fn cpu_wrote(bytes: impl Fn() -> Option>) {
++ if !ANY.load(Ordering::Relaxed) {
++ return;
++ }
++ cpu_reads(&bytes);
++ if !crate::live::on(SCOPED, false) {
+ EPOCH.fetch_add(1, Ordering::Relaxed);
++ return;
++ }
++ let Some(bytes) = bytes() else {
++ return;
++ };
++ for lazy in surfaces() {
++ if lazy.over(&bytes) {
++ lazy.written.fetch_add(1, Ordering::Relaxed);
++ }
+ }
+ }
+
++/// Before a CPU read through a texture over the host bytes `bytes`: each surface over them that
++/// holds writes ahead copies them back, which this waits for.
++pub(crate) fn cpu_reads(bytes: impl Fn() -> Option>) {
++ if !ahead() {
++ return;
++ }
++ let Some(bytes) = bytes() else {
++ return;
++ };
++ for lazy in surfaces() {
++ if lazy.over(&bytes) {
++ if let Some(flush) = lazy.flush() {
++ let _ = flush.wait_until_completed();
++ }
++ }
++ }
++}
++
++/// Note that the display presents the surface over the host bytes `bytes`: it leaves its writes
++/// ahead from now on, and those it holds are copied back now, or once their last writer commits.
++pub(crate) fn presented(bytes: impl Fn() -> Option>) {
++ if !ANY.load(Ordering::Relaxed) || !crate::live::on(PRESENT, false) {
++ return;
++ }
++ let bytes = bytes();
++ let mut matched = false;
++ for lazy in surfaces() {
++ if bytes.as_ref().is_some_and(|bytes| lazy.over(bytes)) {
++ matched = true;
++ lazy.displayed.store(true, Ordering::Relaxed);
++ lazy.presents.fetch_add(1, Ordering::Relaxed);
++ lazy.flush_once_committed();
++ }
++ }
++ let count = if matched { &PRESENTS } else { &PRESENTS_UNMATCHED };
++ count.fetch_add(1, Ordering::Relaxed);
++}
++
+ /// Whether any surface is lazy, one atomic read: while none is, a commit does nothing here.
+ pub(crate) fn active() -> bool {
+ ANY.load(Ordering::Relaxed)
+@@ -109,13 +294,178 @@ pub(super) fn note_writes(uses: &[Use]) {
+ let all = registry().read().unwrap();
+ for used in uses.iter().filter(|used| !used.write.is_empty()) {
+ for lazy in all.iter().filter_map(Weak::upgrade) {
+- if lazy.meets(used) {
++ if lazy.meets(used) && !lazy.own_thread() {
+ lazy.written.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ }
+ }
+
++/// Whether any surface holds writes ahead in its image, one atomic read.
++pub(crate) fn ahead() -> bool {
++ AHEAD.load(Ordering::Relaxed) > 0
++}
++
++/// The surfaces to copy back before the commit of a command buffer whose encoders' uses are
++/// `summaries`: each that committed writes of lie ahead and that it uses the bytes of (the module
++/// docs). A copy in is such a use, so its command buffer's own writes wait for its commit.
++pub(crate) fn met_by(summaries: &[&Summary]) -> Vec> {
++ let mut met = Vec::new();
++ for lazy in surfaces() {
++ let settled = (lazy.pending.lock().unwrap().as_ref())
++ .is_some_and(|left| left.settled.is_some());
++ let used = || (summaries.iter()).any(|s| s.all_uses().iter().any(|u| lazy.meets(u)));
++ if settled && !lazy.own_thread() && used() {
++ met.push(lazy);
++ }
++ }
++ met
++}
++
++/// After the commit of the command buffer of identity `id`: a copy back of what it wrote may run,
++/// and the presents that waited for it do.
++pub(crate) fn after_commit(id: u64) {
++ if !ahead() {
++ return;
++ }
++ for lazy in surfaces() {
++ if let Some(left) = lazy.pending.lock().unwrap().as_mut() {
++ left.committed(id);
++ }
++ let wants =
++ lazy.flush_after
++ .compare_exchange(id, 0, Ordering::Relaxed, Ordering::Relaxed);
++ if wants.is_ok() {
++ lazy.flush();
++ }
++ }
++}
++
++/// What earlier encoders of the command buffer of identity `id` left ahead, for the encoder opening
++/// now to copy back: each surface, its copy and what it holds until the copy completes.
++pub(crate) fn deferred_by(id: u64) -> Vec<(Arc, ShadowCopy, Vec)> {
++ let mut left = Vec::new();
++ for lazy in surfaces() {
++ let mut pending = lazy.pending.lock().unwrap();
++ let Some(ahead) = pending.as_mut() else {
++ continue;
++ };
++ let Some(at) = ahead.open.iter().position(|(open, _)| *open == id) else {
++ continue;
++ };
++ let (_, area) = ahead.open.swap_remove(at);
++ let copy = copy_back_of(ahead.copies.clone(), area);
++ let holds = ahead.holds.clone();
++ if ahead.settled.is_none() && ahead.open.is_empty() {
++ *pending = None;
++ drop(pending);
++ lazy.left_behind();
++ } else {
++ drop(pending);
++ }
++ left.push((lazy, copy, holds));
++ }
++ left
++}
++
++/// The copies back the clock asks for (the module docs): whether any surface holds writes ahead.
++fn flush_due(max: Duration) -> bool {
++ let mut any = false;
++ for lazy in surfaces() {
++ let due = (lazy.pending.lock().unwrap().as_ref()).map(|left| {
++ let waited = left.since.elapsed();
++ waited >= max && (left.settled.is_some() || waited >= max * 4)
++ });
++ any |= due.is_some();
++ if due == Some(true) {
++ let Some(_section) = exit_guard::enter() else {
++ return false;
++ };
++ exit_guard::lowering_program_calls(|| lazy.flush());
++ }
++ }
++ any
++}
++
++/// The thread of the clock, started with the first write left ahead.
++fn start_clock() -> Option {
++ static CLOCK: OnceLock> = OnceLock::new();
++ CLOCK
++ .get_or_init(|| {
++ let builder = std::thread::Builder::new().name("m2v-surface-clock".into());
++ let run = || loop {
++ if exit_guard::closed() {
++ return;
++ }
++ let max = (crate::live::get("surface_lazy_present_max_ms"))
++ .and_then(|v| v.parse().ok())
++ .unwrap_or(DEFAULT_PRESENT_MAX_MS)
++ .max(1);
++ match flush_due(Duration::from_millis(max)) {
++ true => std::thread::sleep(Duration::from_millis(max.div_ceil(4)).min(exit_guard::WAKE)),
++ false => std::thread::park_timeout(exit_guard::WAKE),
++ }
++ };
++ let thread = exit_guard::spawn(builder, run).ok()?;
++ Some(thread.thread().clone())
++ })
++ .clone()
++}
++
++/// The counts by reason and by surface, on stderr at most every [`REPORT_MS`] ms.
++fn report() {
++ static START: OnceLock = OnceLock::new();
++ let now = START.get_or_init(Instant::now).elapsed().as_millis() as u64;
++ let last = REPORTED.load(Ordering::Relaxed);
++ if now < last + REPORT_MS
++ || REPORTED
++ .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
++ .is_err()
++ {
++ return;
++ }
++ let read = |count: &AtomicU64| count.load(Ordering::Relaxed);
++ let (taken, refused, resyncs) = counts();
++ let by = REFUSED_BY.each_ref().map(read);
++ let copied = IN_BY.each_ref().map(read);
++ eprintln!(
++ "surface_lazy: taken {taken} refused {refused} resyncs {resyncs} | refused: touched {} \
++ written {} epoch {} own {} uncommitted {} no-standing {} | in: first {} beyond-held {} \
++ changed {} bounded {} | ahead: deferred {} flushes {} whole {} texels {} discarded {} \
++ presents {} unmatched {}",
++ by[Refused::Touched as usize],
++ by[Refused::Written as usize],
++ by[Refused::Epoch as usize],
++ by[Refused::OwnBuffer as usize],
++ by[Refused::Uncommitted as usize],
++ by[Refused::NoStanding as usize],
++ copied[0],
++ copied[1],
++ copied[2],
++ copied[3],
++ read(&DEFERRED),
++ read(&FLUSHES),
++ read(&FLUSHED_WHOLE),
++ read(&FLUSHED_TEXELS),
++ read(&DISCARDED),
++ read(&PRESENTS),
++ read(&PRESENTS_UNMATCHED),
++ );
++ for lazy in surfaces().iter().take(16) {
++ eprintln!(
++ "surface_lazy: {:#x} {}x{} displayed {} taken {} refused {} in {} presents {}",
++ lazy.pages.as_ref().map_or(0, |pages| pages.start),
++ lazy.size[0],
++ lazy.size[1],
++ lazy.displayed.load(Ordering::Relaxed),
++ read(&lazy.taken),
++ read(&lazy.refused),
++ read(&lazy.copied_in),
++ read(&lazy.presents),
++ );
++ }
++}
++
+ /// The counts so far, for a lane or a stderr line: standings taken, refused, and resyncs.
+ pub fn counts() -> (u64, u64, u64) {
+ (
+@@ -138,34 +488,319 @@ struct Stood {
+ epoch: u64,
+ }
+
++/// What a copy back holds until it completes: its image and its bytes. Also the shape of [`Lazy`]'s
++/// queue, device and copies: named, they lie past the compiler's depth for `Send` and `Sync`, in
++/// this crate and in every crate that uses it.
++pub(crate) type Hold = Arc;
++
++/// What a surface's encoders left ahead in its image: its bytes hold none of it yet.
++struct Pending {
++ /// The rectangle bounding what committed command buffers wrote, `Some(None)` for every texel:
++ /// what a copy back moves. `None` for nothing yet.
++ settled: Option>,
++ /// What each command buffer not committed wrote: no copy back can run after it yet, and one
++ /// over its texels would write what the image holds without it, undefined if it copied none
++ /// in. Moved to `settled` once its commit returns ([`after_commit`]), not at [`committed`],
++ /// which notes a commit about to be made.
++ open: Vec<(u64, Option<[u32; 4]>)>,
++ /// When the first of them was left, or the last copy back that left some.
++ since: Instant,
++ /// The `Arc` to copy back.
++ copies: Hold,
++ holds: Vec,
++}
++
++impl Pending {
++ /// Note that the command buffer of identity `id` committed.
++ fn committed(&mut self, id: u64) {
++ if let Some(at) = self.open.iter().position(|(open, _)| *open == id) {
++ let (_, area) = self.open.swap_remove(at);
++ self.settled = Some(match self.settled {
++ Some(settled) => bounding(settled, area),
++ None => area,
++ });
++ }
++ }
++}
++
++/// A copy back of `area` of `copies`, as an encoder's end makes it.
++fn copy_back_of(copies: Hold, area: Option<[u32; 4]>) -> ShadowCopy {
++ ShadowCopy {
++ copies: copies.downcast().expect("a surface's copies"),
++ step: Step::Back,
++ kept: false,
++ area,
++ cause: None,
++ moves: None,
++ }
++}
++
++/// The writes left ahead so far, for a lane.
++#[derive(Clone, Copy, Debug, Default)]
++pub struct AheadCounts {
++ /// The copies back encoders left for later.
++ pub deferred: u64,
++ /// The copies back made of them.
++ pub flushes: u64,
++ /// Of those, the ones of every texel.
++ pub whole: u64,
++ /// The texels those copies moved.
++ pub texels: u64,
++ /// The copies dropped, their texture gone.
++ pub discarded: u64,
++}
++
++/// The counts of writes left ahead so far.
++pub fn ahead_counts() -> AheadCounts {
++ let read = |count: &AtomicU64| count.load(Ordering::Relaxed);
++ AheadCounts {
++ deferred: read(&DEFERRED),
++ flushes: read(&FLUSHES),
++ whole: read(&FLUSHED_WHOLE),
++ texels: read(&FLUSHED_TEXELS),
++ discarded: read(&DISCARDED),
++ }
++}
++
+ /// One surface's standing.
+-pub(super) struct Lazy {
++pub(crate) struct Lazy {
+ truth: OnceLock<(ResourceKey, Option, UseRange)>,
+ written: AtomicU64,
+ stood: Mutex>,
+ resynced: Mutex,
++ /// The [`Device`] its queue comes from.
++ device: Hold,
++ /// The host addresses of its pages; `None` where they lie in none now.
++ pages: Option>,
++ /// Its width and height, for the counts.
++ size: [u32; 2],
++ /// The display presented it ([`presented`]).
++ displayed: AtomicBool,
++ /// Weakly, what its copies back hold ([`Lazy::keeps`]), set as its texture is made.
++ keeps: OnceLock<[Weak; 2]>,
++ pending: Mutex>,
++ /// `pending` holds one, one atomic read.
++ ahead: AtomicBool,
++ /// The identity of the command buffer to copy back after the commit of, 0 for none.
++ flush_after: AtomicU64,
++ /// The [`CommandQueue`] of its copies back, made with its first write left ahead.
++ queue: OnceLock,
++ taken: AtomicU64,
++ refused: AtomicU64,
++ copied_in: AtomicU64,
++ presents: AtomicU64,
+ }
+
+ impl Lazy {
+- /// The state of a new shadow of `texels` texels with `surface` as its backing, where the switch
+- /// takes it.
+- pub(super) fn of(surface: bool, texels: u64) -> Option> {
+- (surface && takes_surface(texels)).then(|| {
++ /// The state of a new shadow of `size` and `texels` texels of `device` with `surface` as its
++ /// backing over the host addresses `pages`, where the switch takes it.
++ pub(super) fn of(
++ device: &Device,
++ surface: bool,
++ pages: impl FnOnce() -> Option>,
++ size: [u32; 2],
++ texels: u64,
++ ) -> Option> {
++ (surface && takes_surface(size[0], texels)).then(|| {
+ Arc::new(Lazy {
+ truth: OnceLock::new(),
+ written: AtomicU64::new(0),
+ stood: Mutex::new(None),
+ resynced: Mutex::new(Instant::now()),
++ device: Arc::new(device.clone()),
++ pages: pages(),
++ size,
++ displayed: AtomicBool::new(false),
++ keeps: OnceLock::new(),
++ pending: Mutex::new(None),
++ ahead: AtomicBool::new(false),
++ flush_after: AtomicU64::new(0),
++ queue: OnceLock::new(),
++ taken: AtomicU64::new(0),
++ refused: AtomicU64::new(0),
++ copied_in: AtomicU64::new(0),
++ presents: AtomicU64::new(0),
+ })
+ })
+ }
+
++ /// Note what its copies back hold, weakly: its image, and the bytes its texture lies over.
++ pub(crate) fn keeps(&self, image: Weak, bytes: Weak) {
++ let _ = self.keeps.set([image, bytes]);
++ }
++
+ fn meets(&self, used: &Use) -> bool {
+ self.truth.get().is_some_and(|(key, alias, range)| {
+ (used.key == *key || Some(used.key) == *alias) && used.range.overlaps(range)
+ })
+ }
+
++ /// Whether its pages meet the host addresses `bytes`.
++ fn over(&self, bytes: &Range) -> bool {
++ self.pages.as_ref().is_some_and(|pages| meet(pages, bytes))
++ }
++
++ /// Whether this thread records this surface's own copy back.
++ fn own_thread(&self) -> bool {
++ OWN.with(Cell::get) == std::ptr::from_ref(self)
++ }
++
++ /// Mark this thread as recording its own copy back until the mark drops.
++ pub(crate) fn own(&self) -> impl Drop {
++ struct Own(*const Lazy);
++ impl Drop for Own {
++ fn drop(&mut self) {
++ OWN.with(|own| own.set(self.0));
++ }
++ }
++ Own(OWN.with(|own| own.replace(std::ptr::from_ref(self))))
++ }
++
++ /// Note a copy in of its bytes for `cause`.
++ pub(super) fn copied_in(&self, cause: CopyCause) {
++ let at = match cause {
++ CopyCause::First => 0,
++ CopyCause::BeyondHeld => 1,
++ CopyCause::Changed(_) => 2,
++ CopyCause::Bounded => 3,
++ };
++ IN_BY[at].fetch_add(1, Ordering::Relaxed);
++ self.copied_in.fetch_add(1, Ordering::Relaxed);
++ }
++
++ /// Leave what an encoder of the command buffer of identity `id` wrote inside `area`, `None` for
++ /// anywhere, ahead in the image: whether it does, else its copy back goes as ever.
++ pub(super) fn defer(
++ &self,
++ copies: &Arc,
++ area: Option<[u32; 4]>,
++ id: u64,
++ ) -> bool {
++ if !crate::live::on(PRESENT, false)
++ || !(self.displayed.load(Ordering::Relaxed) || crate::live::on(PRESENT_ALL, false))
++ {
++ return false;
++ }
++ let Some(holds) = self.keeps.get() else {
++ return false;
++ };
++ let holds: Option> = holds.iter().map(Weak::upgrade).collect();
++ let Some(holds) = holds else {
++ return false;
++ };
++ if self.queue.get().is_none() {
++ let device = self.device.downcast_ref::();
++ let Some(queue) = device.and_then(|d| d.new_command_queue().ok()) else {
++ return false;
++ };
++ let _ = self.queue.set(Arc::new(queue));
++ }
++ let mut pending = self.pending.lock().unwrap();
++ match &mut *pending {
++ Some(left) => match left.open.iter_mut().find(|(open, _)| *open == id) {
++ Some((_, wrote)) => *wrote = bounding(*wrote, area),
++ None => left.open.push((id, area)),
++ },
++ None => {
++ *pending = Some(Pending {
++ settled: None,
++ open: vec![(id, area)],
++ since: Instant::now(),
++ copies: copies.clone(),
++ holds,
++ });
++ drop(pending);
++ self.ahead.store(true, Ordering::Relaxed);
++ if AHEAD.fetch_add(1, Ordering::Relaxed) == 0 {
++ if let Some(clock) = start_clock() {
++ clock.unpark();
++ }
++ }
++ }
++ }
++ DEFERRED.fetch_add(1, Ordering::Relaxed);
++ true
++ }
++
++ /// `pending` was emptied.
++ fn left_behind(&self) {
++ self.ahead.store(false, Ordering::Relaxed);
++ AHEAD.fetch_sub(1, Ordering::Relaxed);
++ }
++
++ /// Copy what it holds ahead back now, or once its last writer commits ([`after_commit`]).
++ fn flush_once_committed(self: &Arc) {
++ let pending = self.pending.lock().unwrap();
++ let Some(left) = pending.as_ref() else {
++ return;
++ };
++ if let Some((last, _)) = left.open.last() {
++ self.flush_after.store(*last, Ordering::Relaxed);
++ return;
++ }
++ drop(pending);
++ self.flush();
++ }
++
++ /// Copy what committed command buffers left ahead back, in a command buffer of its own,
++ /// committed before this returns: that command buffer, where one was made. Nothing is copied
++ /// over the pages of a texture nothing else holds (the module docs); a copy that cannot be
++ /// recorded stays for the next asker.
++ pub(crate) fn flush(self: &Arc) -> Option {
++ let (area, copies, holds) = {
++ let pending = self.pending.lock().unwrap();
++ let left = pending.as_ref()?;
++ (left.settled, left.copies.clone(), left.holds.clone())
++ };
++ // The image's: `Pending`'s and this one, where neither texture nor command holds it.
++ if holds.first().is_some_and(|image| Arc::strong_count(image) <= 2) {
++ *self.pending.lock().unwrap() = None;
++ self.left_behind();
++ DISCARDED.fetch_add(1, Ordering::Relaxed);
++ return None;
++ }
++ let area = area?;
++ let _own = self.own();
++ let copy = copy_back_of(copies, area);
++ let texels = copy.texels_back();
++ let flush = (|| {
++ let queue = self.queue.get()?.downcast_ref::()?;
++ let command_buffer = queue.command_buffer().ok()?;
++ let mut encoder = command_buffer.blit_command_encoder().ok()?;
++ encoder.surface_copy_back(©, holds);
++ encoder.end_encoding().ok()?;
++ command_buffer.commit().ok()?;
++ Some(command_buffer)
++ })();
++ let Some(flush) = flush else {
++ eprintln!("surface_lazy: a copy back was not recorded");
++ return None;
++ };
++ self.settle(area);
++ FLUSHES.fetch_add(1, Ordering::Relaxed);
++ FLUSHED_TEXELS.fetch_add(texels, Ordering::Relaxed);
++ FLUSHED_WHOLE.fetch_add(u64::from(area.is_none()), Ordering::Relaxed);
++ Some(flush)
++ }
++
++ /// `area` is back in the bytes, and nothing else unless more came since it was read, which
++ /// the next copy back repeats it with.
++ fn settle(&self, area: Option<[u32; 4]>) {
++ let mut pending = self.pending.lock().unwrap();
++ let Some(left) = pending.as_mut() else {
++ return;
++ };
++ if left.settled == Some(area) {
++ left.settled = None;
++ }
++ left.since = Instant::now();
++ if left.settled.is_none() && left.open.is_empty() {
++ *pending = None;
++ drop(pending);
++ self.left_behind();
++ }
++ }
++
+ /// Leave the image's standing: `id`'s encoder ended with the image holding the truth, inside
+ /// `held` where given, stale inside `stale`. Its own copies back are behind it.
+ pub(super) fn stand(
+@@ -201,20 +836,35 @@ impl Lazy {
+ /// Where the image stands for an encoder that met `touched`, of a command buffer of identity
+ /// `id`: `Some((held, stale))` where it needs no copy in (the module docs).
+ pub(super) fn take(&self, id: u64, touched: u64) -> Option<(Option<[u32; 4]>, Option<[u32; 4]>)> {
+- let stood = (*self.stood.lock().unwrap())?;
+- let current = stood.touched == touched
+- && stood.written == self.written.load(Ordering::Relaxed)
+- && stood.epoch == EPOCH.load(Ordering::Relaxed)
+- && stood.id != id
+- && committed_ids().lock().unwrap().contains(&stood.id);
+- if !current {
++ report();
++ let Some(stood) = *self.stood.lock().unwrap() else {
++ REFUSED_BY[Refused::NoStanding as usize].fetch_add(1, Ordering::Relaxed);
++ return None;
++ };
++ let refused = if stood.touched != touched {
++ Some(Refused::Touched)
++ } else if stood.written != self.written.load(Ordering::Relaxed) {
++ Some(Refused::Written)
++ } else if stood.epoch != EPOCH.load(Ordering::Relaxed) {
++ Some(Refused::Epoch)
++ } else if stood.id == id {
++ Some(Refused::OwnBuffer)
++ } else if !committed_ids().lock().unwrap().contains(&stood.id) {
++ Some(Refused::Uncommitted)
++ } else {
++ None
++ };
++ if let Some(refused) = refused {
+ REFUSED.fetch_add(1, Ordering::Relaxed);
++ REFUSED_BY[refused as usize].fetch_add(1, Ordering::Relaxed);
++ self.refused.fetch_add(1, Ordering::Relaxed);
+ return None;
+ }
+ let every = crate::live::get("surface_lazy_resync_ms")
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(DEFAULT_RESYNC_MS);
+- if every > 0 {
++ // Writes left ahead would be lost to a copy in, and a copy back goes over the bytes anyway.
++ if every > 0 && !self.ahead.load(Ordering::Relaxed) {
+ let mut resynced = self.resynced.lock().unwrap();
+ if resynced.elapsed().as_millis() as u64 >= every {
+ *resynced = Instant::now();
+@@ -227,6 +877,7 @@ impl Lazy {
+ }
+ }
+ TAKEN.fetch_add(1, Ordering::Relaxed);
++ self.taken.fetch_add(1, Ordering::Relaxed);
+ Some((stood.held, stood.stale))
+ }
+ }
+diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs
+index dc5b4a08..9644b731 100644
+--- a/crates/metal2vulkan-runtime/src/texture.rs
++++ b/crates/metal2vulkan-runtime/src/texture.rs
+@@ -2429,8 +2429,15 @@ impl Device {
+ (object, why)
+ });
+ self.shared().counts.shadowed_texture_made(aspects != every);
++ let image = image.shared();
++ // LOCAL (Atlas): a copy back left for later holds them (`shadow_lazy.rs`).
++ if let Some(lazy) = &copies.lazy {
++ let (held, bytes): (Arc, Arc) =
++ (image.clone(), texels.clone());
++ lazy.keeps(Arc::downgrade(&held), Arc::downgrade(&bytes));
++ }
+ Ok(Storage::Shadow {
+- image: image.shared(),
++ image,
+ texels,
+ copies: Arc::new(copies),
+ })
+@@ -4223,6 +4230,23 @@ impl Texture {
+ }
+ }
+
++ /// LOCAL (Atlas): the host addresses of the bytes the texture lies over, where it lies over a
++ /// buffer's in host pages.
++ fn host_range(&self) -> Option> {
++ match &self.0.storage {
++ Storage::Texels(texels)
++ | Storage::Alias { texels, .. }
++ | Storage::Shadow { texels, .. } => texels.buffer.host_range(),
++ Storage::Image(_) => None,
++ }
++ }
++
++ /// LOCAL (Atlas): tell the runtime the display presents the texture's bytes
++ /// (`shadow_lazy.rs`). Not a Metal call.
++ pub fn surface_presented(&self) {
++ crate::shadow_lazy::presented(|| self.host_range());
++ }
++
+ /// The buffer's bytes a texture buffer is, or `None` for a texture with an image.
+ pub(super) fn texels(&self) -> Option<&Texels> {
+ match &self.0.storage {
+@@ -5372,7 +5396,7 @@ impl Texture {
+ bytes_per_row: u64,
+ bytes_per_image: u64,
+ ) -> Result<(), Error> {
+- crate::shadow_lazy::everything_written(); // LOCAL (Atlas)
++ crate::shadow_lazy::cpu_wrote(|| self.host_range()); // LOCAL (Atlas)
+ let upload = Upload::Slice(bytes);
+ self.replace(region, level, slice, upload, bytes_per_row, bytes_per_image)
+ }
+@@ -5394,7 +5418,7 @@ impl Texture {
+ bytes_per_row: u64,
+ bytes_per_image: u64,
+ ) -> Result<(), Error> {
+- crate::shadow_lazy::everything_written(); // LOCAL (Atlas)
++ crate::shadow_lazy::cpu_wrote(|| self.host_range()); // LOCAL (Atlas)
+ let upload = Upload::Host {
+ bytes,
+ copy: OnceCell::new(),
+@@ -5599,6 +5623,7 @@ impl Texture {
+ return Ok(());
+ };
+ self.refuse_detached_texels()?;
++ crate::shadow_lazy::cpu_reads(|| self.host_range()); // LOCAL (Atlas)
+ if copy
+ .host
+ .host_len()
+diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs
+index 2724bb88..f2eb5c80 100644
+--- a/crates/metal2vulkan-runtime/src/tracker.rs
++++ b/crates/metal2vulkan-runtime/src/tracker.rs
+@@ -1884,6 +1884,11 @@ impl