perf(gpu,hle): optimize view-memory guards, xmem alias mapping, texture waits, and relay card copy-back #824

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

@⁠powplusplus on GitHub · 2026-11-25 09:19 UTC · original
powplusplus:perf/fast-watch-guards → main · +1282 −312 · 6 files · 1 commits · open

Summary

Cuts CPU-side frame preparation, lock contention, and copy-back overhead in the 3D world from 0.1-0.2 fps (4,244-6,146 ms/frame, GPU 5-18% busy) to 1.9-2.0 fps (498.7-536.7 ms/frame, GPU 71% busy) on RTX 3080 under GE-Proton11-14.

Root Causes & Fixes

  1. View-memory guards (crates/victory-gpu/src/watch.rs, inplace.rs):

    • Replaced per-block BTreeSet<usize> tracking in Guards (protected, clean, absent, aliased) with a coalescing half-open interval RangeSet(BTreeMap<usize, usize>), reducing 174 MiB heap checks to a single O(log intervals) lookup.
    • Separated unmapped placeholder/free holes (Guards::holes) from reserved section views (MEM_MAPPED | MEM_RESERVE), adding placeholder holes to clean until title_memory_remapped removes them. Eliminates thousands of VirtualQuery syscalls per frame on sparse view buffers while preserving VirtualAlloc(MEM_COMMIT) detection on reserved section views.
    • Switched GUARDS from Mutex to RwLock with read-first fast paths in writes_since_kind, guard, ask_once, writing, title_memory_written, and title_memory_remapped.
    • Batched contiguous committed/protected runs into bulk VirtualProtect calls in protect_here and open_here.
    • Added GUARD_GEN and Journal::ahead_guarded to cache guarded view-memory checks across a submission in ask_once, plus Journal::last_write and writes_since_kind so texture.rs avoids duplicate watch::writes calls.
    • Replaced per-block inplace::pages_of calls inside watch::protect with single-lock inplace::aliased_pages_in that checks view count bounds before allocating, eliminating thousands of temporary Vec copies of filler-page view lists. Stored single-view mappings inline in PageSet (One(usize) / Many(BTreeSet<usize>)).
  2. Shadow refresh fast path (crates/victory-gpu/src/shadow.rs, texture.rs):

    • Added Shadow::all_copied and zero-page tracking in Shadow::copied, plus Shadow::copy_stale_sparse, so unchanged refreshes skip per-page scans in O(1).
    • Enabled VICTORY_TEXTURE_NO_WAIT by default (VICTORY_TEXTURE_NO_WAIT=0 to wait on MAPPING.read()), eliminating multi-second texture stalls while xmem remaps streaming pages.
  3. Physical page alias mapping (crates/victory-hle/src/modules/xmem.rs):

    • Stored Physical::shown with inline single-view ShownPages (One(usize) / Many(HashSet<usize>)), replacing O(N) Vec::retain scans on the filler page while holding MAPPING.write().
    • Coalesced consecutive source slices in map_alias into a single view mapping (with MEM_COALESCE_PLACEHOLDERS and page-by-page fallback across split placeholder boundaries).
  4. Card copy-back relay (crates/victory-gpu/src/host.rs, shadow.rs):

    • Sorted and coalesced adjacent flagged card pieces (up to 1 MiB per run) in relay_card_back before CopyBufferRegion and card_merge_relay, with 64 KiB chunk fallback in card_merge_relay when a coalesced span crosses unmapped memory.
    • Enabled VICTORY_WIDE_MERGE by default (VICTORY_WIDE_MERGE=0 for single-threaded) and parallelized relay_card_back merges across up to 8 workers grouped by shadow to avoid Shadow::before lock contention.

Benchmarks (RTX 3080, GE-Proton11-14, live 3D world)

Measured against baseline (8dd30ab + #737 latch fix) on the same binary path and vkd3d-proton shader cache:

Metric (per 3D world frame) Baseline With this PR Speedup
Frame rate (steady 3D world) 0.1-0.2 fps (4,244-6,146 ms) 1.9-2.0 fps (498.7-536.7 ms) ~10x
GPU busy / idle behind CPU 5-18% (2,789-5,817 ms idle) 71% (47.1 ms idle) 60-123x less CPU idle
Buffer copies 1,324.7-2,545.7 ms 37.6-63.6 ms 35-67x
textures (MAPPING.read() wait) 1,382-4,566.9 ms (2,104-4,175.7 ms wait) 5.0-8.0 ms (0.0 ms wait) 173-570x
Write-watch askings >= 1 ms 411/frame, 1,170.4 ms (max 127.9 ms) 3.0/frame, 4.6 ms (max 2.2 ms) 254x
Card copy-back CPU merge 534-846 ms (pre-coalesce relay 3,280 ms) 60.3 ms (61.0 MB, 956 pieces) 9-54x

Verification

  • Rebased cleanly onto origin/main (9376fd6), preserving VICTORY_VIEW_ASK, WatchKnownView/WatchFailed, Tracked, and VICTORY_CARD_FETCH_INFLIGHT.
  • cargo clippy --target x86_64-pc-windows-gnu -p victory-gpu -p victory-hle --all-targets (default and --features diagnostics): zero warnings in touched files.
  • Windows unit tests run under GE-Proton11-14:
    • watch::*: 14/14 passed (including new range_set_merges_splits_and_queries_gaps and placeholder_holes_join_clean_until_remapped)
    • shadow::*: 28/28 passed
    • inplace::*: 6/6 passed
    • host::* / descriptor::host::* / pipeline::host::*: 34/34 passed (1 ignored benchmark)
    • xmem::*: 13/13 passed (including new map_alias_coalesces_consecutive_pages_and_split_placeholders)
  • Verified live 3D opening cutscene rendering visually across a full 360s run with zero crashes or device loss.
**@⁠powplusplus** on GitHub · 2026-11-25 09:19 UTC · [original](https://github.com/fxceless/victory-fork/pull/824) `powplusplus:perf/fast-watch-guards` → `main` · +1282 −312 · 6 files · 1 commits · open ## Summary Cuts CPU-side frame preparation, lock contention, and copy-back overhead in the 3D world from `0.1-0.2 fps` (`4,244-6,146 ms/frame`, GPU 5-18% busy) to `1.9-2.0 fps` (`498.7-536.7 ms/frame`, GPU 71% busy) on RTX 3080 under GE-Proton11-14. ### Root Causes & Fixes 1. **View-memory guards (`crates/victory-gpu/src/watch.rs`, `inplace.rs`)**: - Replaced per-block `BTreeSet<usize>` tracking in `Guards` (`protected`, `clean`, `absent`, `aliased`) with a coalescing half-open interval `RangeSet(BTreeMap<usize, usize>)`, reducing 174 MiB heap checks to a single O(log intervals) lookup. - Separated unmapped placeholder/free holes (`Guards::holes`) from reserved section views (`MEM_MAPPED | MEM_RESERVE`), adding placeholder holes to `clean` until `title_memory_remapped` removes them. Eliminates thousands of `VirtualQuery` syscalls per frame on sparse view buffers while preserving `VirtualAlloc(MEM_COMMIT)` detection on reserved section views. - Switched `GUARDS` from `Mutex` to `RwLock` with read-first fast paths in `writes_since_kind`, `guard`, `ask_once`, `writing`, `title_memory_written`, and `title_memory_remapped`. - Batched contiguous committed/protected runs into bulk `VirtualProtect` calls in `protect_here` and `open_here`. - Added `GUARD_GEN` and `Journal::ahead_guarded` to cache guarded view-memory checks across a submission in `ask_once`, plus `Journal::last_write` and `writes_since_kind` so `texture.rs` avoids duplicate `watch::writes` calls. - Replaced per-block `inplace::pages_of` calls inside `watch::protect` with single-lock `inplace::aliased_pages_in` that checks view count bounds before allocating, eliminating thousands of temporary `Vec` copies of filler-page view lists. Stored single-view mappings inline in `PageSet` (`One(usize)` / `Many(BTreeSet<usize>)`). 2. **Shadow refresh fast path (`crates/victory-gpu/src/shadow.rs`, `texture.rs`)**: - Added `Shadow::all_copied` and zero-page tracking in `Shadow::copied`, plus `Shadow::copy_stale_sparse`, so unchanged refreshes skip per-page scans in O(1). - Enabled `VICTORY_TEXTURE_NO_WAIT` by default (`VICTORY_TEXTURE_NO_WAIT=0` to wait on `MAPPING.read()`), eliminating multi-second texture stalls while `xmem` remaps streaming pages. 3. **Physical page alias mapping (`crates/victory-hle/src/modules/xmem.rs`)**: - Stored `Physical::shown` with inline single-view `ShownPages` (`One(usize)` / `Many(HashSet<usize>)`), replacing O(N) `Vec::retain` scans on the filler page while holding `MAPPING.write()`. - Coalesced consecutive source slices in `map_alias` into a single view mapping (with `MEM_COALESCE_PLACEHOLDERS` and page-by-page fallback across split placeholder boundaries). 4. **Card copy-back relay (`crates/victory-gpu/src/host.rs`, `shadow.rs`)**: - Sorted and coalesced adjacent flagged card pieces (up to 1 MiB per run) in `relay_card_back` before `CopyBufferRegion` and `card_merge_relay`, with 64 KiB chunk fallback in `card_merge_relay` when a coalesced span crosses unmapped memory. - Enabled `VICTORY_WIDE_MERGE` by default (`VICTORY_WIDE_MERGE=0` for single-threaded) and parallelized `relay_card_back` merges across up to 8 workers grouped by shadow to avoid `Shadow::before` lock contention. ## Benchmarks (RTX 3080, GE-Proton11-14, live 3D world) Measured against baseline (`8dd30ab` + `#737` latch fix) on the same binary path and vkd3d-proton shader cache: | Metric (per 3D world frame) | Baseline | With this PR | Speedup | |---|---:|---:|---:| | Frame rate (steady 3D world) | `0.1-0.2 fps` (`4,244-6,146 ms`) | `1.9-2.0 fps` (`498.7-536.7 ms`) | **~10x** | | GPU busy / idle behind CPU | `5-18%` (`2,789-5,817 ms` idle) | `71%` (`47.1 ms` idle) | **60-123x less CPU idle** | | Buffer `copies` | `1,324.7-2,545.7 ms` | `37.6-63.6 ms` | **35-67x** | | `textures` (`MAPPING.read()` wait) | `1,382-4,566.9 ms` (`2,104-4,175.7 ms` wait) | `5.0-8.0 ms` (`0.0 ms` wait) | **173-570x** | | Write-watch askings >= 1 ms | `411/frame, 1,170.4 ms` (max `127.9 ms`) | `3.0/frame, 4.6 ms` (max `2.2 ms`) | **254x** | | Card copy-back CPU merge | `534-846 ms` (pre-coalesce relay `3,280 ms`) | `60.3 ms` (`61.0 MB`, 956 pieces) | **9-54x** | ## Verification - Rebased cleanly onto `origin/main` (`9376fd6`), preserving `VICTORY_VIEW_ASK`, `WatchKnownView`/`WatchFailed`, `Tracked`, and `VICTORY_CARD_FETCH_INFLIGHT`. - `cargo clippy --target x86_64-pc-windows-gnu -p victory-gpu -p victory-hle --all-targets` (default and `--features diagnostics`): zero warnings in touched files. - Windows unit tests run under GE-Proton11-14: - `watch::*`: `14/14` passed (including new `range_set_merges_splits_and_queries_gaps` and `placeholder_holes_join_clean_until_remapped`) - `shadow::*`: `28/28` passed - `inplace::*`: `6/6` passed - `host::*` / `descriptor::host::*` / `pipeline::host::*`: `34/34` passed (1 ignored benchmark) - `xmem::*`: `13/13` passed (including new `map_alias_coalesces_consecutive_pages_and_split_placeholders`) - Verified live 3D opening cutscene rendering visually across a full 360s run with zero crashes or device loss.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:51:58 +00:00
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 09:20 UTC · original · edited 2026-11-25 09:29 UTC

Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T09:29:54.096704Z 9dae0a7 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@⁠codex review" or "@⁠codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 09:20 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#issuecomment-7158189523) · edited 2026-11-25 09:29 UTC <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"9dae0a74e8af72b10ae7ca0da01959d30ccedc76","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-25T09:29:54.096704Z">2026-11-25T09:29:54.096704Z</relative-time> | `9dae0a7` | PR opened | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@⁠codex review" or "@⁠codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
Author
Owner

@⁠MamaLeVrai on GitHub · 2026-11-25 09:54 UTC · original

Test report on real hardware: AMD RX 6950 XT (RDNA2), Windows 11, Rust 1.98.1, with a GPU present. I merged this PR's head 9dae0a7 into main 9376fd6 in a throwaway tree (no conflict). cargo clippy --workspace --all-targets --locked -- -D warnings fails, with the same two errors as main itself on this machine (function placed_filler_twins is never used, field depth_written is never read, victory-gpu): this PR adds none and removes none. cargo test --workspace --locked: first run 543 passed, 0 failed, 10 ignored (main alone: 540 passed). In the second run the victory-gpu test binary died with STATUS_ACCESS_VIOLATION (0xc0000005) after 40 tests, so the run stopped there. I did not find which test it was, and I have not reproduced it since; main alone did not crash in its two runs. The title was not run, so this says nothing about in-game effect. No game data.

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

**@⁠MamaLeVrai** on GitHub · 2026-11-25 09:54 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#issuecomment-7158954343) Test report on real hardware: AMD RX 6950 XT (RDNA2), Windows 11, Rust 1.98.1, with a GPU present. I merged this PR's head `9dae0a7` into `main` `9376fd6` in a throwaway tree (no conflict). `cargo clippy --workspace --all-targets --locked -- -D warnings` fails, with the same two errors as `main` itself on this machine (`function placed_filler_twins is never used`, `field depth_written is never read`, `victory-gpu`): this PR adds none and removes none. `cargo test --workspace --locked`: first run 543 passed, 0 failed, 10 ignored (`main` alone: 540 passed). In the second run the `victory-gpu` test binary died with `STATUS_ACCESS_VIOLATION` (0xc0000005) after 40 tests, so the run stopped there. I did not find which test it was, and I have not reproduced it since; `main` alone did not crash in its two runs. The title was not run, so this says nothing about in-game effect. No game data. AI-assisted (Claude Code); no game data.
Author
Owner

@⁠npanu420 on GitHub · 2026-11-25 10:07 UTC · original

Fixes for the three review findings above, as three commits on top of this PR's head 9dae0a7: https://github.com/npanu420/victory-fork/commits/fix-824-review (cherry-pick or merge as you like).

  1. P1, failed merges at page boundaries (17c0505, shadow.rs): a failed coalesced read is retried in slices cut at absolute 64 KiB title-page boundaries, whatever the trimmed span's size. Test a_relay_merge_writes_the_mapped_side_of_a_page_boundary (changes at PAGE-1 and PAGE, the second page uncommitted) fails before the fix: the mapped byte stayed 0.
  2. P1, overlapping destinations (4732b8c, host.rs, shadow.rs): relay_merge_groups sweeps the shadows' title ranges, so transitively overlapping or nested ones share one serialized group, in their original merge order. Disjoint ones still go to separate workers. Test overlapping_shadows_merge_in_the_same_group.
  3. P2, private reservations as clean holes (3c649db, watch.rs, xmem.rs): only reservations that QueryVirtualMemoryInformation confirms as placeholders are cached as clean. Ordinary and free ones stay in absent. XMemVirtualAlloc commits go through commit_title_memory, which opens guards first and clears the cached state afterwards. Test a_private_reservation_beside_a_view_is_checked_after_commit fails before the fix.

Results on Windows 11, RTX 3070:

  • cargo test -p victory-gpu --features diagnostics --lib -- shadow host watch relay: 86 passed (83 at 9dae0a7), 1 ignored benchmark.
  • victory-hle xmem tests: 13 passed.
  • clippy: no new diagnostics. The existing draw.rs unnecessary_sort_by and depth_written warnings remain.

Not yet run in game on its own. Our in-game runs have this PR merged into a larger stack.

(AI-assisted: drafted with Codex and reviewed with Claude Code. No game data.)

**@⁠npanu420** on GitHub · 2026-11-25 10:07 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#issuecomment-7159248736) Fixes for the three review findings above, as three commits on top of this PR's head `9dae0a7`: https://github.com/npanu420/victory-fork/commits/fix-824-review (cherry-pick or merge as you like). 1. **P1, failed merges at page boundaries** (`17c0505`, `shadow.rs`): a failed coalesced read is retried in slices cut at absolute 64 KiB title-page boundaries, whatever the trimmed span's size. Test `a_relay_merge_writes_the_mapped_side_of_a_page_boundary` (changes at `PAGE-1` and `PAGE`, the second page uncommitted) fails before the fix: the mapped byte stayed 0. 2. **P1, overlapping destinations** (`4732b8c`, `host.rs`, `shadow.rs`): `relay_merge_groups` sweeps the shadows' title ranges, so transitively overlapping or nested ones share one serialized group, in their original merge order. Disjoint ones still go to separate workers. Test `overlapping_shadows_merge_in_the_same_group`. 3. **P2, private reservations as clean holes** (`3c649db`, `watch.rs`, `xmem.rs`): only reservations that `QueryVirtualMemoryInformation` confirms as placeholders are cached as clean. Ordinary and free ones stay in `absent`. `XMemVirtualAlloc` commits go through `commit_title_memory`, which opens guards first and clears the cached state afterwards. Test `a_private_reservation_beside_a_view_is_checked_after_commit` fails before the fix. Results on Windows 11, RTX 3070: - `cargo test -p victory-gpu --features diagnostics --lib -- shadow host watch relay`: 86 passed (83 at `9dae0a7`), 1 ignored benchmark. - `victory-hle` xmem tests: 13 passed. - clippy: no new diagnostics. The existing `draw.rs` `unnecessary_sort_by` and `depth_written` warnings remain. Not yet run in game on its own. Our in-game runs have this PR merged into a larger stack. (AI-assisted: drafted with Codex and reviewed with Claude Code. No game data.)
Author
Owner

@⁠MamaLeVrai on GitHub · 2026-11-25 10:09 UTC · original

Follow-up to my test report above: the STATUS_ACCESS_VIOLATION in the second full run did not come back. On this PR's tree (head 9dae0a7 merged into main 9376fd6), 4 further runs of cargo test -p victory-gpu --lib all passed (146 passed, 3 ignored each). I still do not know which test died the first time, so I cannot say it was not this PR; I can only say I could not reproduce it.

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

**@⁠MamaLeVrai** on GitHub · 2026-11-25 10:09 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#issuecomment-7159302429) Follow-up to my test report above: the `STATUS_ACCESS_VIOLATION` in the second full run did not come back. On this PR's tree (head `9dae0a7` merged into `main` `9376fd6`), 4 further runs of `cargo test -p victory-gpu --lib` all passed (146 passed, 3 ignored each). I still do not know which test died the first time, so I cannot say it was not this PR; I can only say I could not reproduce it. AI-assisted (Claude Code); no game data.
Author
Owner

@⁠sagouindupm on GitHub · 2026-11-25 11:33 UTC · original

Tested #824 (9dae0a7) combined with #827 (f681125) on Windows 11 Pro (Intel i5-12400F, 32 GB RAM, NVIDIA GeForce RTX 3050 8 GB) under --console series-s, A/B against the same local base (9376fd6 + #188 + #518 + #610 + VICTORY_LITE=1280x5120, 20 samples from 100 s to ~290 s):

  • Baseline (bench_k0): entered 3D draws at sample 10/20, max spike 2,357.9 ms/frame, ended at 234.3 ms/frame (2711 draws), walls intact.
  • With #824 + #827 combined (bench_k1): entered 3D draws at sample 2/20, peak spike across all 20 samples 628.3 ms/frame (no multi-second spikes), last 5 samples 211.9–225.8 ms/frame (mean 218.5 ms/frame, ~4.6 FPS; log peak 4.9 fps / 205.2 ms/frame), walls intact, zero crash during the run.

(Note: #824 and #827 were tested together on the same branch.) Next up on our side is testing @⁠npanu420's 3 review-fix commits (npanu420:fix-824-review).

AI-assisted: benchmark analysis and write-up prepared with AI assistance.

**@⁠sagouindupm** on GitHub · 2026-11-25 11:33 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#issuecomment-7161207854) Tested #824 (`9dae0a7`) combined with #827 (`f681125`) on Windows 11 Pro (Intel i5-12400F, 32 GB RAM, NVIDIA GeForce RTX 3050 8 GB) under `--console series-s`, A/B against the same local base (`9376fd6` + #188 + #518 + #610 + `VICTORY_LITE=1280x5120`, 20 samples from 100 s to ~290 s): - **Baseline** (`bench_k0`): entered 3D draws at sample 10/20, max spike **2,357.9 ms/frame**, ended at **234.3 ms/frame** (`2711 draws`), walls intact. - **With #824 + #827 combined** (`bench_k1`): entered 3D draws at sample 2/20, peak spike across all 20 samples **628.3 ms/frame** (no multi-second spikes), last 5 samples **211.9–225.8 ms/frame** (mean **218.5 ms/frame**, ~4.6 FPS; log peak **4.9 fps / 205.2 ms/frame**), walls intact, zero crash during the run. *(Note: #824 and #827 were tested together on the same branch.)* Next up on our side is testing @⁠npanu420's 3 review-fix commits (`npanu420:fix-824-review`). AI-assisted: benchmark analysis and write-up prepared with AI assistance.
Author
Owner

@⁠NotADonky43 on GitHub · 2026-11-25 21:06 UTC · original

Related native Windows reproduction, independent of the performance stack: map three adjacent 64 KiB pages separately, return them to placeholders, then remap the range to three consecutive pages of the same committed section. The larger replacement can fail because it spans three separate placeholders, even though the addresses and section offsets are contiguous. This is consistent with MapViewOfFile3 requiring the replacement to match one placeholder exactly.

A candidate that respects the returned boundaries instead of coalescing them passed both a targeted Windows test and full GPU texture readbacks. It tries the whole view first and only partitions a proven split on a replacement failure; it does not retry a commit failure or suppress invalidation. Tested on Windows with an RTX 5070 Ti, no game files required. This confirms the failure mode #824 deals with, not its end-to-end performance numbers. Keeping GPU/CPU copy-back ordered relative to the remap is a separate issue.

The standalone patch below applies to 085ee7c (not to this PR's head). All 14 XMem tests passed on that base, including two new Windows regression cases. The GPU check was run on the combined local candidate; the diff below contains only the placeholder fix and its Windows tests.

Source-only diff: respect existing placeholder boundaries (12 KB)
diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index e898459..c759cc1 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -769,9 +769,84 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
     true
 }
 
-/// Maps `slice` and the slices after it over `[base, base + len)`, which
-/// must lie in one placeholder.
+/// Maps consecutive slices at `base`. A single backing run can span several
+/// destination placeholders left by earlier page-by-page mappings.
 fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
+    match map_view(physical, base, len, slice) {
+        Ok(()) => true,
+        Err(MapError::Commit) => false,
+        Err(MapError::Replace(error, slice)) => {
+            // Keep the single-view fast path. Only partition a failed request
+            // if the first reserved region really ends within it. Do not
+            // coalesce placeholders or retry a commitment failure.
+            if len > PAGE
+                && let Some(first) = reserved_prefix(base)
+                && first < len
+            {
+                let mut offset = 0;
+                let mut size = first;
+                loop {
+                    let at = base + offset;
+                    let start = Slice {
+                        index: slice.index + offset / PAGE,
+                        section: slice.section.clone(),
+                    };
+                    // As with multiple backing runs, any installed prefix
+                    // remains valid and tracked if a later replacement fails.
+                    match map_view(physical, at, size, start) {
+                        Ok(()) => (),
+                        Err(MapError::Commit) => return false,
+                        Err(MapError::Replace(error, _)) => return replace_failed(at, size, error),
+                    }
+                    offset += size;
+                    if offset == len {
+                        return true;
+                    }
+                    let Some(next) = reserved_prefix(base + offset) else {
+                        return replace_failed(base, len, error);
+                    };
+                    size = next.min(len - offset);
+                }
+            }
+            replace_failed(base, len, error)
+        }
+    }
+}
+
+/// This is only an upper bound on a replaceable span: a reserved region need
+/// not be a placeholder. MapViewOfFile3 still validates each replacement.
+fn reserved_prefix(base: usize) -> Option<usize> {
+    let mut info = MEMORY_BASIC_INFORMATION::default();
+    // SAFETY: querying our process, with a live, correctly sized output buffer.
+    let queried = unsafe {
+        VirtualQueryEx(GetCurrentProcess(), base as *const c_void, &mut info, size_of_val(&info))
+    };
+    (queried != 0
+        && info.State == MEM_RESERVE
+        && info.BaseAddress as usize == base
+        && info.RegionSize >= PAGE
+        && info.RegionSize.is_multiple_of(PAGE))
+    .then_some(info.RegionSize)
+}
+
+enum MapError {
+    Replace(std::io::Error, Slice),
+    Commit,
+}
+
+fn replace_failed(base: usize, len: usize, error: std::io::Error) -> bool {
+    tracing::warn!(
+        address = format_args!("{base:#x}"),
+        len,
+        %error,
+        "mapping physical pages failed (not a placeholder?)"
+    );
+    false
+}
+
+/// Replaces part or all of one placeholder, and records only the view the
+/// host actually installed. Callers hold the page table and remapping guard.
+fn map_view(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> Result<(), MapError> {
     // SAFETY: splits the placeholder around the range (failing harmlessly
     // when the range is the whole placeholder), then maps the section
     // there; both act only on placeholders.
@@ -793,19 +868,13 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
             0,
         )
     };
-    if view.Value as usize != base {
-        tracing::warn!(
-            address = format_args!("{base:#x}"),
-            len,
-            error = %std::io::Error::last_os_error(),
-            "mapping physical pages failed (not a placeholder?)"
-        );
-        return false;
+    if view.Value.is_null() || view.Value as usize != base {
+        return Err(MapError::Replace(std::io::Error::last_os_error(), slice));
     }
     if !commit(base, len) {
         // SAFETY: the view just mapped, back to a placeholder.
         unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
-        return false;
+        return Err(MapError::Commit);
     }
     // New contents, read-write: the GPU side's copies no longer guard it.
     victory_gpu::title_memory_remapped(base, len);
@@ -815,7 +884,7 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
         physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE);
     }
     physical.views.insert(base, (len, slice));
-    true
+    Ok(())
 }
 
 /// Commits the section pages a view shows (once per page, whichever view).
@@ -1034,6 +1103,9 @@ pub(crate) fn module() -> HleModule {
 mod tests {
     use super::*;
 
+    #[cfg(feature = "diagnostics")]
+    mod gpu;
+
     fn query(address: *const c_void) -> BasicInformation {
         // SAFETY: plain data; zero is a valid value.
         let mut info: BasicInformation = unsafe { std::mem::zeroed() };
@@ -1329,6 +1401,151 @@ mod tests {
         pages
     }
 
+    /// Owns a small reservation, possibly split into multiple placeholders.
+    struct AliasWindow {
+        base: usize,
+        pages: usize,
+    }
+
+    impl AliasWindow {
+        fn new(pages: usize) -> Self {
+            let base = XMemVirtualAlloc(
+                std::ptr::null_mut(),
+                pages * PAGE,
+                MEM_RESERVE | PAGES_64K,
+                0,
+                PAGE_READWRITE,
+            );
+            assert!(!base.is_null());
+            Self { base: base as usize, pages }
+        }
+
+        fn at(&self, page: usize) -> *mut c_void {
+            assert!(page < self.pages);
+            (self.base + page * PAGE) as *mut c_void
+        }
+
+        fn assert_bytes(&self, page: usize, byte: u8) {
+            let at = self.at(page);
+            assert_eq!(query(at).host.State, MEM_COMMIT, "page {page} is not mapped");
+            // SAFETY: the fixture owns a committed page and does not remap it concurrently.
+            let bytes = unsafe { std::slice::from_raw_parts(at.cast::<u8>(), PAGE) };
+            assert!(bytes.iter().all(|&b| b == byte), "wrong bytes in page {page}");
+        }
+    }
+
+    impl Drop for AliasWindow {
+        fn drop(&mut self) {
+            XMemMapPhysicalPages(self.at(0), self.pages, std::ptr::null());
+            let end = self.base + self.pages * PAGE;
+            let mut at = self.base;
+            while at < end {
+                let mut info = MEMORY_BASIC_INFORMATION::default();
+                // SAFETY: query our window; the output is a live structure of the supplied size.
+                let queried = unsafe {
+                    VirtualQueryEx(GetCurrentProcess(), at as *const c_void, &mut info, size_of_val(&info))
+                };
+                if queried == 0 || info.AllocationBase as usize != at || info.State != MEM_RESERVE
+                    || info.RegionSize == 0 || info.RegionSize > end - at
+                {
+                    break;
+                }
+                // SAFETY: this is the base of a remaining placeholder owned by the window.
+                unsafe { VirtualFree(at as *mut c_void, 0, MEM_RELEASE) };
+                at += info.RegionSize;
+            }
+        }
+    }
+
+    struct FixturePages(Vec<usize>);
+
+    impl Drop for FixturePages {
+        fn drop(&mut self) {
+            XMemFreePhysicalPages(self.0.len(), self.0.as_ptr());
+        }
+    }
+
+    #[test]
+    fn regrouped_pages_cross_old_placeholder_boundaries() {
+        let original = FixturePages(allocate(3));
+        let replacement = FixturePages(allocate(4));
+        let pool = AliasWindow::new(4);
+        let mapped = AliasWindow::new(3);
+        let other = AliasWindow::new(3);
+        for (set, first) in [(&original.0, 0x10), (&replacement.0, 0x20)] {
+            for (i, id) in set.iter().enumerate() {
+                assert!(write_physical(std::slice::from_ref(id), 0, &vec![first + i as u8; PAGE]));
+            }
+        }
+
+        assert_eq!(XMemMapPhysicalPages(pool.at(0), 4, replacement.0.as_ptr()), pool.at(0));
+        // Three distinct installed views, with distinct placeholders when unmapped.
+        for (i, id) in original.0.iter().enumerate() {
+            assert_eq!(XMemMapPhysicalPages(mapped.at(i), 1, id), mapped.at(i));
+            mapped.assert_bytes(i, 0x10 + i as u8);
+        }
+        assert_eq!(
+            XMemMapPhysicalPages(mapped.at(0), 3, replacement.0.as_ptr()),
+            mapped.at(0),
+            "a contiguous backing run must work across three old single-page views"
+        );
+        assert!(map_alias(other.base as u64, pool.base as u64, (3 * PAGE) as u64));
+        for i in 0..3 {
+            mapped.assert_bytes(i, 0x20 + i as u8);
+            other.assert_bytes(i, 0x20 + i as u8);
+        }
+
+        // Remap the middle pool page. Copied aliases must stay on its old backing.
+        assert_eq!(XMemMapPhysicalPages(pool.at(1), 1, &replacement.0[3]), pool.at(1));
+        pool.assert_bytes(1, 0x23);
+        // The mapped page is still writable through either other view.
+        // SAFETY: both fixture-owned views of this page are committed and writable.
+        unsafe { mapped.at(1).cast::<u8>().write_bytes(0x42, PAGE) };
+        other.assert_bytes(1, 0x42);
+        assert!(write_physical(&replacement.0[1..2], 0, &vec![0x65; PAGE]));
+        mapped.assert_bytes(1, 0x65);
+        other.assert_bytes(1, 0x65);
+        pool.assert_bytes(1, 0x23);
+        assert_eq!(XMemMapPhysicalPages(mapped.at(1), 1, std::ptr::null()), mapped.at(1));
+        assert_eq!(query(mapped.at(1)).host.State, MEM_RESERVE);
+        mapped.assert_bytes(0, 0x20);
+        mapped.assert_bytes(2, 0x22);
+        other.assert_bytes(1, 0x65);
+    }
+
+    #[test]
+    fn regrouped_pages_keep_larger_views_and_an_untouched_suffix() {
+        let original = FixturePages(allocate(5));
+        let replacement = FixturePages(allocate(4));
+        let placed = AliasWindow::new(5);
+        let alias = AliasWindow::new(1);
+        for (pages, start) in [(&original.0, 0x10), (&replacement.0, 0x20)] {
+            for (i, id) in pages.iter().enumerate() {
+                assert!(write_physical(std::slice::from_ref(id), 0, &vec![start + i as u8; PAGE]));
+            }
+        }
+        for (at, pages) in [(0, &original.0[..2]), (2, &original.0[2..])] {
+            assert_eq!(XMemMapPhysicalPages(placed.at(at), pages.len(), pages.as_ptr()), placed.at(at));
+        }
+        assert_eq!(XMemMapPhysicalPages(placed.at(0), 4, replacement.0.as_ptr()), placed.at(0));
+        // The four pages should fit in two views, not four single-page views.
+        let sizes: Vec<_> = physical()
+            .views
+            .range(placed.base..placed.base + 5 * PAGE)
+            .map(|(_, (len, _))| *len)
+            .collect();
+        assert_eq!(sizes, [2 * PAGE, 2 * PAGE, PAGE]);
+        // Installed views continue to own the backing after the page IDs are freed.
+        drop(replacement);
+        drop(original);
+        assert!(map_alias(alias.base as u64, placed.at(3) as u64, PAGE as u64));
+        alias.assert_bytes(0, 0x23);
+        for page in 0..4 {
+            placed.assert_bytes(page, 0x20 + page as u8);
+        }
+        placed.assert_bytes(4, 0x14);
+    }
+
     /// The bytes of one page, through a view of our own.
     fn page_bytes(page: usize) -> Vec<u8> {
         let slice = physical().pages.get(&page).cloned().expect("known page");
**@⁠NotADonky43** on GitHub · 2026-11-25 21:06 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#issuecomment-7174620673) Related native Windows reproduction, independent of the performance stack: map three adjacent 64 KiB pages separately, return them to placeholders, then remap the range to three consecutive pages of the same committed section. The larger replacement can fail because it spans three separate placeholders, even though the addresses and section offsets are contiguous. This is consistent with `MapViewOfFile3` requiring the replacement to match one placeholder exactly. A candidate that respects the returned boundaries instead of coalescing them passed both a targeted Windows test and full GPU texture readbacks. It tries the whole view first and only partitions a proven split on a replacement failure; it does not retry a commit failure or suppress invalidation. Tested on Windows with an RTX 5070 Ti, no game files required. This confirms the failure mode #824 deals with, not its end-to-end performance numbers. Keeping GPU/CPU copy-back ordered relative to the remap is a separate issue. The standalone patch below applies to `085ee7c` (not to this PR's head). All 14 XMem tests passed on that base, including two new Windows regression cases. The GPU check was run on the combined local candidate; the diff below contains only the placeholder fix and its Windows tests. <details><summary>Source-only diff: respect existing placeholder boundaries (12 KB)</summary> ```diff diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index e898459..c759cc1 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -769,9 +769,84 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { true } -/// Maps `slice` and the slices after it over `[base, base + len)`, which -/// must lie in one placeholder. +/// Maps consecutive slices at `base`. A single backing run can span several +/// destination placeholders left by earlier page-by-page mappings. fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { + match map_view(physical, base, len, slice) { + Ok(()) => true, + Err(MapError::Commit) => false, + Err(MapError::Replace(error, slice)) => { + // Keep the single-view fast path. Only partition a failed request + // if the first reserved region really ends within it. Do not + // coalesce placeholders or retry a commitment failure. + if len > PAGE + && let Some(first) = reserved_prefix(base) + && first < len + { + let mut offset = 0; + let mut size = first; + loop { + let at = base + offset; + let start = Slice { + index: slice.index + offset / PAGE, + section: slice.section.clone(), + }; + // As with multiple backing runs, any installed prefix + // remains valid and tracked if a later replacement fails. + match map_view(physical, at, size, start) { + Ok(()) => (), + Err(MapError::Commit) => return false, + Err(MapError::Replace(error, _)) => return replace_failed(at, size, error), + } + offset += size; + if offset == len { + return true; + } + let Some(next) = reserved_prefix(base + offset) else { + return replace_failed(base, len, error); + }; + size = next.min(len - offset); + } + } + replace_failed(base, len, error) + } + } +} + +/// This is only an upper bound on a replaceable span: a reserved region need +/// not be a placeholder. MapViewOfFile3 still validates each replacement. +fn reserved_prefix(base: usize) -> Option<usize> { + let mut info = MEMORY_BASIC_INFORMATION::default(); + // SAFETY: querying our process, with a live, correctly sized output buffer. + let queried = unsafe { + VirtualQueryEx(GetCurrentProcess(), base as *const c_void, &mut info, size_of_val(&info)) + }; + (queried != 0 + && info.State == MEM_RESERVE + && info.BaseAddress as usize == base + && info.RegionSize >= PAGE + && info.RegionSize.is_multiple_of(PAGE)) + .then_some(info.RegionSize) +} + +enum MapError { + Replace(std::io::Error, Slice), + Commit, +} + +fn replace_failed(base: usize, len: usize, error: std::io::Error) -> bool { + tracing::warn!( + address = format_args!("{base:#x}"), + len, + %error, + "mapping physical pages failed (not a placeholder?)" + ); + false +} + +/// Replaces part or all of one placeholder, and records only the view the +/// host actually installed. Callers hold the page table and remapping guard. +fn map_view(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> Result<(), MapError> { // SAFETY: splits the placeholder around the range (failing harmlessly // when the range is the whole placeholder), then maps the section // there; both act only on placeholders. @@ -793,19 +868,13 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { 0, ) }; - if view.Value as usize != base { - tracing::warn!( - address = format_args!("{base:#x}"), - len, - error = %std::io::Error::last_os_error(), - "mapping physical pages failed (not a placeholder?)" - ); - return false; + if view.Value.is_null() || view.Value as usize != base { + return Err(MapError::Replace(std::io::Error::last_os_error(), slice)); } if !commit(base, len) { // SAFETY: the view just mapped, back to a placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; - return false; + return Err(MapError::Commit); } // New contents, read-write: the GPU side's copies no longer guard it. victory_gpu::title_memory_remapped(base, len); @@ -815,7 +884,7 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE); } physical.views.insert(base, (len, slice)); - true + Ok(()) } /// Commits the section pages a view shows (once per page, whichever view). @@ -1034,6 +1103,9 @@ pub(crate) fn module() -> HleModule { mod tests { use super::*; + #[cfg(feature = "diagnostics")] + mod gpu; + fn query(address: *const c_void) -> BasicInformation { // SAFETY: plain data; zero is a valid value. let mut info: BasicInformation = unsafe { std::mem::zeroed() }; @@ -1329,6 +1401,151 @@ mod tests { pages } + /// Owns a small reservation, possibly split into multiple placeholders. + struct AliasWindow { + base: usize, + pages: usize, + } + + impl AliasWindow { + fn new(pages: usize) -> Self { + let base = XMemVirtualAlloc( + std::ptr::null_mut(), + pages * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!base.is_null()); + Self { base: base as usize, pages } + } + + fn at(&self, page: usize) -> *mut c_void { + assert!(page < self.pages); + (self.base + page * PAGE) as *mut c_void + } + + fn assert_bytes(&self, page: usize, byte: u8) { + let at = self.at(page); + assert_eq!(query(at).host.State, MEM_COMMIT, "page {page} is not mapped"); + // SAFETY: the fixture owns a committed page and does not remap it concurrently. + let bytes = unsafe { std::slice::from_raw_parts(at.cast::<u8>(), PAGE) }; + assert!(bytes.iter().all(|&b| b == byte), "wrong bytes in page {page}"); + } + } + + impl Drop for AliasWindow { + fn drop(&mut self) { + XMemMapPhysicalPages(self.at(0), self.pages, std::ptr::null()); + let end = self.base + self.pages * PAGE; + let mut at = self.base; + while at < end { + let mut info = MEMORY_BASIC_INFORMATION::default(); + // SAFETY: query our window; the output is a live structure of the supplied size. + let queried = unsafe { + VirtualQueryEx(GetCurrentProcess(), at as *const c_void, &mut info, size_of_val(&info)) + }; + if queried == 0 || info.AllocationBase as usize != at || info.State != MEM_RESERVE + || info.RegionSize == 0 || info.RegionSize > end - at + { + break; + } + // SAFETY: this is the base of a remaining placeholder owned by the window. + unsafe { VirtualFree(at as *mut c_void, 0, MEM_RELEASE) }; + at += info.RegionSize; + } + } + } + + struct FixturePages(Vec<usize>); + + impl Drop for FixturePages { + fn drop(&mut self) { + XMemFreePhysicalPages(self.0.len(), self.0.as_ptr()); + } + } + + #[test] + fn regrouped_pages_cross_old_placeholder_boundaries() { + let original = FixturePages(allocate(3)); + let replacement = FixturePages(allocate(4)); + let pool = AliasWindow::new(4); + let mapped = AliasWindow::new(3); + let other = AliasWindow::new(3); + for (set, first) in [(&original.0, 0x10), (&replacement.0, 0x20)] { + for (i, id) in set.iter().enumerate() { + assert!(write_physical(std::slice::from_ref(id), 0, &vec![first + i as u8; PAGE])); + } + } + + assert_eq!(XMemMapPhysicalPages(pool.at(0), 4, replacement.0.as_ptr()), pool.at(0)); + // Three distinct installed views, with distinct placeholders when unmapped. + for (i, id) in original.0.iter().enumerate() { + assert_eq!(XMemMapPhysicalPages(mapped.at(i), 1, id), mapped.at(i)); + mapped.assert_bytes(i, 0x10 + i as u8); + } + assert_eq!( + XMemMapPhysicalPages(mapped.at(0), 3, replacement.0.as_ptr()), + mapped.at(0), + "a contiguous backing run must work across three old single-page views" + ); + assert!(map_alias(other.base as u64, pool.base as u64, (3 * PAGE) as u64)); + for i in 0..3 { + mapped.assert_bytes(i, 0x20 + i as u8); + other.assert_bytes(i, 0x20 + i as u8); + } + + // Remap the middle pool page. Copied aliases must stay on its old backing. + assert_eq!(XMemMapPhysicalPages(pool.at(1), 1, &replacement.0[3]), pool.at(1)); + pool.assert_bytes(1, 0x23); + // The mapped page is still writable through either other view. + // SAFETY: both fixture-owned views of this page are committed and writable. + unsafe { mapped.at(1).cast::<u8>().write_bytes(0x42, PAGE) }; + other.assert_bytes(1, 0x42); + assert!(write_physical(&replacement.0[1..2], 0, &vec![0x65; PAGE])); + mapped.assert_bytes(1, 0x65); + other.assert_bytes(1, 0x65); + pool.assert_bytes(1, 0x23); + assert_eq!(XMemMapPhysicalPages(mapped.at(1), 1, std::ptr::null()), mapped.at(1)); + assert_eq!(query(mapped.at(1)).host.State, MEM_RESERVE); + mapped.assert_bytes(0, 0x20); + mapped.assert_bytes(2, 0x22); + other.assert_bytes(1, 0x65); + } + + #[test] + fn regrouped_pages_keep_larger_views_and_an_untouched_suffix() { + let original = FixturePages(allocate(5)); + let replacement = FixturePages(allocate(4)); + let placed = AliasWindow::new(5); + let alias = AliasWindow::new(1); + for (pages, start) in [(&original.0, 0x10), (&replacement.0, 0x20)] { + for (i, id) in pages.iter().enumerate() { + assert!(write_physical(std::slice::from_ref(id), 0, &vec![start + i as u8; PAGE])); + } + } + for (at, pages) in [(0, &original.0[..2]), (2, &original.0[2..])] { + assert_eq!(XMemMapPhysicalPages(placed.at(at), pages.len(), pages.as_ptr()), placed.at(at)); + } + assert_eq!(XMemMapPhysicalPages(placed.at(0), 4, replacement.0.as_ptr()), placed.at(0)); + // The four pages should fit in two views, not four single-page views. + let sizes: Vec<_> = physical() + .views + .range(placed.base..placed.base + 5 * PAGE) + .map(|(_, (len, _))| *len) + .collect(); + assert_eq!(sizes, [2 * PAGE, 2 * PAGE, PAGE]); + // Installed views continue to own the backing after the page IDs are freed. + drop(replacement); + drop(original); + assert!(map_alias(alias.base as u64, placed.at(3) as u64, PAGE as u64)); + alias.assert_bytes(0, 0x23); + for page in 0..4 { + placed.assert_bytes(page, 0x20 + page as u8); + } + placed.assert_bytes(4, 0x14); + } + /// The bytes of one page, through a view of our own. fn page_bytes(page: usize) -> Vec<u8> { let slice = physical().pages.get(&page).cloned().expect("known page"); ``` </details>
Author
Owner

@⁠UwUCammie on GitHub · 2026-11-25 22:46 UTC · original

I tried the readback-command coalescing idea on the RX 7900 XT with 16 KiB pieces. My local variant only joins consecutive CopyBufferRegion calls when the source resource, source offsets and destination offsets all continue. It keeps the CPU merge pieces and their original order. This tests one part of the proposal, on a different integration build.

In the first room it removed 4,152 copy commands per frame. Median readback was 75.1 MB/frame at 16.5 ms on the copy queue. A preceding run with ordinary commands measured 77.2 MB/frame at 4.8 ms. The two sessions averaged 5.25 and 8.87 successful presents/s with 4,931 and 4,854 draws/frame respectively. The joined run also had substantially longer CPU preparation and GPU waits. One run each under shared system load; I can verify the command reduction, but can’t attribute the frame-time difference to coalescing. RADV 26.3.1, Wine 11.22, vkd3d-proton v3.1-83.

**@⁠UwUCammie** on GitHub · 2026-11-25 22:46 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#issuecomment-7176776652) I tried the readback-command coalescing idea on the RX 7900 XT with 16 KiB pieces. My local variant only joins consecutive CopyBufferRegion calls when the source resource, source offsets and destination offsets all continue. It keeps the CPU merge pieces and their original order. This tests one part of the proposal, on a different integration build. In the first room it removed 4,152 copy commands per frame. Median readback was 75.1 MB/frame at 16.5 ms on the copy queue. A preceding run with ordinary commands measured 77.2 MB/frame at 4.8 ms. The two sessions averaged 5.25 and 8.87 successful presents/s with 4,931 and 4,854 draws/frame respectively. The joined run also had substantially longer CPU preparation and GPU waits. One run each under shared system load; I can verify the command reduction, but can’t attribute the frame-time difference to coalescing. RADV 26.3.1, Wine 11.22, vkd3d-proton v3.1-83.
@ -3300,0 +3417,4 @@
let mut written = 0;
let mut off = 0;
while off < n {
let chunk = (n - off).min(crate::watch::PAGE);
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 09:29 UTC · original

P1 Badge Split failed coalesced merges at title-page boundaries

When adjacent flagged pieces straddle mapped and unmapped title memory, trimming to the first and last differing bytes can leave n <= PAGE even though the span crosses the mapping boundary. For example, changes at offsets 65535 and 65536 produce a two-byte read that fails, bypassing this fallback. The subsequent merge advances held without writing the changed byte in the mapped page, permanently losing that GPU result; merging the pieces separately preserves it. Split failed coalesced reads at actual title-page boundaries even when the trimmed span is smaller than PAGE. Fixed-size chunks starting at the trimmed offset can also straddle those boundaries.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 09:29 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#discussion_r4692869010) **<sub><sub>![P1 Badge](https://img.shields.io/badge/P1-orange?style=flat)</sub></sub> Split failed coalesced merges at title-page boundaries** When adjacent flagged pieces straddle mapped and unmapped title memory, trimming to the first and last differing bytes can leave `n <= PAGE` even though the span crosses the mapping boundary. For example, changes at offsets 65535 and 65536 produce a two-byte read that fails, bypassing this fallback. The subsequent merge advances `held` without writing the changed byte in the mapped page, permanently losing that GPU result; merging the pieces separately preserves it. Split failed coalesced reads at actual title-page boundaries even when the trimmed span is smaller than `PAGE`. Fixed-size chunks starting at the trimmed offset can also straddle those boundaries. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
@ -4536,0 +4550,4 @@
for item in pieces {
match groups.last_mut() {
Some(g) if std::sync::Arc::ptr_eq(&g[0].0, &item.0) => g.push(item),
_ => groups.push(vec![item]),
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 09:29 UTC · original

P1 Badge Serialize merges with overlapping title-memory destinations

When at least four dirty runs trigger parallel merging, different shadows backed by overlapping title memory can enter separate workers. Such shadows are supported: shadow::register and lookup retain separate copies for overlapping or nested buffers. Grouping only by Arc leaves their before mutexes independent, so both workers can read the same title snapshot, merge different GPU changes, and then overwrite each other's results when card_merge_relay writes its entire first-to-last-difference span. The previous relay loop serialized these read-modify-write operations. Keep overlapping destinations in the same serialized group rather than treating distinct shadows as necessarily disjoint.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 09:29 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#discussion_r4692869018) **<sub><sub>![P1 Badge](https://img.shields.io/badge/P1-orange?style=flat)</sub></sub> Serialize merges with overlapping title-memory destinations** When at least four dirty runs trigger parallel merging, different shadows backed by overlapping title memory can enter separate workers. Such shadows are supported: `shadow::register` and `lookup` retain separate copies for overlapping or nested buffers. Grouping only by `Arc` leaves their `before` mutexes independent, so both workers can read the same title snapshot, merge different GPU changes, and then overwrite each other's results when `card_merge_relay` writes its entire first-to-last-difference span. The previous relay loop serialized these read-modify-write operations. Keep overlapping destinations in the same serialized group rather than treating distinct shadows as necessarily disjoint. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
@ -708,0 +1073,4 @@
if block < until {
if info.State == MEM_FREE || info.Type != MEM_MAPPED {
g.holes.insert_range(block, until);
g.clean.insert_range(block, until);
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 09:29 UTC · original

P2 Badge Keep ordinary private reservations out of the clean-hole cache

When a guarded window spans a mapped view and an ordinary private reservation, Type != MEM_MAPPED puts the reservation into clean as though it were an immutable placeholder. XMemVirtualAlloc can subsequently commit those private pages without calling title_memory_remapped, so the clean-range fast paths continue reporting no changes and leave the GPU copy holding the previous zeros. The previous implementation kept these blocks in absent and detected the commit through uncommitted_end. Keep ordinary reservations subject to rechecking, or add commit notifications before caching them as clean holes.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 09:29 UTC · [original](https://github.com/fxceless/victory-fork/pull/824#discussion_r4692869024) **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Keep ordinary private reservations out of the clean-hole cache** When a guarded window spans a mapped view and an ordinary private reservation, `Type != MEM_MAPPED` puts the reservation into `clean` as though it were an immutable placeholder. `XMemVirtualAlloc` can subsequently commit those private pages without calling `title_memory_remapped`, so the clean-range fast paths continue reporting no changes and leave the GPU copy holding the previous zeros. The previous implementation kept these blocks in `absent` and detected the commit through `uncommitted_end`. Keep ordinary reservations subject to rechecking, or add commit notifications before caching them as clean holes. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
This pull request has changes conflicting with the target branch.
  • crates/victory-gpu/src/host.rs
  • crates/victory-gpu/src/shadow.rs
  • crates/victory-gpu/src/watch.rs
  • crates/victory-hle/src/modules/xmem.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/824/head:github-bot/gh-824'
git switch 'github-bot/gh-824'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-824'
git switch 'github-bot/gh-824'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-824'
git switch 'github-bot/gh-824'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-824'
git switch 'main'
git merge --squash 'github-bot/gh-824'
git switch 'main'
git merge --ff-only 'github-bot/gh-824'
git switch 'main'
git merge 'github-bot/gh-824'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.