GPU: copy back with NtWriteVirtualMemory, no VirtualQuery before a copy into the title (copy back 1.5 s -> 0.13 s) #1215

Open
github-bot wants to merge 1 commit from github-bot/gh-1215 into main AGit
Owner

@⁠LooperSalty on GitHub · 2026-11-24 16:26 UTC · original
LooperSalty:perf/nt-write-copy-back → main · +407 −3 · 4 files · 1 commits · open

From a tester working with Claude (AI-assisted); measured on my own machine (i7-13700KF, RTX 4070 Super). No game data in the diff.

What

  • write_mapped (the copy back into title memory after a submission) calls NtWriteVirtualMemory directly. WriteProcessMemory queries the destination region first (NtQueryVirtualMemory), about 2 ms a call in the title's big pools. Falls back to WriteProcessMemory if the symbol is not found; an unmapped page is reported the same way.
  • copy_mapped no longer runs VirtualQuery before a copy into title memory; the check only runs after the first attempt failed.
  • Diagnostics feature only: VICTORY_PROFILE=<ms> samples all thread stacks and prints the hottest every 5 s.
  • Two tests in host.rs (partial write into a half-committed range, copy into not-fully-mapped memory).

Measured

World stage, DRED off: copy back of one frame 1.5 s -> 0.13 s. Together with leaving VICTORY_D3D12_DRED unset (it costs about 2.5x per frame on its own), world went from 0.2 fps to 1.6 fps on this change set alone. Numbers are also in #841.

cargo test -p victory-gpu -p victory-shader is green on this branch (based on origin/main ffe310e).

**@⁠LooperSalty** on GitHub · 2026-11-24 16:26 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215) `LooperSalty:perf/nt-write-copy-back` → `main` · +407 −3 · 4 files · 1 commits · open From a tester working with Claude (AI-assisted); measured on my own machine (i7-13700KF, RTX 4070 Super). No game data in the diff. ## What - `write_mapped` (the copy back into title memory after a submission) calls `NtWriteVirtualMemory` directly. `WriteProcessMemory` queries the destination region first (`NtQueryVirtualMemory`), about 2 ms a call in the title's big pools. Falls back to `WriteProcessMemory` if the symbol is not found; an unmapped page is reported the same way. - `copy_mapped` no longer runs `VirtualQuery` before a copy into title memory; the check only runs after the first attempt failed. - Diagnostics feature only: `VICTORY_PROFILE=<ms>` samples all thread stacks and prints the hottest every 5 s. - Two tests in `host.rs` (partial write into a half-committed range, copy into not-fully-mapped memory). ## Measured World stage, DRED off: copy back of one frame 1.5 s -> 0.13 s. Together with leaving `VICTORY_D3D12_DRED` unset (it costs about 2.5x per frame on its own), world went from 0.2 fps to 1.6 fps on this change set alone. Numbers are also in #841. `cargo test -p victory-gpu -p victory-shader` is green on this branch (based on `origin/main` ffe310e).
WriteProcessMemory asks the kernel about the destination region first
(NtQueryVirtualMemory, about 2 ms a call in the title's big pools), so the
copy back after a world submission spent over a second there. write_mapped
now calls NtWriteVirtualMemory directly (falls back to WriteProcessMemory if
the symbol is missing) and reports an unmapped page the same way.

copy_mapped no longer calls VirtualQuery before copying into title memory;
the check runs only after the first attempt failed, so a copy into fully
mapped memory costs one call.

Diagnostics only: VICTORY_PROFILE=<ms> samples every thread's stack and
prints the hottest ones every 5 s.

Measured (i7-13700KF, RTX 4070 Super, world stage, DRED off): copy back of
one frame 1.5 s -> 0.13 s.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LwHrL6fhkpeG9ByE1rJxrt
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:24:02 +00:00
Author
Owner

@⁠TG0000 on GitHub · 2026-11-24 16:57 UTC · original

The direction is right: the VirtualQuery before copies into the title and the one inside WriteProcessMemory are a large part of the time here too (RX 6800, Windows 11).

One behaviour change to check at 6950319, reproduced here: in copy_mapped (host.rs:1306-1327) the committed check now comes after the failed read. By then ReadProcessMemory has written the mapped part of a destination that is not all mapped. On main such a destination is left alone. Example: a copy of 25 pages over a hole (page 30 of 40): main writes nothing, 6950319 writes the pages before the hole. The new test cannot see it, because its two calls copy the same bytes.

Suggested fix: when the destination is title memory, check it before the first read, cheaply: read one byte of each page through the kernel (ReadProcessMemory with the title memory as the source), which costs far less than VirtualQuery in the big pools. I have a test for "written whole or not at all" that passes on main and fails on this head, and will gladly share it.

profile.rs (a sampler behind the diagnostics feature) is unrelated to the change; splitting it out would make this easier to take.

Not checked: Wine. I am comparing the speed of NtWriteVirtualMemory with other ways in the same launch and will post the number.

AI-assisted (Claude Code).

**@⁠TG0000** on GitHub · 2026-11-24 16:57 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7138460592) The direction is right: the `VirtualQuery` before copies into the title and the one inside `WriteProcessMemory` are a large part of the time here too (RX 6800, Windows 11). One behaviour change to check at 6950319, reproduced here: in `copy_mapped` (host.rs:1306-1327) the `committed` check now comes after the failed `read`. By then `ReadProcessMemory` has written the mapped part of a destination that is **not** all mapped. On `main` such a destination is left alone. Example: a copy of 25 pages over a hole (page 30 of 40): `main` writes nothing, 6950319 writes the pages before the hole. The new test cannot see it, because its two calls copy the same bytes. Suggested fix: when the destination is title memory, check it before the first read, cheaply: read one byte of each page through the kernel (`ReadProcessMemory` with the *title memory as the source*), which costs far less than `VirtualQuery` in the big pools. I have a test for "written whole or not at all" that passes on `main` and fails on this head, and will gladly share it. `profile.rs` (a sampler behind the diagnostics feature) is unrelated to the change; splitting it out would make this easier to take. Not checked: Wine. I am comparing the speed of `NtWriteVirtualMemory` with other ways in the same launch and will post the number. _AI-assisted (Claude Code)._
Author
Owner

@⁠TG0000 on GitHub · 2026-11-24 17:02 UTC · original

The number I promised, with your two changes ported into my measuring build, RX 6800, Windows 11, one launch, 9 looped world frames of 48 submissions, paired (submissions only, not frame time):

difference against my own version of the same thing, ms per frame (95 %)
NtWriteVirtualMemory for the copy back 0.0 +-7.3
check only after a failure -2.2 +-7.3
both -3.1 +-5.3
main's way of writing back, for scale +200 +-51
main's check before each title copy, for scale +163 +-32

So no difference found between yours and mine (the noise floor is 9 to 13 ms), and both are far better than main. I drop my two branches in favour of this PR.

For the destination behaviour from my comment above, here is a tested fix, free to take (applied to 6950319: cargo test -p victory-gpu 55 passed, 0 failed, including the two tests that fail without it): a destination is checked by reading one byte of each page through the kernel, so it stays written whole or not at all, and a guard page stays one. Its cost is inside the numbers above (my version already did this).

patch (host.rs and host/destination_tests.rs)
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index 9fd705f..5423f55 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -1283,6 +1283,21 @@ impl Batch {
     }
 }
 
+#[cfg(test)]
+mod destination_tests;
+
+/// Whether all of `[at, at + len)` is mapped memory one can read, found by
+/// having the kernel read a byte of each page (which leaves guard pages
+/// alone): the title's copies are of a few hundred bytes mostly, and asking
+/// for the state of a big pool's memory took 2 ms for each.
+fn all_readable(at: *const u8, len: usize) -> bool {
+    let (mut byte, mut all) = (0, true);
+    for_pieces(at as usize, len, 4 << 10, |at, _| {
+        all = all && read(at as *const u8, &mut byte, 1);
+    });
+    all
+}
+
 /// Copies title memory at submission. The ranges were checked against their
 /// resources when recorded, but the title may since have unmapped pages of
 /// them (tiled memory, page mappings), which read as zeros here; a title
@@ -1303,7 +1318,7 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b
         2 => return,
         _ => {}
     }
-    if len == 0 {
+    if len == 0 || title_dst && !all_readable(dst, len) {
         return;
     }
     if title_dst {
@@ -1318,13 +1333,6 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b
     if whole {
         return;
     }
-    // The kernel reports an unmapped destination as it does a source, so
-    // `VirtualQuery` (which walks page tables to the region's end, ~1 ms a
-    // copy in the title's pools, ~100 ms per world frame) is asked only
-    // after a failure: a destination not all mapped is left alone.
-    if title_dst && !crate::texture::committed(dst, len) {
-        return;
-    }
     #[cfg(feature = "diagnostics")]
     crate::copystat::add(crate::copystat::C::Fallbacks, 1);
     // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
diff --git a/crates/victory-gpu/src/host/destination_tests.rs b/crates/victory-gpu/src/host/destination_tests.rs
new file mode 100644
index 0000000..94da286
--- /dev/null
+++ b/crates/victory-gpu/src/host/destination_tests.rs
@@ -0,0 +1,90 @@
+use super::*;
+use windows_sys::Win32::System::Memory::{
+    MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS,
+    PAGE_READWRITE, VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery,
+};
+
+const KERNEL_PAGE: usize = 4 << 10;
+
+/// `pages` committed pages, none of their bytes zero.
+fn memory(pages: usize) -> usize {
+    let len = pages * KERNEL_PAGE;
+    // SAFETY: a fresh allocation, filled; the tests free it.
+    unsafe {
+        let p = VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
+        assert!(!p.is_null());
+        for i in 0..len {
+            p.cast::<u8>().add(i).write((i * 7 + i / KERNEL_PAGE) as u8 | 1);
+        }
+        p as usize
+    }
+}
+
+fn free(at: usize) {
+    // SAFETY: an allocation of `memory`.
+    unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) };
+}
+
+fn decommit(at: usize, page: usize, n: usize) {
+    // SAFETY: pages of an allocation of `memory`.
+    let ok = unsafe { VirtualFree((at + page * KERNEL_PAGE) as *mut _, n * KERNEL_PAGE, MEM_DECOMMIT) };
+    assert_ne!(ok, 0);
+}
+
+fn byte(at: usize, page: usize) -> u8 {
+    // SAFETY: a readable page of an allocation of `memory`.
+    unsafe { ((at + page * KERNEL_PAGE + 100) as *const u8).read_volatile() }
+}
+
+/// A destination in title memory that is not all mapped is left alone.
+#[test]
+fn title_destinations_are_written_whole_or_not_at_all() {
+    let from = vec![0u8; 25 * KERNEL_PAGE];
+    let at = memory(40);
+    decommit(at, 30, 1);
+    copy_mapped((at + 6 * KERNEL_PAGE) as *mut u8, from.as_ptr(), from.len(), true);
+    assert_ne!(byte(at, 6), 0);
+    copy_mapped((at + 5 * KERNEL_PAGE) as *mut u8, from.as_ptr(), from.len(), true);
+    assert!((5..30).all(|page| byte(at, page) == 0));
+    free(at);
+}
+
+fn protect(at: usize, page: usize, protection: u32) {
+    let mut old = 0;
+    // SAFETY: a page of an allocation of `memory`.
+    let ok = unsafe { VirtualProtect((at + page * KERNEL_PAGE) as *const _, KERNEL_PAGE, protection, &mut old) };
+    assert_ne!(ok, 0);
+}
+
+/// Checking a destination changes nothing in it: a guard page of the
+/// title's stays one, and neither it nor memory without access is written.
+#[test]
+fn guarded_and_inaccessible_destinations_are_left_alone() {
+    let from = vec![0u8; 8 * KERNEL_PAGE];
+    for protection in [PAGE_READWRITE | PAGE_GUARD, PAGE_NOACCESS] {
+        let at = memory(8);
+        protect(at, 5, protection);
+        copy_mapped((at + 100) as *mut u8, from.as_ptr(), 8 * KERNEL_PAGE - 100, true);
+        // SAFETY: plain data filled in by the query.
+        let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+        // SAFETY: a valid out pointer of the right size.
+        unsafe { VirtualQuery((at + 5 * KERNEL_PAGE) as *const _, &mut info, size_of_val(&info)) };
+        assert_eq!(info.Protect, protection);
+        assert!((0..8).filter(|&page| page != 5).all(|page| byte(at, page) != 0));
+        free(at);
+    }
+}
+
+/// Title threads submit, with the stacks the title gave them.
+#[test]
+fn a_small_stack_is_enough() {
+    let copied = std::thread::Builder::new().stack_size(64 << 10).spawn(|| {
+        let at = memory(40);
+        let from = vec![0u8; 40 * KERNEL_PAGE];
+        copy_mapped(at as *mut u8, from.as_ptr(), from.len(), true);
+        let copied = (0..40).all(|page| byte(at, page) == 0);
+        free(at);
+        copied
+    });
+    assert!(copied.unwrap().join().unwrap());
+}

Also: cargo clippy -p victory-gpu --all-targets --all-features -- -D warnings fails at 6950319 in the new profile.rs (line 211 lacks a SAFETY comment, line 263 wants is_multiple_of). The patch does not touch that file.

AI-assisted (Claude Code).

**@⁠TG0000** on GitHub · 2026-11-24 17:02 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7138599025) The number I promised, with your two changes ported into my measuring build, RX 6800, Windows 11, one launch, 9 looped world frames of 48 submissions, paired (submissions only, not frame time): | | difference against my own version of the same thing, ms per frame (95 %) | |---|---| | `NtWriteVirtualMemory` for the copy back | 0.0 +-7.3 | | check only after a failure | -2.2 +-7.3 | | both | -3.1 +-5.3 | | `main`'s way of writing back, for scale | +200 +-51 | | `main`'s check before each title copy, for scale | +163 +-32 | So no difference found between yours and mine (the noise floor is 9 to 13 ms), and both are far better than `main`. I drop my two branches in favour of this PR. For the destination behaviour from my comment above, here is a tested fix, free to take (applied to 6950319: `cargo test -p victory-gpu` 55 passed, 0 failed, including the two tests that fail without it): a destination is checked by reading one byte of each page through the kernel, so it stays written whole or not at all, and a guard page stays one. Its cost is inside the numbers above (my version already did this). <details><summary>patch (host.rs and host/destination_tests.rs)</summary> ```diff diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9fd705f..5423f55 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1283,6 +1283,21 @@ impl Batch { } } +#[cfg(test)] +mod destination_tests; + +/// Whether all of `[at, at + len)` is mapped memory one can read, found by +/// having the kernel read a byte of each page (which leaves guard pages +/// alone): the title's copies are of a few hundred bytes mostly, and asking +/// for the state of a big pool's memory took 2 ms for each. +fn all_readable(at: *const u8, len: usize) -> bool { + let (mut byte, mut all) = (0, true); + for_pieces(at as usize, len, 4 << 10, |at, _| { + all = all && read(at as *const u8, &mut byte, 1); + }); + all +} + /// Copies title memory at submission. The ranges were checked against their /// resources when recorded, but the title may since have unmapped pages of /// them (tiled memory, page mappings), which read as zeros here; a title @@ -1303,7 +1318,7 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b 2 => return, _ => {} } - if len == 0 { + if len == 0 || title_dst && !all_readable(dst, len) { return; } if title_dst { @@ -1318,13 +1333,6 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b if whole { return; } - // The kernel reports an unmapped destination as it does a source, so - // `VirtualQuery` (which walks page tables to the region's end, ~1 ms a - // copy in the title's pools, ~100 ms per world frame) is asked only - // after a failure: a destination not all mapped is left alone. - if title_dst && !crate::texture::committed(dst, len) { - return; - } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Fallbacks, 1); // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece diff --git a/crates/victory-gpu/src/host/destination_tests.rs b/crates/victory-gpu/src/host/destination_tests.rs new file mode 100644 index 0000000..94da286 --- /dev/null +++ b/crates/victory-gpu/src/host/destination_tests.rs @@ -0,0 +1,90 @@ +use super::*; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, + PAGE_READWRITE, VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, +}; + +const KERNEL_PAGE: usize = 4 << 10; + +/// `pages` committed pages, none of their bytes zero. +fn memory(pages: usize) -> usize { + let len = pages * KERNEL_PAGE; + // SAFETY: a fresh allocation, filled; the tests free it. + unsafe { + let p = VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + assert!(!p.is_null()); + for i in 0..len { + p.cast::<u8>().add(i).write((i * 7 + i / KERNEL_PAGE) as u8 | 1); + } + p as usize + } +} + +fn free(at: usize) { + // SAFETY: an allocation of `memory`. + unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }; +} + +fn decommit(at: usize, page: usize, n: usize) { + // SAFETY: pages of an allocation of `memory`. + let ok = unsafe { VirtualFree((at + page * KERNEL_PAGE) as *mut _, n * KERNEL_PAGE, MEM_DECOMMIT) }; + assert_ne!(ok, 0); +} + +fn byte(at: usize, page: usize) -> u8 { + // SAFETY: a readable page of an allocation of `memory`. + unsafe { ((at + page * KERNEL_PAGE + 100) as *const u8).read_volatile() } +} + +/// A destination in title memory that is not all mapped is left alone. +#[test] +fn title_destinations_are_written_whole_or_not_at_all() { + let from = vec![0u8; 25 * KERNEL_PAGE]; + let at = memory(40); + decommit(at, 30, 1); + copy_mapped((at + 6 * KERNEL_PAGE) as *mut u8, from.as_ptr(), from.len(), true); + assert_ne!(byte(at, 6), 0); + copy_mapped((at + 5 * KERNEL_PAGE) as *mut u8, from.as_ptr(), from.len(), true); + assert!((5..30).all(|page| byte(at, page) == 0)); + free(at); +} + +fn protect(at: usize, page: usize, protection: u32) { + let mut old = 0; + // SAFETY: a page of an allocation of `memory`. + let ok = unsafe { VirtualProtect((at + page * KERNEL_PAGE) as *const _, KERNEL_PAGE, protection, &mut old) }; + assert_ne!(ok, 0); +} + +/// Checking a destination changes nothing in it: a guard page of the +/// title's stays one, and neither it nor memory without access is written. +#[test] +fn guarded_and_inaccessible_destinations_are_left_alone() { + let from = vec![0u8; 8 * KERNEL_PAGE]; + for protection in [PAGE_READWRITE | PAGE_GUARD, PAGE_NOACCESS] { + let at = memory(8); + protect(at, 5, protection); + copy_mapped((at + 100) as *mut u8, from.as_ptr(), 8 * KERNEL_PAGE - 100, true); + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { VirtualQuery((at + 5 * KERNEL_PAGE) as *const _, &mut info, size_of_val(&info)) }; + assert_eq!(info.Protect, protection); + assert!((0..8).filter(|&page| page != 5).all(|page| byte(at, page) != 0)); + free(at); + } +} + +/// Title threads submit, with the stacks the title gave them. +#[test] +fn a_small_stack_is_enough() { + let copied = std::thread::Builder::new().stack_size(64 << 10).spawn(|| { + let at = memory(40); + let from = vec![0u8; 40 * KERNEL_PAGE]; + copy_mapped(at as *mut u8, from.as_ptr(), from.len(), true); + let copied = (0..40).all(|page| byte(at, page) == 0); + free(at); + copied + }); + assert!(copied.unwrap().join().unwrap()); +} ``` </details> Also: `cargo clippy -p victory-gpu --all-targets --all-features -- -D warnings` fails at 6950319 in the new `profile.rs` (line 211 lacks a SAFETY comment, line 263 wants `is_multiple_of`). The patch does not touch that file. _AI-assisted (Claude Code)._
Author
Owner

@⁠Zipettte on GitHub · 2026-11-24 17:59 UTC · original

Tested on AMD Radeon RX 7700 XT (RDNA3, gfx1101), driver 32.0.32029.2010, Windows 11, Rust 1.98.1 MSVC at 6950319: cargo test -p victory-gpu passes, 52 passed / 0 failed. Workspace baseline on main (ffe310e) is green on the same machine (342 passed).

Tested with AI assistance (Claude).

**@⁠Zipettte** on GitHub · 2026-11-24 17:59 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7140008636) Tested on AMD Radeon RX 7700 XT (RDNA3, gfx1101), driver 32.0.32029.2010, Windows 11, Rust 1.98.1 MSVC at 6950319: `cargo test -p victory-gpu` passes, 52 passed / 0 failed. Workspace baseline on main (ffe310e) is green on the same machine (342 passed). _Tested with AI assistance (Claude)._
Author
Owner

@⁠Mumogg on GitHub · 2026-11-24 18:38 UTC · original · edited 2026-11-24 19:09 UTC

A/B under Wine, for the Linux side: no measurable difference here, in either direction, and nothing broke.

Setup: RTX 5070 Ti (driver 615.78.08), Ryzen 5 9600X, Nobara 44, Wine 11.22 Staging, vkd3d-proton from GE-Proton11-14. Tree: ffe310e + #454 #177 #259 #233 #646 #578 #334 #493 #724 #725 + the #783 region fallback, with and without this PR (6950319; in write_mapped I kept #783's region walk and used this PR's NtWriteVirtualMemory call inside it). Diagnostics build, DRED off, 1.0.2.1, network off, warm caches, wave64 mesh programs refused (#578), so about 200 draws per world frame.

Four 420 s runs in the order base / PR / PR / base; medians over the frame lines in the world:

run lines fps frame preparing copies on the GPU copying back
base 1 42 1.10 916 ms 563 ms 323 ms 162 ms 123 ms
PR 1 39 1.20 849 ms 516 ms 329 ms 160 ms 92 ms
PR 2 14 1.00 1,017 ms 534 ms 312 ms 168 ms 139 ms
base 2 54 0.90 1,133 ms 719 ms 413 ms 160 ms 101 ms

The spread between the two runs of one side is as large as the spread between sides. That fits what the description says the gain comes from: Windows querying the destination's region inside WriteProcessMemory. My guess, not checked in Wine's source, is that its WriteProcessMemory has no such walk to save; the standalone timings I took earlier of these calls under Wine were microseconds each (#400). PR 2 has fewer lines because the title stopped early with the lookup spin described in #774, which is unrelated.

So: harmless under Wine as far as these runs show, and the win is a Windows one. I did not try the thread-pool branch or VICTORY_PROFILE.

(AI-assisted, Claude Code; runs on my machine.)

Edit: the Wine version was 11.22 Staging, not 11.21 (the system had updated before these runs).

**@⁠Mumogg** on GitHub · 2026-11-24 18:38 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7140941390) · edited 2026-11-24 19:09 UTC A/B under Wine, for the Linux side: no measurable difference here, in either direction, and nothing broke. **Setup:** RTX 5070 Ti (driver 615.78.08), Ryzen 5 9600X, Nobara 44, Wine 11.22 Staging, vkd3d-proton from GE-Proton11-14. Tree: `ffe310e` + #454 #177 #259 #233 #646 #578 #334 #493 #724 #725 + the #783 region fallback, with and without this PR (`6950319`; in `write_mapped` I kept #783's region walk and used this PR's `NtWriteVirtualMemory` call inside it). Diagnostics build, DRED off, 1.0.2.1, network off, warm caches, wave64 mesh programs refused (#578), so about 200 draws per world frame. Four 420 s runs in the order base / PR / PR / base; medians over the frame lines in the world: | run | lines | fps | frame | preparing | copies | on the GPU | copying back | |---|---|---|---|---|---|---|---| | base 1 | 42 | 1.10 | 916 ms | 563 ms | 323 ms | 162 ms | 123 ms | | PR 1 | 39 | 1.20 | 849 ms | 516 ms | 329 ms | 160 ms | 92 ms | | PR 2 | 14 | 1.00 | 1,017 ms | 534 ms | 312 ms | 168 ms | 139 ms | | base 2 | 54 | 0.90 | 1,133 ms | 719 ms | 413 ms | 160 ms | 101 ms | The spread between the two runs of one side is as large as the spread between sides. That fits what the description says the gain comes from: Windows querying the destination's region inside `WriteProcessMemory`. My guess, not checked in Wine's source, is that its `WriteProcessMemory` has no such walk to save; the standalone timings I took earlier of these calls under Wine were microseconds each (#400). PR 2 has fewer lines because the title stopped early with the lookup spin described in #774, which is unrelated. So: harmless under Wine as far as these runs show, and the win is a Windows one. I did not try the thread-pool branch or `VICTORY_PROFILE`. (AI-assisted, Claude Code; runs on my machine.) *Edit: the Wine version was 11.22 Staging, not 11.21 (the system had updated before these runs).*
Author
Owner

@⁠EduAzevedo on GitHub · 2026-11-24 21:21 UTC · original

Measured in game on NVIDIA Turing: RTX 2070 SUPER, driver 610.88, Ryzen 7 5700G, Windows 11, retail 1.0.2.1.

Both runs use the same base: main ffe310e + #493 + #189 + #206, the 2^18 dynamic reserve from #747 applied locally, VICTORY_SHADER_LOOP_LIMIT=32, and the diag build. The only change between them is this PR. Each run went into the world for about 5 minutes. The figures are medians of the one-second fps lines while in the world, where frames take 200 ms or more.

without #1215 with #1215
world samples 23 55
fps 0.30 1.40
ms/frame 3,136 717
copying back 1,713 ms (25 MB) 85 ms (30 MB)
on the GPU 239 ms 210 ms
preparing 642 ms (copies 493) 392 ms (copies 276)
draws/frame 585 2,118
  • The copy back is about 20x cheaper, and it is what made the world 4–5x faster on this card. Once #189 and the loop limit bring the GPU down to about 0.2 s, the copy back was the largest cost of a frame.
  • No regressions seen. In both runs:
    • 0 device removals;
    • 0 no dynamic slots and 0 a table is not made;
    • the same 2 0x80070057 texture failures (2560x1440);
    • a similar count of shaders that don't translate (639 vs 643).
  • What now dominates a frame is preparing, mostly the upload copies (~280 ms), then the GPU (~210 ms).

Only counts and timings here, no game data. AI-assisted measurement.

**@⁠EduAzevedo** on GitHub · 2026-11-24 21:21 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7144824328) Measured in game on NVIDIA Turing: RTX 2070 SUPER, driver 610.88, Ryzen 7 5700G, Windows 11, retail 1.0.2.1. Both runs use the same base: main `ffe310e` + #493 + #189 + #206, the 2^18 dynamic reserve from #747 applied locally, `VICTORY_SHADER_LOOP_LIMIT=32`, and the diag build. The only change between them is this PR. Each run went into the world for about 5 minutes. The figures are medians of the one-second `fps` lines while in the world, where frames take 200 ms or more. | | without #1215 | with #1215 | |---|---|---| | world samples | 23 | 55 | | fps | 0.30 | **1.40** | | ms/frame | 3,136 | **717** | | copying back | 1,713 ms (25 MB) | **85 ms** (30 MB) | | on the GPU | 239 ms | 210 ms | | preparing | 642 ms (copies 493) | 392 ms (copies 276) | | draws/frame | 585 | 2,118 | - **The copy back is about 20x cheaper**, and it is what made the world 4–5x faster on this card. Once #189 and the loop limit bring the GPU down to about 0.2 s, the copy back was the largest cost of a frame. - **No regressions seen.** In both runs: - 0 device removals; - 0 `no dynamic slots` and 0 `a table is not made`; - the same 2 `0x80070057` texture failures (2560x1440); - a similar count of shaders that don't translate (639 vs 643). - **What now dominates a frame** is `preparing`, mostly the upload copies (~280 ms), then the GPU (~210 ms). Only counts and timings here, no game data. AI-assisted measurement.
Author
Owner

@⁠aycow on GitHub · 2026-11-24 21:22 UTC · original

@⁠LooperSalty @⁠avt0m4t48 An independent CPU replay of 4 MiB with 131,072 one-byte runs measured 1,805.628 ms for Win32 checked writes and 114.690 ms for the native write primitive. Metadata replay alone was 2.184 ms. The separate VirtualQuery control took 1,362.622 ms per run set and 10.376 ms when queried once per 4 KiB page. The workload starts at completed change metadata downstream of #1681’s GPU comparison.

On this host both raw write primitives returned zero bytes and consumed PAGE_GUARD on the first attempt. Current write_mapped then retried and wrote one byte, while read_into refused and left the guard intact. The 2.502 ms direct control held a fixture-owned writable mapping. Production still needs an ownership proof for title mappings. This supports evaluating #1215's write backend independently from broad title-copy changes while preserving partial mapping and guard behavior. We are leaving #387 in draft.

AI-assisted using Codex.

**@⁠aycow** on GitHub · 2026-11-24 21:22 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7144855908) @⁠LooperSalty @⁠avt0m4t48 An independent CPU replay of 4 MiB with 131,072 one-byte runs measured 1,805.628 ms for Win32 checked writes and 114.690 ms for the native write primitive. Metadata replay alone was 2.184 ms. The separate VirtualQuery control took 1,362.622 ms per run set and 10.376 ms when queried once per 4 KiB page. The workload starts at completed change metadata downstream of #1681’s GPU comparison. On this host both raw write primitives returned zero bytes and consumed PAGE_GUARD on the first attempt. Current write_mapped then retried and wrote one byte, while read_into refused and left the guard intact. The 2.502 ms direct control held a fixture-owned writable mapping. Production still needs an ownership proof for title mappings. This supports evaluating #1215's write backend independently from broad title-copy changes while preserving partial mapping and guard behavior. We are leaving #387 in draft. AI-assisted using Codex.
Author
Owner

@⁠aycow on GitHub · 2026-11-24 22:43 UTC · original

@⁠s2k721 @⁠avt0m4t48 I rechecked the protected bulk copyback control on 70564ae. A 64 KiB span with a protected 4 KiB subrange delivered 61,440 bytes while stock reported 65,536. The local correction preflights contiguous writable spans and leaves a partially delivered tracked page dirty. It deliberately keeps the existing bulk policy and stays separate from exact fragmented replay. AMD and WARP passed the protected/mapped-neighbor and pending-write controls. The earlier exact-write benchmark still leaves roughly 115 ms for 131,072 fragments with a native per-run call. I’m avoiding per-run preflight and direct stores into mappings with no proven lifetime ownership. The GPU mask and lower-overhead checked writer remain complementary.

AI-assisted using Codex.

**@⁠aycow** on GitHub · 2026-11-24 22:43 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7146574099) @⁠s2k721 @⁠avt0m4t48 I rechecked the protected bulk copyback control on `70564ae`. A 64 KiB span with a protected 4 KiB subrange delivered 61,440 bytes while stock reported 65,536. The local correction preflights contiguous writable spans and leaves a partially delivered tracked page dirty. It deliberately keeps the existing bulk policy and stays separate from exact fragmented replay. AMD and WARP passed the protected/mapped-neighbor and pending-write controls. The earlier exact-write benchmark still leaves roughly 115 ms for 131,072 fragments with a native per-run call. I’m avoiding per-run preflight and direct stores into mappings with no proven lifetime ownership. The GPU mask and lower-overhead checked writer remain complementary. AI-assisted using Codex.
Author
Owner

@⁠aycow on GitHub · 2026-11-24 23:17 UTC · original · edited 2026-11-25 01:33 UTC

@⁠LooperSalty @⁠avt0m4t48 I validated a local opt-in exact-run consumer for XMem-managed physical views on 70564ae + #1816. It retains the physical section and page index with the snapshot, verifies them under XMem’s map lock at delivery, and uses your #1215 native checked primitive through the title address. A replaced page receives no stale callback, a protected subrange is skipped, and an overlapping declaration does not retry a delivered or failed byte. The #1681 GPU mask can remain a separate producer.

In the generated 4 MiB case with 131,072 changed bytes at stride 32, per-run Win32 writes took a median 492.52 ms and the native writer with one protection walk per 64 KiB piece took 45.50 ms. Both produced the same bytes. This is an isolated writer test, excluding GPU time and title mapping-lock contention. The Windows remap, alias and protected-neighbor controls passed. The default bulk path is unchanged. Computed-address writes and mappings outside XMem still need a separate lifetime guarantee.

AI-assisted using Codex.

Current-main recheck on ccfb029: the managed-view candidate compares the GPU copy against its submission snapshot and delivers only changed byte runs while the original XMem view is still mapped. The checked kernel copy from upstream #322 reduced the median against the Win32 wrapper from 351.82 to 59.74 ms for the 4 MiB fragmented fixture, and from 214.94 to 80.89 ms with a partially mapped destination. The dense control rose from 2.78 to 3.21 ms. These are CPU exact-writer comparisons. The mapping lease, title workload, and overall copyback time still need matched measurements. The candidate remains local and default-off.

**@⁠aycow** on GitHub · 2026-11-24 23:17 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7147225905) · edited 2026-11-25 01:33 UTC @⁠LooperSalty @⁠avt0m4t48 I validated a local opt-in exact-run consumer for XMem-managed physical views on `70564ae + #1816`. It retains the physical section and page index with the snapshot, verifies them under XMem’s map lock at delivery, and uses your #1215 native checked primitive through the title address. A replaced page receives no stale callback, a protected subrange is skipped, and an overlapping declaration does not retry a delivered or failed byte. The #1681 GPU mask can remain a separate producer. In the generated 4 MiB case with 131,072 changed bytes at stride 32, per-run Win32 writes took a median 492.52 ms and the native writer with one protection walk per 64 KiB piece took 45.50 ms. Both produced the same bytes. This is an isolated writer test, excluding GPU time and title mapping-lock contention. The Windows remap, alias and protected-neighbor controls passed. The default bulk path is unchanged. Computed-address writes and mappings outside XMem still need a separate lifetime guarantee. AI-assisted using Codex. Current-main recheck on `ccfb029`: the managed-view candidate compares the GPU copy against its submission snapshot and delivers only changed byte runs while the original XMem view is still mapped. The checked kernel copy from upstream #322 reduced the median against the Win32 wrapper from 351.82 to 59.74 ms for the 4 MiB fragmented fixture, and from 214.94 to 80.89 ms with a partially mapped destination. The dense control rose from 2.78 to 3.21 ms. These are CPU exact-writer comparisons. The mapping lease, title workload, and overall copyback time still need matched measurements. The candidate remains local and default-off.
Author
Owner

@⁠vladbondarenko97 on GitHub · 2026-11-24 23:32 UTC · original

Independent numbers for this PR from an RTX 3080 Ti box (i7-12700KF, Windows 11), from a standalone microbenchmark (one write into a committed PAGE_READWRITE allocation of our own process; time per call):

allocation write WriteProcessMemory VirtualQuery alone NtWriteVirtualMemory memcpy
64 MB 256 B 149 µs 151 µs 0.4 µs 0.01 µs
256 MB 256 B 642 µs 643 µs 0.5 µs 0.02 µs
1024 MB 256 B 5.9 ms 5.8 ms 0.5 µs 0.02 µs
256 MB 64 KiB 687 µs 681 µs 10.9 µs 7.0 µs
256 MB 1 MiB 906 µs 675 µs 166 µs 135 µs

So all of WriteProcessMemory's extra cost is its internal region query, which grows with the size of the destination allocation (the title's big pools), and NtWriteVirtualMemory removes it — the same conclusion as this PR. A related negative result: a VirtualQuery per region followed by a direct copy (we tried it on ffe310e) changed nothing in game, because that query is the slow part.

In game on ffe310e + #578 / #454 / #206 / #493 (same card), the copy-back time was ≈ 85 % writes (reads 0.5 %, write-watch 1 %) and copy-back was 85–840 ms of a 750–1230 ms world frame (e.g. 0.8 fps, 1233 ms/frame (… 838 copying back 27.4 MB)), consistent with your 1.5 s → 0.13 s. I have not run this PR's head in game.

AI use: Claude Code (Claude Opus 5.5 and Claude Sonnet 5.5 agents) wrote and ran the benchmark and the profiling build; numbers are from those runs.

**@⁠vladbondarenko97** on GitHub · 2026-11-24 23:32 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7147518141) Independent numbers for this PR from an RTX 3080 Ti box (i7-12700KF, Windows 11), from a standalone microbenchmark (one write into a committed `PAGE_READWRITE` allocation of our own process; time per call): | allocation | write | `WriteProcessMemory` | `VirtualQuery` alone | `NtWriteVirtualMemory` | memcpy | |---|---|---|---|---|---| | 64 MB | 256 B | 149 µs | 151 µs | 0.4 µs | 0.01 µs | | 256 MB | 256 B | 642 µs | 643 µs | 0.5 µs | 0.02 µs | | 1024 MB | 256 B | 5.9 ms | 5.8 ms | 0.5 µs | 0.02 µs | | 256 MB | 64 KiB | 687 µs | 681 µs | 10.9 µs | 7.0 µs | | 256 MB | 1 MiB | 906 µs | 675 µs | 166 µs | 135 µs | So all of `WriteProcessMemory`'s extra cost is its internal region query, which grows with the size of the destination allocation (the title's big pools), and `NtWriteVirtualMemory` removes it — the same conclusion as this PR. A related negative result: a `VirtualQuery` per region followed by a direct copy (we tried it on `ffe310e`) changed nothing in game, because that query is the slow part. In game on `ffe310e` + #578 / #454 / #206 / #493 (same card), the copy-back time was ≈ 85 % writes (reads 0.5 %, write-watch 1 %) and copy-back was 85–840 ms of a 750–1230 ms world frame (e.g. `0.8 fps, 1233 ms/frame (… 838 copying back 27.4 MB)`), consistent with your 1.5 s → 0.13 s. I have not run this PR's head in game. AI use: Claude Code (Claude Opus 5.5 and Claude Sonnet 5.5 agents) wrote and ran the benchmark and the profiling build; numbers are from those runs.
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 01:19 UTC · original

Automated triage for the maintainers.

Needs rebase. This pull request conflicts with main (conflicting: crates/victory-gpu/Cargo.toml, crates/victory-gpu/src/host.rs). It will be reviewed once it is rebased onto the current main.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 01:19 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7149423633) <!-- victory-triage v1 head=6950319ce55684b56c2fe6a8eec25b1f6994c287 verdict=needs-rebase at=2026-11-25T01:19:02Z --> Automated triage for the maintainers. **Needs rebase.** This pull request conflicts with `main` (conflicting: `crates/victory-gpu/Cargo.toml`, `crates/victory-gpu/src/host.rs`). It will be reviewed once it is rebased onto the current `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠r4tedx on GitHub · 2026-11-25 07:42 UTC · original

A note for the triage, from reading this PR against main 940d32f: the two speed changes here are in main since b58d198 (jsthope, "GPU: copy into title memory without asking for its region first", 24 Nov).

  • That commit removes the VirtualQuery before a list's copy into title memory, and stops the copy-back from going through WriteProcessMemory, for the reason this PR gives: the region query costs about 2 ms a call in the title's big pools. write_mapped's comment on main (host.rs:2057) says the same.
  • This PR is on ffe310e, so its 1.5 s to 0.13 s was measured against the code before that commit, and it conflicts with main in the same functions.

What is only here is the diagnostics part, VICTORY_PROFILE=<ms> sampling of thread stacks. That looks worth keeping as a small PR of its own.

So my suggestion: measure the copy-back once on 940d32f with and without NtWriteVirtualMemory. If nothing is left of the gain, close this and send the profiler separately; if something is, a rebase with that number makes the case.

Nothing was run for this comment; I read the diff and main.

AI-assisted (Claude Code).

**@⁠r4tedx** on GitHub · 2026-11-25 07:42 UTC · [original](https://github.com/Marvisak/VIctory/pull/1215#issuecomment-7156165845) A note for the triage, from reading this PR against `main` `940d32f`: the two speed changes here are in `main` since `b58d198` (jsthope, "GPU: copy into title memory without asking for its region first", 24 Nov). - That commit removes the `VirtualQuery` before a list's copy into title memory, and stops the copy-back from going through `WriteProcessMemory`, for the reason this PR gives: the region query costs about 2 ms a call in the title's big pools. `write_mapped`'s comment on `main` (`host.rs:2057`) says the same. - This PR is on `ffe310e`, so its 1.5 s to 0.13 s was measured against the code before that commit, and it conflicts with `main` in the same functions. What is only here is the diagnostics part, `VICTORY_PROFILE=<ms>` sampling of thread stacks. That looks worth keeping as a small PR of its own. So my suggestion: measure the copy-back once on `940d32f` with and without `NtWriteVirtualMemory`. If nothing is left of the gain, close this and send the profiler separately; if something is, a rebase with that number makes the case. Nothing was run for this comment; I read the diff and `main`. AI-assisted (Claude Code).
This pull request has changes conflicting with the target branch.
  • crates/victory-gpu/Cargo.toml
  • crates/victory-gpu/src/host.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/1215/head:github-bot/gh-1215'
git switch 'github-bot/gh-1215'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1215'
git switch 'github-bot/gh-1215'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1215'
git switch 'github-bot/gh-1215'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1215'
git switch 'main'
git merge --squash 'github-bot/gh-1215'
git switch 'main'
git merge --ff-only 'github-bot/gh-1215'
git switch 'main'
git merge 'github-bot/gh-1215'
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!1215
No description provided.