GPU: marked pages go back to title memory on several threads (#2826) #2914

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

@⁠kotekompotek on GitHub · 2026-11-25 23:51 UTC · original
kotekompotek:gpu/marked-pages-threads → main · +91 −4 · 1 files · 1 commits · open

Summary

Ports Machad3x/VIctory-nvidia-3080ti@7229f41 to main, per the #2826 triage invite ("PRs are open to everyone, so please open one with the commit and its test"). Authorship retained; that fork's doc page is left out.

  • copy_back_marks' final loop runs through for_each_by_page: pages sorted and grouped by page index (copies covering one title page keep their order on one thread — the copy_back_marked write/protection sequence stays single-writer per page), groups spread over up to six scoped threads including the submitting one.
  • Fewer than sixteen pages stay serial — no thread cost on small submissions.
  • All shared state touched from workers is already synchronized: Tracked's changed/saved sets and arm bits (Mutex/atomics), watch::writing's guards Mutex, copystat counters (AtomicU64); read_into/write_mapped touch disjoint title ranges per group.

The reporter's measurement (Ryzen 7 5700X, RTX 3080 Ti, medians, on a PR stack — #2120/#2130/#2280 — not main alone): marked pages 166→111 ms, copy-back 184→124 ms, frame 777→690 ms.

Test plan

  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings clean
  • New shadow::tests::many_marked_pages_all_go_back (96 marked pages over two overlapping copies) passes on GTX 1050
  • A measurement on main alone (vs the PR stack) is still open — flagged in the issue

Generated with Devin

**@⁠kotekompotek** on GitHub · 2026-11-25 23:51 UTC · [original](https://github.com/Marvisak/VIctory/pull/2914) `kotekompotek:gpu/marked-pages-threads` → `main` · +91 −4 · 1 files · 1 commits · open ## Summary Ports [Machad3x/VIctory-nvidia-3080ti@`7229f41`](https://github.com/Machad3x/VIctory-nvidia-3080ti/commit/7229f41) to main, per the #2826 triage invite ("PRs are open to everyone, so please open one with the commit and its test"). Authorship retained; that fork's doc page is left out. - `copy_back_marks`' final loop runs through `for_each_by_page`: pages sorted and grouped by page index (copies covering one title page keep their order on one thread — the `copy_back_marked` write/protection sequence stays single-writer per page), groups spread over up to six scoped threads including the submitting one. - Fewer than sixteen pages stay serial — no thread cost on small submissions. - All shared state touched from workers is already synchronized: `Tracked`'s changed/saved sets and arm bits (`Mutex`/atomics), `watch::writing`'s guards `Mutex`, `copystat` counters (`AtomicU64`); `read_into`/`write_mapped` touch disjoint title ranges per group. The reporter's measurement (Ryzen 7 5700X, RTX 3080 Ti, medians, on a PR stack — #2120/#2130/#2280 — not main alone): marked pages 166→111 ms, copy-back 184→124 ms, frame 777→690 ms. #### Test plan - [x] `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings` clean - [x] New `shadow::tests::many_marked_pages_all_go_back` (96 marked pages over two overlapping copies) passes on GTX 1050 - [ ] A measurement on `main` alone (vs the PR stack) is still open — flagged in the issue Generated with [Devin](https://devin.ai)
The copy-back of marked pages compared and wrote about 2,000 pages of
64 KiB a frame on the submitting thread, 55 to 80 us a page. Pages are
now grouped by page index, so two buffers that cover the same page stay
on one thread in their old order, and the groups are taken by up to six
scoped threads, the submitting one among them. Fewer than sixteen pages
stay on that thread.

One run each at the same scene (medians, on a stack including #2120,
#2130 and #2280): marked pages 166 to 111 ms, copy-back 184 to 124 ms,
frame 777 to 690 ms; same dropped draws and untranslated programs, no
device removal.

Ported to main from Machad3x/VIctory-nvidia-3080ti@7229f41 (#2826),
minus that fork's doc page.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 05:17:23 +00:00
Author
Owner

@⁠Marvisak on GitHub · 2026-11-26 02:22 UTC · original

Automated triage for the maintainers.

Merge candidate (a recommendation to look, not an approval). In shadow.rs copy_back_marks, marked pages now go back on up to 6 scoped threads (for_each_by_page) once there are 16 or more. Pages are sorted and grouped so that every copy of one page stays on one thread, in order, and the withheld check is kept. With fewer pages it stays serial. The scope joins before the function returns, so copy-back still finishes before the submission completes. The new test covers two overlapping copies of one memory. CI check passes. Note that #2918 also rewrites this copy-back path (it writes only the bytes that changed), so whichever lands second will need a rebase.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-26 02:22 UTC · [original](https://github.com/Marvisak/VIctory/pull/2914#issuecomment-7180742118) <!-- victory-triage v1 head=1c96dc2d32ddeb7ef644b4f6c98996d1cc754c3d verdict=merge-candidate at=2026-11-26T02:22:14Z --> Automated triage for the maintainers. **Merge candidate** (a recommendation to look, not an approval). In `shadow.rs` `copy_back_marks`, marked pages now go back on up to 6 scoped threads (`for_each_by_page`) once there are 16 or more. Pages are sorted and grouped so that every copy of one page stays on one thread, in order, and the `withheld` check is kept. With fewer pages it stays serial. The scope joins before the function returns, so copy-back still finishes before the submission completes. The new test covers two overlapping copies of one memory. CI `check` passes. Note that #2918 also rewrites this copy-back path (it writes only the bytes that changed), so whichever lands second will need a rebase. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠MeMako on GitHub · 2026-11-26 05:56 UTC · original

Independent AMD RDNA 4 / Ryzen 9 7950X verification of #2914 (1c96dc2):

Setup: Windows 11 (10.0.26200), Ryzen 9 7950X (16C/32T), AMD Radeon RX 9070 XT (driver 32.0.32029.2010), local integration branch on origin/main 63bcca4 with #2051 + #2472 + #2918 + #1010 + #2130 (flags off) + #3055 (copy_back_marks runs #2914's for_each_by_page over #2918's exact-byte copy_back_marked, where SCRATCH is thread_local!).

Checks:

  • cargo clippy -p victory-gpu -p victory --all-targets --locked -- -D warnings: clean.
  • cargo test -p victory-gpu --locked: 266 passed, 0 failed (including new shadow::tests::many_marked_pages_all_go_back).

Live title run (prison cell steady state, release build):

Run World / Heavy samples marks heavy med (avg) Pages / Bytes (heavy med) Wall µs/page (heavy / all world) Heavy frame med (avg) Crashes
Pre-#2914 (1 thread) 83 / 60 79.1 ms (79.3) 2,548 pg / 30.9 MB 31.5 / 33.9 µs 465.0 ms (558.6) 0
With #2914 (up to 6 threads) 51 / 38 67.0 ms (71.1) 2,824 pg / 40.8 MB 26.6 / 27.4 µs 448.0 ms (487.8) 0

Notes:

  • Cleanly reduces marked copy-back wall time by 15–19% per page (-12.1 ms heavy median despite +11% more pages and +32% more written bytes) with 0 crashes across the run.
  • Because this stack already includes #1010 (user-mode read_into) and #2918 (SSE2 diff + plain-store store_runs), scaling past ~15–20% is now mostly bounded by per-page watch guard-lock + VirtualProtect kernel serialization; on main without #1010 (where per-page ReadProcessMemory / WriteProcessMemory cost is higher), the relative speedup should be even larger.

Hardware runs were performed by me on my 7950X / RX 9070 XT; comment drafted with Antigravity.

**@⁠MeMako** on GitHub · 2026-11-26 05:56 UTC · [original](https://github.com/Marvisak/VIctory/pull/2914#issuecomment-7183950164) Independent AMD RDNA 4 / Ryzen 9 7950X verification of `#2914` (`1c96dc2`): **Setup:** Windows 11 (`10.0.26200`), Ryzen 9 7950X (16C/32T), AMD Radeon RX 9070 XT (driver `32.0.32029.2010`), local integration branch on `origin/main` `63bcca4` with `#2051` + `#2472` + `#2918` + `#1010` + `#2130` (flags off) + `#3055` (`copy_back_marks` runs `#2914`'s `for_each_by_page` over `#2918`'s exact-byte `copy_back_marked`, where `SCRATCH` is `thread_local!`). **Checks:** - `cargo clippy -p victory-gpu -p victory --all-targets --locked -- -D warnings`: clean. - `cargo test -p victory-gpu --locked`: **266 passed, 0 failed** (including new `shadow::tests::many_marked_pages_all_go_back`). **Live title run (prison cell steady state, release build):** | Run | World / Heavy samples | `marks` heavy med (`avg`) | Pages / Bytes (heavy med) | Wall `µs/page` (heavy / all world) | Heavy frame med (`avg`) | Crashes | |---|---:|---:|---:|---:|---:|---:| | Pre-`#2914` (1 thread) | 83 / 60 | 79.1 ms (`79.3`) | 2,548 pg / 30.9 MB | 31.5 / 33.9 µs | 465.0 ms (`558.6`) | 0 | | With `#2914` (up to 6 threads) | 51 / 38 | **67.0 ms** (`71.1`) | 2,824 pg / 40.8 MB | **26.6 / 27.4 µs** | **448.0 ms** (`487.8`) | **0** | **Notes:** - Cleanly reduces marked copy-back wall time by **15–19% per page** (`-12.1 ms` heavy median despite +11% more pages and +32% more written bytes) with **0 crashes** across the run. - Because this stack already includes `#1010` (user-mode `read_into`) and `#2918` (SSE2 diff + plain-store `store_runs`), scaling past ~15–20% is now mostly bounded by per-page `watch` guard-lock + `VirtualProtect` kernel serialization; on `main` without `#1010` (where per-page `ReadProcessMemory` / `WriteProcessMemory` cost is higher), the relative speedup should be even larger. *Hardware runs were performed by me on my 7950X / RX 9070 XT; comment drafted with Antigravity.*
Author
Owner

@⁠moe-miau on GitHub · 2026-11-26 06:17 UTC · original

A measurement for this one on an NVIDIA stack (RTX 4070 SUPER, Windows 11; main + #2464 + #2098 + #2626 + #2628 + #2711 + #2851 + #2705 + #2925 + #2958, prologue cell). Medians of the 5 s reports over the last 6 minutes of a 15-minute run:

ms/frame copying back marked pages
stack 291.6 60.6 ms 45.4 ms (2,222 pages)
stack + #2914 299.8 62.6 ms 45.2 ms (2,272 pages)

On this machine the threads did not shorten the loop. Each page takes the guard lock three times (writing, its drop, Tracked::taken) and makes protection calls under it, so that part stays serial. #3069 removes the protection calls and the kernel write for physical-page memory (31 ms in the same scene), and the two should combine. Pictures were as before. AI-assisted (Claude Code). Runs done on my machine.

**@⁠moe-miau** on GitHub · 2026-11-26 06:17 UTC · [original](https://github.com/Marvisak/VIctory/pull/2914#issuecomment-7184288549) A measurement for this one on an NVIDIA stack (RTX 4070 SUPER, Windows 11; main + #2464 + #2098 + #2626 + #2628 + #2711 + #2851 + #2705 + #2925 + #2958, prologue cell). Medians of the 5 s reports over the last 6 minutes of a 15-minute run: | | ms/frame | copying back | marked pages | |---|---|---|---| | stack | 291.6 | 60.6 ms | 45.4 ms (2,222 pages) | | stack + #2914 | 299.8 | 62.6 ms | 45.2 ms (2,272 pages) | On this machine the threads did not shorten the loop. Each page takes the guard lock three times (`writing`, its drop, `Tracked::taken`) and makes protection calls under it, so that part stays serial. #3069 removes the protection calls and the kernel write for physical-page memory (31 ms in the same scene), and the two should combine. Pictures were as before. AI-assisted (Claude Code). Runs done on my machine.
Author
Owner

@⁠TheGrayOrange on GitHub · 2026-11-26 07:22 UTC · original

Tested 1c96dc2 on an i7-14700KF using the actual Shadow::copy_back_marked CPU path. For 2,048 marked 64 KiB pages, median execution time decreased from 46.013 ms serial to 36.619 ms with the PR's worker cap. This excludes GPU submission and bitmap collection.

However, I reproduced an ordering issue with two virtual mappings of the same physical page. With the original mark order high-address then low-address:

  • Original mark order leaves byte 0x11.
  • The PR's virtual-address sorting leaves byte 0x22.

This occurs with only two jobs, before parallel execution. Grouping by virtual address also appears insufficient to establish independence between workers when physical backing is shared.
Suggest preserving original mark order for serial batches and conservatively falling back to that path when physical backing independence cannot be established.

The temporary CPU-only reproduction is available if useful. Testing and analysis were performed with Codex assistance.

**@⁠TheGrayOrange** on GitHub · 2026-11-26 07:22 UTC · [original](https://github.com/Marvisak/VIctory/pull/2914#issuecomment-7185391275) Tested `1c96dc2` on an i7-14700KF using the actual `Shadow::copy_back_marked` CPU path. For 2,048 marked 64 KiB pages, median execution time decreased from 46.013 ms serial to 36.619 ms with the PR's worker cap. This excludes GPU submission and bitmap collection. However, I reproduced an ordering issue with two virtual mappings of the same physical page. With the original mark order high-address then low-address: - Original mark order leaves byte `0x11`. - The PR's virtual-address sorting leaves byte `0x22`. This occurs with only two jobs, before parallel execution. Grouping by virtual address also appears insufficient to establish independence between workers when physical backing is shared. Suggest preserving original mark order for serial batches and conservatively falling back to that path when physical backing independence cannot be established. The temporary CPU-only reproduction is available if useful. Testing and analysis were performed with Codex assistance.
Author
Owner

@⁠fuzeofficlal on GitHub · 2026-11-25 23:59 UTC · original · reviewed

Verified head 1c96dc2d cleanly on origin/main (63bcca43) on Windows 11 x64 (NVIDIA GeForce RTX 5090 + D3D12 WARP + VICTORY_D3D12_DEBUG=1).

Concurrency & Lock-Order Audit

  • Same-page multi-Shadow serialization: for_each_by_page (crates/victory-gpu/src/shadow.rs:901-925) sorts by virtual page and groups via chunk_by(|a, b| a.1 == b.1), ensuring multiple Shadow buffers overlapping the same 64 KiB title page run sequentially on one worker without data races.
  • Lock ordering & panic safety: Lock acquisition stays acyclic (GUARDS -> Changed.0 -> Changed.1), host-copy slices [from - start .. to - start] are disjoint per page, and std::thread::scope propagates worker panics cleanly without deadlock.
  • Minor observations (non-blocking):
    • watch::writing, Writing::drop, and t.taken still serialize VirtualProtect under GUARDS, so the parallel gain comes from host != title, read_into, merge_writeback, and memory copy work.
    • Theoretical edge case: if two distinct virtual pages alias the same physical page (alias_of) and are both marked dirty via separate buffer Shadows simultaneously, grouping by virtual page could process them on different threads (though alias_of is primarily used for tiled texture heaps).

Local Verification (--features diagnostics, VICTORY_D3D12_DEBUG=1)

  • RTX 5090: shadow:: + draw::tests 31/31 (including many_marked_pages_all_go_back), watch::tests 15/15.
  • WARP: shadow:: + draw::tests 31/31.
  • cargo clippy --locked -p victory-gpu --all-targets -- -D warnings (default and --features diagnostics) & cargo xtask policy (191 files ok): clean.

Looks clean and ready to merge.

**@⁠fuzeofficlal** on GitHub · 2026-11-25 23:59 UTC · [original](https://github.com/Marvisak/VIctory/pull/2914#pullrequestreview-6066691652) · **reviewed** Verified head `1c96dc2d` cleanly on `origin/main` (`63bcca43`) on Windows 11 x64 (NVIDIA GeForce RTX 5090 + D3D12 WARP + `VICTORY_D3D12_DEBUG=1`). ### Concurrency & Lock-Order Audit - **Same-page multi-Shadow serialization**: `for_each_by_page` (`crates/victory-gpu/src/shadow.rs:901-925`) sorts by virtual page and groups via `chunk_by(|a, b| a.1 == b.1)`, ensuring multiple `Shadow` buffers overlapping the same 64 KiB title page run sequentially on one worker without data races. - **Lock ordering & panic safety**: Lock acquisition stays acyclic (`GUARDS` -> `Changed.0` -> `Changed.1`), host-copy slices `[from - start .. to - start]` are disjoint per page, and `std::thread::scope` propagates worker panics cleanly without deadlock. - **Minor observations (non-blocking)**: - `watch::writing`, `Writing::drop`, and `t.taken` still serialize `VirtualProtect` under `GUARDS`, so the parallel gain comes from `host != title`, `read_into`, `merge_writeback`, and memory copy work. - Theoretical edge case: if two *distinct* virtual pages alias the same physical page (`alias_of`) and are both marked dirty via separate buffer `Shadow`s simultaneously, grouping by virtual page could process them on different threads (though `alias_of` is primarily used for tiled texture heaps). ### Local Verification (`--features diagnostics`, `VICTORY_D3D12_DEBUG=1`) - **RTX 5090**: `shadow::` + `draw::tests` **31/31** (including `many_marked_pages_all_go_back`), `watch::tests` **15/15**. - **WARP**: `shadow::` + `draw::tests` **31/31**. - `cargo clippy --locked -p victory-gpu --all-targets -- -D warnings` (default and `--features diagnostics`) & `cargo xtask policy` (`191 files ok`): clean. Looks clean and ready to merge.
Author
Owner

@⁠Dukestar69 on GitHub · 2026-11-26 02:26 UTC · original · approved these changes

Tested merged onto origin/main (63bcca4) on Windows 11 x64 (NVIDIA GeForce RTX 5090):

  • cargo test -p victory-gpu --lib shadow::tests: 10 passed, 0 failed (including new many_marked_pages_all_go_back).
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Parallelizing marked-page copy-back by page via for_each_by_page is clean and verified on hardware.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

**@⁠Dukestar69** on GitHub · 2026-11-26 02:26 UTC · [original](https://github.com/Marvisak/VIctory/pull/2914#pullrequestreview-6067747530) · **approved these changes** Tested merged onto `origin/main` (`63bcca4`) on Windows 11 x64 (NVIDIA GeForce RTX 5090): - `cargo test -p victory-gpu --lib shadow::tests`: **10 passed, 0 failed** (including new `many_marked_pages_all_go_back`). - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 191 files ok. Parallelizing marked-page copy-back by page via `for_each_by_page` is clean and verified on hardware. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Author
Owner

@⁠imjustprism on GitHub · 2026-11-26 15:48 UTC · original · requested changes

tested 1c96dc2 in the title and read it against watch.rs. the gain is real on main, and there is one case where it loses shader writes, so i am asking for a change before this goes in.

the measurement on main alone that the description lists as open, rx 9070 xt, world, two runs each way:

marked pages going back main this pr
microseconds per page, run 1 18.7 14.5
microseconds per page, run 2 18.4 15.1
ms per frame, run 1 / run 2 27.8 / 33.4 22.2 / 23.7
marked pages per frame, run 1 / run 2 1,483 / 1,814 1,534 / 1,569

63bcca4 plus #2122 (this card needs it) with a timer around copy_back_marks, with and without this pr merged in. diag build, series-x, the same scripted key presses, warm shader and pipeline caches, quiet machine, 12-minute runs, medians over 47 to 74 world frame lines. no errors, no device removed in any run. about 20% less per page, the same in both runs. the frame as a whole did not move outside run-to-run spread. the code comment's 55 to 80 microseconds per page and 2,000 pages a frame are 18.5 and 1,500 to 1,800 here.

what needs changing: two mappings of one physical page.

for_each_by_page groups by page address, so the two addresses of one physical page (watch::title_memory_aliased, linked from XMemMapPhysicalPages) are two groups and go back on two threads at once. in the serial loop the first copy's watch::writing saves the alias page for the second copy before its own write lands (changed -> mark_changed(.., true) -> Changed::save), and the second copy merges onto it, so both copies' bytes reach title memory. on threads the second copy can already have run unarm, saved (none) and changed (false) at shadow.rs:501-507; then the first copy's writing saves nothing for it, and the second writes its whole host page over the first one's bytes at shadow.rs:518-525, or drops its own. so the description's "read_into/write_mapped touch disjoint title ranges per group" does not hold for aliased pages.

a test that shows it (below): one section mapped at two addresses 32 times over, a copy of each mapping, both armed and marked, a byte written through each, 200 rounds.

result
main (63bcca4 plus #2122) passes, 3 runs of 200 rounds
this pr fails, 200 of 200 rounds lose a byte
this pr with 7 pairs (14 pages, under the threshold of 16) passes

this is the threaded side of what @⁠TheGrayOrange reported for the sorted order. i have not seen the title mark both mappings of a page in one submission, and it does map physical pages itself, so i cannot rule it out. keeping every mapping of a physical page in one group (the links are in Guards::alias_of), or sending pages that have an alias back on the submitting thread, would settle it; the test then passes.

smaller things in the same code:

  • shadow.rs:135-136 and shadow.rs:509: both // SAFETY: lines say the copy's data is written only on the submitting thread. the workers write it now. it is still sound (one thread per page of a copy, and the scope joins before anything reads), but the comments should say that.
  • shadow.rs:921: scope.spawn panics when the thread cannot start, and this runs under ExecuteCommandLists, so that would abort the process. Builder::spawn_scoped with the work left to the caller on error avoids it. texture::in_parallel has the same pattern.
  • every call with 16 or more pages starts up to five new threads and ends them. in my runs a submission marks about 70 to 80 pages on average, at about 20 submissions a frame, so that can be around a hundred thread starts a frame (not counted, an estimate from those averages). each start and end goes through the loader's thread hook (victory-loader/src/threads.rs:240), which runs the title's own thread-attach and thread-exit code. workers that stay alive, as #2051's copy_pool has, would avoid that; it may also be why the per-page gain stops at 20%.
  • shadow.rs:903: the thread count comes from the (copy, page) pairs, the work is handed out by page group. 48 pairs on two pages start five threads and four find nothing.
  • many_marked_pages_all_go_back marks every page through one copy only, so the per-page order the grouping exists for is not exercised: the test passes on main too, and would pass without the grouping.
the test (goes into the tests module of shadow.rs)
    /// One page of memory mapped at two addresses, a copy of each mapping,
    /// both marked in one submission: the bytes the shaders wrote through
    /// both copies reach title memory, whichever order or thread their
    /// copy-backs run on.
    #[test]
    fn marked_pages_of_aliased_mappings_both_go_back() {
        use windows_sys::Win32::Foundation::CloseHandle;
        use windows_sys::Win32::System::Memory::{
            CreateFileMappingW, FILE_MAP_WRITE, MEM_RELEASE, MEM_RESERVE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFileEx,
            PAGE_READWRITE, UnmapViewOfFile, VirtualAlloc, VirtualFree,
        };
        // 64 marked (copy, page) pairs: enough for `for_each_by_page`'s
        // threads (6 of them).
        const PAIRS: usize = 32;
        const ROUNDS: usize = 200;
        // SAFETY: a pagefile section of `PAIRS` pages; its views keep it.
        let section = unsafe {
            CreateFileMappingW(
                -1isize as _,
                std::ptr::null(),
                PAGE_READWRITE,
                0,
                (PAIRS * PAGE) as u32,
                std::ptr::null(),
            )
        };
        assert!(!section.is_null());
        // Page k of the section shown at pages 2k and 2k + 1 of a free
        // range: sorted by address, the two mappings of a page are next to
        // each other, so their copy-backs are handed out one after the other
        // and run at once on two threads. Other tests allocate meanwhile: a
        // range taken under our feet is tried again.
        let base = (0..8)
            .find_map(|_| {
                // SAFETY: a fresh reservation, released at once; then views
                // where it was, unmapped unless all land there.
                unsafe {
                    let base = VirtualAlloc(std::ptr::null(), 2 * PAIRS * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize;
                    if base == 0 {
                        return None;
                    }
                    VirtualFree(base as *mut _, 0, MEM_RELEASE);
                    let views: Vec<usize> = (0..2 * PAIRS)
                        .map(|n| {
                            let offset = (n / 2 * PAGE) as u32;
                            MapViewOfFileEx(section, FILE_MAP_WRITE, 0, offset, PAGE, (base + n * PAGE) as *const _).Value
                                as usize
                        })
                        .collect();
                    if views.iter().enumerate().all(|(n, &view)| view == base + n * PAGE) {
                        return Some(base);
                    }
                    for view in views.into_iter().filter(|&view| view != 0) {
                        UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ });
                    }
                    None
                }
            })
            .expect("a free range for the views");
        // SAFETY: our section's handle; the views keep the section.
        unsafe { CloseHandle(section) };
        // Pair k: copy X at `a`, copy Y at `b` (the same memory), and the
        // offsets in the page the shaders write through each.
        let pairs: Vec<(usize, usize, usize, usize)> = (0..PAIRS)
            .map(|k| (base + 2 * k * PAGE, base + (2 * k + 1) * PAGE, 10 + 32 * k, 20 + 32 * k))
            .collect();
        for &(a, b, ..) in &pairs {
            crate::watch::title_memory_aliased(b, &[a]);
            register(a, a as u64, PAGE as u64);
            register(b, b as u64, PAGE as u64);
        }
        let unregister_all = || {
            for &(a, b, ..) in &pairs {
                unregister(a, a as u64);
                unregister(b, b as u64);
            }
        };
        let copies: Option<Vec<_>> = pairs
            .iter()
            .map(|&(a, b, ..)| Some((find(a as u64, PAGE as u64)?, find(b as u64, PAGE as u64)?)))
            .collect();
        let (Some(copies), Some(map)) = (copies, bitmap(false)) else {
            unregister_all();
            return; // no host GPU here
        };
        let words = map.data as *mut u32;
        let mark = |copy: &Arc<Shadow>| {
            let n = copy.marks.expect("tracked memory gets mark bits") as usize;
            // SAFETY: a dword of the mapped bitmap.
            unsafe { *words.add(n / 32) |= 1 << (n % 32) };
        };
        // SAFETY: a byte of our views (a guarded page faults into the
        // handler, which opens it).
        let write = |at: usize, value: u8| unsafe { (at as *mut u8).write_volatile(value) };
        // SAFETY: a byte of our views.
        let read = |at: usize| unsafe { (at as *const u8).read_volatile() };
        let mut lost = 0;
        for _ in 0..ROUNDS {
            for (&(a, b, x, y), (copy_x, copy_y)) in pairs.iter().zip(&copies) {
                // Title memory and both copies start from zeros, taken and
                // guarded; then both copies are armed, and the shaders write
                // a byte through each.
                write(a + x, 0);
                write(a + y, 0);
                copy_x.update(a, PAGE);
                copy_y.update(b, PAGE);
                copy_x.writing(a, PAGE, true);
                copy_y.writing(b, PAGE, true);
                copy_x.write_host((a + x) as u64, &[0xaa]);
                copy_y.write_host((b + y) as u64, &[0xbb]);
                mark(copy_x);
                mark(copy_y);
            }
            copy_back_marks(&[], false);
            if pairs.iter().any(|&(a, _, x, y)| [read(a + x), read(a + y)] != [0xaa, 0xbb]) {
                lost += 1;
            }
            // The submission's ranges are done: the copies are disarmed.
            for (&(a, b, ..), (copy_x, copy_y)) in pairs.iter().zip(&copies) {
                copy_x.copy_back(a, PAGE);
                copy_y.copy_back(b, PAGE);
            }
        }
        unregister_all();
        assert_eq!(lost, 0, "{lost} of {ROUNDS} rounds lost a copy's byte");
        // The views stay mapped (as the other tests' pools): a copy some page
        // table still holds must not name memory reused meanwhile.
    }
**@⁠imjustprism** on GitHub · 2026-11-26 15:48 UTC · [original](https://github.com/Marvisak/VIctory/pull/2914#pullrequestreview-6077021933) · **requested changes** tested 1c96dc2 in the title and read it against `watch.rs`. the gain is real on main, and there is one case where it loses shader writes, so i am asking for a change before this goes in. the measurement on main alone that the description lists as open, rx 9070 xt, world, two runs each way: | marked pages going back | main | this pr | |---|---|---| | microseconds per page, run 1 | 18.7 | 14.5 | | microseconds per page, run 2 | 18.4 | 15.1 | | ms per frame, run 1 / run 2 | 27.8 / 33.4 | 22.2 / 23.7 | | marked pages per frame, run 1 / run 2 | 1,483 / 1,814 | 1,534 / 1,569 | 63bcca4 plus #2122 (this card needs it) with a timer around `copy_back_marks`, with and without this pr merged in. diag build, series-x, the same scripted key presses, warm shader and pipeline caches, quiet machine, 12-minute runs, medians over 47 to 74 world frame lines. no errors, no device removed in any run. about 20% less per page, the same in both runs. the frame as a whole did not move outside run-to-run spread. the code comment's 55 to 80 microseconds per page and 2,000 pages a frame are 18.5 and 1,500 to 1,800 here. what needs changing: two mappings of one physical page. `for_each_by_page` groups by page address, so the two addresses of one physical page (`watch::title_memory_aliased`, linked from `XMemMapPhysicalPages`) are two groups and go back on two threads at once. in the serial loop the first copy's `watch::writing` saves the alias page for the second copy before its own write lands (`changed` -> `mark_changed(.., true)` -> `Changed::save`), and the second copy merges onto it, so both copies' bytes reach title memory. on threads the second copy can already have run `unarm`, `saved` (none) and `changed` (false) at `shadow.rs:501-507`; then the first copy's `writing` saves nothing for it, and the second writes its whole host page over the first one's bytes at `shadow.rs:518-525`, or drops its own. so the description's "read_into/write_mapped touch disjoint title ranges per group" does not hold for aliased pages. a test that shows it (below): one section mapped at two addresses 32 times over, a copy of each mapping, both armed and marked, a byte written through each, 200 rounds. | | result | |---|---| | main (63bcca4 plus #2122) | passes, 3 runs of 200 rounds | | this pr | fails, 200 of 200 rounds lose a byte | | this pr with 7 pairs (14 pages, under the threshold of 16) | passes | this is the threaded side of what @⁠TheGrayOrange reported for the sorted order. i have not seen the title mark both mappings of a page in one submission, and it does map physical pages itself, so i cannot rule it out. keeping every mapping of a physical page in one group (the links are in `Guards::alias_of`), or sending pages that have an alias back on the submitting thread, would settle it; the test then passes. smaller things in the same code: - `shadow.rs:135-136` and `shadow.rs:509`: both `// SAFETY:` lines say the copy's data is written only on the submitting thread. the workers write it now. it is still sound (one thread per page of a copy, and the scope joins before anything reads), but the comments should say that. - `shadow.rs:921`: `scope.spawn` panics when the thread cannot start, and this runs under `ExecuteCommandLists`, so that would abort the process. `Builder::spawn_scoped` with the work left to the caller on error avoids it. `texture::in_parallel` has the same pattern. - every call with 16 or more pages starts up to five new threads and ends them. in my runs a submission marks about 70 to 80 pages on average, at about 20 submissions a frame, so that can be around a hundred thread starts a frame (not counted, an estimate from those averages). each start and end goes through the loader's thread hook (`victory-loader/src/threads.rs:240`), which runs the title's own thread-attach and thread-exit code. workers that stay alive, as #2051's `copy_pool` has, would avoid that; it may also be why the per-page gain stops at 20%. - `shadow.rs:903`: the thread count comes from the (copy, page) pairs, the work is handed out by page group. 48 pairs on two pages start five threads and four find nothing. - `many_marked_pages_all_go_back` marks every page through one copy only, so the per-page order the grouping exists for is not exercised: the test passes on main too, and would pass without the grouping. <details> <summary>the test (goes into the tests module of shadow.rs)</summary> ```rust /// One page of memory mapped at two addresses, a copy of each mapping, /// both marked in one submission: the bytes the shaders wrote through /// both copies reach title memory, whichever order or thread their /// copy-backs run on. #[test] fn marked_pages_of_aliased_mappings_both_go_back() { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Memory::{ CreateFileMappingW, FILE_MAP_WRITE, MEM_RELEASE, MEM_RESERVE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFileEx, PAGE_READWRITE, UnmapViewOfFile, VirtualAlloc, VirtualFree, }; // 64 marked (copy, page) pairs: enough for `for_each_by_page`'s // threads (6 of them). const PAIRS: usize = 32; const ROUNDS: usize = 200; // SAFETY: a pagefile section of `PAIRS` pages; its views keep it. let section = unsafe { CreateFileMappingW( -1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (PAIRS * PAGE) as u32, std::ptr::null(), ) }; assert!(!section.is_null()); // Page k of the section shown at pages 2k and 2k + 1 of a free // range: sorted by address, the two mappings of a page are next to // each other, so their copy-backs are handed out one after the other // and run at once on two threads. Other tests allocate meanwhile: a // range taken under our feet is tried again. let base = (0..8) .find_map(|_| { // SAFETY: a fresh reservation, released at once; then views // where it was, unmapped unless all land there. unsafe { let base = VirtualAlloc(std::ptr::null(), 2 * PAIRS * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; if base == 0 { return None; } VirtualFree(base as *mut _, 0, MEM_RELEASE); let views: Vec<usize> = (0..2 * PAIRS) .map(|n| { let offset = (n / 2 * PAGE) as u32; MapViewOfFileEx(section, FILE_MAP_WRITE, 0, offset, PAGE, (base + n * PAGE) as *const _).Value as usize }) .collect(); if views.iter().enumerate().all(|(n, &view)| view == base + n * PAGE) { return Some(base); } for view in views.into_iter().filter(|&view| view != 0) { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }); } None } }) .expect("a free range for the views"); // SAFETY: our section's handle; the views keep the section. unsafe { CloseHandle(section) }; // Pair k: copy X at `a`, copy Y at `b` (the same memory), and the // offsets in the page the shaders write through each. let pairs: Vec<(usize, usize, usize, usize)> = (0..PAIRS) .map(|k| (base + 2 * k * PAGE, base + (2 * k + 1) * PAGE, 10 + 32 * k, 20 + 32 * k)) .collect(); for &(a, b, ..) in &pairs { crate::watch::title_memory_aliased(b, &[a]); register(a, a as u64, PAGE as u64); register(b, b as u64, PAGE as u64); } let unregister_all = || { for &(a, b, ..) in &pairs { unregister(a, a as u64); unregister(b, b as u64); } }; let copies: Option<Vec<_>> = pairs .iter() .map(|&(a, b, ..)| Some((find(a as u64, PAGE as u64)?, find(b as u64, PAGE as u64)?))) .collect(); let (Some(copies), Some(map)) = (copies, bitmap(false)) else { unregister_all(); return; // no host GPU here }; let words = map.data as *mut u32; let mark = |copy: &Arc<Shadow>| { let n = copy.marks.expect("tracked memory gets mark bits") as usize; // SAFETY: a dword of the mapped bitmap. unsafe { *words.add(n / 32) |= 1 << (n % 32) }; }; // SAFETY: a byte of our views (a guarded page faults into the // handler, which opens it). let write = |at: usize, value: u8| unsafe { (at as *mut u8).write_volatile(value) }; // SAFETY: a byte of our views. let read = |at: usize| unsafe { (at as *const u8).read_volatile() }; let mut lost = 0; for _ in 0..ROUNDS { for (&(a, b, x, y), (copy_x, copy_y)) in pairs.iter().zip(&copies) { // Title memory and both copies start from zeros, taken and // guarded; then both copies are armed, and the shaders write // a byte through each. write(a + x, 0); write(a + y, 0); copy_x.update(a, PAGE); copy_y.update(b, PAGE); copy_x.writing(a, PAGE, true); copy_y.writing(b, PAGE, true); copy_x.write_host((a + x) as u64, &[0xaa]); copy_y.write_host((b + y) as u64, &[0xbb]); mark(copy_x); mark(copy_y); } copy_back_marks(&[], false); if pairs.iter().any(|&(a, _, x, y)| [read(a + x), read(a + y)] != [0xaa, 0xbb]) { lost += 1; } // The submission's ranges are done: the copies are disarmed. for (&(a, b, ..), (copy_x, copy_y)) in pairs.iter().zip(&copies) { copy_x.copy_back(a, PAGE); copy_y.copy_back(b, PAGE); } } unregister_all(); assert_eq!(lost, 0, "{lost} of {ROUNDS} rounds lost a copy's byte"); // The views stay mapped (as the other tests' pools): a copy some page // table still holds must not name memory reused meanwhile. } ``` </details>
This pull request can be merged automatically.
You are not authorized to merge this pull request.
View command line instructions

Checkout

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

Merge

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