GPU: the views' written-pages bitmap lives in video memory #2465

Open
github-bot wants to merge 2 commits from github-bot/gh-2465 into main AGit
Owner

@⁠wbkepler on GitHub · 2026-11-25 14:04 UTC · original
wbkepler:gpu/view-marks-in-vram → main · +438 −48 · 4 files · 2 commits · draft

What

Translated shaders mark each 64 KiB page they write through views ("Write marks", crate::shadow::copy_back_marks) with an atomic OR into one bitmap. That bitmap was a shared buffer in CPU-cached system memory. On an NVIDIA host, atomics there cost about 600 times what they cost in video memory: 1M InterlockedOr to one dword take 18 ms there and 0.03 ms in video memory. The lanes of a pass writing one region all OR the same few dwords.

The bitmap now lives in video memory:

  • shadow::bitmap() makes a DEFAULT-heap UAV buffer (Host::uav_buffer), a mapped read-back buffer (Host::readback_buffer) and an upload buffer of zeros. It also records one list, once, and closes it: a UAV barrier, a copy of the bitmap into the read-back buffer, COPY_SOURCE -> COPY_DEST, and a copy of the zeros over the bitmap.
  • A list that binds the bitmap says so (HostList::marks_views, from draw.rs). Host::execute then runs that closed list after the submission's lists, and copy_back_marks reads the marks from the read-back mapping. The CPU no longer clears them.
  • Lists record nothing more, so there is no extra barrier inside them. The cost is two 512 KiB copies per submission that marks. Two runs of one list in a submission both leave their marks.
  • Only the bitmap's last bit (where marks of offsets past it land) is ignored now. Before, the whole last dword was ignored.

Nothing changes in the translator, so shader cache entries stay valid.

Based on #2175 (gpu/title-memory-bitmap-in-vram, which did the same for the title memory page bitmaps in memory.rs). This branch includes its commit, for Host::uav_buffer / Host::readback_buffer and the memory::tests shader helper (now pub(crate)). Review the second commit only; it rebases trivially once #2175 lands.

Verification (Windows 11, NVIDIA RTX 5090)

Live runs on an integration build (this change on top of several open PRs needed to reach the world on a 32-lane host). Diag build, same settings and same 300 s script, averaged over 150–285 s in the world (about 4,900 draws per frame):

fps ms/frame GPU ms copy-back ms preparing ms
before 2.55 395 85.7 111.8 176
this PR 2.38 423 85.2 115.2 201

GPU and copy-back time are unchanged within noise in this scene. The frame-time difference is in "preparing", the CPU side, which this change does not touch and which varies about as much between runs of identical builds (another build of the same series measured 2.13 fps / 208 ms there). The marks' atomics are evidently not a large share of the GPU time here. With them in video memory they stay cheap where passes mark heavily, as the microbenchmark shows. Stable: no device removal, and world captures look like before.

A first version gave each list its own bitmap (cleared where the list first used it, read back at its end, as #2175 does). It cost about 5 ms more GPU time per frame (an extra barrier inside each list plus two 512 KiB copies per list), so this version uses one bitmap and one fixed list per submission.

  • cargo clippy -p victory-gpu --all-targets -- -D warnings, cargo clippy -p victory --features diagnostics --all-targets -- -D warnings: clean
  • cargo test -p victory-gpu: 143 passed. New shadow::tests::view_marks_are_read_back_and_cleared_each_submission: two lists mark from a shader, and both marks are read back; the next submission's read-back holds only its own mark. marked_pages_go_back_by_the_bytes_the_gpu_changed now takes the marks as read back. Two tests fail identically on main on this host because they assume 2^21 view slots and NVIDIA caps heaps at 1,000,000: memory::tests::lists_share_a_table_and_copies_keep_their_views and descriptor::host::tests::dynamic_slots_are_held_until_released.
  • cargo xtask policy: ok

🤖 Generated with Claude Code

**@⁠wbkepler** on GitHub · 2026-11-25 14:04 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465) `wbkepler:gpu/view-marks-in-vram` → `main` · +438 −48 · 4 files · 2 commits · draft ## What Translated shaders mark each 64 KiB page they write through views ("Write marks", `crate::shadow::copy_back_marks`) with an atomic OR into one bitmap. That bitmap was a shared buffer in CPU-cached **system memory**. On an NVIDIA host, atomics there cost about 600 times what they cost in video memory: 1M `InterlockedOr` to one dword take 18 ms there and 0.03 ms in video memory. The lanes of a pass writing one region all OR the same few dwords. The bitmap now lives in **video memory**: - `shadow::bitmap()` makes a `DEFAULT`-heap UAV buffer (`Host::uav_buffer`), a mapped read-back buffer (`Host::readback_buffer`) and an upload buffer of zeros. It also records one list, once, and closes it: a UAV barrier, a copy of the bitmap into the read-back buffer, `COPY_SOURCE -> COPY_DEST`, and a copy of the zeros over the bitmap. - A list that binds the bitmap says so (`HostList::marks_views`, from `draw.rs`). `Host::execute` then runs that closed list after the submission's lists, and `copy_back_marks` reads the marks from the read-back mapping. The CPU no longer clears them. - Lists record nothing more, so there is no extra barrier inside them. The cost is two 512 KiB copies per submission that marks. Two runs of one list in a submission both leave their marks. - Only the bitmap's last bit (where marks of offsets past it land) is ignored now. Before, the whole last dword was ignored. Nothing changes in the translator, so shader cache entries stay valid. **Based on #2175** (`gpu/title-memory-bitmap-in-vram`, which did the same for the title memory page bitmaps in `memory.rs`). This branch includes its commit, for `Host::uav_buffer` / `Host::readback_buffer` and the `memory::tests` shader helper (now `pub(crate)`). Review the second commit only; it rebases trivially once #2175 lands. ## Verification (Windows 11, NVIDIA RTX 5090) Live runs on an integration build (this change on top of several open PRs needed to reach the world on a 32-lane host). Diag build, same settings and same 300 s script, averaged over 150–285 s in the world (about 4,900 draws per frame): | | fps | ms/frame | GPU ms | copy-back ms | preparing ms | |---|---|---|---|---|---| | before | 2.55 | 395 | 85.7 | 111.8 | 176 | | this PR | 2.38 | 423 | 85.2 | 115.2 | 201 | GPU and copy-back time are unchanged within noise in this scene. The frame-time difference is in "preparing", the CPU side, which this change does not touch and which varies about as much between runs of identical builds (another build of the same series measured 2.13 fps / 208 ms there). The marks' atomics are evidently not a large share of the GPU time here. With them in video memory they stay cheap where passes mark heavily, as the microbenchmark shows. Stable: no device removal, and world captures look like before. A first version gave each list its own bitmap (cleared where the list first used it, read back at its end, as #2175 does). It cost about 5 ms more GPU time per frame (an extra barrier inside each list plus two 512 KiB copies per list), so this version uses one bitmap and one fixed list per submission. - `cargo clippy -p victory-gpu --all-targets -- -D warnings`, `cargo clippy -p victory --features diagnostics --all-targets -- -D warnings`: clean - `cargo test -p victory-gpu`: 143 passed. New `shadow::tests::view_marks_are_read_back_and_cleared_each_submission`: two lists mark from a shader, and both marks are read back; the next submission's read-back holds only its own mark. `marked_pages_go_back_by_the_bytes_the_gpu_changed` now takes the marks as read back. Two tests fail identically on `main` on this host because they assume 2^21 view slots and NVIDIA caps heaps at 1,000,000: `memory::tests::lists_share_a_table_and_copies_keep_their_views` and `descriptor::host::tests::dynamic_slots_are_held_until_released`. - `cargo xtask policy`: ok 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Translated shaders that use title memory mark every page they write
(and every page they miss) with an atomic OR into their list's page
bitmap. That bitmap was a shared buffer in system memory, so each of
those atomics went over the bus, and the lanes of a pass writing one
output region all hit the same few dwords one after another. On an
NVIDIA host the title's acceleration-structure build passes (two
straight-line compute programs with two root UAVs, dispatched a few
thousand times in one list) then ran for seconds and the device was
removed with DEVICE_HUNG.

The bitmap is now a video-memory buffer: the list clears it (a copy from
a shared zero buffer) where it first uses title memory and copies it
into a read-back buffer when it is closed (HostList::read_back_at_close),
so every run of the list, also a repeated one, starts clear and the CPU
reads the marks after the run as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Translated shaders mark each page they write through views ("Write
marks") with an atomic OR into one bitmap. That bitmap was a shared
buffer in CPU-cached system memory, where on an NVIDIA host atomics cost
about 600 times what they cost in video memory (1M ORs to one dword:
18 ms against 0.03 ms), and the lanes of a pass writing one region all
OR the same few dwords.

The bitmap is now a video-memory buffer. A list recorded once and closed
copies it into a mapped read-back buffer and clears it (a copy from
zeros in upload memory); a submission runs that list after its own lists
when one of them binds the bitmap (HostList::marks_views), and the
copy-back reads the marks from the read-back buffer. Lists record
nothing more, and two runs of one list in a submission both leave their
marks. Only the last bit of the bitmap (where marks past it land) is
ignored now, not its whole last dword.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 05:06:42 +00:00
Author
Owner

@⁠kotekompotek on GitHub · 2026-11-25 14:24 UTC · original

Reviewed — this is a real device-removal fix, not just perf: >2 s marking lists trip TDR, and the 600× atomic-write penalty on a shared-heap buffer explains why. Both bitmaps follow the same sound pattern:

  • clear moved GPU-side at list start (zeros copy inside the list recording, so a re-recorded list starts clean — previously the CPU take cleared, which only ran if the read-back ran)
  • read back at close via UAV→COPY_SOURCE barrier + copy into a mapped readback buffer; CPU side reads it as const — no mutation, so the mem::take clearing is correctly replaced by the GPU zeros copy
  • marks_views tracking means marks_tail is appended only when a marking list ran, so copy_back_marks always reads a populated read-back
  • last-bit masking moved from "clear word" to word & !(1 << 31) — equivalent on a read-only slice

The video-memory view_marks_are_read_back_and_cleared_each_submission test exercises the full path on a real device (runs the marking pipeline).

**@⁠kotekompotek** on GitHub · 2026-11-25 14:24 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#issuecomment-7165218466) Reviewed — this is a real device-removal fix, not just perf: >2 s marking lists trip TDR, and the 600× atomic-write penalty on a shared-heap buffer explains why. Both bitmaps follow the same sound pattern: - clear moved GPU-side at list start (zeros copy inside the list recording, so a re-recorded list starts clean — previously the CPU `take` cleared, which only ran if the read-back ran) - read back at close via UAV→COPY_SOURCE barrier + copy into a mapped readback buffer; CPU side reads it as `const` — no mutation, so the `mem::take` clearing is correctly replaced by the GPU zeros copy - `marks_views` tracking means `marks_tail` is appended only when a marking list ran, so `copy_back_marks` always reads a populated read-back - last-bit masking moved from "clear word" to `word & !(1 << 31)` — equivalent on a read-only slice The video-memory `view_marks_are_read_back_and_cleared_each_submission` test exercises the full path on a real device (runs the marking pipeline).
Author
Owner

@⁠kais7654 on GitHub · 2026-11-25 17:12 UTC · original

Verified on the branch (Windows 11, RTX 5070 Laptop GPU, driver 616.87,
hardware + WARP, rustc 1.98.1, --locked): merge into current main
(67e8ae1) is clean, clippy -D warnings clean with and without
--all-features, and the runs are green on the machines' known anomalies:
victory-gpu lib 143 passed / 2 failed (the two heap-cap tests #1943's
fix owns), victory-shader lib 244 passed / 3 failed (the gathers + 2
stride tests of the NVIDIA HEAP_VIEWS family, #2317). No new failure
against a same-base control.

**@⁠kais7654** on GitHub · 2026-11-25 17:12 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#issuecomment-7169169520) Verified on the branch (Windows 11, RTX 5070 Laptop GPU, driver 616.87, hardware + WARP, rustc 1.98.1, `--locked`): merge into current main (67e8ae1) is clean, clippy `-D warnings` clean with and without --all-features, and the runs are green on the machines' known anomalies: victory-gpu lib 143 passed / 2 failed (the two heap-cap tests #1943's fix owns), victory-shader lib 244 passed / 3 failed (the gathers + 2 stride tests of the NVIDIA HEAP_VIEWS family, #2317). No new failure against a same-base control.
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 18:20 UTC · original

Automated triage for the maintainers.

Needs rebase. This branch now conflicts with main in crates/victory-gpu/src/host.rs, memory.rs and shadow.rs. It will be reviewed once it is rebased and out of draft.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 18:20 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#issuecomment-7170768100) <!-- victory-triage v1 head=482899f10a37e068da2434823ada17068782f015 verdict=needs-rebase at=2026-11-25T18:31:00Z --> Automated triage for the maintainers. **Needs rebase.** This branch now conflicts with `main` in `crates/victory-gpu/src/host.rs`, `memory.rs` and `shadow.rs`. It will be reviewed once it is rebased and out of draft. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠catminou4 on GitHub · 2026-11-25 14:57 UTC · original · reviewed

Written-pages bitmap moved to video memory (+438). Static review only: victory-gpu/victory-hle are Windows-only (D3D12/windows-sys); not compiled or tested on this macOS arm64 host. rustc 1.98.1.

**@⁠catminou4** on GitHub · 2026-11-25 14:57 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#pullrequestreview-6059995984) · **reviewed** Written-pages bitmap moved to video memory (+438). Static review only: victory-gpu/victory-hle are Windows-only (D3D12/windows-sys); not compiled or tested on this macOS arm64 host. rustc 1.98.1.
Author
Owner

@⁠latentdev on GitHub · 2026-11-26 14:46 UTC · original

In the title on an RTX 4090: the bitmap's place was ~90 % of the GPU's time (on a tree with more marks)

A data point where this change matters a lot, plus notes on porting it to current main.

Setup

  • RTX 4090, driver 621.24, Windows 11 26300.
  • Retail 1.0.2.1, Series X profile, diag build, warm caches.
  • Scene: the opening cutscene into the first gameplay.
  • Tree: main 63bcca4 + #1630, #1832, #2332, #2178, #2121, #439, #2214, with the structure builder held back.
  • That tree marks more than main does: #2121's views read through paged heaps set page-read marks in the same bitmap.
  • Medians of the frame-rate lines over the world:
views' bitmap ms/frame GPU ms samples
system memory (as on main) 5,537 4,627 141
video memory (this PR's approach) 745 528 ¹ 35

¹ measured with VICTORY_GPU_TIMING=1, which adds about a quarter here.

With the bitmap in system memory, VICTORY_GPU_TIMING named:

  • deferred_tiled:CS_ResetTilesMask (a7eeed0646be1ab7) at about 1 s per dispatch;
  • full-screen passes at about 100 ms each.

With it in video memory, most commands drop to a few milliseconds. One program still runs long in some frames (100 ms to 1 s): depth_pyramid:CS_InitDepthPyramidWithCpuOcclusion3x3 (42683eebec081520), which I'm still looking at. Adding #3102's copies in video memory took the GPU to about 140 ms per frame (numbers on #3102).

Porting it to main 63bcca4. Since this PR was written, main has made two changes to the bitmap:

  • it split it in two (bitmap(memory); marks of shaders using title memory go back only while not withheld);
  • it added read marks (VIEW_READS, take_reads, forget_read, reads_since).

What worked here, keeping all of the CPU-side code:

  • Each Bitmap is a DEFAULT-heap UAV buffer (Host::uav_buffer), plus a read-back buffer, an upload buffer of zeros, and one closed tail list (UAV barrier, copy to read-back, COPY_SOURCE -> COPY_DEST, copy of zeros).
  • Host::execute appends both tails to every submission's lists.
  • Bitmap::data now points at the read-back mapping. take_reads, take_page_reads, copy_back_marks and forget_read then work unchanged on cached memory.
  • One change in meaning: read marks used to stay set in the bitmap between reads_since calls. The GPU copy is now cleared after each submission, so take_reads keeps their union on the CPU for reads_since.

I ran it in about fifteen runs of up to 9 minutes. The removals in them were of two kinds, and neither points at this change:

  • the #71 hang family, after vfx_proj_decal_hit_detection programs bind;
  • the PC running out of memory: a monitor alongside showed commit at its limit and under 1 GB of RAM free at the removal.

I can post the patch if it helps the rebase.

**@⁠latentdev** on GitHub · 2026-11-26 14:46 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#issuecomment-7195311142) ### In the title on an RTX 4090: the bitmap's place was ~90 % of the GPU's time (on a tree with more marks) A data point where this change matters a lot, plus notes on porting it to current `main`. **Setup** - RTX 4090, driver 621.24, Windows 11 26300. - Retail 1.0.2.1, Series X profile, diag build, warm caches. - Scene: the opening cutscene into the first gameplay. - Tree: `main` 63bcca4 + #1630, #1832, #2332, #2178, #2121, #439, #2214, with the structure builder held back. - That tree marks more than `main` does: #2121's views read through paged heaps set page-read marks in the same bitmap. - Medians of the frame-rate lines over the world: | views' bitmap | ms/frame | GPU ms | samples | |---|---:|---:|---:| | system memory (as on `main`) | 5,537 | 4,627 | 141 | | video memory (this PR's approach) | 745 | 528 ¹ | 35 | ¹ measured with `VICTORY_GPU_TIMING=1`, which adds about a quarter here. With the bitmap in system memory, `VICTORY_GPU_TIMING` named: - `deferred_tiled:CS_ResetTilesMask` (`a7eeed0646be1ab7`) at about 1 s per dispatch; - full-screen passes at about 100 ms each. With it in video memory, most commands drop to a few milliseconds. One program still runs long in some frames (100 ms to 1 s): `depth_pyramid:CS_InitDepthPyramidWithCpuOcclusion3x3` (`42683eebec081520`), which I'm still looking at. Adding #3102's copies in video memory took the GPU to about 140 ms per frame (numbers on #3102). **Porting it to `main` 63bcca4.** Since this PR was written, `main` has made two changes to the bitmap: - it split it in two (`bitmap(memory)`; marks of shaders using title memory go back only while not withheld); - it added read marks (`VIEW_READS`, `take_reads`, `forget_read`, `reads_since`). What worked here, keeping all of the CPU-side code: - Each `Bitmap` is a `DEFAULT`-heap UAV buffer (`Host::uav_buffer`), plus a read-back buffer, an upload buffer of zeros, and one closed tail list (UAV barrier, copy to read-back, `COPY_SOURCE -> COPY_DEST`, copy of zeros). - `Host::execute` appends both tails to every submission's lists. - `Bitmap::data` now points at the read-back mapping. `take_reads`, `take_page_reads`, `copy_back_marks` and `forget_read` then work unchanged on cached memory. - One change in meaning: read marks used to stay set in the bitmap between `reads_since` calls. The GPU copy is now cleared after each submission, so `take_reads` keeps their union on the CPU for `reads_since`. I ran it in about fifteen runs of up to 9 minutes. The removals in them were of two kinds, and neither points at this change: - the #71 hang family, after `vfx_proj_decal_hit_detection` programs bind; - the PC running out of memory: a monitor alongside showed commit at its limit and under 1 GB of RAM free at the removal. I can post the patch if it helps the rebase.
Author
Owner

@⁠neonbyte1 on GitHub · 2026-11-26 17:24 UTC · original

@⁠wbkepler I'd like to test this on an RTX 5090 under Wine (vkd3d-proton), where marks are expensive. The marks bitmap sits in system memory (CUSTOM, WRITE_BACK, L0) here. Turning view marks off cut GPU command time from 579 to 251 ms/frame, and #2958's wave-coalesced marks bring it to 346 ms (numbers on #2958).

The branch currently conflicts with main in host.rs, memory.rs and shadow.rs. Main's bitmap now holds view read marks next to the write bits, and title-memory bitmaps are pooled, so it's more than a mechanical merge and I haven't tried to resolve it myself. Once it's rebased, I'll run it in game on its own and on top of #2958, and post the frame times and GPU command times here.

AI-assisted (Claude); measured on my machine, no game data shared.

**@⁠neonbyte1** on GitHub · 2026-11-26 17:24 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#issuecomment-7198952249) @⁠wbkepler I'd like to test this on an RTX 5090 under Wine (vkd3d-proton), where marks are expensive. The marks bitmap sits in system memory (CUSTOM, WRITE_BACK, L0) here. Turning view marks off cut GPU command time from 579 to 251 ms/frame, and #2958's wave-coalesced marks bring it to 346 ms (numbers on #2958). The branch currently conflicts with `main` in `host.rs`, `memory.rs` and `shadow.rs`. Main's bitmap now holds view read marks next to the write bits, and title-memory bitmaps are pooled, so it's more than a mechanical merge and I haven't tried to resolve it myself. Once it's rebased, I'll run it in game on its own and on top of #2958, and post the frame times and GPU command times here. _AI-assisted (Claude); measured on my machine, no game data shared._
Author
Owner

@⁠latentdev on GitHub · 2026-11-26 17:39 UTC · original · edited 2026-11-26 19:37 UTC

@⁠neonbyte1, here is a port of both halves of this PR onto main 63bcca4, in case it helps you test before wbkepler rebases. It follows wbkepler's design and adapts it to what main changed since:

Views' bitmaps (shadow.rs). main now has two of them (bitmap(memory)), and each also holds the read marks.

  • Each is a DEFAULT-heap UAV buffer, with a read-back buffer, an upload buffer of zeros, and one closed tail list (UAV barrier, copy to read-back, COPY_SOURCE -> COPY_DEST, copy of zeros).
  • Host::execute appends both tails to every submission.
  • Bitmap::data is the read-back mapping, so take_reads, take_page_reads, copy_back_marks and forget_read read and clear it as before.
  • One change in meaning: read marks used to stay set in the bitmap between reads_since calls, so take_reads now keeps their union on the CPU for reads_since.

Title-memory bitmaps (memory.rs). These are now pooled.

  • Each pooled Bitmap is a video-memory UAV buffer plus a read-back buffer.
  • bind records a clear (a copy from shared zeros, then COPY_DEST -> UNORDERED_ACCESS) and asks HostList::read_back_at_close to copy the bitmap out when the list closes, as #2175 does.
  • defer_missed and defer_after read the read-back mapping.

Tested on an RTX 4090 (--features diagnostics, --test-threads=1):

  • memory::, shadow::, bindless:: and draw:: tests: 40 pass, 1 fails. The failure, memory::tests::lists_share_a_table_and_copies_keep_their_views, fails the same way on plain 63bcca4 here (the 2^21-slot assumption #2175 mentions).
  • I have run the same changes in the title on a larger stack (numbers in my comment above), not on main alone.
Patch against 63bcca4 (3 files, +203/-14)
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index 3c2ed78..9f12199 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -1002,6 +1002,9 @@ enum Step {
 /// the upload buffers its GPU commands read, kept until the list is reset.
 #[derive(Default)]
 struct Deferred {
+    /// Buffers shaders wrote, copied at the list's end into read-back
+    /// buffers (from, to, bytes; [`HostList::read_back_at_close`]).
+    read_backs: Vec<(ID3D12Resource, ID3D12Resource, u64)>,
     /// Destination, source, bytes.
     copies: Vec<Step>,
     uploads: Vec<ID3D12Resource>,
@@ -1248,6 +1251,12 @@ impl Host {
             }
             lists.push(list.list.cast().ok());
         }
+        // The views' bitmaps are in video memory; after the
+        // submission's lists, each is copied into its read-back buffer and
+        // cleared (`crate::shadow::marks_tails`), for the CPU to read.
+        for tail in crate::shadow::marks_tails() {
+            lists.push(tail.list.cast().ok());
+        }
         batch.flush();
         let prepared = std::time::Instant::now();
         #[cfg(feature = "diagnostics")]
@@ -1760,7 +1769,25 @@ impl HostList {
             || node_is_list(None, ansi.as_deref(), &pointers, &name)
     }
 
+    /// At the list's end (when it is closed), `bytes` of `from` (in the
+    /// unordered-access state) are copied into the read-back buffer `to`.
+    pub(crate) fn read_back_at_close(&self, from: &ID3D12Resource, to: &ID3D12Resource, bytes: u64) {
+        self.deferred().read_backs.push((from.clone(), to.clone(), bytes));
+    }
+
     pub(crate) fn close(&self) {
+        let read_backs = std::mem::take(&mut self.deferred().read_backs);
+        for (from, to, bytes) in &read_backs {
+            // SAFETY: an open list; buffers of ours it holds.
+            unsafe {
+                self.list.ResourceBarrier(&[transition(
+                    from,
+                    D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+                    D3D12_RESOURCE_STATE_COPY_SOURCE,
+                )]);
+                self.list.CopyBufferRegion(to, 0, from, 0, *bytes);
+            }
+        }
         #[cfg(feature = "diagnostics")]
         if let Some((heap, back)) = self.stamps() {
             let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
@@ -2715,6 +2742,48 @@ impl Host {
         self.mapped_buffer(size, false)
     }
 
+    /// A mapped buffer of `size` bytes in readback memory, in the
+    /// copy-destination state.
+    pub(crate) fn readback_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
+        self.mapped_buffer(size, true)
+    }
+
+    /// A buffer of `size` bytes in video memory that shaders may write
+    /// (unordered access), zeroed, in the common state.
+    pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
+        let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
+        let desc = D3D12_RESOURCE_DESC {
+            Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+            Width: size.max(1),
+            Height: 1,
+            DepthOrArraySize: 1,
+            MipLevels: 1,
+            SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+            Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+            Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
+            ..Default::default()
+        };
+        let mut buffer: Option<ID3D12Resource> = None;
+        // SAFETY: plain creation of a committed buffer (zeroed by the system).
+        let made = unsafe {
+            self.device.CreateCommittedResource(
+                &heap,
+                D3D12_HEAP_FLAG_NONE,
+                &desc,
+                D3D12_RESOURCE_STATE_COMMON,
+                None,
+                &mut buffer,
+            )
+        };
+        match made {
+            Ok(()) => buffer,
+            Err(e) => {
+                tracing::warn!(error = %e, size, "no buffer in video memory");
+                None
+            }
+        }
+    }
+
     /// A mapped buffer of `size` bytes: upload memory, or (`readback`)
     /// readback memory in the copy-destination state.
     fn mapped_buffer(&self, size: u64, readback: bool) -> Option<(ID3D12Resource, *mut u8)> {
diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs
index 7e09ba7..9e27632 100644
--- a/crates/victory-gpu/src/memory.rs
+++ b/crates/victory-gpu/src/memory.rs
@@ -104,12 +104,32 @@ struct Layout {
 }
 
 /// A 256 KiB dirty-page bitmap buffer kept zeroed while in [`BITMAP_POOL`].
+///
+/// The bitmap shaders mark (`_resource`, `gpu`) is in video memory, cleared
+/// by the list where it binds it and copied at the list's end into the
+/// read-back buffer `_back`, whose mapping `data` the CPU reads (and clears)
+/// as it did the bitmap. In system memory every mark crossed the bus.
 struct Bitmap {
     _resource: ID3D12Resource,
+    _back: ID3D12Resource,
     data: usize,
     gpu: u64,
 }
 
+/// Zeros the bitmaps are cleared from where a list binds one.
+fn zeros() -> Option<ID3D12Resource> {
+    static ZEROS: Mutex<Option<ID3D12Resource>> = Mutex::new(None);
+    let mut zeros = ZEROS.lock().unwrap_or_else(|e| e.into_inner());
+    if zeros.is_none() {
+        let (buffer, data) = crate::host::host()?.upload_buffer(BITMAP_BYTES)?;
+        // SAFETY: our mapped buffer of `BITMAP_BYTES` bytes.
+        unsafe { std::ptr::write_bytes(data, 0, BITMAP_BYTES as usize) };
+        crate::host::name(&buffer, || "title memory bitmap zeros".into());
+        *zeros = Some(buffer);
+    }
+    zeros.clone()
+}
+
 // SAFETY: `data` is the persistent mapping of `_resource`, owned exclusively by
 // one `PooledBitmap` while bound or by `BITMAP_POOL` while idle; D3D12
 // resources are free-threaded.
@@ -127,14 +147,18 @@ impl Bitmap {
         if let Some(bitmap) = BITMAP_POOL.lock().unwrap_or_else(|e| e.into_inner()).pop() {
             return Some(bitmap);
         }
-        let (resource, data) = crate::host::host()?.shared_buffer(BITMAP_BYTES)?;
+        let host = crate::host::host()?;
+        let resource = host.uav_buffer(BITMAP_BYTES)?;
         crate::host::name(&resource, || "title memory written pages".into());
-        // SAFETY: `data` is a newly mapped shared buffer of at least `BITMAP_WORDS` dwords.
+        let (back, data) = host.readback_buffer(BITMAP_BYTES)?;
+        crate::host::name(&back, || "title memory written pages read back".into());
+        // SAFETY: `data` is a newly mapped read-back buffer of at least `BITMAP_WORDS` dwords.
         unsafe { std::ptr::write_bytes(data.cast::<u32>(), 0, BITMAP_WORDS) };
         // SAFETY: `resource` is a live D3D12 buffer.
         let gpu = unsafe { resource.GetGPUVirtualAddress() };
         Some(Self {
             _resource: resource,
+            _back: back,
             data: data as usize,
             gpu,
         })
@@ -630,6 +654,27 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option<Map> {
     .flatten()?;
     let pooled = Arc::new(PooledBitmap::new(Bitmap::acquire()?));
     let dirty = pooled.gpu();
+    // The bitmap in video memory is cleared here, in the list (each run of
+    // it), and read back at its end.
+    {
+        use windows::Win32::Graphics::Direct3D12::{
+            D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+        };
+        let b = pooled.bitmap.as_ref().expect("bitmap present until drop");
+        let zeros = zeros()?;
+        // SAFETY: an open list; buffers of ours it keeps (the bitmap is in the
+        // common state, which a copy promotes to copy destination).
+        unsafe {
+            list.list.CopyBufferRegion(&b._resource, 0, &zeros, 0, BITMAP_BYTES);
+            list.list.ResourceBarrier(&[crate::host::transition(
+                &b._resource,
+                D3D12_RESOURCE_STATE_COPY_DEST,
+                D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+            )]);
+        }
+        list.read_back_at_close(&b._resource, &b._back, BITMAP_BYTES);
+        list.keep(&zeros);
+    }
     list.defer_memory(key);
     let precise: Arc<Mutex<Vec<(u64, u64)>>> = Arc::default();
     let byte_for_byte = precise.clone();
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index a455a96..8efc891 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -767,45 +767,104 @@ impl Marks {
     }
 }
 
-/// The buffer views' written-pages bitmap: the buffer, its mapping (bits
-/// as dwords) and host GPU address.
+/// The buffer views' written-pages bitmap and read marks: the buffer, the
+/// mapping the CPU reads the marks in (bits as dwords) and host GPU address.
+///
+/// The bitmap is in video memory (after #2465). Every
+/// marked write or read is a load and an atomic OR, and in system memory
+/// (where it was) each crosses the bus: on the RTX 4090 a 1.5M-thread clear
+/// that marks took ~1 s. After each submission [`marks_tails`] copies it
+/// into the read-back buffer `data` (cached system memory, which the CPU
+/// reads and clears as it did the bitmap) and clears it from zeros.
 struct Bitmap {
     _buffer: ID3D12Resource,
     data: usize,
     gpu: u64,
+    /// Copies the bitmap into `data`'s buffer, then clears it. Recorded
+    /// once, closed, and run after every submission's lists.
+    tail: HostList,
+    _back: ID3D12Resource,
+    _zeros: ID3D12Resource,
 }
 
-// SAFETY: D3D12 resources are free-threaded; the mapping is read and cleared
-// only between submissions, which run one at a time.
+// SAFETY: D3D12 resources are free-threaded; the read-back mapping is read
+// and cleared only between submissions, which run one at a time, and the
+// tail list runs in one submission at a time.
 unsafe impl Send for Bitmap {}
 // SAFETY: as above.
 unsafe impl Sync for Bitmap {}
 
+static BITMAPS: [std::sync::OnceLock<Option<Bitmap>>; 2] = [const { std::sync::OnceLock::new() }; 2];
+
 /// The bitmap of other shaders, or (`memory`) of shaders that use title
 /// memory, whose marks go back only while it is not withheld
 /// (`crate::memory::withholding`).
 fn bitmap(memory: bool) -> Option<&'static Bitmap> {
-    static BITMAPS: [std::sync::OnceLock<Option<Bitmap>>; 2] = [const { std::sync::OnceLock::new() }; 2];
     BITMAPS[usize::from(memory)]
         .get_or_init(|| {
+            use windows::Win32::Graphics::Direct3D12::{
+                D3D12_RESOURCE_BARRIER, D3D12_RESOURCE_BARRIER_0, D3D12_RESOURCE_BARRIER_FLAG_NONE,
+                D3D12_RESOURCE_BARRIER_TYPE_UAV, D3D12_RESOURCE_STATE_COPY_DEST,
+                D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_UAV_BARRIER,
+            };
             // Written pages, then one read mark per heap index.
             let bits = victory_shader::emit::VIEW_READS + victory_shader::emit::HEAP_VIEWS;
             let bytes = u64::from(bits / 8);
-            let (buffer, data) = host()?.shared_buffer(bytes)?;
+            let host = host()?;
+            let buffer = host.uav_buffer(bytes)?;
             crate::host::name(&buffer, || "views' written pages and read slots".into());
-            // SAFETY: our mapped buffer of `bytes` bytes.
-            unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
+            let (back, data) = host.readback_buffer(bytes)?;
+            crate::host::name(&back, || "views' marks read back".into());
+            let (zeros, z) = host.upload_buffer(bytes)?;
+            // SAFETY: our mapped buffers of `bytes` bytes.
+            unsafe {
+                std::ptr::write_bytes(z, 0, bytes as usize);
+                std::ptr::write_bytes(data, 0, bytes as usize);
+            }
+            let tail = host.new_list().ok()?;
+            // The lists before it wrote the bitmap as unordered access (from
+            // the common state); the copy takes it as its source.
+            let done = D3D12_RESOURCE_BARRIER {
+                Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
+                Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
+                Anonymous: D3D12_RESOURCE_BARRIER_0 {
+                    UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
+                        pResource: std::mem::ManuallyDrop::new(None),
+                    }),
+                },
+            };
+            // SAFETY: an open list; buffers of ours the bitmap keeps.
+            unsafe {
+                tail.list.ResourceBarrier(&[done]);
+                tail.list.CopyBufferRegion(&back, 0, &buffer, 0, bytes);
+                tail.list.ResourceBarrier(&[crate::host::transition(
+                    &buffer,
+                    D3D12_RESOURCE_STATE_COPY_SOURCE,
+                    D3D12_RESOURCE_STATE_COPY_DEST,
+                )]);
+                tail.list.CopyBufferRegion(&buffer, 0, &zeros, 0, bytes);
+            }
+            tail.close();
             // SAFETY: a live buffer.
             let gpu = unsafe { buffer.GetGPUVirtualAddress() };
             Some(Bitmap {
                 _buffer: buffer,
                 data: data as usize,
                 gpu,
+                tail,
+                _back: back,
+                _zeros: zeros,
             })
         })
         .as_ref()
 }
 
+/// The lists that read the bitmaps made so far back and clear them, to run
+/// after every submission's lists (`Host::execute`).
+pub(crate) fn marks_tails() -> Vec<&'static HostList> {
+    BITMAPS.iter().filter_map(|b| b.get()?.as_ref()).map(|b| &b.tail).collect()
+}
+
 /// The host GPU address of the buffer views' written-pages bitmap, for the
 /// root UAV of shaders that mark their writes (`memory`: shaders that use
 /// title memory, see [`bitmap`]).
@@ -816,7 +875,10 @@ pub(crate) fn view_writes(memory: bool) -> Option<u64> {
 /// Heap slots whose texture views shaders read: the marks seen so far (a
 /// slot's stays set in the bitmap until [`forget_read`]), and the slots to
 /// clear at the next [`take_reads`].
-static READS: Mutex<(Vec<u32>, Vec<u32>)> = Mutex::new((Vec::new(), Vec::new()));
+/// Also the read marks since the last [`reads_since`] (the bitmap in
+/// video memory is cleared after every submission, so it no longer keeps
+/// them between calls).
+static READS: Mutex<(Vec<u32>, Vec<u32>, Vec<u32>)> = Mutex::new((Vec::new(), Vec::new(), Vec::new()));
 
 /// After a submission: the heap slots its shaders first read texture views
 /// at (`victory_shader::emit`, "Read marks"), each once until
@@ -836,8 +898,9 @@ pub(crate) fn take_reads() -> Vec<u32> {
         return Vec::new();
     }
     let mut reads = READS.lock().unwrap_or_else(|e| e.into_inner());
-    let (seen, forgotten) = &mut *reads;
+    let (seen, forgotten, since) = &mut *reads;
     seen.resize(words, 0);
+    since.resize(words, 0);
     for slot in forgotten.drain(..) {
         let (w, bit) = ((slot / 32) as usize, 1u32 << (slot % 32));
         if w < words {
@@ -847,7 +910,9 @@ pub(crate) fn take_reads() -> Vec<u32> {
     }
     let mut new = Vec::new();
     for (w, s) in seen.iter_mut().enumerate() {
-        let mut fresh = maps.iter().fold(0, |x, bits| x | bits[w]) & !*s;
+        let all = maps.iter().fold(0, |x, bits| x | bits[w]);
+        since[w] |= all;
+        let mut fresh = all & !*s;
         *s |= fresh;
         while fresh != 0 {
             new.push(w as u32 * 32 + fresh.trailing_zeros());
@@ -866,8 +931,18 @@ pub(crate) fn reads_since() -> Vec<u32> {
     let words = (victory_shader::emit::HEAP_VIEWS / 32) as usize;
     let first = (victory_shader::emit::VIEW_READS / 32) as usize;
     let mut slots = Vec::new();
+    // The marks `take_reads` saw since the last call, then those of
+    // the read-back copies it has not seen yet.
+    let since = std::mem::take(&mut READS.lock().unwrap_or_else(|e| e.into_inner()).2);
+    for (w, &x) in since.iter().enumerate() {
+        let mut x = x;
+        while x != 0 {
+            slots.push(w as u32 * 32 + x.trailing_zeros());
+            x &= x - 1;
+        }
+    }
     for b in [false, true].into_iter().filter_map(bitmap) {
-        // SAFETY: the mapped bitmap's read marks; no submission runs.
+        // SAFETY: the read-back copy's read marks; no submission runs.
         let bits = unsafe { std::slice::from_raw_parts_mut((b.data as *mut u32).add(first), words) };
         for (w, word) in bits.iter_mut().enumerate() {
             let mut x = std::mem::take(word);

**@⁠latentdev** on GitHub · 2026-11-26 17:39 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#issuecomment-7199419243) · edited 2026-11-26 19:37 UTC @⁠neonbyte1, here is a port of both halves of this PR onto `main` 63bcca4, in case it helps you test before wbkepler rebases. It follows wbkepler's design and adapts it to what `main` changed since: **Views' bitmaps (`shadow.rs`).** `main` now has two of them (`bitmap(memory)`), and each also holds the read marks. - Each is a `DEFAULT`-heap UAV buffer, with a read-back buffer, an upload buffer of zeros, and one closed tail list (UAV barrier, copy to read-back, `COPY_SOURCE -> COPY_DEST`, copy of zeros). - `Host::execute` appends both tails to every submission. - `Bitmap::data` is the read-back mapping, so `take_reads`, `take_page_reads`, `copy_back_marks` and `forget_read` read and clear it as before. - One change in meaning: read marks used to stay set in the bitmap between `reads_since` calls, so `take_reads` now keeps their union on the CPU for `reads_since`. **Title-memory bitmaps (`memory.rs`).** These are now pooled. - Each pooled `Bitmap` is a video-memory UAV buffer plus a read-back buffer. - `bind` records a clear (a copy from shared zeros, then `COPY_DEST -> UNORDERED_ACCESS`) and asks `HostList::read_back_at_close` to copy the bitmap out when the list closes, as #2175 does. - `defer_missed` and `defer_after` read the read-back mapping. **Tested on an RTX 4090** (`--features diagnostics`, `--test-threads=1`): - `memory::`, `shadow::`, `bindless::` and `draw::` tests: 40 pass, 1 fails. The failure, `memory::tests::lists_share_a_table_and_copies_keep_their_views`, fails the same way on plain 63bcca4 here (the 2^21-slot assumption #2175 mentions). - I have run the same changes in the title on a larger stack (numbers in my comment above), not on `main` alone. <details> <summary>Patch against 63bcca4 (3 files, +203/-14)</summary> ```diff diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 3c2ed78..9f12199 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1002,6 +1002,9 @@ enum Step { /// the upload buffers its GPU commands read, kept until the list is reset. #[derive(Default)] struct Deferred { + /// Buffers shaders wrote, copied at the list's end into read-back + /// buffers (from, to, bytes; [`HostList::read_back_at_close`]). + read_backs: Vec<(ID3D12Resource, ID3D12Resource, u64)>, /// Destination, source, bytes. copies: Vec<Step>, uploads: Vec<ID3D12Resource>, @@ -1248,6 +1251,12 @@ impl Host { } lists.push(list.list.cast().ok()); } + // The views' bitmaps are in video memory; after the + // submission's lists, each is copied into its read-back buffer and + // cleared (`crate::shadow::marks_tails`), for the CPU to read. + for tail in crate::shadow::marks_tails() { + lists.push(tail.list.cast().ok()); + } batch.flush(); let prepared = std::time::Instant::now(); #[cfg(feature = "diagnostics")] @@ -1760,7 +1769,25 @@ impl HostList { || node_is_list(None, ansi.as_deref(), &pointers, &name) } + /// At the list's end (when it is closed), `bytes` of `from` (in the + /// unordered-access state) are copied into the read-back buffer `to`. + pub(crate) fn read_back_at_close(&self, from: &ID3D12Resource, to: &ID3D12Resource, bytes: u64) { + self.deferred().read_backs.push((from.clone(), to.clone(), bytes)); + } + pub(crate) fn close(&self) { + let read_backs = std::mem::take(&mut self.deferred().read_backs); + for (from, to, bytes) in &read_backs { + // SAFETY: an open list; buffers of ours it holds. + unsafe { + self.list.ResourceBarrier(&[transition( + from, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + self.list.CopyBufferRegion(to, 0, from, 0, *bytes); + } + } #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -2715,6 +2742,48 @@ impl Host { self.mapped_buffer(size, false) } + /// A mapped buffer of `size` bytes in readback memory, in the + /// copy-destination state. + pub(crate) fn readback_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + self.mapped_buffer(size, true) + } + + /// A buffer of `size` bytes in video memory that shaders may write + /// (unordered access), zeroed, in the common state. + pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a committed buffer (zeroed by the system). + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + }; + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no buffer in video memory"); + None + } + } + } + /// A mapped buffer of `size` bytes: upload memory, or (`readback`) /// readback memory in the copy-destination state. fn mapped_buffer(&self, size: u64, readback: bool) -> Option<(ID3D12Resource, *mut u8)> { diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 7e09ba7..9e27632 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -104,12 +104,32 @@ struct Layout { } /// A 256 KiB dirty-page bitmap buffer kept zeroed while in [`BITMAP_POOL`]. +/// +/// The bitmap shaders mark (`_resource`, `gpu`) is in video memory, cleared +/// by the list where it binds it and copied at the list's end into the +/// read-back buffer `_back`, whose mapping `data` the CPU reads (and clears) +/// as it did the bitmap. In system memory every mark crossed the bus. struct Bitmap { _resource: ID3D12Resource, + _back: ID3D12Resource, data: usize, gpu: u64, } +/// Zeros the bitmaps are cleared from where a list binds one. +fn zeros() -> Option<ID3D12Resource> { + static ZEROS: Mutex<Option<ID3D12Resource>> = Mutex::new(None); + let mut zeros = ZEROS.lock().unwrap_or_else(|e| e.into_inner()); + if zeros.is_none() { + let (buffer, data) = crate::host::host()?.upload_buffer(BITMAP_BYTES)?; + // SAFETY: our mapped buffer of `BITMAP_BYTES` bytes. + unsafe { std::ptr::write_bytes(data, 0, BITMAP_BYTES as usize) }; + crate::host::name(&buffer, || "title memory bitmap zeros".into()); + *zeros = Some(buffer); + } + zeros.clone() +} + // SAFETY: `data` is the persistent mapping of `_resource`, owned exclusively by // one `PooledBitmap` while bound or by `BITMAP_POOL` while idle; D3D12 // resources are free-threaded. @@ -127,14 +147,18 @@ impl Bitmap { if let Some(bitmap) = BITMAP_POOL.lock().unwrap_or_else(|e| e.into_inner()).pop() { return Some(bitmap); } - let (resource, data) = crate::host::host()?.shared_buffer(BITMAP_BYTES)?; + let host = crate::host::host()?; + let resource = host.uav_buffer(BITMAP_BYTES)?; crate::host::name(&resource, || "title memory written pages".into()); - // SAFETY: `data` is a newly mapped shared buffer of at least `BITMAP_WORDS` dwords. + let (back, data) = host.readback_buffer(BITMAP_BYTES)?; + crate::host::name(&back, || "title memory written pages read back".into()); + // SAFETY: `data` is a newly mapped read-back buffer of at least `BITMAP_WORDS` dwords. unsafe { std::ptr::write_bytes(data.cast::<u32>(), 0, BITMAP_WORDS) }; // SAFETY: `resource` is a live D3D12 buffer. let gpu = unsafe { resource.GetGPUVirtualAddress() }; Some(Self { _resource: resource, + _back: back, data: data as usize, gpu, }) @@ -630,6 +654,27 @@ pub(crate) fn bind(list: &HostList, key: usize) -> Option<Map> { .flatten()?; let pooled = Arc::new(PooledBitmap::new(Bitmap::acquire()?)); let dirty = pooled.gpu(); + // The bitmap in video memory is cleared here, in the list (each run of + // it), and read back at its end. + { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }; + let b = pooled.bitmap.as_ref().expect("bitmap present until drop"); + let zeros = zeros()?; + // SAFETY: an open list; buffers of ours it keeps (the bitmap is in the + // common state, which a copy promotes to copy destination). + unsafe { + list.list.CopyBufferRegion(&b._resource, 0, &zeros, 0, BITMAP_BYTES); + list.list.ResourceBarrier(&[crate::host::transition( + &b._resource, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + list.read_back_at_close(&b._resource, &b._back, BITMAP_BYTES); + list.keep(&zeros); + } list.defer_memory(key); let precise: Arc<Mutex<Vec<(u64, u64)>>> = Arc::default(); let byte_for_byte = precise.clone(); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index a455a96..8efc891 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -767,45 +767,104 @@ impl Marks { } } -/// The buffer views' written-pages bitmap: the buffer, its mapping (bits -/// as dwords) and host GPU address. +/// The buffer views' written-pages bitmap and read marks: the buffer, the +/// mapping the CPU reads the marks in (bits as dwords) and host GPU address. +/// +/// The bitmap is in video memory (after #2465). Every +/// marked write or read is a load and an atomic OR, and in system memory +/// (where it was) each crosses the bus: on the RTX 4090 a 1.5M-thread clear +/// that marks took ~1 s. After each submission [`marks_tails`] copies it +/// into the read-back buffer `data` (cached system memory, which the CPU +/// reads and clears as it did the bitmap) and clears it from zeros. struct Bitmap { _buffer: ID3D12Resource, data: usize, gpu: u64, + /// Copies the bitmap into `data`'s buffer, then clears it. Recorded + /// once, closed, and run after every submission's lists. + tail: HostList, + _back: ID3D12Resource, + _zeros: ID3D12Resource, } -// SAFETY: D3D12 resources are free-threaded; the mapping is read and cleared -// only between submissions, which run one at a time. +// SAFETY: D3D12 resources are free-threaded; the read-back mapping is read +// and cleared only between submissions, which run one at a time, and the +// tail list runs in one submission at a time. unsafe impl Send for Bitmap {} // SAFETY: as above. unsafe impl Sync for Bitmap {} +static BITMAPS: [std::sync::OnceLock<Option<Bitmap>>; 2] = [const { std::sync::OnceLock::new() }; 2]; + /// The bitmap of other shaders, or (`memory`) of shaders that use title /// memory, whose marks go back only while it is not withheld /// (`crate::memory::withholding`). fn bitmap(memory: bool) -> Option<&'static Bitmap> { - static BITMAPS: [std::sync::OnceLock<Option<Bitmap>>; 2] = [const { std::sync::OnceLock::new() }; 2]; BITMAPS[usize::from(memory)] .get_or_init(|| { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_BARRIER, D3D12_RESOURCE_BARRIER_0, D3D12_RESOURCE_BARRIER_FLAG_NONE, + D3D12_RESOURCE_BARRIER_TYPE_UAV, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_UAV_BARRIER, + }; // Written pages, then one read mark per heap index. let bits = victory_shader::emit::VIEW_READS + victory_shader::emit::HEAP_VIEWS; let bytes = u64::from(bits / 8); - let (buffer, data) = host()?.shared_buffer(bytes)?; + let host = host()?; + let buffer = host.uav_buffer(bytes)?; crate::host::name(&buffer, || "views' written pages and read slots".into()); - // SAFETY: our mapped buffer of `bytes` bytes. - unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; + let (back, data) = host.readback_buffer(bytes)?; + crate::host::name(&back, || "views' marks read back".into()); + let (zeros, z) = host.upload_buffer(bytes)?; + // SAFETY: our mapped buffers of `bytes` bytes. + unsafe { + std::ptr::write_bytes(z, 0, bytes as usize); + std::ptr::write_bytes(data, 0, bytes as usize); + } + let tail = host.new_list().ok()?; + // The lists before it wrote the bitmap as unordered access (from + // the common state); the copy takes it as its source. + let done = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }; + // SAFETY: an open list; buffers of ours the bitmap keeps. + unsafe { + tail.list.ResourceBarrier(&[done]); + tail.list.CopyBufferRegion(&back, 0, &buffer, 0, bytes); + tail.list.ResourceBarrier(&[crate::host::transition( + &buffer, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + tail.list.CopyBufferRegion(&buffer, 0, &zeros, 0, bytes); + } + tail.close(); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; Some(Bitmap { _buffer: buffer, data: data as usize, gpu, + tail, + _back: back, + _zeros: zeros, }) }) .as_ref() } +/// The lists that read the bitmaps made so far back and clear them, to run +/// after every submission's lists (`Host::execute`). +pub(crate) fn marks_tails() -> Vec<&'static HostList> { + BITMAPS.iter().filter_map(|b| b.get()?.as_ref()).map(|b| &b.tail).collect() +} + /// The host GPU address of the buffer views' written-pages bitmap, for the /// root UAV of shaders that mark their writes (`memory`: shaders that use /// title memory, see [`bitmap`]). @@ -816,7 +875,10 @@ pub(crate) fn view_writes(memory: bool) -> Option<u64> { /// Heap slots whose texture views shaders read: the marks seen so far (a /// slot's stays set in the bitmap until [`forget_read`]), and the slots to /// clear at the next [`take_reads`]. -static READS: Mutex<(Vec<u32>, Vec<u32>)> = Mutex::new((Vec::new(), Vec::new())); +/// Also the read marks since the last [`reads_since`] (the bitmap in +/// video memory is cleared after every submission, so it no longer keeps +/// them between calls). +static READS: Mutex<(Vec<u32>, Vec<u32>, Vec<u32>)> = Mutex::new((Vec::new(), Vec::new(), Vec::new())); /// After a submission: the heap slots its shaders first read texture views /// at (`victory_shader::emit`, "Read marks"), each once until @@ -836,8 +898,9 @@ pub(crate) fn take_reads() -> Vec<u32> { return Vec::new(); } let mut reads = READS.lock().unwrap_or_else(|e| e.into_inner()); - let (seen, forgotten) = &mut *reads; + let (seen, forgotten, since) = &mut *reads; seen.resize(words, 0); + since.resize(words, 0); for slot in forgotten.drain(..) { let (w, bit) = ((slot / 32) as usize, 1u32 << (slot % 32)); if w < words { @@ -847,7 +910,9 @@ pub(crate) fn take_reads() -> Vec<u32> { } let mut new = Vec::new(); for (w, s) in seen.iter_mut().enumerate() { - let mut fresh = maps.iter().fold(0, |x, bits| x | bits[w]) & !*s; + let all = maps.iter().fold(0, |x, bits| x | bits[w]); + since[w] |= all; + let mut fresh = all & !*s; *s |= fresh; while fresh != 0 { new.push(w as u32 * 32 + fresh.trailing_zeros()); @@ -866,8 +931,18 @@ pub(crate) fn reads_since() -> Vec<u32> { let words = (victory_shader::emit::HEAP_VIEWS / 32) as usize; let first = (victory_shader::emit::VIEW_READS / 32) as usize; let mut slots = Vec::new(); + // The marks `take_reads` saw since the last call, then those of + // the read-back copies it has not seen yet. + let since = std::mem::take(&mut READS.lock().unwrap_or_else(|e| e.into_inner()).2); + for (w, &x) in since.iter().enumerate() { + let mut x = x; + while x != 0 { + slots.push(w as u32 * 32 + x.trailing_zeros()); + x &= x - 1; + } + } for b in [false, true].into_iter().filter_map(bitmap) { - // SAFETY: the mapped bitmap's read marks; no submission runs. + // SAFETY: the read-back copy's read marks; no submission runs. let bits = unsafe { std::slice::from_raw_parts_mut((b.data as *mut u32).add(first), words) }; for (w, word) in bits.iter_mut().enumerate() { let mut x = std::mem::take(word); ``` </details>
Author
Owner

@⁠neonbyte1 on GitHub · 2026-11-26 17:43 UTC · original

@⁠latentdev thank you, that's very helpful. I'm applying your patch on my test base (main plus a few unmerged PRs this setup needs) and will run it in game on the RTX 5090 under Wine, on its own and on top of #2958. I'll compare it with the baselines I already have (871 ms/frame without either, 673 ms with #2958) and post frame time, GPU time and any read-back cost here.

AI-assisted (Claude); no game data shared.

**@⁠neonbyte1** on GitHub · 2026-11-26 17:43 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#issuecomment-7199523234) @⁠latentdev thank you, that's very helpful. I'm applying your patch on my test base (`main` plus a few unmerged PRs this setup needs) and will run it in game on the RTX 5090 under Wine, on its own and on top of #2958. I'll compare it with the baselines I already have (871 ms/frame without either, 673 ms with #2958) and post frame time, GPU time and any read-back cost here. _AI-assisted (Claude); no game data shared._
Author
Owner

@⁠neonbyte1 on GitHub · 2026-11-26 18:43 UTC · original

@⁠latentdev @⁠wbkepler results with latentdev's port on an RTX 5090 (driver 620.73.04), Linux, GE-Proton11-14 Wine with vkd3d-proton.

Setup:

  • Base: main plus a few unmerged PRs this setup needs.
  • The port: applied with git apply --3way, clean on both bases. I reviewed it first. The resource states are fine: buffers decay to COMMON after each ExecuteCommandLists, the bitmap's tail is the last list in each submission, and a pooled bitmap returns to the pool only after its fence.
  • Runs: untimed, 10 minutes each in the opening yard, medians of the last 30 frame-rate reports. One run per build.
base + #2958 (wave-coalesced marks) + this PR (port) + both
ms/frame 871 (1.1 fps) 673 (1.5 fps) 665 (1.5 fps) 674 (1.5 fps)
on the GPU 755 459 450 425
preparing / copying back 67 / 48 62 / 44 63 / 46 65 / 51
device removed, Xid, panics 0 0 0 0

So on NVIDIA under Wine, moving the bitmap to video memory removes about the same ~300 ms/frame of GPU time as coalescing the atomics. Together they gain only another ~25–35 ms of GPU time and no frame time; this scene varies by more than that between runs, so I wouldn't read anything into it. Either one fixes the system-memory atomic cost here.

The cell frames match the run without either change, apart from this scene's usual lit/hazy variation. One frame in the combined run shows heavy cyan blotches on the outdoor establishing shot. Two earlier runs on builds without either PR show the same blotches on the same shot, so that's a separate issue in that shot, not caused by these.

AI-assisted (Claude); measured on my machine, no game data shared.

**@⁠neonbyte1** on GitHub · 2026-11-26 18:43 UTC · [original](https://github.com/Marvisak/VIctory/pull/2465#issuecomment-7200786918) @⁠latentdev @⁠wbkepler results with latentdev's port on an RTX 5090 (driver 620.73.04), Linux, GE-Proton11-14 Wine with vkd3d-proton. **Setup:** - **Base:** `main` plus a few unmerged PRs this setup needs. - **The port:** applied with `git apply --3way`, clean on both bases. I reviewed it first. The resource states are fine: buffers decay to COMMON after each `ExecuteCommandLists`, the bitmap's tail is the last list in each submission, and a pooled bitmap returns to the pool only after its fence. - **Runs:** untimed, 10 minutes each in the opening yard, medians of the last 30 frame-rate reports. One run per build. | | base | + #2958 (wave-coalesced marks) | + this PR (port) | + both | |---|---|---|---|---| | ms/frame | 871 (1.1 fps) | 673 (1.5 fps) | **665 (1.5 fps)** | 674 (1.5 fps) | | on the GPU | 755 | 459 | **450** | 425 | | preparing / copying back | 67 / 48 | 62 / 44 | 63 / 46 | 65 / 51 | | device removed, Xid, panics | 0 | 0 | 0 | 0 | So on NVIDIA under Wine, moving the bitmap to video memory removes about the same ~300 ms/frame of GPU time as coalescing the atomics. Together they gain only another ~25–35 ms of GPU time and no frame time; this scene varies by more than that between runs, so I wouldn't read anything into it. Either one fixes the system-memory atomic cost here. The cell frames match the run without either change, apart from this scene's usual lit/hazy variation. One frame in the combined run shows heavy cyan blotches on the outdoor establishing shot. Two earlier runs on builds without either PR show the same blotches on the same shot, so that's a separate issue in that shot, not caused by these. _AI-assisted (Claude); measured on my machine, no game data shared._
This pull request has changes conflicting with the target branch.
  • crates/victory-gpu/src/host.rs
  • crates/victory-gpu/src/memory.rs
  • crates/victory-gpu/src/shadow.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2465/head:github-bot/gh-2465'
git switch 'github-bot/gh-2465'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2465'
git switch 'github-bot/gh-2465'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2465'
git switch 'github-bot/gh-2465'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2465'
git switch 'main'
git merge --squash 'github-bot/gh-2465'
git switch 'main'
git merge --ff-only 'github-bot/gh-2465'
git switch 'main'
git merge 'github-bot/gh-2465'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory!2465
No description provided.